{"id":38656678,"url":"https://github.com/ali-zahedi/django-telethon","last_synced_at":"2026-01-17T09:28:38.301Z","repository":{"id":46660829,"uuid":"479945660","full_name":"ali-zahedi/django-telethon","owner":"ali-zahedi","description":"Integrate Django with Telethon(Pure Python 3 MTProto API Telegram client library, for bots too!).","archived":false,"fork":false,"pushed_at":"2024-12-03T18:25:30.000Z","size":63,"stargazers_count":88,"open_issues_count":6,"forks_count":14,"subscribers_count":3,"default_branch":"main","last_synced_at":"2026-01-03T19:17:33.393Z","etag":null,"topics":["bot","django","library","mtproto","python","python-library","telegram","telegram-api","telethon","telethon-bot","telethon-userbot"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ali-zahedi.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2022-04-10T07:34:07.000Z","updated_at":"2025-09-30T11:01:41.000Z","dependencies_parsed_at":"2023-01-20T23:04:06.101Z","dependency_job_id":null,"html_url":"https://github.com/ali-zahedi/django-telethon","commit_stats":null,"previous_names":[],"tags_count":9,"template":false,"template_full_name":null,"purl":"pkg:github/ali-zahedi/django-telethon","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ali-zahedi%2Fdjango-telethon","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ali-zahedi%2Fdjango-telethon/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ali-zahedi%2Fdjango-telethon/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ali-zahedi%2Fdjango-telethon/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ali-zahedi","download_url":"https://codeload.github.com/ali-zahedi/django-telethon/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ali-zahedi%2Fdjango-telethon/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28505560,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-17T06:57:29.758Z","status":"ssl_error","status_checked_at":"2026-01-17T06:56:03.931Z","response_time":85,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["bot","django","library","mtproto","python","python-library","telegram","telegram-api","telethon","telethon-bot","telethon-userbot"],"created_at":"2026-01-17T09:28:38.206Z","updated_at":"2026-01-17T09:28:38.283Z","avatar_url":"https://github.com/ali-zahedi.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003c!--![GitHub All Releases](https://img.shields.io/github/downloads/ali-zahedi/django-telethon/total)--\u003e\n\u003c!--![GitHub issues](https://img.shields.io/github/issues/ali-zahedi/django-telethon)--\u003e\n![GitHub](https://img.shields.io/github/license/ali-zahedi/django-telethon)\n![GitHub](https://img.shields.io/pypi/pyversions/django-telethon.svg)\n![GitHub](https://img.shields.io/pypi/v/django-telethon.svg)\n# Django Telethon config\n\n\n  ⭐️ Thanks **everyone** who has starred the project, it means a lot!\n\nThis project is to help you use [Telethon](https://docs.telethon.dev/en/stable/index.html).\n\nDjango-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).\n\n### What is this?\n\nTelegram 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.\n\nDjango-Telethon is a session storage implementation backend for Django ORM to use telethon in Django projects.\n\n## Compatibility\n\n* Python 3.7+\n* Django 3.0+\n\n## Installation\n\n* Use the following command to install using pip:\n\n```bash\npip install django-telethon\n```\n\n**OR**\n\n* You can use the following command to set it up locally so that you can fix bugs or whatever and send pull requests:\n\n```shell script\npip install -e \".[dev]\"\npre-commit install\n```\nFor better understanding, please read the:\n* [Telethon](https://docs.telethon.dev/en/stable/index.html) documentation.\n* [Telethon Session](https://docs.telethon.dev/en/stable/modules/sessions.html) documentation.\n* [pre-commit](https://pre-commit.com/docs/installation/) documentation.\n* [pip](https://pip.pypa.io/en/stable/installing/) documentation.\n* [python package](https://packaging.python.org/en/latest/tutorials/packaging-projects/) documentation.\n* [github pull requests](https://help.github.com/en/articles/about-pull-requests/) documentation.\n\n### settings.py\n\n\n ``` python\nINSTALLED_APPS = [\n    # ....\n    'django_telethon',\n    # ...\n]\n```\n### urls.py\n\n```shell\nfrom django.contrib import admin\nfrom django.urls import path\n\nfrom django_telethon.urls import django_telethon_urls\n\nadmin.autodiscover()\n\nurlpatterns = [\n    path('admin/', admin.site.urls),\n    path('telegram/', django_telethon_urls()),\n]\n```\n### Migration\n\n\n```shell script\npython manage.py migrate\n```\n\n## Signing In\n\nBefore working with Telegram’s API, you need to get your own API ID and hash:\n\n- [Login to your Telegram account](https://my.telegram.org/auth) with the phone number of the developer account to use.\n- Click under API Development tools.\n- 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.\n- 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!\n\n***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.***\n\nRead more (proxy, bot and etc) [Here](https://docs.telethon.dev/en/stable/basic/signing-in.html).\n\n## Usage\n\n### Interactive mode\n\n1. Open a terminal and run the following command:\n\n    ```shell script\n    python manage.py shell\n    ```\n1. Enable ```DJANGO_ALLOW_ASYNC_UNSAFE``` in your environment.\n\n    ```python\n    import os\n    os.environ[\"DJANGO_ALLOW_ASYNC_UNSAFE\"] = \"true\"\n    ```\n\n1. You can import these from ```django_telethon.sessions```. For example, using the ```DjangoSession``` is done as follows:\n\n    ```python\n    from telethon.sync import TelegramClient\n    from django_telethon.sessions import DjangoSession\n    from django_telethon.models import App, ClientSession\n    from telethon.errors import SessionPasswordNeededError\n\n    # Use your own values from my.telegram.org\n    API_ID = 12345\n    API_HASH = '0123456789abcdef0123456789abcdef'\n\n    app, is_created = App.objects.update_or_create(\n        api_id=API_ID,\n        api_hash=API_HASH\n    )\n    cs, cs_is_created = ClientSession.objects.update_or_create(\n        name='default',\n    )\n    telegram_client = TelegramClient(DjangoSession(client_session=cs), app.api_id, app.api_hash)\n    telegram_client.connect()\n\n    if not telegram_client.is_user_authorized():\n        phone = input('Enter your phone number: ')\n        telegram_client.send_code_request(phone)\n        code = input('Enter the code you received: ')\n        try:\n            telegram_client.sign_in(phone, code)\n        except SessionPasswordNeededError:\n            password = input('Enter your password: ')\n            telegram_client.sign_in(password=password)\n    ```\n\n#### Doing stuffs\n\n```python\nprint((await telegram_client.get_me()).stringify())\n\nawait telegram_client.send_message('username', 'Hello! Talking to you from Telethon')\nawait telegram_client.send_file('username', '/home/myself/Pictures/holidays.jpg')\n\nawait telegram_client.download_profile_photo('me')\nmessages = await telegram_client.get_messages('username')\nawait messages[0].download_media()\n\n@telegram_client.on(telegram_client.NewMessage(pattern='(?i)hi|hello'))\nasync def handler(event):\n    await event.respond('Hey!')\n```\n\n### API\n#### User Login\n1. Run the following command to start the server:\n\n    ```shell script\n    python manage.py runserver\n    ```\n\n1. Run the following command to start telegram client:\n\n    ```shell script\n    python manage.py runtelegram\n    ```\n\n1. go to [admin panel](http://127.0.0.1:8000/admin/) and [telegram app section](http://127.0.0.1:8000/admin/django_telethon/app/). create a new app. get data from the [your Telegram account](https://my.telegram.org/auth).\n\n1. Request code from telegram:\n\n   ```python\n   import requests\n   import json\n\n   url = \"http://127.0.0.1:8000/telegram/send-code-request/\"\n\n   payload = json.dumps({\n     \"phone_number\": \"+12345678901\",\n     \"client_session_name\": \"name of the client session\"\n   })\n   headers = {\n     'Content-Type': 'application/json'\n   }\n\n   response = requests.request(\"POST\", url, headers=headers, data=payload)\n\n   print(response.text)\n    ```\n\n1. Send this request for sign in:\n\n   ```python\n   import requests\n   import json\n\n   url = \"http://127.0.0.1:8000/telegram/login-user-request/\"\n\n   payload = json.dumps({\n     \"phone_number\": \"+12345678901\",\n     \"client_session_name\": \"name of the client session\",\n     \"code\": \"1234\",\n     \"password\": \"1234\"\n   })\n   headers = {\n     'Content-Type': 'application/json'\n   }\n\n   response = requests.request(\"POST\", url, headers=headers, data=payload)\n\n   print(response.text)\n\n   ```\n\n#### Bot login\nSend this request for sign in:\n\n   ```python\n   import requests\n   import json\n\n   url = \"http://127.0.0.1:8000/telegram/login-bot-request/\"\n\n   payload = json.dumps({\n     \"bot_token\": \"bot token\",\n     \"client_session_name\": \"name of the client session\",\n   })\n   headers = {\n     'Content-Type': 'application/json'\n   }\n\n   response = requests.request(\"POST\", url, headers=headers, data=payload)\n\n   print(response.text)\n\n   ```\n\n### Server-side\n\nIf you are using **supervisord** or **another process manager**, you can use the following command to start the server:\n\n```shell script\npython manage.py runtelegram\n```\n\n#### Supervisord\n\n1. Add the following lines to your ```/etc/supervisord.d/[yourproject].ini``` file:\n\n    ```ini\n    [program:telegram_worker]\n    directory=/home/projectuser/[your_project_directory]/\n    command=/home/projectuser/venv/bin/python manage.py runtelegram\n    autostart=true\n    autorestart=true\n    stderr_logfile=/home/projectuser/logs/telegramworker.err.log\n    stdout_logfile=/home/projectuser/logs/telegramworker.out.log\n    ```\n\n1. Reload the supervisor daemon:\n\n    ```shell\n    supervisorctl reread\n    supervisorctl update\n    supervisorctl start telegram_worker\n    supervisorctl status\n    ```\n\n## Listen to events\n\nAfter login telegram client the signal `telegram_client_registered` is emitted.\n\n1. You can listen to this signal by using the following code for example put this code to your ```receivers.py``` file in app directory:\n\n   ```python\n   from functools import partial\n\n   from django.dispatch import receiver\n   from telethon import events\n\n   from django_telethon.signals import telegram_client_registered\n\n   async def event_handler(event, client_session):\n       print(client_session.name, event.raw_text, sep=' | ')\n       # if you need access to telegram client, you can use event.client\n       # telegram_client = event.client\n       await event.respond('!pong')\n\n\n   @receiver(telegram_client_registered)\n   def receiver_telegram_registered(telegram_client, client_session, *args, **kwargs):\n       handler = partial(event_handler, client_session=client_session)\n       telegram_client.add_event_handler(\n           handler,\n           events.NewMessage(incoming=True, pattern='ping'),\n       )\n\n   ```\n\n1. In the `apps.py` file, add the following code:\n\n   ```python\n   from django.apps import AppConfig\n\n   class MyAppConfig(AppConfig):\n       ...\n\n       def ready(self):\n           from .receivers import receiver_telegram_registered  # noqa: F401\n   ```\n\n1. Read more about signals in [Django signals](https://docs.djangoproject.com/en/4.0/topics/signals/)\n1. Read more about events in [Telethon events](https://docs.telethon.dev/en/stable/modules/events.html)\n\n\n\n## Django Configuration[Optional]\n\nTo configure the Django Telethon library, you need to update your Django settings. Add the following dictionary to your Django settings:\n\n```python\nDJANGO_TELETHON = {\n    'RABBITMQ_ACTIVE': True or False,   # Set to True if you want to use RabbitMQ. Otherwise, set to False.\n    'RABBITMQ_URL': 'your_rabbitmq_url',   # The URL to your RabbitMQ server.\n    'QUEUE_CHANNEL_NAME': 'your_channel_name',   # Name of the channel you want to use for the queue.\n    'QUEUE_CALLBACK': 'path_to_custom_callback'   # (Optional) Path to your custom callback. Default is 'django_telethon.callback.on_message'.\n}\n```\n\n#### Example\n```python\nDJANGO_TELETHON = {\n    'RABBITMQ_ACTIVE': True,\n    'RABBITMQ_URL': 'amqp://app:app@localhost:5672/app',\n    'QUEUE_CHANNEL_NAME': 'EXAMPLE_CHANNEL',   # Name of the channel you want to use for the queue.\n    'QUEUE_CALLBACK': 'django_telethon.callback.on_message'   # (Optional) Path to your custom callback. Default is 'django_telethon.callback.on_message'.\n}\n\n```\n\n### Default Callback\n\nBy default, the library uses a callback `on_message` which logs the received message. If you want to use a custom callback, set the `QUEUE_CALLBACK` in your settings.\n\n\n## Usage\n\nWhen 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.\n\n## Using RabbitMQ for Inter-thread Communication\nIn 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.\n\nTo solve this, Django Telethon library has introduced a mechanism to send messages across threads/machines using RabbitMQ. Here's how you can utilize it:\n\nConnect to RabbitMQ\n\nThe library initializes a connection to RabbitMQ and listens for incoming messages. Once a message arrives, the specified callback function is invoked\n\nSending Messages to Telegram Thread\n\nFor components that want to communicate with the Telegram thread, you can use the `send_to_telegra_thread` function. This function sends a message to the Telegram thread via RabbitMQ.\n\n```python\nfrom django_telethon import send_to_telegra_thread\n\n# Send a payload/message to the Telegram thread\nsend_to_telegra_thread(some_key=\"some_value\", another_key=\"another_value\")\n```\nThe `send_to_telegra_thread` function 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.\n\n## Callbacks\n\n### Default `on_message` Callback\n\nHere's the default callback provided by the library:\n\n```python\nimport logging\n\n\nasync def on_message(byte_string: bytes):\n    logging.debug(\"Received message:\", byte_string)\n\n```\n\n### Custom Callback\n\nTo use a custom callback:\n\n1. Define your custom callback function. Ensure it's an `async` function and has a single parameter of type `aio_pika.IncomingMessage`.\n2. Set the `QUEUE_CALLBACK` in `DJANGO_TELETHON` settings to point to your custom callback function's path.\n\n## License\n\nThe MIT License (MIT). Please see [License File](LICENSE) for more information.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fali-zahedi%2Fdjango-telethon","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fali-zahedi%2Fdjango-telethon","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fali-zahedi%2Fdjango-telethon/lists"}