Python Aiogram开发Telegram机器人反垃圾功能出现IndexError报错
Telegram机器人防重复点击提示功能报错修复
问题场景
我在实现Telegram机器人按钮频繁点击时弹出提示消息的功能,为添加多语言支持修改了防Flood函数,运行时触发了索引越界错误。
修改后报错的代码
async def anti_flood(message: types.Message, *args, **kwargs): m = args[0] await m.answer(locales.hello_user[f'anti_flood_{BotDB.user_language(message.from_user.id)}'])
报错详情
m = args[0] ~~~~^^^ IndexError: tuple index out of range
原正常运行的代码
async def anti_flood(*args, **kwargs): m = args[0] await m.answer("Not spam :) One message per second")
问题原因与解决方法
问题出在函数参数定义:原函数通过*args接收Telegram Bot API传入的触发限制的消息对象,修改后的函数把message: types.Message设为第一个位置参数,导致原本应该进入args的消息对象被这个参数接收,args变成空元组,因此取args[0]会报错。
提供两种修复方案:
- 方案一:保留
*args参数,从args中获取消息对象后处理多语言逻辑async def anti_flood(*args, **kwargs): m = args[0] user_lang = BotDB.user_language(m.from_user.id) await m.answer(locales.hello_user[f'anti_flood_{user_lang}']) - 方案二:直接用明确的参数接收消息对象,不再依赖
argsasync def anti_flood(message: types.Message, **kwargs): user_lang = BotDB.user_language(message.from_user.id) await message.answer(locales.hello_user[f'anti_flood_{user_lang}'])
内容的提问来源于stack exchange,提问作者Ivan Kachula
相关产品推荐
相关产品推荐

