-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtelegram_member_adder.py
More file actions
152 lines (126 loc) · 5.37 KB
/
telegram_member_adder.py
File metadata and controls
152 lines (126 loc) · 5.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
import os
import time
import csv
import getpass
from telethon import TelegramClient
from telethon.tl.functions.channels import InviteToChannelRequest
from telethon.tl.types import InputPeerUser, InputPeerChannel
from telethon.errors import UserPrivacyRestrictedError, FloodWaitError, SessionPasswordNeededError
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# Your Telegram API credentials
API_ID = os.getenv('API_ID')
API_HASH = os.getenv('API_HASH')
PHONE = os.getenv('PHONE') # Your phone number with country code
# Channel username or ID
CHANNEL_USERNAME = os.getenv('CHANNEL_USERNAME')
def read_members_from_csv(csv_file):
"""
Read member information from CSV file
Returns a list of usernames
"""
usernames = []
try:
with open(csv_file, 'r', encoding='utf-8') as file:
# Skip the header row
next(file)
for line in file:
# Split the line by comma and take the username
parts = line.strip().split(',')
if len(parts) >= 2 and parts[1]: # Check if username exists
username = parts[1].strip()
if username: # Make sure username is not empty
usernames.append(username)
except Exception as e:
print(f"Error reading CSV file: {str(e)}")
raise
print(f"Successfully read {len(usernames)} usernames from CSV")
return usernames
async def add_members(client, channel, usernames):
"""
Add members to the specified channel using usernames
"""
added_count = 0
failed_count = 0
privacy_restricted = 0
# Get the channel entity properly
try:
channel_entity = await client.get_entity(channel)
channel_input = InputPeerChannel(channel_entity.id, channel_entity.access_hash)
except Exception as e:
print(f"Error getting channel entity: {str(e)}")
return added_count, failed_count, privacy_restricted
for username in usernames:
try:
# Get user entity by username
try:
user = await client.get_entity(username)
user_input = InputPeerUser(user.id, user.access_hash)
except ValueError:
print(f"Could not find user with username {username}")
failed_count += 1
continue
# Add the user to the channel
await client(InviteToChannelRequest(
channel=channel_input,
users=[user_input]
))
print(f"Successfully added user {username}")
added_count += 1
# Add delay to avoid rate limiting
time.sleep(2)
except UserPrivacyRestrictedError:
print(f"User {username} has privacy settings enabled")
privacy_restricted += 1
time.sleep(2)
except FloodWaitError as e:
print(f"Rate limit hit. Waiting for {e.seconds} seconds...")
time.sleep(e.seconds)
except Exception as e:
print(f"Failed to add user {username}: {str(e)}")
failed_count += 1
time.sleep(5) # Longer delay on failure
return added_count, failed_count, privacy_restricted
async def main():
# Create the client and connect
client = TelegramClient('session_name', API_ID, API_HASH)
try:
print("\nStarting Telegram authentication...")
print("If you have 2FA enabled, you will be asked for your password.")
print("Note: The password field will not show any characters as you type (this is normal for security).")
# Start the client with phone number
await client.start(phone=PHONE)
# Get the channel entity
channel = await client.get_entity(CHANNEL_USERNAME)
# Read usernames from CSV file
usernames = read_members_from_csv('dom_mem.csv')
print(f"\nFound {len(usernames)} usernames to process")
# Add members
added, failed, privacy_restricted = await add_members(client, channel, usernames)
print(f"\nSummary:")
print(f"Successfully added: {added} members")
print(f"Failed to add: {failed} members")
print(f"Privacy restricted: {privacy_restricted} members")
except SessionPasswordNeededError:
print("\n2FA Password required!")
print("Please enter your 2FA password below.")
print("Note: The password field will not show any characters as you type.")
password = getpass.getpass("Enter your 2FA password: ")
await client.sign_in(password=password)
# Continue with the rest of the process
channel = await client.get_entity(CHANNEL_USERNAME)
usernames = read_members_from_csv('dom_mem.csv')
print(f"\nFound {len(usernames)} usernames to process")
added, failed, privacy_restricted = await add_members(client, channel, usernames)
print(f"\nSummary:")
print(f"Successfully added: {added} members")
print(f"Failed to add: {failed} members")
print(f"Privacy restricted: {privacy_restricted} members")
except Exception as e:
print(f"An error occurred: {str(e)}")
finally:
await client.disconnect()
if __name__ == '__main__':
import asyncio
asyncio.run(main())