File size: 23,354 Bytes
02208da 4022ba6 945bdfa 26f69f0 02208da ecf9cee 4022ba6 945bdfa 4022ba6 408a96e 02208da 06f97fe 4022ba6 98aa906 02208da 3447c31 02208da 408a96e 02208da 4022ba6 02208da 945bdfa 4022ba6 945bdfa 4022ba6 02208da 6f4ab5b 4022ba6 26f69f0 4022ba6 26f69f0 4022ba6 26f69f0 4022ba6 26f69f0 4022ba6 26f69f0 4022ba6 26f69f0 4022ba6 26f69f0 4022ba6 26f69f0 4022ba6 950aea9 26f69f0 4022ba6 26f69f0 4022ba6 26f69f0 4022ba6 26f69f0 4022ba6 26f69f0 6f4ab5b 26f69f0 f85f929 945bdfa f85f929 945bdfa f85f929 945bdfa 408a96e 945bdfa d0f5094 945bdfa f85f929 408a96e f85f929 945bdfa f85f929 945bdfa f85f929 945bdfa 408a96e 945bdfa 408a96e f85f929 408a96e 945bdfa bce442a 408a96e 945bdfa 408a96e bce442a 07b817c 945bdfa 408a96e 945bdfa 408a96e 945bdfa 408a96e bce442a 408a96e 945bdfa 6f4ab5b 02208da f85f929 02208da f85f929 02208da f85f929 02208da f85f929 02208da f85f929 137bc9e f85f929 02208da f85f929 02208da f85f929 137bc9e 02208da f85f929 02208da 6f4ab5b 26f69f0 6f4ab5b 2d1549e 6f4ab5b |
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 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 |
import csv
import asyncio
import time
from telethon import TelegramClient
from tqdm import tqdm # Import tqdm for progress bar
from telethon.tl.functions.channels import JoinChannelRequest
from telethon.tl.functions.messages import ImportChatInviteRequest
from telethon.errors.rpcerrorlist import InviteHashExpiredError
from flask import Flask, jsonify, send_from_directory
# Directory for storing files
from flask import Flask, render_template, send_from_directory
from telethon.tl.functions.channels import GetParticipantsRequest
from telethon.tl.types import ChannelParticipantsSearch
from telethon.errors import FloodWaitError, UserAdminInvalidError
import json
import asyncio
import nest_asyncio
import logging
from telethon import TelegramClient, events
from supabase import create_client, Client
from flask import Flask, jsonify
from threading import Thread
from multiprocessing import Process, Queue
import unicodedata
from telegram.helpers import escape_markdown
import re
import os
from telethon.tl.functions.channels import JoinChannelRequest, InviteToChannelRequest
from telethon.tl.functions.channels import EditBannedRequest
from telethon.tl.types import ChatBannedRights
from telethon.errors.rpcerrorlist import UserAdminInvalidError, UserNotParticipantError
from telethon.errors.rpcerrorlist import InviteHashExpiredError, UserAlreadyParticipantError
from telethon.tl.types import Channel, Chat
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s",
handlers=[
logging.FileHandler("join_groups.log"), # Log to a file
logging.StreamHandler() # Log to console
]
)
# Replace with your API credentials (from https://my.telegram.org/apps)
API_ID = 25216912 # Your API ID
API_HASH = "f65f6050fe9b342a4996c59e4283ab5e"
PHONE_NUMBER = "+967735201519" # Your phone number with country code
OUTPUT_CSV = "groups_with_status.csv"
# Path to your CSV file
CSV_FILENAME = "8.csv"
session_dir = "mfoud73"
FILE_DIRECTORY = os.getcwd() # Current working directory
SLEEP_TIME = 280
# Flask App
app = Flask(__name__)
# πΉ Flask API Endpoints
@app.route('/')
def index():
"""Show available files for download as an HTML page."""
files = os.listdir(FILE_DIRECTORY)
return render_template("index.html", files=files)
@app.route('/download/<filename>')
def download_file(filename):
"""Allow downloading any file from the directory."""
return send_from_directory(FILE_DIRECTORY, filename, as_attachment=True)
def run_flask():
app.run(host='0.0.0.0', port=7860)
USER_CSV = "user_list.csv"
# SLEEP_TIME = 280 # Delay between adding users
# Logging setup
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
BATCH_SIZE = 30 # Fetch 200 users at a time (Telegram's limit)
MAX_USERS = 200 # Set your desired limit here
async def fetch_users_from_source_group(source_group, max_users=MAX_USERS):
"""
Fetch up to `max_users` from a Telegram group using pagination and save them to a CSV file.
:param source_group: The source group username or ID.
:param max_users: The maximum number of users to fetch. Use `None` to fetch all users.
"""
async with TelegramClient(session_dir, API_ID, API_HASH) as client:
await client.start(PHONE_NUMBER)
try:
entity = await client.get_entity(source_group)
offset = 0 # Pagination start
total_users = 0
csv_filename = f"{source_group}.csv" # Save with group name
with open(csv_filename, mode="a", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
writer.writerow(["user_id", "username", "first_name", "last_name"]) # CSV headers
with tqdm(desc=f"Fetching users from {source_group}", unit="user", ncols=100) as pbar:
while max_users is None or total_users < max_users:
remaining_users = max_users - total_users if max_users else BATCH_SIZE
batch_size = min(BATCH_SIZE, remaining_users) # Adjust batch size if close to max
try:
participants = await client(GetParticipantsRequest(
entity, ChannelParticipantsSearch(''), offset, batch_size, hash=0
))
if not participants.users:
break # Stop when no more users are found
for user in participants.users:
writer.writerow([user.id, user.username or "N/A", user.first_name or "N/A", user.last_name or "N/A"])
pbar.update(1) # Update progress bar
pbar.set_postfix(user=user.username or "N/A") # Show last processed user
total_users += len(participants.users)
offset += len(participants.users) # Move offset forward
except FloodWaitError as e:
pbar.set_postfix(waiting=f"{e.seconds}s") # Show cooldown time
await asyncio.sleep(e.seconds) # Wait for Telegram cooldown
pbar.set_description(f"β
Done! Fetched {total_users} users")
except Exception as e:
print(f"β Failed to fetch users from {source_group}: {e}")
async def fetch_users_from_source_group1(source_group, max_users=MAX_USERS):
"""
Fetch up to `max_users` from a Telegram group using pagination and save them to a CSV file.
:param source_group: The source group username or ID.
:param max_users: The maximum number of users to fetch. Use `None` to fetch all users.
"""
logging.info(f"Fetching users from {source_group} (Limit: {max_users if max_users else 'All'})...")
async with TelegramClient(session_dir, API_ID, API_HASH) as client:
await client.start(PHONE_NUMBER)
try:
entity = await client.get_entity(source_group)
offset = 0 # Pagination start
total_users = 0
csv_filename = f"{source_group}.csv" # Save with group name
with open(csv_filename, mode="w", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
writer.writerow(["user_id", "username", "first_name", "last_name"]) # CSV headers
while max_users is None or total_users < max_users:
remaining_users = max_users - total_users if max_users else BATCH_SIZE
batch_size = min(BATCH_SIZE, remaining_users) # Adjust batch size if close to max
try:
participants = await client(GetParticipantsRequest(
entity, ChannelParticipantsSearch(''), offset, batch_size, hash=0
))
if not participants.users:
break # Stop when no more users are found
for user in participants.users:
writer.writerow([user.id, user.username or "N/A", user.first_name or "N/A", user.last_name or "N/A"])
logging.info(f"β User saved: {user.id} | {user.username}")
total_users += len(participants.users)
offset += len(participants.users) # Move offset forward
except FloodWaitError as e:
logging.warning(f"β οΈ Telegram rate limit hit! Waiting {e.seconds} seconds...")
await asyncio.sleep(e.seconds) # Wait for Telegram cooldown
await asyncio.sleep(SLEEP_TIME) # Avoid hitting limits
logging.info(f"β
Fetched {total_users} users from {source_group}. Saved to {csv_filename}.")
except Exception as e:
logging.error(f"β Failed to fetch users from {source_group}: {e}")
async def fetch_users_from_source_group1(source_group, max_users=MAX_USERS):
"""
Fetch up to `max_users` from a Telegram group using client.iter_participants() and save them to a CSV file.
:param source_group: The source group username or ID.
:param max_users: The maximum number of users to fetch.
"""
logging.info(f"Fetching up to {max_users} users from {source_group}...")
async with TelegramClient(session_dir, API_ID, API_HASH) as client:
await client.start(PHONE_NUMBER)
try:
entity = await client.get_entity(source_group)
count = 0 # Counter for fetched users
with open(USER_CSV, mode="w", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
writer.writerow(["user_id", "username", "first_name", "last_name"]) # CSV headers
async for user in client.iter_participants(entity, limit=None, aggressive=True):
if count >= max_users:
break # Stop when max_users limit is reached
writer.writerow([user.id, user.username or "N/A", user.first_name or "N/A", user.last_name or "N/A"])
logging.info(f"β User saved: {user.id} | {user.username}")
count += 1 # Increase user count
await asyncio.sleep(1) # Delay to prevent rate limits
logging.info(f"β
Fetched {count}/{max_users} users from {source_group}. Saved to {USER_CSV}.")
except Exception as e:
logging.error(f"β Failed to fetch users from {source_group}: {e}")
async def add_users_to_destination_group(destination_group, csvfile):
"""
Reads users from the CSV file and adds them to the destination group while handling rate limits.
Before adding, it fetches current members of the destination group and filters out any users already present.
:param destination_group: The destination group username or ID.
:param csvfile: The CSV file containing the list of user IDs.
"""
logging.info(f"Adding users to {destination_group} from {csvfile}...")
async with TelegramClient(session_dir, API_ID, API_HASH) as client:
await client.start(PHONE_NUMBER)
try:
# Get the destination group entity
dest_entity = await client.get_entity(destination_group)
# Fetch existing members in the destination group
existing_user_ids = set()
async for user in client.iter_participants(dest_entity, limit=None):
existing_user_ids.add(user.id)
logging.info(f"Fetched {len(existing_user_ids)} existing users from {destination_group}.")
# Read users from CSV file and filter out those already in the destination group
users = []
with open(csvfile, mode="r", encoding="utf-8") as file:
reader = csv.reader(file)
# Skip header row
header = next(reader, None)
for row in reader:
# Check if the first cell is a valid integer (skip row if not)
try:
user_id = int(row[0].strip())
except ValueError:
logging.debug(f"Skipping row with non-numeric user_id: {row}")
continue
if user_id not in existing_user_ids:
users.append(user_id)
logging.info(f"Filtered CSV: {len(users)} users to add after removing existing members.")
count = 0
for index, user_id in enumerate(users, start=1):
try:
logging.info(f"[{index}/{len(users)}] Adding user {user_id} to {destination_group}...")
await client(InviteToChannelRequest(dest_entity, [user_id]))
logging.info(f"β
Successfully added user {user_id}.")
count += 1
if count % BATCH_SIZE == 0: # Pause after each batch to avoid rate limits
logging.info(f"β³ Waiting {SLEEP_TIME} seconds to avoid rate limits...")
await asyncio.sleep(SLEEP_TIME)
except FloodWaitError as e:
logging.warning(f"β οΈ FloodWait: Waiting {e.seconds} seconds...")
await asyncio.sleep(e.seconds)
except UserAdminInvalidError:
logging.error(f"β Cannot add {user_id}: Bot lacks admin rights.")
except Exception as e:
logging.error(f"β Failed to add {user_id}: {e}")
logging.info(f"β
Process completed: Added {count} new users to {destination_group}.")
except Exception as e:
logging.error(f"β Failed to add users to {destination_group}: {e}")
async def get_user_groups(client):
"""Fetch all groups/channels the user is already a member of using get_dialogs."""
joined_groups = set()
dialogs = await client.get_dialogs()
# Filter only groups and channels
groups = [d for d in dialogs if d.is_group or d.is_channel]
for group in groups:
username = f"https://t.me/{group.entity.username}" if hasattr(group.entity, "username") and group.entity.username else "private_group" # Get the group/channel ID
joined_groups.add(username)
logging.info(f"Joined group/channel: {group.entity.title} (ID: {username})")
return joined_groups
async def join_groups():
async with TelegramClient(session_dir, API_ID, API_HASH) as client:
await client.start(PHONE_NUMBER)
me = await client.get_me()
logging.info(f"Logged in as {me.first_name} (ID: {me.id})")
# Fetch all groups/channels the user is already a member of
user_groups = await get_user_groups(client)
logging.info(f"β
Retrieved {len(user_groups)} joined groups/channels.")
logging.info(f"β
Retrieved {user_groups} joined groups/channels.")
# Read the CSV file containing group information
with open(CSV_FILENAME, mode="r", newline="", encoding="utf-8") as file:
reader = csv.reader(file)
header = next(reader) # Skip header row
groups = [row for row in reader]
# Filter out groups the user is already a member of 1183631472
filtered_groups = []
for row in groups:
phone_number, group_name, username, group_id = row
if username and username in user_groups:
logging.info(f"β‘ Already a member: {group_name} ({username}) - Skipping")
else:
filtered_groups.append(row)
# Prepare output CSV file
with open(OUTPUT_CSV, mode="a", newline="", encoding="utf-8") as output_file:
writer = csv.writer(output_file)
writer.writerow(header + ["status"]) # Add "status" column
for index, row in enumerate(filtered_groups, start=2):
phone_number, group_name, username, group_id = row
status = ""
try:
if username != "private_group":
# Join a public group/channel
await client(JoinChannelRequest(username))
status = "Joined (public)"
logging.info(f"[{index}/{len(filtered_groups)}] β
Joined public group: {group_name} ({username})")
# Sleep only after a successful join
# time.sleep(SLEEP_TIME)
else:
# Join a private group using its invite hash (group_id)
await client(ImportChatInviteRequest(group_id))
status = "Joined (private)"
logging.info(f"[{index}/{len(filtered_groups)}] β
Joined private group: {group_name}")
# Sleep only after a successful join
# time.sleep(SLEEP_TIME)
except FloodWaitError as e:
logging.warning(f"β οΈ FloodWait: Waiting {e.seconds} seconds...")
await asyncio.sleep(e.seconds)
except UserAlreadyParticipantError:
status = "Already a member"
logging.info(f"[{index}/{len(filtered_groups)}] β‘ Already a member: {group_name} ({username})")
except InviteHashExpiredError:
status = "Failed (private) - Invite link expired"
logging.error(f"[{index}/{len(filtered_groups)}] β Failed to join private group: {group_name} - Invite link expired")
except Exception as e:
status = f"Failed - {e}"
logging.error(f"[{index}/{len(filtered_groups)}] β Failed to join {group_name}: {e}")
writer.writerow(row + [status])
time.sleep(SLEEP_TIME)
logging.info(f"β
Process completed. Results saved to {OUTPUT_CSV}")
# async def join_groups():
# async with TelegramClient(session_dir, API_ID, API_HASH) as client:
# await client.start(PHONE_NUMBER)
# me = await client.get_me()
# user_id = me.id
# logging.info(f"Logged in as {me.first_name} (ID: {user_id})")
# # Read the CSV file containing group information
# with open(CSV_FILENAME, mode="r", newline="", encoding="utf-8") as file:
# reader = csv.reader(file)
# header = next(reader) # Skip header row
# groups = [row for row in reader]
# # Prepare output CSV file
# with open(OUTPUT_CSV, mode="a", newline="", encoding="utf-8") as output_file:
# writer = csv.writer(output_file)
# writer.writerow(header + ["status"]) # Add "status" column
# for index, row in enumerate(groups, start=1):
# phone_number, group_name, username, group_id = row
# status = ""
# try:
# if username != "private_group":
# # Join a public group/channel
# entity = await client.get_entity(username)
# participants = await client.get_participants(entity)
# if not any(p.id == user_id for p in participants):
# await client(JoinChannelRequest(username))
# status = "Joined (public)"
# logging.info(f"[{index}/{len(groups)}] β
Joined public group: {group_name} ({username})")
# # Sleep only after a successful join
# time.sleep(SLEEP_TIME)
# else:
# status = "Already a member"
# logging.info(f"[{index}/{len(groups)}] β‘ Already a member: {group_name} ({username})")
# else:
# # Join a private group using its invite hash (group_id)
# await client(ImportChatInviteRequest(group_id))
# status = "Joined (private)"
# logging.info(f"[{index}/{len(groups)}] β
Joined private group: {group_name}")
# # Sleep only after a successful join
# time.sleep(SLEEP_TIME)
# except InviteHashExpiredError:
# status = "Failed (private) - Invite link expired"
# logging.error(f"[{index}/{len(groups)}] β Failed to join private group: {group_name} - Invite link expired")
# except Exception as e:
# status = f"Failed - {e}"
# logging.error(f"[{index}/{len(groups)}] β Failed to join {group_name}: {e}")
# writer.writerow(row + [status])
# logging.info(f"β
Process completed. Results saved to {OUTPUT_CSV}")
# Async function to join groups
# async def join_groups_tqdm():
# async with TelegramClient(session_dir, API_ID, API_HASH) as client:
# await client.start(PHONE_NUMBER)
# me = await client.get_me()
# user_id = me.id
# # Read the CSV file containing group information
# with open(CSV_FILENAME, mode="r", newline="", encoding="utf-8") as file:
# reader = csv.reader(file)
# header = next(reader) # Skip header row
# groups = [row for row in reader]
# # Prepare output CSV file
# with open(OUTPUT_CSV, mode="w", newline="", encoding="utf-8") as output_file:
# writer = csv.writer(output_file)
# writer.writerow(header + ["status"]) # Add "status" column
# for row in tqdm(groups, desc="Joining groups", unit="group"):
# phone_number, group_name, username, group_id = row
# status = ""
# try:
# if username != "private_group":
# # Join a public group/channel
# entity = await client.get_entity(username)
# participants = await client.get_participants(entity)
# if not any(p.id == user_id for p in participants):
# await client(JoinChannelRequest(username))
# status = "Joined (public)"
# print(f"β
Joined public group: {group_name} ({username})")
# time.sleep(SLEEP_TIME)
# else:
# status = "Already a member"
# print(f"β‘ Already a member: {group_name} ({username})")
# else:
# # Join a private group using its invite hash (group_id)
# await client(ImportChatInviteRequest(group_id))
# status = "Joined (private)"
# print(f"β
Joined private group: {group_name}")
# time.sleep(SLEEP_TIME)
# except InviteHashExpiredError:
# status = "Failed (private) - Invite link expired"
# print(f"β Failed to join private group: {group_name} - Invite link expired")
# except Exception as e:
# status = f"Failed - {e}"
# print(f"β Failed to join {group_name}: {e}")
# writer.writerow(row + [status])
# print(f"\nβ
Process completed. Results saved to {OUTPUT_CSV}")
def run_telegram():
asyncio.run(join_groups())
def run_telegram_mov():
asyncio.run(fetch_users_from_source_group("UT_CHEM", None))
def run_telegram_mov2():
asyncio.run(add_users_to_destination_group("@searchai090", 'UT_CHEM.csv'))
if __name__ == "__main__":
p1 = Process(target=run_flask)
p2 = Process(target=run_telegram)
# p2 = Process(target=run_telegram_mov2)
p1.start()
p2.start()
p1.join()
p2.join()
|