Reooiq commited on
Commit
e00b530
·
verified ·
1 Parent(s): 5b7850b

Update bot.py

Browse files
Files changed (1) hide show
  1. bot.py +37 -63
bot.py CHANGED
@@ -6,18 +6,18 @@ import json
6
  import sys
7
  from threading import Thread
8
  from http.server import HTTPServer, SimpleHTTPRequestHandler
9
- from telethon import TelegramClient, functions, types
10
  from telethon.sessions import StringSession
11
  from telethon.tl.functions.channels import InviteToChannelRequest
12
  from telethon.tl.functions.messages import ExportChatInviteRequest
13
  from telethon.tl.types import InputPeerUser
14
  from telethon.errors import *
15
 
16
- # 1. إعداد اللوق
17
- logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s', handlers=[logging.StreamHandler(sys.stdout)])
18
  logger = logging.getLogger(__name__)
19
 
20
- # 2. المتغيرات
21
  API_ID = int(os.getenv("API_ID", "0"))
22
  API_HASH = os.getenv("API_HASH", "")
23
  SESSION_STRING = os.getenv("SESSION_STRING") or os.getenv("STRING_SESSION") or ""
@@ -25,15 +25,12 @@ SOURCE_CHANNEL = os.getenv("SOURCE_CHANNEL", "")
25
  TARGET_CHANNEL = os.getenv("TARGET_CHANNEL", "")
26
  DB_FILE = "members_inventory.json"
27
 
28
- # 3. الجسر (سيرفر الويب)
29
  def run_server():
30
- try:
31
- server = HTTPServer(("0.0.0.0", 7860), SimpleHTTPRequestHandler)
32
- server.serve_forever()
33
  except: pass
34
  Thread(target=run_server, daemon=True).start()
35
 
36
- # 4. وظائف المخزن
37
  def load_db():
38
  if os.path.exists(DB_FILE):
39
  try:
@@ -42,94 +39,71 @@ def load_db():
42
  return []
43
 
44
  def save_db(data):
45
- with open(DB_FILE, "w") as f: json.dump(data, f)
46
-
47
- def get_smart_msg(name, link):
48
- return f"أهلاً {name or 'يا غالي'} 👋\nانضم لجروبنا الرسمي وتفاعل معنا:\n{link}"
49
 
50
- # 5. المهمة الرئيسية
51
  async def start_cyclone():
52
- logger.info("🌪️ جاري بدء محرك الإعصار...")
 
 
53
  client = TelegramClient(StringSession(SESSION_STRING.strip()), API_ID, API_HASH)
54
 
55
  try:
56
  await client.connect()
57
  if not await client.is_user_authorized():
58
- logger.error("❌ الجلسة غير صالحة")
59
  return
60
 
61
- # جلب القنوات والروابط
62
- source = await client.get_entity(SOURCE_CHANNEL)
63
- target = await client.get_entity(TARGET_CHANNEL)
64
- try:
65
- invite = await client(ExportChatInviteRequest(peer=target))
66
- invite_link = invite.link
67
- except: invite_link = f"https://t.me/{TARGET_CHANNEL}"
68
-
69
  # فحص المخزن
70
- inventory = load_db()
71
  if not inventory:
72
  logger.info("📡 المخزن فارغ، جاري سحب قائمة جديدة...")
 
73
  participants = await client.get_participants(source, limit=5000)
74
- inventory = [{"id": m.id, "hash": m.access_hash, "name": m.first_name} for m in participants if not m.bot and not m.deleted]
75
  random.shuffle(inventory)
76
  save_db(inventory)
77
- logger.info(f"✅ تم سحب وتخزين {len(inventory)} عضو.")
78
-
79
- logger.info(f"🔥 بدء الهجوم.. المتبقي في المخزن: {len(inventory)}")
80
 
81
- success_add = 0
82
- success_msg = 0
 
 
 
83
 
 
84
  while inventory:
85
  member = inventory.pop(0)
86
- name = member['name'] or "صديقي"
87
-
88
  try:
89
- # محاكاة التفاعل
90
- await client(functions.account.UpdateStatusRequest(offline=False))
91
-
92
- # أ. محاولة الحشر المباشر
93
  await client(InviteToChannelRequest(target, [InputPeerUser(member['id'], member['hash'])]))
94
- success_add += 1
95
- logger.info(f"✅ حشر مباشر: {name} (إجمالي: {success_add})")
96
- await asyncio.sleep(random.randint(20, 40))
97
-
98
- except (PeerFloodError, UserPrivacyRestrictedError, FloodWaitError) as e:
99
- # ب. محاولة المراسلة (محاكاة بشرية)
100
  try:
101
- logger.info(f"✉️ تحويل {name} للمراسلة الخاصة...")
102
- async with client.action(member['id'], 'typing'):
103
- await asyncio.sleep(3)
104
- await client(functions.messages.ReadHistoryRequest(peer=member['id'], max_id=0))
105
-
106
- await client.send_message(member['id'], get_smart_msg(name, invite_link))
107
- success_msg += 1
108
- logger.info(f"📨 قصف خاص ناجح: {name} (إجمالي: {success_msg})")
109
- await asyncio.sleep(random.randint(25, 45))
110
- except:
111
- continue
112
  except Exception: continue
113
 
114
- # حفظ التقدم
115
  if len(inventory) % 5 == 0: save_db(inventory)
