Search code examples
djangotelegramtelethon

Using telethon with a django application


I want to watch updates on telegram messages in an django application and interact with django orm.

I found telethon library, it works with user api which is what I want.

Below code simply works on its own.

from telethon import TelegramClient
from telethon import events

api_id = 231232131
api_hash = '32131232312312312edwq'
client = TelegramClient('anon', api_id, api_hash)


@client.on(events.NewMessage)
async def my_event_handler(event):
    if 'hello' in event.raw_text:
        await event.reply('hi!')


client.start()

But telethon requires phone message verification and it needs to work in a seperate thread.

I couldn't find a way to put this code in a django application. And when django starts, I dont know how to bypass phone verification.

It should always work in an seperate loop and interact with django orm. Which is very confusing for me.


Solution

  • You can simply use django-telethon and use the API endpoints for signing bot and user session.

    1. run the following command to start the server:

      python manage.py runserver
      
    2. run the following command to start telegram client:

      python manage.py runtelegram
      
    3. go to admin panel and telegram app section. create a new app. get data from the your Telegram account.

    4. request code from telegram:

      import requests
      import json
      
      url = "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)
      
    5. send this request for sign in:

      import requests
      import json
      
      url = "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)