I'm trying to use Flet libray with an async function to login into telegram. The functionality at the moment are really basic, it just detects if the user is already logged in or not, and if not opens a login page, with a phone number field and a button:
import flet as ft
from flet import AppBar, ElevatedButton, Page, Text, View, colors
from telethon import TelegramClient
import sys
import re
from asyncio import new_event_loop, run
# you can get telegram development credentials in telegram API Development Tools
api_id = '***'
api_hash = '***'
client = TelegramClient('session_name', api_id, api_hash)
def main(page: Page):
page.title = "Tel"
def startup_async():
new_event_loop().run_until_complete(startup())
def get_verif_async(phone_num):
print('ciao')
new_event_loop().run_until_complete(get_verification_code(phone_num))
async def get_verification_code(phone_number):
if phone_number and re.match(r"^\+\d+$", phone_number):
await client.send_code_request(phone_number)
else:
page.add(ft.Text(value='errore'))
#view.update()
async def startup():
print('startup')
await client.connect()
if not await client.is_user_authorized():
page.route = "/login_screen"
else:
page.route = "/homepage"
def route_change(e):
page.views.clear()
if page.route == "/login_screen":
phone_num_field = ft.TextField(hint_text="Your phone number", expand=True)
page.views.append(
View(
"/login_screen",
[
AppBar(title=Text("Login"), bgcolor=colors.SURFACE_VARIANT),
phone_num_field,
ElevatedButton(text='Get code', on_click= get_verif_async(phone_num_field.value)),
],
)
)
if page.route == "/homepage":
page.views.append(
View(
"/homepage",
[
AppBar(title=Text("homepage"), bgcolor=colors.SURFACE_VARIANT),
],
)
)
page.update()
def view_pop(e):
page.views.pop()
top_view = page.views[-1]
page.go(top_view.route)
# async script startup
startup_async()
page.on_route_change = route_change
page.on_view_pop = view_pop
page.go(page.route)
ft.app(target=main)
I don't know what I'm doing wrong but the function get_verification_code is executed all the time at startup, even if I don't click the button the function is linked to. Why?