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

Telegram问答UserBot运行异常求助(同步/异步版本均报错)

问题:Pyrogram + g4f 开发Telegram私聊自动回复Bot时的异步/同步错误

我用Pyrogram和g4f做了个Telegram问答UserBot,想实现私聊自动回复,但运行出问题。试了同步和异步两种写法,都报错,具体代码和错误如下:

同步代码

import asyncio
from pyrogram import Client, filters
import g4f

app = Client("my_account")

@app.on_message(filters.text & filters.private)
def echo(client, message):
    result = g4f.ChatCompletion.create(
        model="gpt-3.5-turbo",
        provider=g4f.Provider.ChatBase,
        messages=[{"role": "user", "content": message.text}],
        stream=False)
    print(result)
    message.reply(result)

app.run()

同步代码报错

Task <Task pending name='Task-108' coro=<Message.reply_text() running at C:\Users\ПК\AppData\Local\Programs\Python\Python311\Lib\site-packages\pyrogram\types\messages_and_media\message.py:970> cb=[_run_until_complete_cb() at C:\Users\ПК\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py:180]> got Future <Future pending cb=[_chain_future.<locals>._call_check_cancel() at C:\Users\ПК\AppData\Local\Programs\Python\Python311\Lib\asyncio\futures.py:387]> attached to a different loop
Traceback (most recent call last):
File "C:\Users\ПК\AppData\Local\Programs\Python\Python311\Lib\site-packages\pyrogram\dispatcher.py", line 242, in handler_worker
await self.loop.run_in_executor(
File "C:\Users\ПК\AppData\Local\Programs\Python\Python311\Lib\concurrent\futures\thread.py", line 58, in run
result = self.fn(*self.args, **self.kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\ПК\Desktop\PYTHON1\Python\UserBot\Test1.py", line 18, in echo
message.reply(result)
File "C:\Users\ПК\AppData\Local\Programs\Python\Python311\Lib\site-packages\pyrogram\sync.py", line 66, in async_to_sync_wrap
return loop.run_until_complete(coroutine)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\ПК\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "C:\Users\ПК\AppData\Local\Programs\Python\Python311\Lib\site-packages\pyrogram\types\messages_and_media\message.py", line 970, in reply_text
return await self._client.send_message(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\ПК\AppData\Local\Programs\Python\Python311\Lib\site-packages\pyrogram\methods\messages\send_message.py", line 126, in send_message
r = await self.invoke(
^^^^^^^^^^^^^^^^^^
File "C:\Users\ПК\AppData\Local\Programs\Python\Python311\Lib\site-packages\pyrogram\methods\advanced\invoke.py", line 79, in invoke
r = await self.session.invoke(
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\ПК\AppData\Local\Programs\Python\Python311\Lib\site-packages\pyrogram\session\session.py", line 389, in invoke
return await self.send(query, timeout=timeout)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\ПК\AppData\Local\Programs\Python\Python311\Lib\site-packages\pyrogram\session\session.py", line 326, in send
payload = await self.loop.run_in_executor(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
RuntimeError: Task <Task pending name='Task-108' coro=<Message.reply_text() running at C:\Users\ПК\AppData\Local\Programs\Python\Python311\Lib\site-packages\pyrogram\types\messages_and_media\message.py:970> cb=[_run_until_complete_cb() at C:\Users\ПК\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py:180]> got Future <Future pending cb=[_chain_future.<locals>._call_check_cancel() at C:\Users\ПК\AppData\Local\Programs\Python\Python311\Lib\asyncio\futures.py:387]> attached to a different loop

异步代码

import asyncio
from pyrogram import Client, filters
import g4f

app = Client("my_account")

@app.on_message(filters.text & filters.private)
async def echo(client, message):
    result = g4f.ChatCompletion.create(
        model="gpt-3.5-turbo",
        provider=g4f.Provider.ChatBase,
        messages=[{"role": "user", "content": message.text}],
        stream=False)
    print(result)
    await message.reply(result)

app.run()

异步代码报错

Exception in callback Task.task_wakeup(<Future finished result=None>)
handle: <Handle Task.task_wakeup(<Future finished result=None>)>
Traceback (most recent call last):
File "C:\Users\ПК\AppData\Local\Programs\Python\Python311\Lib\asyncio\events.py", line 80, in _run
self._context.run(self._callback, *self._args)
RuntimeError: Cannot enter into task <Task pending name='Task-37' coro=<Dispatcher.handler_worker() running at C:\Users\ПК\AppData\Local\Programs\Python\Python311\Lib\site-packages\pyrogram\dispatcher.py:204> wait_for=<Future finished result=None>> while another task <Task pending name='Task-36' coro=<Dispatcher.handler_worker() running at C:\Users\ПК\AppData\Local\Programs\Python\Python311\Lib\site-packages\pyrogram\dispatcher.py:240>> is being executed.
Exception in callback Task.task_wakeup(<Future finished result=None>)
handle: <Handle Task.task_wakeup(<Future finished result=None>)>
Traceback (most recent call last):
File "C:\Users\ПК\AppData\Local\Programs\Python\Python311\Lib\asyncio\events.py", line 80, in _run
self._context.run(self._callback, *self._args)
RuntimeError: Cannot enter into task <Task pending name='Task-19' coro=<Session.ping_worker() running at C:\Users\ПК\AppData\Local\Programs\Python\Python311\Lib\site-packages\pyrogram\session\session.py:276> wait_for=<Future finished result=None>> while another task <Task pending name='Task-36' coro=<Dispatcher.handler_worker() running at C:\Users\ПК\AppData\Local\Programs\Python\Python311\Lib\site-packages\pyrogram\dispatcher.py:240>> is being executed.
Exception in callback Task.task_wakeup(<Future finished result=None>)
handle: <Handle Task.task_wakeup(<Future finished result=None>)>
Traceback (most recent call last):
File "C:\Users\ПК\AppData\Local\Programs\Python\Python311\Lib\asyncio\events.py", line 80, in _run
self._context.run(self._callback, *self._args)
RuntimeError: Cannot enter into task <Task pending name='Task-4' coro=<Session.recv_worker() running at C:\Users\ПК\AppData\Local\Programs\Python\Python311\Lib\site-packages\pyrogram\session\session.py:297> wait_for=<Future finished result=None>> while another task <Task pending name='Task-36' coro=<Dispatcher.handler_worker() running at C:\Users\ПК\AppData\Local\Programs\Python\Python311\Lib\site-packages\pyrogram\dispatcher.py:240>> is being executed.
解决方案

核心问题是g4f.ChatCompletion.create是同步阻塞方法:

  • 异步写法里直接调用会卡死Pyrogram的事件循环,引发任务冲突
  • 同步写法里调用Pyrogram的异步回复方法,会出现事件循环不匹配错误

解决思路是把g4f的同步调用放到单独线程池执行,不占用Pyrogram的异步事件循环:

import asyncio
from pyrogram import Client, filters
import g4f
from concurrent.futures import ThreadPoolExecutor

app = Client("my_account")
# 创建线程池,控制并发数
executor = ThreadPoolExecutor(max_workers=2)

@app.on_message(filters.text & filters.private)
async def echo(client, message):
    # 将g4f的同步调用委托给线程池执行
    result = await app.loop.run_in_executor(
        executor,
        lambda: g4f.ChatCompletion.create(
            model="gpt-3.5-turbo",
            provider=g4f.Provider.ChatBase,
            messages=[{"role": "user", "content": message.text}],
            stream=False
        )
    )
    print(result)
    await message.reply(result)

app.run()

如果g4f对应provider支持异步接口,也可以直接使用异步版本,但线程池方法兼容性更强,适配所有同步provider。

内容的提问来源于stack exchange,提问作者Макс

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 23:55:54