async def amain(client, allclients, web, arguments): """Entrypoint for async init, run once for each user""" setup = arguments.setup local = arguments.local web_only = arguments.web_only async with client: client.parse_mode = "HTML" await client.start() [handler] = logging.getLogger().handlers dbc = local_backend.LocalBackend if local else backend.CloudBackend if setup: db = dbc(client) await db.init(lambda e: None) jdb = await db.do_download() try: pdb = json.loads(jdb) except (json.decoder.JSONDecodeError, TypeError): pdb = {} modules = loader.Modules() babelfish = Translator([]) await babelfish.init(client) modules.register_all(babelfish) fdb = frontend.Database(None) await fdb.init() modules.send_config(fdb, babelfish) await modules.send_ready(client, fdb, allclients) # Allow normal init even in setup handler.setLevel(50) pdb = run_config(pdb, getattr(client, "phone", "Unknown Number"), modules) if pdb is None: await client(DeleteChannelRequest(db.db)) return try: await db.do_upload(json.dumps(pdb)) except MessageNotModifiedError: pass return db = frontend.Database(dbc(client)) await db.init() logging.debug("got db") logging.info("Loading logging config...") handler.setLevel(db.get(__name__, "loglevel", logging.WARNING)) babelfish = Translator(db.get(__name__, "langpacks", []), db.get(__name__, "language", ["en"])) await babelfish.init(client) modules = loader.Modules() modules.register_all(babelfish) modules.send_config(db, babelfish) await modules.send_ready(client, db, allclients) if not web_only: client.add_event_handler(functools.partial(handle_incoming, modules, db), events.NewMessage(incoming=True)) client.add_event_handler(functools.partial(handle_command, modules, db), events.NewMessage(outgoing=True, forwards=False)) print("Started for " + str((await client.get_me(True)).user_id)) # noqa: T001 if web: await web.add_loader(client, modules, db) await web.start_if_ready(len(allclients)) await client.run_until_disconnected()
async def _(e): xx = await eor(e, "`Processing...`") try: await e.client(DeleteChannelRequest(e.chat_id)) except TypeError: return await eod(xx, "`Cant delete this chat`", time=10) except no_admin: return await eod(xx, "`I m not an admin`", time=10) await e.client.send_message(Var.LOG_CHANNEL, f"#Deleted\nDeleted {e.chat_id}")
async def amain(client, allclients, setup=False): async with client as c: c.parse_mode = "HTML" await c.start() [handler] = logging.getLogger().handlers if setup: db = backend.CloudBackend(c) await db.init(lambda e: None) jdb = await db.do_download() try: pdb = json.loads(jdb) except (json.decoder.JSONDecodeError, TypeError): pdb = {} modules = loader.Modules() modules.register_all([], Translator()) fdb = frontend.Database(None) await fdb.init() modules.send_config(fdb) await modules.send_ready(client, fdb, allclients ) # Allow normal init even in setup handler.setLevel(50) pdb = run_config(pdb, getattr(c, "phone", "Unknown Number"), modules) if pdb is None: print("Factory reset triggered...") await client(DeleteChannelRequest(db.db)) return try: await db.do_upload(json.dumps(pdb)) except MessageNotModifiedError: pass return db = frontend.Database(backend.CloudBackend(c)) await db.init() logging.debug("got db") logging.info("Loading logging config...") handler.setLevel(db.get(__name__, "loglevel", logging.WARNING)) babelfish = Translator(["en"]) # TODO modules = loader.Modules() modules.register_all(db.get(__name__, "disable_modules", []), babelfish) modules.send_config(db) await modules.send_ready(client, db, allclients) client.add_event_handler( functools.partial(handle_incoming, modules, db), events.NewMessage(incoming=True)) client.add_event_handler( functools.partial(handle_command, modules, db), events.NewMessage(outgoing=True, forwards=False)) print("Started for " + str((await c.get_me(True)).user_id)) await c.run_until_disconnected()
async def _(ev): if BOT_MODE: return await eor(ev, "`Kamu tidak bisa menggunakan perintah ini menggunakan BOT_MODE") xx = await eor(ev, "`Memprossess...`") try: await ev.client(DeleteChannelRequest(ev.chat_id)) except TypeError: return await eod(xx, "`Tidak Bisa menghapus grup ini.`", time=10) except NoAdmin: return await eod(xx, "`Saya bukanlah admin.`", time=10) await ev.client.send_message(Var.LOG_CHANNEL, f"#Dihapus\nMenghapus {ev.chat_id}")
async def do_upload(self, data): """Attempt to upload the database. Return True or throw""" if not self.db: self.db = await self._find_data_channel() if not self.db: self.db = await self._make_data_channel() self._client.add_event_handler(self._callback, telethon.events.messageedited.MessageEdited(chats=[self.db])) msgs = await self._client.get_messages( entity=self.db, reverse=True ) ops = [] sdata = data newmsg = False for msg in msgs: logger.debug(msg) if isinstance(msg, Message): if len(sdata): logging.debug("editing message " + msg.stringify() + " last is " + msgs[-1].stringify()) if msg.id == msgs[-1].id: newmsg = True if sdata[:4096] != msg.message: ops += [msg.edit("<code>" + utils.escape_html(sdata[:4096]) + "</code>")] sdata = sdata[4096:] else: logging.debug("maybe deleting message") if not msg.id == msgs[-1].id: ops += [msg.delete()] try: for r in await asyncio.gather(*ops, return_exceptions=True): if isinstance(r, MessageNotModifiedError): logging.warning("db not modified", exc_info=r) elif isinstance(r, Exception): raise r # Makes more sense to raise even for MessageEditTimeExpiredError elif r is not None: logging.debug("unknown ret from gather, %r", r) except MessageEditTimeExpiredError: logging.debug("Making new channel.") _db = self.db self.db = None await self._client(DeleteChannelRequest(channel=_db)) return await self.do_upload(data) while len(sdata): # Only happens if newmsg is True or there was no message before newmsg = True await self._client.send_message(self.db, utils.escape_html(sdata[:4096])) sdata = sdata[4096:] if newmsg: await self._client.send_message(self.db, "Please ignore this chat.") return True
async def leave_channel(channel_name): ''' 退出无用的频道/组 Args: channel_name ([type]): [description] ''' try: await client(LeaveChannelRequest(channel_name)) await client(DeleteChannelRequest(channel_name)) await client(DeleteHistoryRequest(channel_name)) logger.info(f'退出 {channel_name}') except Exception as _e: # 不存在的频道 return f'无法退出该频道:{channel_name}, {_e}'
async def _(e): xx = await e.eor(get_string("com_1")) try: match = e.text.split(" ", maxsplit=1)[1] chat = await e.client.parse_id(match) except IndexError: chat = e.chat_id try: await e.client(DeleteChannelRequest(chat)) except TypeError: return await xx.eor(get_string("chats_1"), time=10) except no_admin: return await xx.eor(get_string("chats_2"), time=10) await e.client.send_message(int(udB.get_key("LOG_CHANNEL")), get_string("chats_6").format(e.chat_id))
async def _(e): xx = await eor(e, "`Processing...`") try: match = e.text.split(" ", maxsplit=1)[1] chat = "-100" + str(await get_user_id(match)) except IndexError: chat = e.chat_id try: await e.client(DeleteChannelRequest(chat)) except TypeError: return await eor(xx, "`Cant delete this chat`", time=10) except no_admin: return await eor(xx, "`I m not an admin`", time=10) await e.client.send_message(int(udB.get("LOG_CHANNEL")), f"#Deleted\nDeleted {e.chat_id}")
async def _do_ops(self, ops): try: for r in await asyncio.gather(*ops, return_exceptions=True): if isinstance(r, MessageNotModifiedError): logging.debug("db not modified", exc_info=r) elif isinstance(r, Exception): raise r # Makes more sense to raise even for MessageEditTimeExpiredError elif not isinstance(r, Message): logging.debug("unknown ret from gather, %r", r) except MessageEditTimeExpiredError: logging.debug("Making new channel.") _db = self.db self.db = None await self._client(DeleteChannelRequest(channel=_db)) return True return False
async def test_group_chat_migration(client, helper, channel, slave, bot_id): slave_chats = slave.chats_by_chat_type["PrivateChat"] response = await client( CreateChatRequest(users=[bot_id], title=f"Chat upgrade test {uuid4()}")) chat: TelethonChat = response.chats[0] with link_chats(channel, slave_chats, get_peer_id(chat)): mega_chat_response = await client(MigrateChatRequest(chat_id=chat.id)) mega_chat: TelethonChat = mega_chat_response.chats[1] await asyncio.sleep(10) assert_is_linked(channel, slave_chats, get_peer_id(mega_chat)) assert_is_linked(channel, tuple(), get_peer_id(chat)) # Clean up unlink_all_chats(channel, get_peer_id(mega_chat)) unlink_all_chats(channel, get_peer_id(chat)) await client(DeleteChannelRequest(mega_chat.id))
async def do_upload(self, data): """Attempt to upload the database. Return True or throw""" if not self._db: self._db = await self._find_data_channel() if not self._db: self._db = await self._make_data_channel() msgs = await self._client.get_messages( entity=self._db, reverse=True ) ops = [] sdata = data newmsg = False for msg in msgs: logger.debug(msg) if isinstance(msg, Message): if len(sdata): logging.debug("editing message "+msg.stringify()+" last is "+msgs[-1].stringify()) if msg.id == msgs[-1].id: newmsg = True ops += [msg.edit(utils.escape_html(sdata[:4096]))] sdata = sdata[4096:] else: logging.debug("maybe deleting message") if not msg.id == msgs[-1].id: ops += [msg.delete()] try: await asyncio.gather(*ops) except MessageEditTimeExpiredError: logging.debug("Making new channel.") _db = self._db self._db = None await self._client(DeleteChannelRequest(channel=_db)) return await self.do_upload(data) while len(sdata): # Only happens if newmsg is True or there was no message before newmsg = True await self._client.send_message(self._db, utils.escape_html(sdata[:4096])) sdata = sdata[4096:] if newmsg: await self._client.send_message(self._db, "Please ignore this chat.") return True
async def run(): session_file = [ f for f in listdir('.') if isfile(join('.', f)) and f.endswith('.session') ][0][:-len('.session')] client = TelegramClient(session_file, int(os.environ.get('API_ID')), os.environ.get('API_HASH')) # noinspection PyUnresolvedReferences await client.start() # Getting information about yourself me = await client.get_me() print(f'Signed in as @{me.username} (+{me.phone})') # You can print all the dialogs/conversations that you are part of: async for dialog in client.iter_dialogs(): print(dialog.name, dialog.id) if dialog.name.endswith('*'): await client(DeleteChannelRequest(dialog.id)) print(f'{dialog.name}: deleted') else: print(dialog.name)
async def amain(first, client, allclients, web, arguments): """Entrypoint for async init, run once for each user""" setup = arguments.setup local = arguments.local or arguments.test_dc web_only = arguments.web_only client.parse_mode = "HTML" await client.start() is_bot = await client.is_bot() if is_bot: local = True [handler] = logging.getLogger().handlers db = local_backend.LocalBackend( client, arguments.data_root) if local else backend.CloudBackend(client) if setup: await db.init(lambda e: None) jdb = await db.do_download() try: pdb = json.loads(jdb) except (json.decoder.JSONDecodeError, TypeError): pdb = {} modules = loader.Modules() babelfish = Translator([], [], arguments.data_root) await babelfish.init(client) modules.register_all(babelfish) fdb = frontend.Database(db, True) await fdb.init() modules.send_config(fdb, babelfish) await modules.send_ready(client, fdb, allclients) # Allow normal init even in setup handler.setLevel(50) pdb = run_config(pdb, arguments.data_root, getattr(client, "phone", "Unknown Number"), modules) if pdb is None: await client(DeleteChannelRequest(db.db)) return try: await db.do_upload(json.dumps(pdb)) except MessageNotModifiedError: pass return False db = frontend.Database( db, arguments.heroku_deps_internal or arguments.docker_deps_internal) await db.init() logging.debug("got db") logging.info("Loading logging config...") handler.setLevel(db.get(__name__, "loglevel", logging.WARNING)) to_load = None if arguments.heroku_deps_internal or arguments.docker_deps_internal: to_load = ["loader.py"] if __debug__ and arguments.self_test: tester = TestManager(client, db, allclients, arguments.self_test) to_load = await tester.init() babelfish = Translator(db.get(__name__, "langpacks", []), db.get(__name__, "language", ["en"]), arguments.data_root) await babelfish.init(client) modules = loader.Modules() if not (arguments.heroku_deps_internal or arguments.docker_deps_internal): if web: await web.add_loader(client, modules, db) await web.start_if_ready(len(allclients)) if not web_only: dispatcher = CommandDispatcher(modules, db, is_bot, __debug__ and arguments.self_test) if is_bot: modules.added_modules = functools.partial( set_commands, dispatcher.security) modules.register_all(babelfish, to_load) modules.send_config(db, babelfish) await modules.send_ready(client, db, allclients) if arguments.heroku_deps_internal or arguments.docker_deps_internal: # Loader has installed all dependencies return # We are done if not web_only: await dispatcher.init(client) modules.check_security = dispatcher.check_security client.add_event_handler(dispatcher.handle_incoming, events.NewMessage) client.add_event_handler(dispatcher.handle_incoming, events.ChatAction) client.add_event_handler(dispatcher.handle_command, events.NewMessage(forwards=False)) client.add_event_handler(dispatcher.handle_command, events.MessageEdited()) if first: if __debug__ and arguments.self_test: await client(GetStateRequest()) # Start receiving updates print("Started for " + str( (await client.get_me(True)).user_id)) # noqa: T001 if __debug__ and arguments.self_test: await asyncio.wait([client.disconnected, tester.restart], return_when=asyncio.FIRST_COMPLETED) else: await client.run_until_disconnected() await db.close() if __debug__ and arguments.self_test and tester.should_restart(): for cb, _ in client.list_event_handlers(): client.remove_event_handler(cb) return True return False
async def amain(first, client, allclients, web, arguments): """Entrypoint for async init, run once for each user""" setup = arguments.setup web_only = arguments.web_only client.parse_mode = "HTML" await client.start() handlers = logging.getLogger().handlers db = backend.CloudBackend(client) if setup: await db.init(lambda e: None) jdb = await db.do_download() try: pdb = json.loads(jdb) except (json.decoder.JSONDecodeError, TypeError): pdb = {} modules = loader.Modules(arguments.use_inline) babelfish = Translator([], [], arguments.data_root) await babelfish.init(client) modules.register_all(babelfish) fdb = frontend.Database(db, True) await fdb.init() modules.send_config(fdb, babelfish) await modules.send_ready(client, fdb, allclients) # Allow normal init even in setup for handler in handlers: handler.setLevel(50) pdb = run_config( pdb, arguments.data_root, getattr(client, "phone", "Unknown Number"), modules, ) if pdb is None: await client(DeleteChannelRequest(db.db)) return try: await db.do_upload(json.dumps(pdb)) except MessageNotModifiedError: pass return False db = frontend.Database( db, arguments.heroku_deps_internal or arguments.docker_deps_internal) await db.init() logging.debug("got db") logging.info("Loading logging config...") for handler in handlers: handler.setLevel(db.get(__name__, "loglevel", logging.WARNING)) to_load = None if arguments.heroku_deps_internal or arguments.docker_deps_internal: to_load = ["loader.py"] babelfish = Translator( db.get(__name__, "langpacks", []), db.get(__name__, "language", ["en"]), arguments.data_root, ) await babelfish.init(client) modules = loader.Modules() no_nickname = arguments.no_nickname if not (arguments.heroku_deps_internal or arguments.docker_deps_internal): if web: await web.add_loader(client, modules, db) await web.start_if_ready(len(allclients), arguments.port) if not web_only: dispatcher = CommandDispatcher(modules, db, no_nickname) client.dispatcher = dispatcher if arguments.heroku_deps_internal or arguments.docker_deps_internal: # Loader has installed all dependencies return # We are done if not web_only: await dispatcher.init(client) modules.check_security = dispatcher.check_security client.add_event_handler(dispatcher.handle_incoming, events.NewMessage) client.add_event_handler(dispatcher.handle_incoming, events.ChatAction) client.add_event_handler(dispatcher.handle_command, events.NewMessage(forwards=False)) client.add_event_handler(dispatcher.handle_command, events.MessageEdited()) modules.register_all(babelfish, to_load) modules.send_config(db, babelfish) await modules.send_ready(client, db, allclients) if first: try: import git repo = git.Repo() build = repo.heads[0].commit.hexsha diff = repo.git.log(["HEAD..origin/master", "--oneline"]) upd = r"\33[31mUpdate required" if diff else r"Up-to-date" termux = bool( os.popen('echo $PREFIX | grep -o "com.termux"').read() ) # skipcq: BAN-B605, BAN-B607 is_heroku = os.environ.get("DYNO", False) _platform = r"Termux" if termux else ( r"Heroku" if is_heroku else "VDS") logo1 = f""" ) ( ( /( ) ) ( ( )()) (()/( ) ) |((_) /((_)_((_)((_)|_((_) (_)/ __| __| __| |/ / | (_ | _|| _| ' < ___|___|___|_|_\\ • Build: {build[:7]} • Version: {'.'.join(list(map(str, list(__version__))))} • {upd} • Platform: {_platform} - Started for {(await client.get_me(True)).user_id} -""" print(logo1) logging.info(f"=== BUILD: {build} ===") logging.info( f"=== VERSION: {'.'.join(list(map(str, list(__version__))))} ===" ) logging.info( f"=== PLATFORM: {'Termux' if termux else ('Heroku' if is_heroku else 'VDS')} ===" ) except Exception: logging.exception( "Badge error" ) # This part is not so necessary, so if error occures, ignore it await client.run_until_disconnected() # Previous line will stop code execution, so this part is # reached only when client is by some reason disconnected # At this point we need to close database await db.close() return False