如何解决telebot多机器人运行时的协程未等待RuntimeWarning错误?
问题描述
我需要编写一个通过telebot运行多个机器人的程序,遇到了如下报错,请帮忙解决:
代码
def start_bot(*args): token = a.bot_token.split()[0] bot = telebot.TeleBot(token) @bot.message_handler(commands=['start']) async def start_fun(message): bot.send_message( message.chat.id, 'message', parse_mode="Markdown", reply_markup=webAppKeyboard()) bot.infinity_polling()
错误信息
C:\Users\admin\AppData\Local\Programs\Python\Python311\Lib\site-packages\telebot\util.py:100: RuntimeWarning: coroutine 'start_bot.<locals>.start_fun' was never awaited task(*args, **kwargs) RuntimeWarning: Enable tracemalloc to get the object allocation traceback
解决方案
这个报错的核心是你把消息处理函数定义成了async异步函数,但当前使用的是pyTelegramBotAPI的同步运行模式,异步函数未被正确触发执行,以下是两种解决方式:
方案1:改用同步消息处理函数
直接去掉async关键字,适配pyTelegramBotAPI默认的同步运行逻辑:
def start_bot(*args): token = a.bot_token.split()[0] bot = telebot.TeleBot(token) @bot.message_handler(commands=['start']) def start_fun(message): # 移除async关键字 bot.send_message(message.chat.id, 'message', parse_mode="Markdown", reply_markup=webAppKeyboard()) bot.infinity_polling()
方案2:切换到异步运行模式
如果确实需要使用异步函数,要改用pyTelegramBotAPI的异步实例,并通过异步框架调度:
import asyncio import telebot def start_bot(*args): token = a.bot_token.split()[0] # 初始化异步Bot实例 bot = telebot.AsyncTeleBot(token) @bot.message_handler(commands=['start']) async def start_fun(message): # 调用异步版本的send_message方法并await await bot.send_message(message.chat.id, 'message', parse_mode="Markdown", reply_markup=webAppKeyboard()) # 通过asyncio启动异步轮询 asyncio.run(bot.infinity_polling())
多机器人运行补充
要同时运行多个机器人,可通过线程或异步任务实现并发:
- 线程方式(适配同步/异步模式):
import threading # 假设你有多个机器人token列表 bot_tokens = ["token_1", "token_2", "token_3"] for token in bot_tokens: thread = threading.Thread(target=start_bot, args=(token,)) thread.start()
- 异步方式(仅适配异步Bot实例):
import asyncio async def run_multiple_bots(tokens): tasks = [] for token in tokens: bot = telebot.AsyncTeleBot(token) @bot.message_handler(commands=['start']) async def start_fun(message): await bot.send_message(message.chat.id, 'message', parse_mode="Markdown", reply_markup=webAppKeyboard()) tasks.append(bot.infinity_polling()) await asyncio.gather(*tasks) # 启动多机器人异步任务 asyncio.run(run_multiple_bots(["token_1", "token_2", "token_3"]))
内容的提问来源于stack exchange,提问作者Ggfg Dtfff
相关产品推荐
相关产品推荐

