I have the code for handler in my Telegram bot.
The bot is written in aiogram.
async def login_and_save_session(session_name, phone_number, call: types.CallbackQuery, state: FSMContext):
try:
await state.update_data(session_file_path=my_files.get_session_file_path(session_name))
session_file_path = await get_session_file_path_for_session(state=state)
client = TelegramClient(session_file_path, config.api_id, config.api_hash)
await client.connect()
if await client.is_user_authorized():
if not await client.is_user_authorized():
try:
await client.sign_in(phone=str(phone_number))
await handle_request_code(call, state)
while await get_add_session_flag(state):
await asyncio.sleep(3)
code = await get_code_for_session(state)
await client.sign_in(phone=str(phone_number), code=str(code))
except SessionPasswordNeededError:
await handle_request_2fa_password(call, state)
while await get_add_session_flag(state):
await asyncio.sleep(3)
password = await get_2fa_password_for_session(state)
await client.sign_in(password=str(password))
except Exception as e:
if client:
await client.disconnect()
if session_file_path and os.path.exists(session_file_path):
my_files.delete_file(session_file_path)
From the logs we can see that the error occurs when trying to send a code or authorize here.
if not await client.is_user_authorized():
try:
await client.sign_in(phone=str(phone_number))
await handle_request_code(call, state)
while await get_add_session_flag(state):
await asyncio.sleep(3)
code = await get_code_for_session(state)
await client.sign_in(phone=str(phone_number), code=str(code))
except SessionPasswordNeededError:
await handle_request_2fa_password(call, state)
while await get_add_session_flag(state):
await asyncio.sleep(3)
password = await get_2fa_password_for_session(state)
await client.sign_in(password=str(password))
except Exception as e:
if client:
await client.disconnect()
if session_file_path and os.path.exists(session_file_path):
my_files.delete_file(session_file_path)
I am sure that the data format is correct, but the error **bytes or str expected, not <class 'int'> ** comes out
Simplified the function and it worked.
async def send_code(phone_number):
client = TelegramClient(StringSession(), api_id, api_hash)
await client.connect()
if not await client.is_user_authorized():
await client.send_code_request(phone_number)
else:
await client.disconnect()
asyncio.run(send_code(phone_number))
But I can't make authorization inside the bot as I mentioned above.
I corrected the mistake myself.
All I had to do was to specify the parameters in client more precisely...
That's it.
client = TelegramClient(session=session_file_path, api_id=config.api_id, api_hash=config.api_hash)