Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
18 views5 pages

Bot

The document outlines the creation of a Telegram bot called FileGrabberBot, which allows users to grab files from a channel after bypassing a link shortener for a token valid for 6 hours. It imposes limits on file grabs (40 per hour) and file validity (20 minutes), while restricting forwarding and saving of files. Step-by-step instructions and complete code for setting up the bot are provided, including database management and command handling.

Uploaded by

sjijajaddm
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views5 pages

Bot

The document outlines the creation of a Telegram bot called FileGrabberBot, which allows users to grab files from a channel after bypassing a link shortener for a token valid for 6 hours. It imposes limits on file grabs (40 per hour) and file validity (20 minutes), while restricting forwarding and saving of files. Step-by-step instructions and complete code for setting up the bot are provided, including database management and command handling.

Uploaded by

sjijajaddm
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 5

so today i want your help in a thing, i want to make a telegram bot which is used

to grab file from a telegram channel through the link which when created when we
send file to the channel and the bot has a feature that whenever anyone uses the
bot for grabing file they need to bypass a link shortner (through which i will earn
money),which will give a token validity for 6 hours, they can use bot for 6 hours
after that they need to refresh the token and the bot restricts the user to grab 40
links of grabing file from channel in 1 hour ,and the files which grabbed from the
channel to the bot is only valid for 20 minutes and after that file will disappear
and bot restricts forwarding and saving the file.

Token-based Access: When a user starts the bot they must “bypass” a (simulated)
link shortener; afterward they refresh to get a token valid for 6 hours.

Hourly Limit: The bot tracks each user so that a maximum of 40 file grabs are
allowed per hour.

File Expiry: Each file sent is valid for 20 minutes. After that time, a scheduled
job notifies the user that the file has expired.

Restricted Forwarding/Saving: The message is sent with protect_content=True (a


feature introduced in Telegram’s API) that aims to restrict forwarding and saving.
(Keep in mind that no method can completely stop a determined user, but this is the
built-in option.)

Below you will find the step-by-step instructions and the complete code.

Step 1. Create Your Bot on Telegram


Open Telegram and Chat with BotFather:

Search for “BotFather.”

Type /newbot and follow the prompts.

Provide a name (for example, “FileGrabberBot”) and a username (ending with “bot”,
e.g., FileGrabber_Bot).

Save the API token provided by BotFather. You’ll need it in the script as
BOT_TOKEN.

Step 2. Install Required Libraries


Make sure you have Python installed. Then install the necessary packages using pip:

bash
pip install python-telegram-bot
(We use Python’s standard sqlite3, so no extra installation is required for that
module.)

Step 3. Set Up Database and Token Functions


We will use an SQLite database to store user information (their token, expiration
time, file count, and the timestamp of their hourly limit reset). A simple token
generator produces a random alphanumeric string for the token. In your production
system you might replace this with a more secure method.

Step 4. The Complete Bot Script


Below is the full script. Save it (for example, as file_grabber_bot.py) and run it.
Replace "YOUR_BOT_TOKEN_HERE" with your actual BotFather token.
python
import logging
import asyncio
import sqlite3
import time
import random
import string
from telegram import Update, InlineKeyboardMarkup, InlineKeyboardButton
from telegram.ext import (
Application,
CommandHandler,
ContextTypes,
)

# Set up logging to help diagnose issues


logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO
)

# Replace this with your BotFather token.


BOT_TOKEN = "YOUR_BOT_TOKEN_HERE"

# Initialize a SQLite database (users.db)


