Having trobles Django + Telethon

I am going to make a Django applicaton that gets telegram username as input and sends message to that username. Currently using Telethon, and creating some account in Telegram to make this possible. But my telethon threads not gonna work. Account connected and working properly (session 'anon'). Here is the views.py:

from django.shortcuts import render
from telethon.sync import TelegramClient
from django_telethon.sessions import DjangoSession
from django_telethon.models import App, ClientSession
from telethon.errors import SessionPasswordNeededError

API_ID = '12345678'
API_HASH = '123465789456123asdas'

def index(request):
    if request.method == "POST":
        app, is_created = App.objects.update_or_create(
            api_id=API_ID,
            api_hash=API_HASH
        )

        cs = ClientSession.objects.get(
            name='anon'
        )

        telegram_client = TelegramClient(DjangoSession(client_session=cs), app.api_id, app.api_hash)

        target_user = request.POST['username_telegram']
        target_user = str(target_user)

        async def send():
            try:
                await telegram_client.send_message(f'@{target_user}', 'Hello from django!')
            except ValueError:
                print(f'Sorry no {target_user} user was found')

        with telegram_client:
            telegram_client.loop.run_until_complete(send())

    return render(request, 'index.html')


Output: enter image description here

Back to Top