You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Telethon send_request_code/sign_in调用失败,类型错误求助

问题排查:Telethon授权时抛出"bytes or str expected, not <class 'int'>"错误

核心问题分析

1. 错误的验证码发送逻辑

你在机器人代码中使用await client.sign_in(phone=str(phone_number))触发验证码发送,但Telethon的sign_in方法并非用于发送验证码——该方法是用来验证验证码/2FA密码的接口。正确的验证码发送方式是你测试函数中使用的send_code_request,错误调用sign_in会直接导致参数类型不匹配的异常。

2. 潜在的参数类型隐患

假设get_code_for_session返回的是整数类型(比如用户输入的验证码被存为int),即便你做了str(code)转换,若状态存储/读取过程中存在类型异常,仍可能触发该错误。需确保从状态中取出的验证码、2FA密码均为字符串类型。

3. 无效代码的语法影响

原代码中有一个空的if await client.is_user_authorized():代码块,这不仅是无效代码,还可能导致语法解析异常,干扰后续逻辑执行。

修正后的代码示例

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():
            await call.answer("当前会话已授权")
            return

        if not await client.is_user_authorized():
            try:
                # 替换为正确的验证码发送方法
                await client.send_code_request(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))
                
                await call.answer("登录成功")
                # 可在此添加会话保存后的后续逻辑
            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))
                await call.answer("2FA验证成功")
            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)
                await call.answer(f"登录失败:{str(e)}")
    except Exception as e:
        await call.answer(f"操作异常:{str(e)}")

额外排查点

  • 检查config.api_hash的类型:Telethon要求api_hash必须是字符串,若配置中误存为整数,会触发类似的类型错误。
  • 验证状态读取函数的返回值:确保get_code_for_session和get_2fa_password_for_session返回的是字符串,而非整数或其他类型。比如用户输入的验证码若被转为int存储,取出时需强制转回字符串。

内容的提问来源于stack exchange,提问作者Vladislav

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 20:24:53