Update bot.py
Browse files
bot.py
CHANGED
|
@@ -2,139 +2,107 @@ import asyncio
|
|
| 2 |
import os
|
| 3 |
import logging
|
| 4 |
import random
|
| 5 |
-
|
|
|
|
|
|
|
|
|
|
| 6 |
from telethon.sessions import StringSession
|
| 7 |
from telethon.tl.functions.channels import InviteToChannelRequest
|
| 8 |
from telethon.tl.types import InputPeerUser, UserStatusRecently, UserStatusOnline
|
| 9 |
from telethon.errors import (
|
| 10 |
-
FloodWaitError,
|
| 11 |
-
|
| 12 |
-
ChatAdminRequiredError,
|
| 13 |
-
UserNotMutualContactError,
|
| 14 |
-
UserChannelsTooMuchError,
|
| 15 |
-
PeerFloodError
|
| 16 |
)
|
| 17 |
|
| 18 |
-
# إ
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 20 |
logger = logging.getLogger(__name__)
|
| 21 |
|
| 22 |
-
# المتغيرات
|
| 23 |
API_ID = int(os.getenv("API_ID", "0"))
|
| 24 |
API_HASH = os.getenv("API_HASH", "")
|
| 25 |
SESSION_STRING = os.getenv("SESSION_STRING") or os.getenv("STRING_SESSION") or ""
|
| 26 |
SOURCE_CHANNEL = os.getenv("SOURCE_CHANNEL", "")
|
| 27 |
TARGET_CHANNEL = os.getenv("TARGET_CHANNEL", "")
|
|
|
|
| 28 |
LIMIT = int(os.getenv("LIMIT", "50"))
|
| 29 |
-
BASE_DELAY = int(os.getenv("DELAY_SECONDS", "300"))
|
| 30 |
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
sys.exit()
|
| 34 |
|
| 35 |
-
|
| 36 |
-
try:
|
| 37 |
client = TelegramClient(StringSession(SESSION_STRING.strip()), API_ID, API_HASH)
|
| 38 |
-
except Exception as e:
|
| 39 |
-
logger.error(f"🚨 خطأ فادح في إنشاء الجلسة: {e}")
|
| 40 |
-
sys.exit()
|
| 41 |
-
|
| 42 |
-
def load_added_users():
|
| 43 |
-
if os.path.exists('added_users.txt'):
|
| 44 |
-
try:
|
| 45 |
-
with open('added_users.txt', 'r') as f:
|
| 46 |
-
return set(line.strip() for line in f)
|
| 47 |
-
except:
|
| 48 |
-
return set()
|
| 49 |
-
return set()
|
| 50 |
-
|
| 51 |
-
def save_added_user(user_id):
|
| 52 |
try:
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
|
| 58 |
-
async def main():
|
| 59 |
-
logger.info("✅ جاري الاتصال بتيليجرام...")
|
| 60 |
-
added_users_memory = load_added_users()
|
| 61 |
-
logger.info(f"📂 يوجد {len(added_users_memory)} عضو في السجل (سيتم تخطيهم)")
|
| 62 |
-
|
| 63 |
-
try:
|
| 64 |
source = await client.get_entity(SOURCE_CHANNEL)
|
| 65 |
target = await client.get_entity(TARGET_CHANNEL)
|
| 66 |
-
except Exception as e:
|
| 67 |
-
logger.error(f"❌ خطأ في الوصول للقنوات: {e}")
|
| 68 |
-
return
|
| 69 |
-
|
| 70 |
-
try:
|
| 71 |
-
members = await client.get_participants(source, limit=LIMIT * 3)
|
| 72 |
-
except Exception as e:
|
| 73 |
-
logger.error(f"❌ خطأ في جلب الأعضاء: {e}")
|
| 74 |
-
return
|
| 75 |
-
|
| 76 |
-
success, failed = 0, 0
|
| 77 |
-
actual_processed = 0
|
| 78 |
-
|
| 79 |
-
random.shuffle(members)
|
| 80 |
-
|
| 81 |
-
for member in members:
|
| 82 |
-
if actual_processed >= LIMIT:
|
| 83 |
-
break
|
| 84 |
-
|
| 85 |
-
str_id = str(member.id)
|
| 86 |
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
is_active = isinstance(member.status, (UserStatusOnline, UserStatusRecently))
|
| 91 |
-
if not is_active:
|
| 92 |
-
continue
|
| 93 |
-
|
| 94 |
-
actual_processed += 1
|
| 95 |
-
name = member.first_name or "مستخدم"
|
| 96 |
-
logger.info(f"[{actual_processed}/{LIMIT}] 📩 محاولة إضافة: {name}")
|
| 97 |
|
| 98 |
-
|
| 99 |
-
|
| 100 |
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
|
|
|
|
|
|
| 104 |
|
| 105 |
-
|
| 106 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
logger.error("🚨 تم حظرك مؤقتاً من الإضافة! توقف العمل.")
|
| 117 |
-
break
|
| 118 |
-
except UserPrivacyRestrictedError:
|
| 119 |
-
failed += 1
|
| 120 |
-
logger.info("🔒 خصوصية مقيدة للمستخدم")
|
| 121 |
-
except UserChannelsTooMuchError:
|
| 122 |
-
failed += 1
|
| 123 |
-
logger.info("📛 المستخدم في قنوات كثيرة")
|
| 124 |
-
except Exception as e:
|
| 125 |
-
failed += 1
|
| 126 |
-
logger.info(f"❌ خطأ بسيط: {type(e).__name__}")
|
| 127 |
|
| 128 |
-
|
| 129 |
-
logger.info(f"✅ انتهى! (نجاح: {success} | فشل/خصوصية: {failed})")
|
| 130 |
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
await main()
|
| 134 |
|
| 135 |
if __name__ == "__main__":
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
|
|
|
| 2 |
import os
|
| 3 |
import logging
|
| 4 |
import random
|
| 5 |
+
import sys
|
| 6 |
+
from threading import Thread
|
| 7 |
+
from http.server import HTTPServer, SimpleHTTPRequestHandler
|
| 8 |
+
from telethon import TelegramClient, functions
|
| 9 |
from telethon.sessions import StringSession
|
| 10 |
from telethon.tl.functions.channels import InviteToChannelRequest
|
| 11 |
from telethon.tl.types import InputPeerUser, UserStatusRecently, UserStatusOnline
|
| 12 |
from telethon.errors import (
|
| 13 |
+
FloodWaitError, UserPrivacyRestrictedError, PeerFloodError,
|
| 14 |
+
UserChannelsTooMuchError, UserAlreadyParticipantError
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
)
|
| 16 |
|
| 17 |
+
# --- الجسر لإبقاء البوت حياً ---
|
| 18 |
+
class HealthHandler(SimpleHTTPRequestHandler):
|
| 19 |
+
def do_GET(self):
|
| 20 |
+
self.send_response(200)
|
| 21 |
+
self.send_header("Content-type", "text/html; charset=utf-8")
|
| 22 |
+
self.end_headers()
|
| 23 |
+
self.wfile.write("<h1>✅ البوت شغال: نقل + دعوات خاصة</h1>".encode("utf-8"))
|
| 24 |
+
def log_message(self, format, *args): pass
|
| 25 |
+
|
| 26 |
+
Thread(target=lambda: HTTPServer(("0.0.0.0", 7860), HealthHandler).serve_forever(), daemon=True).start()
|
| 27 |
+
|
| 28 |
+
# --- إعداد اللوق ---
|
| 29 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 30 |
logger = logging.getLogger(__name__)
|
| 31 |
|
| 32 |
+
# --- المتغيرات ---
|
| 33 |
API_ID = int(os.getenv("API_ID", "0"))
|
| 34 |
API_HASH = os.getenv("API_HASH", "")
|
| 35 |
SESSION_STRING = os.getenv("SESSION_STRING") or os.getenv("STRING_SESSION") or ""
|
| 36 |
SOURCE_CHANNEL = os.getenv("SOURCE_CHANNEL", "")
|
| 37 |
TARGET_CHANNEL = os.getenv("TARGET_CHANNEL", "")
|
| 38 |
+
INVITE_LINK = os.getenv("INVITE_LINK", f"https://t.me/{TARGET_CHANNEL}") # رابط الدعوة
|
| 39 |
LIMIT = int(os.getenv("LIMIT", "50"))
|
| 40 |
+
BASE_DELAY = int(os.getenv("DELAY_SECONDS", "300"))
|
| 41 |
|
| 42 |
+
# رسالة الدعوة التي ستصل للأعضاء
|
| 43 |
+
MESSAGE_TEXT = f"مرحباً بك! 👋\nلقد تمت دعوتك للانضمام إلى مجموعتنا المميزة. يشرفنا انضمامك عبر الرابط التالي:\n\n{INVITE_LINK}"
|
|
|
|
| 44 |
|
| 45 |
+
async def main():
|
|
|
|
| 46 |
client = TelegramClient(StringSession(SESSION_STRING.strip()), API_ID, API_HASH)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
try:
|
| 48 |
+
await client.connect()
|
| 49 |
+
if not await client.is_user_authorized():
|
| 50 |
+
logger.error("❌ الجلسة غير صالحة!")
|
| 51 |
+
return
|
| 52 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
source = await client.get_entity(SOURCE_CHANNEL)
|
| 54 |
target = await client.get_entity(TARGET_CHANNEL)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
+
participants = await client.get_participants(source, limit=LIMIT * 2)
|
| 57 |
+
random.shuffle(participants)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
|
| 59 |
+
success_add = 0
|
| 60 |
+
success_msg = 0
|
| 61 |
|
| 62 |
+
for member in participants:
|
| 63 |
+
if (success_add + success_msg) >= LIMIT: break
|
| 64 |
+
if member.bot or member.deleted: continue
|
| 65 |
+
|
| 66 |
+
name = member.first_name or "مستخدم"
|
| 67 |
|
| 68 |
+
try:
|
| 69 |
+
# 1. محاولة الإضافة المباشرة أولاً
|
| 70 |
+
logger.info(f"📩 محاولة إضافة: {name}...")
|
| 71 |
+
await client(InviteToChannelRequest(target, [InputPeerUser(member.id, member.access_hash or 0)]))
|
| 72 |
+
success_add += 1
|
| 73 |
+
logger.info(f"✅ تمت إضافة {name} مباشرة!")
|
| 74 |
+
|
| 75 |
+
except (UserPrivacyRestrictedError, PeerFloodError, UserChannelsTooMuchError):
|
| 76 |
+
# 2. إذا فشلت الإضافة، نرسل رسالة خاصة (الدعوة)
|
| 77 |
+
try:
|
| 78 |
+
logger.info(f"✉️ الإضافة مقيدة. إرسال دعوة خاصة لـ {name}...")
|
| 79 |
+
await client.send_message(member.id, MESSAGE_TEXT)
|
| 80 |
+
success_msg += 1
|
| 81 |
+
logger.info(f"✅ تم إرسال الدعوة بنجاح لـ {name}")
|
| 82 |
+
except Exception as e:
|
| 83 |
+
logger.info(f"❌ فشل إرسال الرسالة أيضاً: {type(e).__name__}")
|
| 84 |
|
| 85 |
+
except UserAlreadyParticipantError:
|
| 86 |
+
continue
|
| 87 |
+
except FloodWaitError as e:
|
| 88 |
+
logger.warning(f"⏳ فلود! انتظار {e.seconds} ثانية.")
|
| 89 |
+
await asyncio.sleep(e.seconds + 5)
|
| 90 |
+
except Exception as e:
|
| 91 |
+
logger.info(f"❌ خطأ غير متوقع مع {name}: {type(e).__name__}")
|
| 92 |
|
| 93 |
+
# انتظار بين العمليات
|
| 94 |
+
wait = BASE_DELAY + random.randint(10, 30)
|
| 95 |
+
logger.info(f"⏳ انتظار {wait} ثانية...")
|
| 96 |
+
await asyncio.sleep(wait)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
|
| 98 |
+
logger.info(f"🏁 انتهى: مضافين ({success_add}) | مرسل لهم دعوات ({success_msg})")
|
|
|
|
| 99 |
|
| 100 |
+
finally:
|
| 101 |
+
await client.disconnect()
|
|
|
|
| 102 |
|
| 103 |
if __name__ == "__main__":
|
| 104 |
+
while True:
|
| 105 |
+
asyncio.run(main())
|
| 106 |
+
logger.info("💤 استراحة 15 دقيقة...")
|
| 107 |
+
import time
|
| 108 |
+
time.sleep(900)
|