Ultimate Guide: Multi-Account Telegram Automation Bot with Python Code
In this comprehensive guide, we'll explore how to create an advanced Telegram automation system using Python's Telethon library. Whether you're looking to manage community growth, automate marketing tasks, or conduct research through group monitoring, this multi-functional bot handles various Telegram automation tasks while operating through multiple accounts simultaneously.
Why Build a Multi-Session Telegram Bot?
Telegram automation using multiple accounts offers several advantages:
- Distribute tasks across accounts to avoid rate limits
- Scale your Telegram marketing efforts safely
- Manage large community migrations efficiently
- Conduct mass messaging without triggering spam filters
- Automate group participation across multiple niches
Core Features Breakdown
1. Group Member Crawling
Our script can extract member data from any Telegram group or channel, collecting:
- User IDs (essential for direct messaging)
- Usernames (for @ mentions and tracking)
- Profile names (for personalization)
- Account creation dates (for filtering new accounts)
2. Smart Member Migration
The automated transfer system features:
- Progressive delay algorithm to mimic human behavior
- Automatic flood wait detection and handling
- Multi-account distribution for large migrations
- CSV-based member tracking and reporting
3. Mass Messaging System
Our bulk messenger includes:
- Username or ID-based targeting
- Dynamic message templating
- Parallel message distribution across accounts
- Intelligent throttling to maintain account safety
Prerequisites
- Python 3.8+ installed
- Telegram API credentials (api_id and api_hash)
- Multiple Telegram accounts (recommended)
Installation
pip install telethon pandas
Configuration
Create config.ini
:
[API] api_id = your_api_id api_hash = your_api_hash [Sessions] session_files = session1,session2,session3
Full Code
import asyncio
from telethon import TelegramClient
from telethon.errors import FloodWaitError
import pandas as pd
import configparser
from typing import List
class TelegramAutomation:
def __init__(self):
config = configparser.ConfigParser()
config.read('config.ini')
self.api_id = config['API']['api_id']
self.api_hash = config['API']['api_hash']
self.session_files = config['Sessions']['session_files'].split(',')
self.clients = []
for session in self.session_files:
client = TelegramClient(session, self.api_id, self.api_hash)
self.clients.append(client)
async def crawl_members(self, group_link: str, output_file: str):
"""Crawl members from a group"""
async with self.clients[0] as client:
group = await client.get_entity(group_link)
members = await client.get_participants(group)
user_data = []
for member in members:
user_data.append({
'id': member.id,
'username': member.username,
'first_name': member.first_name,
'last_name': member.last_name
})
df = pd.DataFrame(user_data)
df.to_csv(output_file, index=False)
print(f"Saved {len(user_data)} members to {output_file}")
async def add_members(self, source_file: str, target_group: str):
"""Add members to a group"""
df = pd.read_csv(source_file)
target_entity = await self.clients[0].get_entity(target_group)
for index, client in enumerate(self.clients):
try:
async with client:
for _, row in df.iterrows():
try:
user = await client.get_entity(int(row['id']))
await client(AddChatUserRequest(
target_entity,
user_id=user,
fwd_limit=0
))
print(f"Client {index}: Added {row['id']}")
await asyncio.sleep(60) # Avoid flood
except FloodWaitError as e:
print(f"Flood wait: {e.seconds}")
await asyncio.sleep(e.seconds)
except Exception as e:
print(f"Error in client {index}: {str(e)}")
async def mass_message(self, users_file: str, message: str):
"""Send messages to multiple users"""
df = pd.read_csv(users_file)
for index, client in enumerate(self.clients):
try:
async with client:
for _, row in df.iterrows():
try:
user = await client.get_entity(int(row['id']))
await client.send_message(user, message)
print(f"Client {index}: Message sent to {row['id']}")
await asyncio.sleep(30)
except FloodWaitError as e:
print(f"Flood wait: {e.seconds}")
await asyncio.sleep(e.seconds)
except Exception as e:
print(f"Error in client {index}: {str(e)}")
async def join_groups(self, group_links: List[str]):
"""Join multiple groups"""
for index, client in enumerate(self.clients):
try:
async with client:
for link in group_links:
try:
group = await client.get_entity(link)
await client(JoinChannelRequest(group))
print(f"Client {index}: Joined {link}")
await asyncio.sleep(60)
except FloodWaitError as e:
print(f"Flood wait: {e.seconds}")
await asyncio.sleep(e.seconds)
except Exception as e:
print(f"Error in client {index}: {str(e)}")
if __name__ == "__main__":
bot = TelegramAutomation()
# Example usage
async def main():
await bot.crawl_members("target_group", "members.csv")
await bot.add_members("members.csv", "destination_group")
await bot.mass_message("users.csv", "Hello from our service!")
await bot.join_groups(["group_link1", "group_link2"])
asyncio.run(main())
Usage Tutorial
- Create multiple Telegram accounts
- Obtain API credentials from my.telegram.org
- Configure
config.ini
with your credentials - Run each session file once to authenticate:
python -c "from telethon.sync import TelegramClient; TelegramClient('session1').start()"
- Modify the main() function according to your needs
- Run the script:
python bot.py
Important Notes
- Respect Telegram's terms of service
- Avoid aggressive automation to prevent account bans
- Use delays between actions
- Consider using proxies for multiple accounts
Conclusion
This script provides powerful Telegram automation capabilities using multiple accounts simultaneously. Always use responsibly and consider ethical implications when automating social media interactions.
0 Comments
Leave a Comment