Package: aiotdlib
aiotdlib - Python asyncio Telegram client based onTDLibThis wrapper is actual
forTDLib v1.8.14 (958fed6e8e440afe87b57c98216a5c8d3f3caed8)This package includes prebuilt TDLib binaries for macOS (arm64) and Debian Bullseye (amd64).
You can use your own binary by passinglibrary_pathargument toClientclass constructor. Make sure it's built
fromthis commit. Compatibility with
other versions of library is not guaranteed.FeaturesAll types and functions are generated automatically
fromtl schemaAll types and functions come with validation and good IDE type hinting (thanks
toPydantic)A set of high-level API methods which makes work with tdlib much simplerRequirementsPython 3.9+Get yourapi_idandapi_hash. Read more
inTelegram docsInstallationPyPIpipinstallaiotdlibor if you usePoetrypoetryaddaiotdlibExamplesBase exampleimportasyncioimportloggingfromaiotdlibimportClientAPI_ID=123456API_HASH=""PHONE_NUMBER=""asyncdefmain():client=Client(api_id=API_ID,api_hash=API_HASH,phone_number=PHONE_NUMBER)asyncwithclient:me=awaitclient.api.get_me()logging.info(f"Successfully logged in as{me.json()}")if__name__=='__main__':logging.basicConfig(level=logging.INFO)asyncio.run(main())Any parameter of Client class could be also set via environment variables.importasyncioimportloggingfromaiotdlibimportClientasyncdefmain():asyncwithClient()asclient:me=awaitclient.api.get_me()logging.info(f"Successfully logged in as{me.json()}")if__name__=='__main__':logging.basicConfig(level=logging.INFO)asyncio.run(main())and run it like this:exportAIOTDLIB_API_ID=123456exportAIOTDLIB_API_HASH=<my_api_hash>exportAIOTDLIB_BOT_TOKEN=<my_bot_token>
pythonmain.pyEvents handlersimportasyncioimportloggingfromaiotdlibimportClientfromaiotdlib.apiimportAPI,BaseObject,UpdateNewMessageAPI_ID=123456API_HASH=""PHONE_NUMBER=""asyncdefon_update_new_message(client:Client,update:UpdateNewMessage):chat_id=update.message.chat_id# api field of client instance contains all TDLib functions, for example get_chatchat=awaitclient.api.get_chat(chat_id)logging.info(f'Message received in chat{chat.title}')asyncdefany_event_handler(client:Client,update:BaseObject):logging.info(f'Event of type{update.ID}received')asyncdefmain():client=Client(api_id=API_ID,api_hash=API_HASH,phone_number=PHONE_NUMBER)# Registering event handler for 'updateNewMessage' event# You can register many handlers for certain event typeclient.add_event_handler(on_update_new_message,update_type=API.Types.UPDATE_NEW_MESSAGE)# You can register handler for special event type "*".# It will be called for each received eventclient.add_event_handler(any_event_handler,update_type=API.Types.ANY)asyncwithclient:# idle() will run client until it's stoppedawaitclient.idle()if__name__=='__main__':logging.basicConfig(level=logging.INFO)asyncio.run(main())Bot command handlerimportloggingfromaiotdlibimportClientfromaiotdlib.apiimportUpdateNewMessageAPI_ID=123456API_HASH=""BOT_TOKEN=""bot=Client(api_id=API_ID,api_hash=API_HASH,bot_token=BOT_TOKEN)# Note: bot_command_handler method is universal and can be used directly or as decorator# Registering handler for '/help' command@bot.bot_command_handler(command='help')asyncdefon_help_command(client:Client,update:UpdateNewMessage):# Each command handler registered with this method will update update.EXTRA field# with command related data: {'bot_command': 'help', 'bot_command_args': []}awaitclient.send_text(update.message.chat_id,"I will help you!")asyncdefon_start_command(client:Client,update:UpdateNewMessage):# So this will print "{'bot_command': 'help', 'bot_command_args': []}"print(update.EXTRA)awaitclient.send_text(update.message.chat_id,"Have a good day! :)")asyncdefon_custom_command(client:Client,update:UpdateNewMessage):# So when you send a message "/custom 1 2 3 test"# So this will print "{'bot_command': 'custom', 'bot_command_args': ['1', '2', '3', 'test']}"print(update.EXTRA)if__name__=='__main__':logging.basicConfig(level=logging.INFO)# Registering handler for '/start' commandbot.bot_command_handler(on_start_command,command='start')bot.bot_command_handler(on_custom_command,command='custom')bot.run()ProxyimportasyncioimportloggingfromaiotdlibimportClient,ClientProxySettings,ClientProxyTypeAPI_ID=123456API_HASH=""PHONE_NUMBER=""asyncdefmain():client=Client(api_id=API_ID,api_hash=API_HASH,phone_number=PHONE_NUMBER,proxy_settings=ClientProxySettings(host="10.0.0.1",port=3333,type=ClientProxyType.SOCKS5,username="aiotdlib",password="somepassword",))asyncwithclient:awaitclient.idle()if__name__=='__main__':logging.basicConfig(level=logging.INFO)asyncio.run(main())MiddlewaresimportasyncioimportloggingfromaiotdlibimportClient,HandlerCallablefromaiotdlib.apiimportAPI,BaseObject,UpdateNewMessageAPI_ID=12345API_HASH=""PHONE_NUMBER=""asyncdefsome_pre_updates_work(event:BaseObject):logging.info(f"Before call all update handlers for event{event.ID}")asyncdefsome_post_updates_work(event:BaseObject):logging.info(f"After call all update handlers for event{event.ID}")# Note that call_next argument would always be passed as keyword argument,# so it should be called "call_next" only.asyncdefmy_middleware(client:Client,event:BaseObject,*,call_next:HandlerCallable):# Middlewares useful for opening database connections for exampleawaitsome_pre_updates_work(event)try:awaitcall_next(client,event)finally:awaitsome_post_updates_work(event)asyncdefon_update_new_message(client:Client,update:UpdateNewMessage):logging.info('on_update_new_message handler called')asyncdefmain():client=Client(api_id=API_ID,api_hash=API_HASH,phone_number=PHONE_NUMBER)client.add_event_handler(on_update_new_message,update_type=API.Types.UPDATE_NEW_MESSAGE)# Registering middleware.# Note that middleware would be called for EVERY EVENT.# Don't use them for long-running tasks as it could be heavy performance hit# You can add as much middlewares as you want.# They would be called in order you've added themclient.add_middleware(my_middleware)asyncwithclient:awaitclient.idle()if__name__=='__main__':logging.basicConfig(level=logging.INFO)asyncio.run(main())LICENSEThis project is licensed under the terms of theMITlicense.