使用Python telebot库开发Telegram Bot时部分功能失效的原因排查
问题原因及修复方案
你的Telegram Bot代码存在几个关键错误,直接导致message_handler、reply_to和infinity_polling无法正常工作,具体问题和修复方法如下:
1. infinity_polling调用参数错误
bot.infinity_polling(5)的写法不符合pyTelegramBotAPI的参数规范,当前版本中infinity_polling的位置参数并非超时时间,必须显式指定参数名:
# 错误写法 bot.infinity_polling(5) # 正确写法 bot.infinity_polling(timeout=5, none_stop=True)
timeout用于设置请求超时时长,none_stop=True保证bot在网络波动后自动重连。
2. 全局消息处理器的参数与文本提取错误
全局处理器函数javab的参数应该是message对象,你错误地将其当作文本处理,且直接把整个对象转成字符串,导致永远无法匹配用户输入(转成字符串后是类似<telebot.types.Message object at 0x...>的内容):
# 错误写法 def javab(in_text): user_mess = str(in_text).lower() # 正确写法 def javab(message): # 先判断是否为文本消息,避免非文本消息触发报错 if not message.text: return user_mess = message.text.lower()
3. reply_to的参数错误
bot.reply_to的第一个参数必须是message对象,你错误地传入了处理后的文本user_mess,导致无法正确定位回复对象:
# 错误写法 bot.reply_to(user_mess, "hi bro wtf do u want") # 正确写法 bot.reply_to(message, "hi bro wtf do u want")
4. 重复函数名(潜在问题)
两个命令处理器都使用send_welcome作为函数名,虽然语法上允许,但会降低代码可读性,建议改为不同命名:
# 错误写法 @bot.message_handler(commands=['start']) def send_welcome(message): ... @bot.message_handler(commands=['help']) def send_welcome(message): ... # 正确写法 @bot.message_handler(commands=['start']) def send_start_welcome(message): bot.reply_to(message, "Howdy, how are you doing?") @bot.message_handler(commands=['help']) def send_help_info(message): bot.reply_to(message, "you can ask me datetime and hi to me and ask who am i and how am i")
5. /stop命令处理错误
if user_mess in ('/stop'):的写法错误,单元素元组必须加逗号(否则会被识别为字符串);且return 'ok good bye'无法停止bot,需要调用bot.stop_polling():
# 错误写法 if user_mess in ('/stop'): return 'ok good bye' # 正确写法 if user_mess == '/stop': bot.reply_to(message, "ok good bye") bot.stop_polling()
修复后的完整代码
import telebot import constant from datetime import datetime BOT_TOKEN = constant.api_key bot = telebot.TeleBot(BOT_TOKEN) @bot.message_handler(commands=['start']) def send_start_welcome(message): bot.reply_to(message, "Howdy, how are you doing?") @bot.message_handler(commands=['help']) def send_help_info(message): bot.reply_to(message, "you can ask me datetime and hi to me and ask who am i and how am i") @bot.message_handler(func=lambda message: True) def javab(message): if not message.text: return user_mess = message.text.lower() if user_mess in ('hi','hello','sup'): bot.reply_to(message, "hi bro wtf do u want") elif user_mess in ('time','what time is it?','time?'): now = datetime.now() date_time = now.strftime("%d/%m/%Y,%H:%M:%S") bot.reply_to(message, str(date_time)) elif user_mess in ('who are u','who are you?','you?'): bot.reply_to(message, 'non of your business , im hironside') elif user_mess in ('how are u?','how are you?'): bot.reply_to(message, 'im good') elif user_mess == '/stop': bot.reply_to(message, 'ok good bye') bot.stop_polling() else: bot.reply_to(message, 'go fly a kite') print('bot is running ......') bot.infinity_polling(timeout=5, none_stop=True)
内容的提问来源于stack exchange,提问作者hamid ironside
相关产品推荐
相关产品推荐

