Update app.py
Browse files
app.py
CHANGED
|
@@ -16,6 +16,11 @@ from telethon.sessions import StringSession
|
|
| 16 |
from telethon.tl import functions
|
| 17 |
import re
|
| 18 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
logging.basicConfig(
|
| 20 |
level=logging.INFO,
|
| 21 |
format="%(asctime)s | %(message)s",
|
|
@@ -33,60 +38,56 @@ ADMIN_ID = int(os.getenv("ADMIN_ID", 6574063018))
|
|
| 33 |
client = MongoClient(MONGO_URI)
|
| 34 |
db = client["telethon_bots"]
|
| 35 |
accounts = db["accounts"]
|
| 36 |
-
|
| 37 |
-
userbots = {}
|
| 38 |
-
|
| 39 |
-
scheduler = AsyncIOScheduler(timezone=pytz.timezone("Asia/Kolkata"))
|
| 40 |
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
accounts.update_many({}, {"$set": {"created": 0, "schedule_times": []}})
|
| 44 |
-
all_accounts = list(accounts.find())
|
| 45 |
|
| 46 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
limit = random.randint(3, 5)
|
| 48 |
-
times =
|
| 49 |
while len(times) < limit:
|
| 50 |
h, m = random.randint(0, 23), random.randint(0, 59)
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
|
| 61 |
-
|
| 62 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
|
| 64 |
scheduler.add_job(reset_and_plan, CronTrigger(hour=0, minute=0))
|
| 65 |
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
def random_group_name():
|
| 71 |
-
return f"{random.choice(adjectives)} {random.choice(nouns)}"
|
| 72 |
-
|
| 73 |
-
def schedule_random_group_creation(userbot, acc_doc):
|
| 74 |
-
if acc_doc.get("schedule_times"):
|
| 75 |
-
for run_time in acc_doc["schedule_times"]:
|
| 76 |
-
scheduler.add_job(auto_create_groups, 'date', run_date=run_time, args=[userbot, acc_doc])
|
| 77 |
|
| 78 |
-
# βββββ Group Creation ββοΏ½οΏ½οΏ½ββ
|
| 79 |
-
async def auto_create_groups(userbot, acc_doc):
|
| 80 |
try:
|
| 81 |
-
if acc_doc["created"] >= len(acc_doc.get("schedule_times", [])):
|
| 82 |
-
return
|
| 83 |
-
|
| 84 |
title = random_group_name()
|
| 85 |
-
result = await userbot(functions.channels.CreateChannelRequest(
|
| 86 |
-
title=title,
|
| 87 |
-
about=",",
|
| 88 |
-
megagroup=True
|
| 89 |
-
))
|
| 90 |
group = result.chats[0].id
|
| 91 |
|
| 92 |
for _ in range(4):
|
|
@@ -96,25 +97,16 @@ async def auto_create_groups(userbot, acc_doc):
|
|
| 96 |
try:
|
| 97 |
stickers = ["CAACAgUAAxkBAAEKZStlTxkC-cvQJwABvHoUjRacAVIHCFcAAgECAALaTqVVCpx_Lc2ZoLguBA"]
|
| 98 |
await userbot.send_file(group, random.choice(stickers))
|
| 99 |
-
except
|
| 100 |
-
pass
|
| 101 |
|
| 102 |
-
|
| 103 |
-
{"_id": acc_doc["_id"]},
|
| 104 |
-
{"$inc": {"created": 1}, "$set": {"last_created": datetime.now(pytz.timezone("Asia/Kolkata"))}}
|
| 105 |
-
)
|
| 106 |
|
| 107 |
info = await userbot.get_me()
|
| 108 |
-
await bot.send_message(
|
| 109 |
-
ADMIN_ID,
|
| 110 |
-
f"β
Created 1 group\nπ€ {info.first_name}\nπ @{info.username or 'N/A'}\nπ Total today: {acc_doc['created'] + 1}"
|
| 111 |
-
)
|
| 112 |
-
log.info(f"π₯ 1 group created for {acc_doc['name']}")
|
| 113 |
except Exception as e:
|
| 114 |
await bot.send_message(ADMIN_ID, f"β Group creation failed for {acc_doc['name']}: {e}")
|
| 115 |
log.error(f"β Group creation failed: {e}")
|
| 116 |
|
| 117 |
-
# βββββ Userbot Setup βββββ
|
| 118 |
async def start_userbot(session_str, owner_id):
|
| 119 |
try:
|
| 120 |
userbot = TelegramClient(StringSession(session_str), API_ID, API_HASH)
|
|
@@ -133,14 +125,12 @@ async def start_userbot(session_str, owner_id):
|
|
| 133 |
}
|
| 134 |
accounts.insert_one(doc)
|
| 135 |
userbots[info.id] = userbot
|
| 136 |
-
schedule_random_group_creation(userbot, doc)
|
| 137 |
asyncio.create_task(userbot.run_until_disconnected())
|
| 138 |
return info
|
| 139 |
except Exception as e:
|
| 140 |
log.info(f"β Failed to add account: {e}")
|
| 141 |
return None
|
| 142 |
|
| 143 |
-
# βββββ Load All βββββ
|
| 144 |
async def load_all_userbots():
|
| 145 |
log.info("π Loading all stored userbots...")
|
| 146 |
for acc in accounts.find():
|
|
@@ -148,13 +138,13 @@ async def load_all_userbots():
|
|
| 148 |
ub = TelegramClient(StringSession(acc["session"]), API_ID, API_HASH)
|
| 149 |
await ub.start()
|
| 150 |
userbots[acc["user_id"]] = ub
|
| 151 |
-
schedule_random_group_creation(ub, acc)
|
| 152 |
asyncio.create_task(ub.run_until_disconnected())
|
| 153 |
log.info(f"β
Loaded: {acc['name']} (@{acc.get('username', 'N/A')})")
|
| 154 |
except Exception as e:
|
| 155 |
await bot.send_message(ADMIN_ID, f"β Failed to start {acc['name']}")
|
| 156 |
log.info(f"β Failed to start {acc['name']}: {e}")
|
| 157 |
|
|
|
|
| 158 |
# βββββ Bot Commands βββββ
|
| 159 |
@bot.on(events.NewMessage(pattern="/start"))
|
| 160 |
async def start_cmd(event):
|
|
|
|
| 16 |
from telethon.tl import functions
|
| 17 |
import re
|
| 18 |
|
| 19 |
+
# βββββ Utils βββββ
|
| 20 |
+
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"]
|
| 21 |
+
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"]
|
| 22 |
+
|
| 23 |
+
|
| 24 |
logging.basicConfig(
|
| 25 |
level=logging.INFO,
|
| 26 |
format="%(asctime)s | %(message)s",
|
|
|
|
| 38 |
client = MongoClient(MONGO_URI)
|
| 39 |
db = client["telethon_bots"]
|
| 40 |
accounts = db["accounts"]
|
| 41 |
+
plans = db["plans"] # new collection to track next day schedule
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
+
def random_group_name():
|
| 44 |
+
return f"{random.choice(adjectives)} {random.choice(nouns)}"
|
|
|
|
|
|
|
| 45 |
|
| 46 |
+
def create_tomorrow_plan():
|
| 47 |
+
tz = pytz.timezone("Asia/Kolkata")
|
| 48 |
+
tomorrow = (datetime.now(tz) + timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0)
|
| 49 |
+
plans.delete_many({}) # clear old plans
|
| 50 |
+
for acc in accounts.find():
|
| 51 |
limit = random.randint(3, 5)
|
| 52 |
+
times = set()
|
| 53 |
while len(times) < limit:
|
| 54 |
h, m = random.randint(0, 23), random.randint(0, 59)
|
| 55 |
+
t = tomorrow + timedelta(hours=h, minutes=m)
|
| 56 |
+
times.add(t)
|
| 57 |
+
schedule_times = sorted(list(times))
|
| 58 |
+
plans.insert_one({"user_id": acc["user_id"], "times": schedule_times, "created": 0})
|
| 59 |
+
log.info("π
Tomorrow's plan created.")
|
| 60 |
+
|
| 61 |
+
def apply_today_plan():
|
| 62 |
+
tz = pytz.timezone("Asia/Kolkata")
|
| 63 |
+
now = datetime.now(tz)
|
| 64 |
+
plans_today = list(plans.find())
|
| 65 |
+
for plan in plans_today:
|
| 66 |
+
acc = accounts.find_one({"user_id": plan["user_id"]})
|
| 67 |
+
if not acc or plan.get("created", 0) >= len(plan["times"]):
|
| 68 |
+
continue
|
| 69 |
+
for run_time in plan["times"]:
|
| 70 |
+
if run_time.date() == now.date():
|
| 71 |
+
scheduler.add_job(auto_create_groups, 'date', run_date=run_time, args=[userbots[plan["user_id"]], acc, plan])
|
| 72 |
|
| 73 |
+
def reset_and_plan():
|
| 74 |
+
tz = pytz.timezone("Asia/Kolkata")
|
| 75 |
+
plans.delete_many({})
|
| 76 |
+
create_tomorrow_plan()
|
| 77 |
+
apply_today_plan()
|
| 78 |
+
log.info("π New day plan set.")
|
| 79 |
+
asyncio.create_task(bot.send_message(ADMIN_ID, "ποΈ Daily schedule reset and updated."))
|
| 80 |
|
| 81 |
scheduler.add_job(reset_and_plan, CronTrigger(hour=0, minute=0))
|
| 82 |
|
| 83 |
+
async def auto_create_groups(userbot, acc_doc, plan_doc):
|
| 84 |
+
if plan_doc["created"] >= len(plan_doc["times"]):
|
| 85 |
+
await bot.send_message(ADMIN_ID, f"β Group creation skipped: Limit exceeded for {acc_doc['name']}")
|
| 86 |
+
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
|
|
|
|
|
|
|
| 88 |
try:
|
|
|
|
|
|
|
|
|
|
| 89 |
title = random_group_name()
|
| 90 |
+
result = await userbot(functions.channels.CreateChannelRequest(title=title, about=",", megagroup=True))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
group = result.chats[0].id
|
| 92 |
|
| 93 |
for _ in range(4):
|
|
|
|
| 97 |
try:
|
| 98 |
stickers = ["CAACAgUAAxkBAAEKZStlTxkC-cvQJwABvHoUjRacAVIHCFcAAgECAALaTqVVCpx_Lc2ZoLguBA"]
|
| 99 |
await userbot.send_file(group, random.choice(stickers))
|
| 100 |
+
except: pass
|
|
|
|
| 101 |
|
| 102 |
+
plans.update_one({"user_id": acc_doc["user_id"]}, {"$inc": {"created": 1}})
|
|
|
|
|
|
|
|
|
|
| 103 |
|
| 104 |
info = await userbot.get_me()
|
| 105 |
+
await bot.send_message(ADMIN_ID, f"β
Created 1 group\nπ€ {info.first_name}\nπ @{info.username or 'N/A'}\nπ Created today: {plan_doc['created'] + 1}")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
async def start_userbot(session_str, owner_id):
|
| 111 |
try:
|
| 112 |
userbot = TelegramClient(StringSession(session_str), API_ID, API_HASH)
|
|
|
|
| 125 |
}
|
| 126 |
accounts.insert_one(doc)
|
| 127 |
userbots[info.id] = userbot
|
|
|
|
| 128 |
asyncio.create_task(userbot.run_until_disconnected())
|
| 129 |
return info
|
| 130 |
except Exception as e:
|
| 131 |
log.info(f"β Failed to add account: {e}")
|
| 132 |
return None
|
| 133 |
|
|
|
|
| 134 |
async def load_all_userbots():
|
| 135 |
log.info("π Loading all stored userbots...")
|
| 136 |
for acc in accounts.find():
|
|
|
|
| 138 |
ub = TelegramClient(StringSession(acc["session"]), API_ID, API_HASH)
|
| 139 |
await ub.start()
|
| 140 |
userbots[acc["user_id"]] = ub
|
|
|
|
| 141 |
asyncio.create_task(ub.run_until_disconnected())
|
| 142 |
log.info(f"β
Loaded: {acc['name']} (@{acc.get('username', 'N/A')})")
|
| 143 |
except Exception as e:
|
| 144 |
await bot.send_message(ADMIN_ID, f"β Failed to start {acc['name']}")
|
| 145 |
log.info(f"β Failed to start {acc['name']}: {e}")
|
| 146 |
|
| 147 |
+
|
| 148 |
# βββββ Bot Commands βββββ
|
| 149 |
@bot.on(events.NewMessage(pattern="/start"))
|
| 150 |
async def start_cmd(event):
|