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

Python Telegram Bot在两台Linux设备上运行输出不一致问题求助

解决方案:Telegram Bot协程未await警告

问题原因

你遇到的警告是因为新版python-telegram-bot库中,Bot.send_message已改为异步协程方法,必须通过await关键字调用才能执行。笔记本端可能安装的是旧版库(该方法为同步实现),所以未触发警告;树莓派端的库版本为v13+,严格检测到协程未被正确执行,因此抛出警告。

修复方案

方案1:改用异步IO执行协程(推荐,符合新版库规范)

修改代码为异步结构,使用asyncio.run启动协程:

# Telegram bot practice
from bs4 import BeautifulSoup as bs
from urllib import request
import telegram
import json
import asyncio

chat_id = '********'
token = '***********************************'
bot = telegram.Bot(token=token)

async def send_message(message):
    # 用await调用异步协程方法
    await bot.send_message(chat_id=chat_id, text=f'{message}')

# 运行异步函数
asyncio.run(send_message('hey there'))

方案2:使用同步兼容写法(适配习惯同步代码的场景)

如果偏好同步逻辑,可以使用Updater类的同步包装:

# Telegram bot practice
from bs4 import BeautifulSoup as bs
from urllib import request
from telegram.ext import Updater
import json

chat_id = '********'
token = '***********************************'

def send_message(message):
    updater = Updater(token=token)
    # Updater的bot实例提供同步的send_message方法
    updater.bot.send_message(chat_id=chat_id, text=f'{message}')
    updater.stop()

send_message('hey there')

额外建议

检查两台设备的python-telegram-bot版本是否一致,执行命令查看版本:

pip show python-telegram-bot

如果版本差异导致问题,建议统一升级到最新版并使用异步写法,避免后续版本兼容问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 18:26:03