Update app.py
Browse files
app.py
CHANGED
|
@@ -1,4 +1,5 @@
|
|
| 1 |
import os
|
|
|
|
| 2 |
import logging
|
| 3 |
import nest_asyncio
|
| 4 |
import random
|
|
@@ -14,12 +15,16 @@ from telethon import TelegramClient, events, Button
|
|
| 14 |
from telethon.sessions import StringSession
|
| 15 |
from telethon.tl import functions
|
| 16 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
# βββββ Setup βββββ
|
| 18 |
nest_asyncio.apply()
|
| 19 |
-
logging.getLogger("telethon").setLevel(logging.CRITICAL)
|
| 20 |
-
logging.getLogger("apscheduler").setLevel(logging.CRITICAL)
|
| 21 |
-
logging.getLogger("werkzeug").setLevel(logging.ERROR)
|
| 22 |
-
|
| 23 |
API_ID = int(os.getenv("API_ID", 3704772))
|
| 24 |
API_HASH = os.getenv("API_HASH", "b8e50a035abb851c0dd424e14cac4c06")
|
| 25 |
BOT_TOKEN = os.getenv("BOT_TOKEN")
|
|
@@ -35,14 +40,15 @@ userbots = {}
|
|
| 35 |
|
| 36 |
scheduler = AsyncIOScheduler(timezone=pytz.timezone("Asia/Kolkata"))
|
| 37 |
|
| 38 |
-
# βββββ Reset Daily
|
| 39 |
def reset_daily_counts():
|
| 40 |
accounts.update_many({}, {"$set": {"created": 0}})
|
| 41 |
asyncio.create_task(bot.send_message(ADMIN_ID, "π Daily group creation count reset."))
|
|
|
|
| 42 |
|
| 43 |
scheduler.add_job(reset_daily_counts, CronTrigger(hour=0, minute=0))
|
| 44 |
|
| 45 |
-
# βββββ Schedule Group Creation βββββ
|
| 46 |
def schedule_random_group_creation(userbot, acc_doc):
|
| 47 |
hour = random.randint(0, 23)
|
| 48 |
minute = random.randint(0, 59)
|
|
@@ -54,7 +60,8 @@ def schedule_random_group_creation(userbot, acc_doc):
|
|
| 54 |
return
|
| 55 |
await auto_create_groups(userbot, acc_doc)
|
| 56 |
except Exception as e:
|
| 57 |
-
await bot.send_message(ADMIN_ID, f"β Error
|
|
|
|
| 58 |
|
| 59 |
scheduler.add_job(job, trigger)
|
| 60 |
|
|
@@ -63,18 +70,20 @@ async def auto_create_groups(userbot, acc_doc):
|
|
| 63 |
created = 0
|
| 64 |
try:
|
| 65 |
for i in range(random.randint(3, 5)):
|
| 66 |
-
|
| 67 |
-
await userbot(functions.messages.CreateChatRequest(users=[], title=
|
| 68 |
created += 1
|
| 69 |
await asyncio.sleep(1)
|
| 70 |
accounts.update_one({"_id": acc_doc["_id"]}, {"$inc": {"created": created}})
|
| 71 |
info = await userbot.get_me()
|
| 72 |
await bot.send_message(
|
| 73 |
ADMIN_ID,
|
| 74 |
-
f"β
Created {created} groups\nπ€
|
| 75 |
)
|
|
|
|
| 76 |
except Exception as e:
|
| 77 |
-
await bot.send_message(ADMIN_ID, f"β
|
|
|
|
| 78 |
|
| 79 |
# βββββ Start Userbot βββββ
|
| 80 |
async def start_userbot(session_str, owner_id):
|
|
@@ -97,10 +106,12 @@ async def start_userbot(session_str, owner_id):
|
|
| 97 |
userbots[info.id] = userbot
|
| 98 |
schedule_random_group_creation(userbot, doc)
|
| 99 |
asyncio.create_task(userbot.run_until_disconnected())
|
| 100 |
-
await bot.send_message(ADMIN_ID, f"β
|
|
|
|
| 101 |
return info
|
| 102 |
except Exception as e:
|
| 103 |
-
await bot.send_message(ADMIN_ID, f"β Failed to add
|
|
|
|
| 104 |
return None
|
| 105 |
|
| 106 |
# βββββ Bot Commands βββββ
|
|
@@ -108,14 +119,14 @@ async def start_userbot(session_str, owner_id):
|
|
| 108 |
async def start_cmd(event):
|
| 109 |
if event.sender_id != ADMIN_ID:
|
| 110 |
return
|
| 111 |
-
await event.reply("π Welcome!
|
| 112 |
|
| 113 |
@bot.on(events.NewMessage(pattern="/addacc"))
|
| 114 |
async def addacc_cmd(event):
|
| 115 |
if event.sender_id != ADMIN_ID:
|
| 116 |
return
|
| 117 |
async with bot.conversation(event.chat_id, timeout=60) as conv:
|
| 118 |
-
await conv.send_message("βοΈ Send your
|
| 119 |
session_msg = await conv.get_response()
|
| 120 |
session_str = session_msg.text.strip()
|
| 121 |
info = await start_userbot(session_str, event.sender_id)
|
|
@@ -129,7 +140,7 @@ async def total_accounts_cmd(event):
|
|
| 129 |
if event.sender_id != ADMIN_ID:
|
| 130 |
return
|
| 131 |
count = accounts.count_documents({})
|
| 132 |
-
await event.respond(f"π Total connected
|
| 133 |
|
| 134 |
@bot.on(events.NewMessage(pattern="/delacc"))
|
| 135 |
async def delacc_cmd(event):
|
|
@@ -137,10 +148,9 @@ async def delacc_cmd(event):
|
|
| 137 |
return
|
| 138 |
user_accs = list(accounts.find({"owner_id": ADMIN_ID}))
|
| 139 |
if not user_accs:
|
| 140 |
-
await event.reply("πΆ No accounts
|
| 141 |
return
|
| 142 |
-
buttons = []
|
| 143 |
-
row = []
|
| 144 |
for idx, acc in enumerate(user_accs, 1):
|
| 145 |
row.append(Button.inline(f"{acc['name']} (@{acc.get('username', 'N/A')})", data=f"del_{acc['user_id']}"))
|
| 146 |
if idx % 2 == 0:
|
|
@@ -148,7 +158,7 @@ async def delacc_cmd(event):
|
|
| 148 |
row = []
|
| 149 |
if row:
|
| 150 |
buttons.append(row)
|
| 151 |
-
await event.respond("Select
|
| 152 |
|
| 153 |
@bot.on(events.CallbackQuery(pattern=b"del_"))
|
| 154 |
async def handle_delete(event):
|
|
@@ -157,9 +167,9 @@ async def handle_delete(event):
|
|
| 157 |
user_id = int(event.data.decode().split("_")[1])
|
| 158 |
acc_doc = accounts.find_one({"user_id": user_id})
|
| 159 |
if not acc_doc:
|
| 160 |
-
await event.answer("
|
| 161 |
return
|
| 162 |
-
await event.edit(f"β οΈ Confirm
|
| 163 |
[Button.inline("β
Confirm", data=f"confdel_{user_id}"), Button.inline("β Cancel", data=b"cancel")]
|
| 164 |
])
|
| 165 |
|
|
@@ -174,10 +184,11 @@ async def confirm_delete(event):
|
|
| 174 |
if user_id in userbots:
|
| 175 |
await userbots[user_id].disconnect()
|
| 176 |
del userbots[user_id]
|
| 177 |
-
await event.edit(f"β
Deleted
|
| 178 |
-
await bot.send_message(ADMIN_ID, f"ποΈ
|
|
|
|
| 179 |
except Exception as e:
|
| 180 |
-
await event.edit(f"Deleted from DB,
|
| 181 |
else:
|
| 182 |
await event.edit("β οΈ Not found.")
|
| 183 |
|
|
@@ -187,8 +198,9 @@ async def cancel_cb(event):
|
|
| 187 |
return
|
| 188 |
await event.edit("β Cancelled.")
|
| 189 |
|
| 190 |
-
# βββββ Load
|
| 191 |
async def load_all_userbots():
|
|
|
|
| 192 |
for acc in accounts.find():
|
| 193 |
try:
|
| 194 |
ub = TelegramClient(StringSession(acc["session"]), API_ID, API_HASH)
|
|
@@ -196,32 +208,33 @@ async def load_all_userbots():
|
|
| 196 |
userbots[acc["user_id"]] = ub
|
| 197 |
schedule_random_group_creation(ub, acc)
|
| 198 |
asyncio.create_task(ub.run_until_disconnected())
|
| 199 |
-
|
| 200 |
-
|
|
|
|
|
|
|
| 201 |
|
| 202 |
# βββββ Flask App βββββ
|
| 203 |
app = Flask(__name__)
|
| 204 |
-
cli = type('cli', (), {'show_server_banner': lambda *a, **kw: None})
|
| 205 |
-
|
| 206 |
@app.route("/")
|
| 207 |
def home():
|
| 208 |
return "β
Channel-making bot is running."
|
| 209 |
|
| 210 |
def flask_thread():
|
| 211 |
-
app.run(host="0.0.0.0", port=
|
| 212 |
|
| 213 |
-
# βββββ Start
|
| 214 |
-
async def start_scheduler():
|
| 215 |
-
scheduler.start()
|
| 216 |
-
await load_all_userbots()
|
| 217 |
async def full_start():
|
| 218 |
Thread(target=flask_thread).start()
|
| 219 |
scheduler.start()
|
| 220 |
await load_all_userbots()
|
| 221 |
-
|
|
|
|
| 222 |
|
| 223 |
def main():
|
| 224 |
loop = asyncio.new_event_loop()
|
| 225 |
asyncio.set_event_loop(loop)
|
| 226 |
loop.run_until_complete(full_start())
|
| 227 |
-
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
+
import sys
|
| 3 |
import logging
|
| 4 |
import nest_asyncio
|
| 5 |
import random
|
|
|
|
| 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",
|
| 22 |
+
stream=sys.stdout,
|
| 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")
|
| 30 |
BOT_TOKEN = os.getenv("BOT_TOKEN")
|
|
|
|
| 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 |
+
# βββββ Schedule Random Group Creation βββββ
|
| 52 |
def schedule_random_group_creation(userbot, acc_doc):
|
| 53 |
hour = random.randint(0, 23)
|
| 54 |
minute = random.randint(0, 59)
|
|
|
|
| 60 |
return
|
| 61 |
await auto_create_groups(userbot, acc_doc)
|
| 62 |
except Exception as e:
|
| 63 |
+
await bot.send_message(ADMIN_ID, f"β Error for {acc_doc['name']}: {e}")
|
| 64 |
+
log.info(f"β Group creation error for {acc_doc['name']}: {e}")
|
| 65 |
|
| 66 |
scheduler.add_job(job, trigger)
|
| 67 |
|
|
|
|
| 70 |
created = 0
|
| 71 |
try:
|
| 72 |
for i in range(random.randint(3, 5)):
|
| 73 |
+
title = f"Auto Group {i + 1}"
|
| 74 |
+
await userbot(functions.messages.CreateChatRequest(users=[], title=title))
|
| 75 |
created += 1
|
| 76 |
await asyncio.sleep(1)
|
| 77 |
accounts.update_one({"_id": acc_doc["_id"]}, {"$inc": {"created": created}})
|
| 78 |
info = await userbot.get_me()
|
| 79 |
await bot.send_message(
|
| 80 |
ADMIN_ID,
|
| 81 |
+
f"β
Created {created} groups\nπ€ {info.first_name}\nπ @{info.username or 'N/A'}\nπ Total: {acc_doc['created'] + created}"
|
| 82 |
)
|
| 83 |
+
log.info(f"π₯ {created} groups created for {acc_doc['name']}")
|
| 84 |
except Exception as e:
|
| 85 |
+
await bot.send_message(ADMIN_ID, f"β Group creation failed: {e}")
|
| 86 |
+
log.info(f"β Group creation failed for {acc_doc['name']}: {e}")
|
| 87 |
|
| 88 |
# βββββ Start Userbot βββββ
|
| 89 |
async def start_userbot(session_str, owner_id):
|
|
|
|
| 106 |
userbots[info.id] = userbot
|
| 107 |
schedule_random_group_creation(userbot, doc)
|
| 108 |
asyncio.create_task(userbot.run_until_disconnected())
|
| 109 |
+
await bot.send_message(ADMIN_ID, f"β
Added: {info.first_name} (@{info.username or 'N/A'})")
|
| 110 |
+
log.info(f"β
Added account: {info.first_name} (@{info.username or 'N/A'})")
|
| 111 |
return info
|
| 112 |
except Exception as e:
|
| 113 |
+
await bot.send_message(ADMIN_ID, f"β Failed to add: {e}")
|
| 114 |
+
log.info(f"β Failed to add account: {e}")
|
| 115 |
return None
|
| 116 |
|
| 117 |
# βββββ Bot Commands βββββ
|
|
|
|
| 119 |
async def start_cmd(event):
|
| 120 |
if event.sender_id != ADMIN_ID:
|
| 121 |
return
|
| 122 |
+
await event.reply("π Welcome!\n/addacc β Add account\n/delacc β Delete\n/total β Count")
|
| 123 |
|
| 124 |
@bot.on(events.NewMessage(pattern="/addacc"))
|
| 125 |
async def addacc_cmd(event):
|
| 126 |
if event.sender_id != ADMIN_ID:
|
| 127 |
return
|
| 128 |
async with bot.conversation(event.chat_id, timeout=60) as conv:
|
| 129 |
+
await conv.send_message("βοΈ Send your String Session:")
|
| 130 |
session_msg = await conv.get_response()
|
| 131 |
session_str = session_msg.text.strip()
|
| 132 |
info = await start_userbot(session_str, event.sender_id)
|
|
|
|
| 140 |
if event.sender_id != ADMIN_ID:
|
| 141 |
return
|
| 142 |
count = accounts.count_documents({})
|
| 143 |
+
await event.respond(f"π Total connected: **{count}**")
|
| 144 |
|
| 145 |
@bot.on(events.NewMessage(pattern="/delacc"))
|
| 146 |
async def delacc_cmd(event):
|
|
|
|
| 148 |
return
|
| 149 |
user_accs = list(accounts.find({"owner_id": ADMIN_ID}))
|
| 150 |
if not user_accs:
|
| 151 |
+
await event.reply("πΆ No accounts.")
|
| 152 |
return
|
| 153 |
+
buttons, row = [], []
|
|
|
|
| 154 |
for idx, acc in enumerate(user_accs, 1):
|
| 155 |
row.append(Button.inline(f"{acc['name']} (@{acc.get('username', 'N/A')})", data=f"del_{acc['user_id']}"))
|
| 156 |
if idx % 2 == 0:
|
|
|
|
| 158 |
row = []
|
| 159 |
if row:
|
| 160 |
buttons.append(row)
|
| 161 |
+
await event.respond("Select to delete:", buttons=buttons)
|
| 162 |
|
| 163 |
@bot.on(events.CallbackQuery(pattern=b"del_"))
|
| 164 |
async def handle_delete(event):
|
|
|
|
| 167 |
user_id = int(event.data.decode().split("_")[1])
|
| 168 |
acc_doc = accounts.find_one({"user_id": user_id})
|
| 169 |
if not acc_doc:
|
| 170 |
+
await event.answer("Not found.", alert=True)
|
| 171 |
return
|
| 172 |
+
await event.edit(f"β οΈ Confirm delete {acc_doc['name']}?", buttons=[
|
| 173 |
[Button.inline("β
Confirm", data=f"confdel_{user_id}"), Button.inline("β Cancel", data=b"cancel")]
|
| 174 |
])
|
| 175 |
|
|
|
|
| 184 |
if user_id in userbots:
|
| 185 |
await userbots[user_id].disconnect()
|
| 186 |
del userbots[user_id]
|
| 187 |
+
await event.edit(f"β
Deleted: {acc_doc['name']}")
|
| 188 |
+
await bot.send_message(ADMIN_ID, f"ποΈ Deleted: {acc_doc['name']} (@{acc_doc.get('username', 'N/A')})")
|
| 189 |
+
log.info(f"ποΈ Deleted account: {acc_doc['name']} (@{acc_doc.get('username', 'N/A')})")
|
| 190 |
except Exception as e:
|
| 191 |
+
await event.edit(f"Deleted from DB, error stopping: {e}")
|
| 192 |
else:
|
| 193 |
await event.edit("β οΈ Not found.")
|
| 194 |
|
|
|
|
| 198 |
return
|
| 199 |
await event.edit("β Cancelled.")
|
| 200 |
|
| 201 |
+
# βββββ Load All Bots βββββ
|
| 202 |
async def load_all_userbots():
|
| 203 |
+
log.info("π Loading all stored userbots...")
|
| 204 |
for acc in accounts.find():
|
| 205 |
try:
|
| 206 |
ub = TelegramClient(StringSession(acc["session"]), API_ID, API_HASH)
|
|
|
|
| 208 |
userbots[acc["user_id"]] = ub
|
| 209 |
schedule_random_group_creation(ub, acc)
|
| 210 |
asyncio.create_task(ub.run_until_disconnected())
|
| 211 |
+
log.info(f"β
Loaded: {acc['name']} (@{acc.get('username', 'N/A')})")
|
| 212 |
+
except Exception as e:
|
| 213 |
+
await bot.send_message(ADMIN_ID, f"β Failed to start {acc['name']}")
|
| 214 |
+
log.info(f"β Failed to start {acc['name']}: {e}")
|
| 215 |
|
| 216 |
# βββββ Flask App βββββ
|
| 217 |
app = Flask(__name__)
|
|
|
|
|
|
|
| 218 |
@app.route("/")
|
| 219 |
def home():
|
| 220 |
return "β
Channel-making bot is running."
|
| 221 |
|
| 222 |
def flask_thread():
|
| 223 |
+
app.run(host="0.0.0.0", port=7860, use_reloader=False)
|
| 224 |
|
| 225 |
+
# βββββ Full Start βββββ
|
|
|
|
|
|
|
|
|
|
| 226 |
async def full_start():
|
| 227 |
Thread(target=flask_thread).start()
|
| 228 |
scheduler.start()
|
| 229 |
await load_all_userbots()
|
| 230 |
+
asyncio.create_task(bot.run_until_disconnected())
|
| 231 |
+
log.info("π€ Bot is now running on Hugging Face")
|
| 232 |
|
| 233 |
def main():
|
| 234 |
loop = asyncio.new_event_loop()
|
| 235 |
asyncio.set_event_loop(loop)
|
| 236 |
loop.run_until_complete(full_start())
|
| 237 |
+
loop.run_forever()
|
| 238 |
+
|
| 239 |
+
if __name__ == "__main__":
|
| 240 |
+
main()
|