Package: django-telethon
Django Telethon config⭐️ Thankseveryonewho has starred the project, it means a lot!This project is to help you useTelethon.Django-Telethon is an asyncio Python 3 MTProto library to interact with Telegram's API as a user or through a bot account (bot API alternative).What is this?Telegram is a popular messaging application. This library is meant to make it easy for you to write Python programs that can interact with Telegram. Think of it as a wrapper that has already done the heavy job for you, so you can focus on developing an application.Django-Telethon is a session storage implementation backend for Django ORM to use telethon in Django projects.CompatibilityPython 3.7+Django 3.0+InstallationUse the following command to install using pip:pipinstalldjango-telethonORYou can use the following command to set it up locally so that you can fix bugs or whatever and send pull requests:pipinstall-e".[dev]"pre-commitinstallFor better understanding, please read the:Telethondocumentation.Telethon Sessiondocumentation.pre-commitdocumentation.pipdocumentation.python packagedocumentation.github pull requestsdocumentation.settings.pyINSTALLED_APPS=[# ....'django_telethon',# ...]urls.pyfromdjango.contribimportadmin
fromdjango.urlsimportpath

fromdjango_telethon.urlsimportdjango_telethon_urls

admin.autodiscover()urlpatterns=[path('admin/',admin.site.urls),path('telegram/',django_telethon_urls()),]Migrationpythonmanage.pymigrateSigning InBefore working with Telegram’s API, you need to get your own API ID and hash:Login to your Telegram accountwith the phone number of the developer account to use.Click under API Development tools.Create new application window will appear. Fill in your application details. There is no need to enter any URL, and only the first two fields (App title and Short name) can currently be changed later.Click on Create application at the end. Remember that your API hash is secret and Telegram won’t let you revoke it. Don’t post it anywhere!This API ID and hash is the one used by your application, not your phone number. You can use this API ID and hash with any phone number or even for bot accounts.Read more (proxy, bot and etc)Here.UsageInteractive modeOpen a terminal and run the following command:pythonmanage.pyshellEnableDJANGO_ALLOW_ASYNC_UNSAFEin your environment.importosos.environ["DJANGO_ALLOW_ASYNC_UNSAFE"]="true"You can import these fromdjango_telethon.sessions. For example, using theDjangoSessionis done as follows:fromtelethon.syncimportTelegramClientfromdjango_telethon.sessionsimportDjangoSessionfromdjango_telethon.modelsimportApp,ClientSessionfromtelethon.errorsimportSessionPasswordNeededError# Use your own values from my.telegram.orgAPI_ID=12345API_HASH='0123456789abcdef0123456789abcdef'app,is_created=App.objects.update_or_create(api_id=API_ID,api_hash=API_HASH)cs,cs_is_created=ClientSession.objects.update_or_create(name='default',)telegram_client=TelegramClient(DjangoSession(client_session=cs),app.api_id,app.api_hash)telegram_client.connect()ifnottelegram_client.is_user_authorized():phone=input('Enter your phone number: ')telegram_client.send_code_request(phone)code=input('Enter the code you received: ')try:telegram_client.sign_in(phone,code)exceptSessionPasswordNeededError:password=input('Enter your password: ')telegram_client.sign_in(password=password)Doing stuffsprint((awaittelegram_client.get_me()).stringify())awaittelegram_client.send_message('username','Hello! Talking to you from Telethon')awaittelegram_client.send_file('username','/home/myself/Pictures/holidays.jpg')awaittelegram_client.download_profile_photo('me')messages=awaittelegram_client.get_messages('username')awaitmessages[0].download_media()@telegram_client.on(telegram_client.NewMessage(pattern='(?i)hi|hello'))asyncdefhandler(event):awaitevent.respond('Hey!')APIUser LoginRun the following command to start the server:pythonmanage.pyrunserverRun the following command to start telegram client:pythonmanage.pyruntelegramgo toadmin panelandtelegram app section. create a new app. get data from theyour Telegram account.Request code from telegram:importrequestsimportjsonurl="http://127.0.0.1:8000/telegram/send-code-request/"payload=json.dumps({"phone_number":"+12345678901","client_session_name":"name of the client session"})headers={'Content-Type':'application/json'}response=requests.request("POST",url,headers=headers,data=payload)print(response.text)Send this request for sign in:importrequestsimportjsonurl="http://127.0.0.1:8000/telegram/login-user-request/"payload=json.dumps({"phone_number":"+12345678901","client_session_name":"name of the client session","code":"1234","password":"1234"})headers={'Content-Type':'application/json'}response=requests.request("POST",url,headers=headers,data=payload)print(response.text)Bot loginSend this request for sign in:importrequestsimportjsonurl="http://127.0.0.1:8000/telegram/login-bot-request/"payload=json.dumps({"bot_token":"bot token","client_session_name":"name of the client session",})headers={'Content-Type':'application/json'}response=requests.request("POST",url,headers=headers,data=payload)print(response.text)Server-sideIf you are usingsupervisordoranother process manager, you can use the following command to start the server:pythonmanage.pyruntelegramSupervisordAdd the following lines to your/etc/supervisord.d/[yourproject].inifile:[program:telegram_worker]directory=/home/projectuser/[your_project_directory]/command=/home/projectuser/venv/bin/python manage.py runtelegramautostart=trueautorestart=truestderr_logfile=/home/projectuser/logs/telegramworker.err.logstdout_logfile=/home/projectuser/logs/telegramworker.out.logReload the supervisor daemon:supervisorctlreread
supervisorctlupdate
supervisorctlstarttelegram_worker
supervisorctlstatusListen to eventsAfter login telegram client the signaltelegram_client_registeredis emitted.You can listen to this signal by using the following code for example put this code to yourreceivers.pyfile in app directory:fromfunctoolsimportpartialfromdjango.dispatchimportreceiverfromtelethonimporteventsfromdjango_telethon.signalsimporttelegram_client_registeredasyncdefevent_handler(event,client_session):print(client_session.name,event.raw_text,sep=' | ')# if you need access to telegram client, you can use event.client# telegram_client = event.clientawaitevent.respond('!pong')@receiver(telegram_client_registered)defreceiver_telegram_registered(telegram_client,client_session,*args,**kwargs):handler=partial(event_handler,client_session=client_session)telegram_client.add_event_handler(handler,events.NewMessage(incoming=True,pattern='ping'),)In theapps.pyfile, add the following code:fromdjango.appsimportAppConfigclassMyAppConfig(AppConfig):...defready(self):from.receiversimportreceiver_telegram_registered# noqa: F401Read more about signals inDjango signalsRead more about events inTelethon eventsDjango Configuration[Optional]To configure the Django Telethon library, you need to update your Django settings. Add the following dictionary to your Django settings:DJANGO_TELETHON={'RABBITMQ_ACTIVE':TrueorFalse,# Set to True if you want to use RabbitMQ. Otherwise, set to False.'RABBITMQ_URL':'your_rabbitmq_url',# The URL to your RabbitMQ server.'QUEUE_CHANNEL_NAME':'your_channel_name',# Name of the channel you want to use for the queue.'QUEUE_CALLBACK':'path_to_custom_callback'# (Optional) Path to your custom callback. Default is 'django_telethon.callback.on_message'.}ExampleDJANGO_TELETHON={'RABBITMQ_ACTIVE':True,'RABBITMQ_URL':'amqp://app:app@localhost:5672/app','QUEUE_CHANNEL_NAME':'EXAMPLE_CHANNEL',# Name of the channel you want to use for the queue.'QUEUE_CALLBACK':'django_telethon.callback.on_message'# (Optional) Path to your custom callback. Default is 'django_telethon.callback.on_message'.}Default CallbackBy default, the library uses a callbackon_messagewhich logs the received message. If you want to use a custom callback, set theQUEUE_CALLBACKin your settings.UsageWhen a new message arrives at the RabbitMQ channel specified, the configured callback function will be invoked. The default callback logs the message using the Python logging module. You can replace this with your own callback function to process the message as desired.Using RabbitMQ for Inter-thread CommunicationIn the scenario where different parts of your application (like web servers managed by Gunicorn, background workers managed by Celery, etc.) are running on different threads or even different machines, communicating directly might be a challenge. If, for instance, you receive a message directly from Telegram and want to respond or if some event happens on the web front and you wish to notify a Telegram user, it's not straightforward due to these separate threads.To solve this, Django Telethon library has introduced a mechanism to send messages across threads/machines using RabbitMQ. Here's how you can utilize it:Connect to RabbitMQThe library initializes a connection to RabbitMQ and listens for incoming messages. Once a message arrives, the specified callback function is invokedSending Messages to Telegram ThreadFor components that want to communicate with the Telegram thread, you can use thesend_to_telegra_threadfunction. This function sends a message to the Telegram thread via RabbitMQ.fromdjango_telethonimportsend_to_telegra_thread# Send a payload/message to the Telegram threadsend_to_telegra_thread(some_key="some_value",another_key="another_value")Thesend_to_telegra_threadfunction serializes the payload and sends it to RabbitMQ. The Telegram thread, which is already listening to RabbitMQ, receives this message and can then process it, for example, to send a response back to a Telegram user.CallbacksDefaulton_messageCallbackHere's the default callback provided by the library:importloggingasyncdefon_message(byte_string:bytes):logging.debug("Received message:",byte_string)Custom CallbackTo use a custom callback:Define your custom callback function. Ensure it's anasyncfunction and has a single parameter of typeaio_pika.IncomingMessage.Set theQUEUE_CALLBACKinDJANGO_TELETHONsettings to point to your custom callback function's path.LicenseThe MIT License (MIT). Please seeLicense Filefor more information.