conn = sqlite3.connect("users.db", check_same_thread=False)
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
user_id INTEGER PRIMARY KEY,
token TEXT,
expiration INTEGER,
file_count INTEGER,
last_reset INTEGER
)
''')
conn.commit()

# --- Token and Rate-Limiting Functions ---


def generate_token():
"""Generate a secure (if simple) token: a random alphanumeric string."""
return ''.join(random.choices(string.ascii_letters + string.digits, k=12))

def refresh_token_db(user_id):
"""Generate a new token valid for 6 hours and update the database."""
new_token = generate_token()
expiration = int(time.time()) + 6 * 3600 # 6 hours validity (in seconds)
# Insert or update the user record:
cursor.execute("""
INSERT OR REPLACE INTO users (user_id, token, expiration, file_count,
last_reset)
VALUES (?, ?, ?, ?, ?)
""", (user_id, new_token, expiration, 0, int(time.time())))
conn.commit()
return new_token, expiration

def is_token_valid(user_id):
"""Return True if a valid token exists for the user."""
cursor.execute("SELECT expiration FROM users WHERE user_id=?", (user_id,))
result = cursor.fetchone()
if result and int(time.time()) < result[0]:
return True
return False

def check_and_update_file_limit(user_id):
"""
Check the current file count for the user.
If more than an hour has passed since the last reset, reset the count.
"""
cursor.execute("SELECT file_count, last_reset FROM users WHERE user_id=?",
(user_id,))
res = cursor.fetchone()
if res:
file_count, last_reset = res
now = int(time.time())
if now - last_reset >= 3600:
file_count = 0
last_reset = now
cursor.execute("UPDATE users SET file_count=?, last_reset=? WHERE
user_id=?", (file_count, last_reset, user_id))
conn.commit()
return file_count
else:
return 0

def increment_file_count(user_id):
"""Increment the file count for the user in the database."""
cursor.execute("UPDATE users SET file_count=file_count+1 WHERE user_id=?",
(user_id,))
conn.commit()

# --- Bot Command Handlers ---


async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
user_id = update.effective_chat.id
# If token is not valid, ask the user to bypass the link shortener.
if not is_token_valid(user_id):
# Simulate link shortener: incorporate an inline button with your monetized
URL.
keyboard = [
[InlineKeyboardButton("Bypass Link Shortener", url="https://your-link-
shortener.com")]
]
reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_text(
"Welcome to FileGrabberBot! To start, please click the button below to
bypass our link shortener. "
"Then, use the /refresh command to obtain your 6-hour access token.",
reply_markup=reply_markup
)
else:
await update.message.reply_text("You already have a valid token. Use /grab
to retrieve your file.")

async def refresh(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:


"""
Refresh (or create) a token for the user.
This token will be valid for 6 hours.
"""
user_id = update.effective_chat.id
new_token, expiration = refresh_token_db(user_id)
expiration_time = time.strftime('%Y-%m-%d %H:%M:%S',
time.localtime(expiration))
await update.message.reply_text(
f"Token refreshed!\nYour new token: `{new_token}`\nExpires at:
{expiration_time}",
parse_mode='Markdown'
)

async def grab(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:


"""
Handle the file grab request. This checks for:
- A valid token.
- That the user has not exceeded 40 file grabs in the last hour.
It then simulates grabbing a file from the channel and sends it with a
20-minute expiry.
"""
user_id = update.effective_chat.id

# Validate the user’s token


if not is_token_valid(user_id):
await update.message.reply_text("Your token has expired. Use /refresh to
get a new token.")
return

# Check the hourly file grab limit for the user


current_file_count = check_and_update_file_limit(user_id)
if current_file_count >= 40:
await update.message.reply_text(
"You've reached your limit of 40 file grabs per hour. Please try again
later."
)
return

# Increment file count for this request


increment_file_count(user_id)

# The file link is simulated here. In your production system, generate the link
dynamically
file_link = "https://t.me/your_channel/12345" # Replace or generate
dynamically

# Send the file link with content protection.


# The protect_content parameter aims to restrict forwarding/saving.
sent_message = await update.message.reply_text(
f"Here is your file:\n{file_link}\n\nNote: This file will expire in 20
minutes.",
protect_content=True
)

# Schedule a job to notify the user after 20 minutes that the file is expired.
context.job_queue.run_once(expire_file, when=20*60, data={
'chat_id': update.effective_chat.id,
'message_id': sent_message.message_id
})

async def expire_file(context: ContextTypes.DEFAULT_TYPE) -> None:


"""
A callback that informs the user the file has expired.
In a full implementation, you might also delete or revoke the file.
"""
job_data = context.job.data
chat_id = job_data['chat_id']
# Inform the user that the file is no longer available.
await context.bot.send_message(chat_id=chat_id, text="The file you received has
now expired and is no longer available.")

# --- Main Entrypoint ---


if __name__ == '__main__':
# Build the application with your Bot Token.
application = Application.builder().token(BOT_TOKEN).build()

# Add command handlers


application.add_handler(CommandHandler("start", start))
application.add_handler(CommandHandler("refresh", refresh))
application.add_handler(CommandHandler("grab", grab))

# Run the bot. (Using polling here – consider webhooks for production.)
application.run_polling()

Step 5. Deploying Your Bot


You can run this script locally with:

bash
python file_grabber_bot.py
For a production environment, consider deploying on a cloud platform (like Heroku,
Render, or AWS) and using webhooks instead of polling.

Message Copilot

You might also like