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

使用Telethon监听Telegram更新并触发群组消息的客户端连接问题求助

Telegram监听Telegram更新并触发群组消息的客户端连接问题求助

我现在碰到一个Telethon的使用难题:想同时监听Telegram的更新,当满足特定条件时自动把消息发送到指定群组,但这两个操作没法同时正常跑起来,一直卡在客户端连接的问题上。

具体情况是这样的:

  • 要是直接调用client.send_message,不先检查客户端是否处于连接状态,就会收到错误提示:"can't send message when client is not connected"
  • 但如果我在发送消息的函数里加了连接判断,发现断开就重新连接,又会碰到*"the account is likely misusing the session: database is locked"*的错误

我用的是全局的client变量,已经在main方法里调用了client.start(),目前接收更新是完全正常的,可就是没法用这个客户端给群组发消息。下面是我的代码:

client = TelegramClient('sess', api_id, api_hash)

async def send_update_filter(html_content, group_id):
    try:
        if not client.is_connected():
            print("connecting client again")
            await client.connect()
        await client.send_message(entity=group_id,  # Group ID or username
                                  message=html_content,  # HTML message content
                                  parse_mode='html')  # Specify HTML parsing
    except Exception as e:
        print(f"Failed to send message: {e}")


async def main():
    try:
        await client.start()

        await asyncio.gather(
            get_edit_update(),
            get_updates()
        )
    except Exception as e:
        print(f"Error occurred: {e}")

    finally:
        # Ensure disconnection in all scenarios
        await client.disconnect()


if __name__ == "__main__":
    try:
        asyncio.run(main())
    except Exception as e:
        print(f"Main execution error: {e}")

有没有大佬能帮我分析下问题出在哪?怎么才能同时正常监听更新和发送消息呢?

备注:内容来源于stack exchange,提问作者Hrozone

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 14:55:26