"""Telegram verify for FreeModel: /start + join channel/group. Prints JSON.""" import asyncio, json, os, sys, time API_ID = 2040 API_HASH = "b18441a1ff607e10a989891a5462e627" BOT = "FreeModels_bbot" CHAN = "FreeModel_in" GROUP = "FreeModelChat" async def free_room(cl, n=3): """Leave oldest channels to get under the 500-chat join limit.""" from telethon.tl.functions.channels import LeaveChannelRequest from telethon.tl.types import Channel left = [] try: async for d in cl.iter_dialogs(limit=400): if len(left) >= n: break ent = d.entity if isinstance(ent, Channel) and ent.megagroup is False and not ent.creator: try: await cl(LeaveChannelRequest(ent)) left.append(d.name) except Exception: pass except Exception: pass return left async def main(sess, start_param, join=False, wait_reply=18): from telethon import TelegramClient from telethon.errors import FloodWaitError from telethon.tl.functions.channels import JoinChannelRequest out = {"session": os.path.basename(sess), "start": start_param} try: cl = TelegramClient(sess, API_ID, API_HASH, connection_retries=2, timeout=25, request_retries=2) await cl.connect() except Exception as e: out["err"] = "connect: %s" % str(e)[:160] return out try: if not await cl.is_user_authorized(): out["err"] = "notauth" return out me = await cl.get_me() out["me"] = [me.id, me.username] bot = await cl.get_entity(BOT) await cl.send_message(bot, "/start " + start_param) t0 = time.time() while time.time() - t0 < wait_reply: msgs = await cl.get_messages(bot, limit=3) if msgs and msgs[0].out is False: out["bot_reply"] = (msgs[0].message or "")[:400] break await asyncio.sleep(2) if join: for tgt in (CHAN, GROUP): for attempt in range(2): try: await cl(JoinChannelRequest(await cl.get_entity(tgt))) out.setdefault("joined", []).append(tgt) break except FloodWaitError as e: out.setdefault("flood", []).append([tgt, e.seconds]) break except Exception as e: msg = str(e)[:120] if attempt == 0 and ("too many channels" in msg or "CHANNELS_TOO_MUCH" in msg): left = await free_room(cl, 3) out.setdefault("left", []).append(left) continue out.setdefault("join_err", []).append([tgt, msg]) break except Exception as e: out["err"] = "flow: %s" % str(e)[:200] finally: try: await cl.disconnect() except Exception: pass return out if __name__ == "__main__": sess = sys.argv[1] sp = sys.argv[2] join = len(sys.argv) > 3 and sys.argv[3] == "join" print(json.dumps(asyncio.run(main(sess, sp, join)), ensure_ascii=False))