116
-
117
- # استراحة كل 20 محاولة
118
- if (success_add + success_msg) % 20 == 0:
119
- logger.info("☕ استراحة محارب (5 دقائق)...")
120
- await asyncio.sleep(300)
121
 
122
  except Exception as e:
123
- logger.error(f"💥 خطأ فادح: {e}")
124
  finally:
125
  save_db(inventory)
126
  await client.disconnect()
127
 
128
- # 6. تشغيل الحلقة بطريقة مستقرة
129
  async def main_loop():
130
  while True:
 
 
 
 
131
  await start_cyclone()
132
- logger.info("🔄 إعادة شحن الطاقة.. دورة جديدة بعد 10 دقائق")
133
  await asyncio.sleep(600)
134
 
135
  if __name__ == "__main__":
 
6
  import sys
7
  from threading import Thread
8
  from http.server import HTTPServer, SimpleHTTPRequestHandler
9
+ from telethon import TelegramClient, functions
10
  from telethon.sessions import StringSession
11
  from telethon.tl.functions.channels import InviteToChannelRequest
12
  from telethon.tl.functions.messages import ExportChatInviteRequest
13
  from telethon.tl.types import InputPeerUser
14
  from telethon.errors import *
15
 
16
+ # إعداد اللوق
17
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s')
18
  logger = logging.getLogger(__name__)
19
 
20
+ # المتغيرات
21
  API_ID = int(os.getenv("API_ID", "0"))
22
  API_HASH = os.getenv("API_HASH", "")
23
  SESSION_STRING = os.getenv("SESSION_STRING") or os.getenv("STRING_SESSION") or ""
 
25
  TARGET_CHANNEL = os.getenv("TARGET_CHANNEL", "")
26
  DB_FILE = "members_inventory.json"
27
 
28
+ # الجسر
29
  def run_server():
30
+ try: HTTPServer(("0.0.0.0", 7860), SimpleHTTPRequestHandler).serve_forever()
 
 
31
  except: pass
32
  Thread(target=run_server, daemon=True).start()
33
 
 
34
  def load_db():
35
  if os.path.exists(DB_FILE):
36
  try:
 
39
  return []
40
 
41
  def save_db(data):
42
+ try:
43
+ with open(DB_FILE, "w") as f: json.dump(data, f)
44
+ except: pass
 
45
 
 
46
  async def start_cyclone():
47
+ logger.info("🌪️ محاولة بدء الدورة...")
48
+ inventory = load_db() # تحميل البيانات في بداية الدالة لتجنب UnboundLocalError
49
+
50
  client = TelegramClient(StringSession(SESSION_STRING.strip()), API_ID, API_HASH)
51
 
52
  try:
53
  await client.connect()
54
  if not await client.is_user_authorized():
55
+ logger.error("❌ الجلسة محظورة أو منتهية. يرجى وضع SESSION_STRING جديدة.")
56
  return
57
 
 
 
 
 
 
 
 
 
58
  # فحص المخزن
 
59
  if not inventory:
60
  logger.info("📡 المخزن فارغ، جاري سحب قائمة جديدة...")
61
+ source = await client.get_entity(SOURCE_CHANNEL)
62
  participants = await client.get_participants(source, limit=5000)
63
+ inventory = [{"id": m.id, "hash": m.access_hash, "name": m.first_name} for m in participants if not m.bot]
64
  random.shuffle(inventory)
65
  save_db(inventory)
 
 
 
66
 
67
+ target = await client.get_entity(TARGET_CHANNEL)
68
+ try:
69
+ invite = await client(ExportChatInviteRequest(peer=target))
70
+ invite_link = invite.link
71
+ except: invite_link = f"https://t.me/{TARGET_CHANNEL}"
72
 
73
+ success = 0
74
  while inventory:
75
  member = inventory.pop(0)
 
 
76
  try:
77
+ # محاولة الحشر
 
 
 
78
  await client(InviteToChannelRequest(target, [InputPeerUser(member['id'], member['hash'])]))
79
+ success += 1
80
+ logger.info(f"✅ تمت إضافة: {member['name']} | المجموع: {success}")
81
+ await asyncio.sleep(random.randint(30, 60))
82
+ except (PeerFloodError, FloodWaitError, UserPrivacyRestrictedError):
83
+ # محاولة المراسلة كخيار بديل
 
84
  try:
85
+ await client.send_message(member['id'], f"أهلاً {member['name']}! تشرفنا في جروبنا: {invite_link}")
86
+ logger.info(f"📨 أرسلت دعوة خاصة لـ {member['name']}")
87
+ await asyncio.sleep(random.randint(30, 60))
88
+ except: continue
 
 
 
 
 
 
 
89
  except Exception: continue
90
 
 
91
  if len(inventory) % 5 == 0: save_db(inventory)
 
 
 
 
 
92
 
93
  except Exception as e:
94
+ logger.error(f"💥 خطأ أثناء التشغيل: {e}")
95
  finally:
96
  save_db(inventory)
97
  await client.disconnect()
98
 
 
99
  async def main_loop():
100
  while True:
101
+ if not SESSION_STRING:
102
+ logger.error("❌ لا يوجد SESSION_STRING في الـ Secrets!")
103
+ await asyncio.sleep(60)
104
+ continue
105
  await start_cyclone()
106
+ logger.info("💤 استراحة 10 دقائق...")
107
  await asyncio.sleep(600)
108
 
109
  if __name__ == "__main__":