To create a Telegram userbot that forwards all messages from one Telegram channel to another, we'll use the Telethon library in Python. This library allows you to interact with the Telegram API as a user, enabling you to create userbots that can automate tasks like message forwarding.
Below is a step-by-step guide along with the code to set up the userbot.
Prerequisites
-
Python Installation: Ensure that you have Python 3.6 or higher installed on your system.
-
Telethon Library: We'll use the Telethon library. Install it using pip:
pip install telethon
-
Telegram API Credentials: You'll need your own api_id and api_hash from Telegram:
- Visit my.telegram.org.
- Log in with your Telegram account.
- Go to API Development Tools.
- Create a new application to get your
api_id and api_hash.
Step-by-Step Guide
1. Import Necessary Libraries
from telethon import TelegramClient, events
2. Define Your API Credentials
Replace 'YOUR_API_ID' and 'YOUR_API_HASH' with the credentials you obtained from Telegram.
# Your Telegram API credentials
api_id = YOUR_API_ID # Replace with your api_id (integer)
api_hash = 'YOUR_API_HASH' # Replace with your api_hash (string)
3. Create the Telegram Client
# Create the client and connect
client = TelegramClient('session_name', api_id, api_hash)
'session_name' is the name of the session file that will be created to store your login information.
- This avoids the need to log in every time you run the script.
4. Specify Source and Target Channels
Replace 'source_channel_username_or_id' and 'target_channel_username_or_id' with the respective channel usernames or IDs.
# Replace these with the usernames or IDs of your channels
source_channel = 'source_channel_username_or_id'
target_channel = 'target_channel_username_or_id'
Note:
- If using IDs, make sure to use integers. Channel IDs are usually prefixed with
-100. For example, -1001234567890.
- If using usernames, provide them as strings without the '@' symbol, e.g.,
'examplechannel'.
5. Define the Event Handler to Forward Messages
@client.on(events.NewMessage(chats=source_channel))
async def handler(event):
# Forward the message to the target channel
await client.send_message(target_channel, event.message)
- The
@client.on(events.NewMessage(chats=source_channel)) decorator listens for new messages in the source channel.
- When a new message is detected, the
handler function forwards it to the target channel.
6. Start the Client and Run Until Disconnected
# Start the client
client.start()
print("Userbot is running...")
# Run the client until you disconnect (e.g., press Ctrl+C)
client.run_until_disconnected()
Complete Code
from telethon import TelegramClient, events
# Your Telegram API credentials
api_id = YOUR_API_ID # Replace with your api_id (integer)
api_hash = 'YOUR_API_HASH' # Replace with your api_hash (string)
# Replace these with the usernames or IDs of your channels
source_channel = 'source_channel_username_or_id'
target_channel = 'target_channel_username_or_id'
# Create the client and connect
client = TelegramClient('session_name', api_id, api_hash)
@client.on(events.NewMessage(chats=source_channel))
async def handler(event):
# Forward the message to the target channel
await client.send_message(target_channel, event.message)
# Start the client
client.start()
print("Userbot is running...")
# Run the client until you disconnect (e.g., press Ctrl+C)
client.run_until_disconnected()
Additional Notes
-
Login Prompt: The first time you run this script, you'll be prompted to enter the phone number associated with your Telegram account and then enter the code sent to your Telegram app. This is to authenticate your user session.
-
Session File: A session file named session_name.session will be created in your working directory. Keep this file secure, as it contains your login information.
-
Permissions:
- Source Channel: Your user account must have access to the source channel (you should be a subscriber).
- Target Channel:
- If it's a supergroup or channel where you are an admin, you can post messages directly.
- If it's a private chat or group, ensure that your account has permission to send messages.
-
Private Channels:
- If either the source or target channel is private and doesn't have a username, you'll need to use their IDs.
- You can obtain the IDs by:
- Enabling Telegram's debug mode (in settings) to see IDs in the app.
- Using the script to print out updates and extract IDs.
-
Handling Media and Files: The above script forwards all types of messages, including text, photos, videos, documents, etc.
-
Error Handling: For production use, consider adding try-except blocks to handle potential errors and exceptions.
Running the Script
-
Save the Script: Save the complete code in a file, for example, forwarder.py.
-
Install Dependencies: Ensure Telethon is installed:
pip install telethon
-
Run the Script:
python forwarder.py
-
Authentication: On the first run, enter your phone number and the code sent to your Telegram app when prompted.
Testing
- Send a test message to the source channel.
- Verify that the message appears in the target channel.
Customization
-
Multiple Source Channels: To listen to multiple channels, you can provide a list to the chats parameter:
source_channels = ['channel1', 'channel2', 'channel3']
@client.on(events.NewMessage(chats=source_channels))
async def handler(event):
await client.send_message(target_channel, event.message)
-
Filtering Messages: You can add conditions to filter messages before forwarding:
@client.on(events.NewMessage(chats=source_channel))
async def handler(event):
if 'keyword' in event.raw_text:
await client.send_message(target_channel, event.message)
-
Adding Delay: If you want to add a delay between receiving and forwarding messages:
import asyncio
@client.on(events.NewMessage(chats=source_channel))
async def handler(event):
await asyncio.sleep(5) # Delay for 5 seconds
await client.send_message(target_channel, event.message)
Security Considerations
-
Protect Your API Credentials: Never share your api_id, api_hash, or session file. Treat them like passwords.
-
Avoid Hardcoding Sensitive Data: For better security, consider storing your credentials in environment variables or a separate configuration file that's not checked into version control.
Conclusion
You now have a Telegram userbot that forwards all messages from one channel to another. This script can run continuously on a server or your local machine. Ensure that your user account complies with Telegram's terms of service to avoid any potential issues like account suspension.
Feel free to customize and extend this script to suit your specific needs!