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

使用Pyrogram与Flask无法发送Telegram消息的问题排查

Flask + Pyrogram 发送Telegram消息时的异步循环错误

问题描述

我基于Flask开发了一个带有/listen端点的应用,意图通过Pyrogram调用Telegram API发送消息,但请求端点时触发错误:

Task <Task pending name='Task-46' coro=<AsyncToSync.main_wrap() attached to a different loop

错误发生在调用app.send_message(recipient, message_text)的代码行。

原代码

from flask import Flask, request, jsonify
from pyrogram import Client, filters

# Replace 'YOUR_API_ID' and 'YOUR_API_HASH' with your actual API credentials
API_ID = 'YOUR_API_ID'
API_HASH = 'YOUR_API_HASH'

# Create a Pyrogram client
app = Client("my_bot", api_id=API_ID, api_hash=API_HASH)

# Create a Flask web application
flask_app = Flask(__name__)

# Define a route for the '/listen' endpoint
@flask_app.route('/listen', methods=['POST'])
def listen():
    # Get the JSON data from the incoming message
    data = request.get_json()

    # Check if the message contains a 'command' key with the value 'send_message'
    if 'command' in data and data['command'] == 'send_message':
        # Extract the 'message' field from the incoming data
        message_text = data.get('message')

        # Replace 'me' with your own Telegram username or recipient chat ID
        recipient = 'me'

        # Send the message to the recipient
        app.send_message(recipient, message_text)

        return "Message sent successfully!"

    return "Command not recognized."

if __name__ == '__main__':
    # Start the Flask server
    flask_app.run(host='0.0.0.0', port=5000)

问题根源

  1. Pyrogram客户端未启动:代码仅创建了Client实例,但未调用启动方法建立Telegram连接,直接调用发送方法必然失败。
  2. 异步/同步环境冲突:Pyrogram是异步框架,而Flask默认以同步模式运行,直接在同步视图函数中调用异步方法,会导致异步任务绑定到错误的事件循环,触发报错。

修复方案

修复后的代码

from flask import Flask, request
from pyrogram import Client
import asyncio

API_ID = 'YOUR_API_ID'
API_HASH = 'YOUR_API_HASH'

# 创建Pyrogram客户端实例
tg_client = Client("my_bot", api_id=API_ID, api_hash=API_HASH)

# 初始化Flask应用(需Flask 2.0+支持异步视图)
flask_app = Flask(__name__)

# 定义异步视图函数
@flask_app.route('/listen', methods=['POST'])
async def listen():
    data = request.get_json()
    if data.get('command') == 'send_message':
        message_text = data.get('message')
        recipient = 'me'
        
        # 确保客户端已连接
        if not tg_client.is_connected:
            await tg_client.start()
        
        # 异步发送消息
        await tg_client.send_message(recipient, message_text)
        
        return "Message sent successfully!"
    return "Command not recognized."

if __name__ == '__main__':
    # 启动Flask服务
    flask_app.run(host='0.0.0.0', port=5000)

额外优化建议

  • 提前初始化连接:如果需要长期保持Telegram连接,可在启动Flask前先初始化客户端,避免每次请求重复建立连接:
    async def init_tg_connection():
        await tg_client.start()
    
    if __name__ == '__main__':
        # 先启动Telegram客户端
        asyncio.run(init_tg_connection())
        # 再启动Flask服务
        flask_app.run(host='0.0.0.0', port=5000)
    
  • 生产环境部署:生产环境建议使用ASGI服务器(如Uvicorn)运行异步Flask应用,替代默认的Werkzeug同步服务器。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 11:30:31