Discord消息日志Bot报错:TypeError: event()缺少必选参数'coro'
解决Discord Bot的TypeError: event()缺失必填参数'coro'问题
错误原因
报错的核心问题是代码中client = commands.Bot这一行仅将commands.Bot类本身赋值给了client变量,而非创建Bot的实例对象。直接通过类调用client.event装饰器时,会因为缺少实例上下文(self参数),导致触发event()方法缺失必填参数coro的错误。
同时代码中存在重复创建client对象的冗余逻辑:先实例化了discord.Client(),随后又用commands.Bot覆盖了该对象,这也会导致功能异常。
修正步骤及完整代码
- 移除冗余的
discord.Client和client = discord.Client()代码 - 正确实例化
commands.Bot对象,必须指定command_prefix参数,同时配置Discord所需的intents(当前Discord要求启用消息内容权限才能读取消息) - 修复日志打印的字符串格式化问题,添加Bot自消息过滤逻辑
修正后的完整代码:
import os import discord from discord.ext import commands import logging # 配置intents,需先在Discord开发者门户启用消息内容权限 intents = discord.Intents.default() intents.message_content = True # 实例化Bot对象,指定命令前缀与intents client = commands.Bot(command_prefix="!", intents=intents) logging.basicConfig(filename='std.log', filemode='a', format='%(name)s - %(levelname)s - %(message)s') @client.event async def on_ready(): print(f'We have logged in as {client.user}') logging.debug('bot running') @client.event async def on_message(message): # 跳过Bot自身发送的消息 if message.author == client.user: return print("-----------------------------------") print(message.author) print(message.content) print("-----------------------------------") logging.info('-----------------------------------') logging.info(message.author) logging.info(message.content) logging.info("-----------------------------------") # 确保Bot能处理后续添加的命令(必须保留) await client.process_commands(message) token = os.environ['TOKEN'] client.run(token)
额外注意事项
- 需前往Discord开发者门户的Bot页面,启用Message Content Intent权限,否则
on_message事件无法读取到消息内容 command_prefix可根据需求自定义,例如改成"?"或其他符号
内容的提问来源于stack exchange,提问作者Ronnie Ranyard
相关产品推荐
相关产品推荐

