soxogvv commited on
Commit
5d85537
Β·
verified Β·
1 Parent(s): a4daa67

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +53 -91
app.py CHANGED
@@ -15,7 +15,6 @@ from telethon import TelegramClient, events, Button
15
  from telethon.sessions import StringSession
16
  from telethon.tl import functions
17
 
18
- # ───── Logging ─────
19
  logging.basicConfig(
20
  level=logging.INFO,
21
  format="%(asctime)s | %(message)s",
@@ -23,7 +22,6 @@ logging.basicConfig(
23
  )
24
  log = logging.getLogger("app")
25
 
26
- # ───── Setup ─────
27
  nest_asyncio.apply()
28
  API_ID = int(os.getenv("API_ID", 3704772))
29
  API_HASH = os.getenv("API_HASH", "b8e50a035abb851c0dd424e14cac4c06")
@@ -34,116 +32,80 @@ ADMIN_ID = int(os.getenv("ADMIN_ID", 6574063018))
34
  client = MongoClient(MONGO_URI)
35
  db = client["telethon_bots"]
36
  accounts = db["accounts"]
37
-
38
  bot = TelegramClient("main_bot", API_ID, API_HASH).start(bot_token=BOT_TOKEN)
39
  userbots = {}
40
 
41
  scheduler = AsyncIOScheduler(timezone=pytz.timezone("Asia/Kolkata"))
42
 
43
- # ───── Reset Daily Counts ─────
44
- def reset_daily_counts():
45
- accounts.update_many({}, {"$set": {"created": 0}})
46
- asyncio.create_task(bot.send_message(ADMIN_ID, "πŸ”„ Daily group creation count reset."))
47
- log.info("πŸ”„ Daily reset of group creation count")
48
-
49
- scheduler.add_job(reset_daily_counts, CronTrigger(hour=0, minute=0))
50
-
51
- adjectives = [
52
- "Silent", "Crazy", "Golden", "Hidden", "Brave",
53
- "Fierce", "Mysterious", "Savage", "Royal", "Witty",
54
- "Legendary", "Epic", "Noble", "Clever", "Loyal",
55
- "Wild", "Electric", "Fearless", "Crimson", "Frozen",
56
- "Charming", "Rebel", "Turbo", "Lone", "Radiant",
57
- "Raging", "Dusty", "Majestic", "Grumpy", "Shadow"
58
- ]
59
- nouns = [
60
- "Warriors", "Coders", "Friends", "Legends", "Pirates",
61
- "Tigers", "Wolves", "Hackers", "Ninjas", "Riders",
62
- "Hunters", "Kings", "Queens", "Giants", "Lords",
63
- "Champions", "Stormers", "Creators", "Ghosts", "Wizards",
64
- "Knights", "Samurais", "Explorers", "Titans", "Outlaws",
65
- "Rebels", "Squad", "Troopers", "Dreamers", "Avengers"
66
- ]
 
 
 
67
 
68
  def random_group_name():
69
  return f"{random.choice(adjectives)} {random.choice(nouns)}"
70
 
71
- # Group name generator (with internal clean)
72
  async def auto_create_groups(userbot, acc_doc):
73
- created = 0
74
  try:
75
- for _ in range(random.randint(3, 5)):
76
- title = random_group_name()
77
- me = await userbot.get_me()
78
-
79
- result = await userbot(functions.channels.CreateChannelRequest(
80
- title=title,
81
- about=",", # already clean
82
- megagroup=True
83
- ))
84
-
85
- group = result.chats[0].id
86
- if not group:
87
- raise Exception("Couldn't find created group")
88
-
89
- # Send intro messages
90
- for _ in range(4):
91
- await userbot.send_message(group, random_group_name())
92
- await asyncio.sleep(2)
93
-
94
- # Send random sticker from a predefined list (example)
95
- try:
96
- stickers = ["CAACAgUAAxkBAAEKZStlTxkC-cvQJwABvHoUjRacAVIHCFcAAgECAALaTqVVCpx_Lc2ZoLguBA"]
97
- await userbot.send_file(group, random.choice(stickers))
98
- except Exception:
99
- pass # If sticker fails, skip
100
-
101
- created += 1
102
- await asyncio.sleep(1)
103
-
104
- # Update DB with total created and last IST time
105
- ist_time = datetime.now(pytz.timezone("Asia/Kolkata"))
106
  accounts.update_one(
107
  {"_id": acc_doc["_id"]},
108
- {"$inc": {"created": created}, "$set": {"last_created": ist_time}}
109
  )
110
 
111
  info = await userbot.get_me()
112
  await bot.send_message(
113
  ADMIN_ID,
114
- f"βœ… Created {created} groups\nπŸ‘€ {info.first_name}\nπŸ”— @{info.username or 'N/A'}\nπŸ“Š Total today: {acc_doc['created'] + created}"
115
  )
116
- log.info(f"πŸ‘₯ {created} groups created for {acc_doc['name']}")
117
-
118
  except Exception as e:
119
- try:
120
- name = acc_doc['name'] if acc_doc else "Unknown"
121
- await bot.send_message(ADMIN_ID, f"❌ Group creation failed for {name}: {e}")
122
- except Exception:
123
- pass
124
  log.error(f"❌ Group creation failed: {e}")
125
- # ───── Scheduler ─────
126
- def schedule_random_group_creation(userbot, acc_doc):
127
- async def job():
128
- try:
129
- if acc_doc["user_id"] not in userbots:
130
- return
131
- acc_doc = accounts.find_one({"user_id": acc_doc["user_id"]})
132
- if acc_doc["created"] < 5: # daily limit per account
133
- await auto_create_groups(userbot, acc_doc)
134
- except Exception as e:
135
- await bot.send_message(ADMIN_ID, f"❌ Error for {acc_doc['name']}: {e}")
136
- finally:
137
- schedule_random_group_creation(userbot, acc_doc)
138
-
139
- now = datetime.now(pytz.timezone("Asia/Kolkata"))
140
- random_minute = random.randint(1, 59)
141
- random_hour = random.randint(0, 23)
142
- run_time = now.replace(hour=random_hour, minute=random_minute, second=0, microsecond=0)
143
- if run_time < now:
144
- run_time += timedelta(days=1)
145
-
146
- scheduler.add_job(job, trigger='date', run_date=run_time)
147
 
148
  # ───── Userbot Setup ─────
149
  async def start_userbot(session_str, owner_id):
 
15
  from telethon.sessions import StringSession
16
  from telethon.tl import functions
17
 
 
18
  logging.basicConfig(
19
  level=logging.INFO,
20
  format="%(asctime)s | %(message)s",
 
22
  )
23
  log = logging.getLogger("app")
24
 
 
25
  nest_asyncio.apply()
26
  API_ID = int(os.getenv("API_ID", 3704772))
27
  API_HASH = os.getenv("API_HASH", "b8e50a035abb851c0dd424e14cac4c06")
 
32
  client = MongoClient(MONGO_URI)
33
  db = client["telethon_bots"]
34
  accounts = db["accounts"]
 
35
  bot = TelegramClient("main_bot", API_ID, API_HASH).start(bot_token=BOT_TOKEN)
36
  userbots = {}
37
 
38
  scheduler = AsyncIOScheduler(timezone=pytz.timezone("Asia/Kolkata"))
39
 
40
+ # ───── Reset + Plan ─────
41
+ def reset_and_plan():
42
+ accounts.update_many({}, {"$set": {"created": 0, "schedule_times": []}})
43
+ all_accounts = list(accounts.find())
44
+
45
+ for acc in all_accounts:
46
+ limit = random.randint(3, 5)
47
+ times = []
48
+ while len(times) < limit:
49
+ h, m = random.randint(0, 23), random.randint(0, 59)
50
+ dt = datetime.now(pytz.timezone("Asia/Kolkata")).replace(hour=h, minute=m, second=0, microsecond=0)
51
+ if dt not in times:
52
+ times.append(dt)
53
+ times.sort()
54
+ accounts.update_one({"_id": acc["_id"]}, {"$set": {"schedule_times": times}})
55
+
56
+ if acc["user_id"] in userbots:
57
+ for run_time in times:
58
+ scheduler.add_job(auto_create_groups, 'date', run_date=run_time, args=[userbots[acc["user_id"]], acc])
59
+
60
+ asyncio.create_task(bot.send_message(ADMIN_ID, "πŸ”„ Daily limits & schedules updated."))
61
+ log.info("πŸ”„ Daily plan and reset done.")
62
+
63
+ scheduler.add_job(reset_and_plan, CronTrigger(hour=0, minute=0))
64
+
65
+ adjectives = ["Silent", "Crazy", "Golden", "Hidden", "Brave", "Fierce", "Mysterious", "Savage", "Royal", "Witty", "Legendary", "Epic", "Noble", "Clever", "Loyal", "Wild", "Electric", "Fearless", "Crimson", "Frozen", "Charming", "Rebel", "Turbo", "Lone", "Radiant", "Raging", "Dusty", "Majestic", "Grumpy", "Shadow"]
66
+ nouns = ["Warriors", "Coders", "Friends", "Legends", "Pirates", "Tigers", "Wolves", "Hackers", "Ninjas", "Riders", "Hunters", "Kings", "Queens", "Giants", "Lords", "Champions", "Stormers", "Creators", "Ghosts", "Wizards", "Knights", "Samurais", "Explorers", "Titans", "Outlaws", "Rebels", "Squad", "Troopers", "Dreamers", "Avengers"]
67
 
68
  def random_group_name():
69
  return f"{random.choice(adjectives)} {random.choice(nouns)}"
70
 
 
71
  async def auto_create_groups(userbot, acc_doc):
 
72
  try:
73
+ if acc_doc["created"] >= len(acc_doc.get("schedule_times", [])):
74
+ return
75
+
76
+ title = random_group_name()
77
+ me = await userbot.get_me()
78
+ result = await userbot(functions.channels.CreateChannelRequest(
79
+ title=title,
80
+ about=",",
81
+ megagroup=True
82
+ ))
83
+ group = result.chats[0].id
84
+
85
+ for _ in range(4):
86
+ await userbot.send_message(group, random_group_name())
87
+ await asyncio.sleep(2)
88
+
89
+ try:
90
+ stickers = ["CAACAgUAAxkBAAEKZStlTxkC-cvQJwABvHoUjRacAVIHCFcAAgECAALaTqVVCpx_Lc2ZoLguBA"]
91
+ await userbot.send_file(group, random.choice(stickers))
92
+ except Exception:
93
+ pass
94
+
 
 
 
 
 
 
 
 
 
95
  accounts.update_one(
96
  {"_id": acc_doc["_id"]},
97
+ {"$inc": {"created": 1}, "$set": {"last_created": datetime.now(pytz.timezone("Asia/Kolkata"))}}
98
  )
99
 
100
  info = await userbot.get_me()
101
  await bot.send_message(
102
  ADMIN_ID,
103
+ f"βœ… Created 1 group\nπŸ‘€ {info.first_name}\nπŸ”— @{info.username or 'N/A'}\nπŸ“Š Total today: {acc_doc['created'] + 1}"
104
  )
105
+ log.info(f"πŸ‘₯ 1 group created for {acc_doc['name']}")
 
106
  except Exception as e:
107
+ await bot.send_message(ADMIN_ID, f"❌ Group creation failed for {acc_doc['name']}: {e}")
 
 
 
 
108
  log.error(f"❌ Group creation failed: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
 
110
  # ───── Userbot Setup ─────
111
  async def start_userbot(session_str, owner_id):