Discord.py开发机器人遇TypeError: Client.event()缺失coro参数
解决Discord.py机器人启动错误:TypeError: Client.event() missing 1 required positional argument: 'coro'
错误核心原因
你用了@Bot.event装饰器,但Bot是类而非实例化后的对象。Discord.py要求必须用Bot/client的实例绑定事件,直接操作类会导致参数缺失错误。
代码里的其他问题
除了这个启动错误,你的代码还有几个需要修正的问题:
- 重复定义
on_ready和on_reaction_add:Python中重复定义函数会覆盖之前的版本,你写的两个on_ready和两个on_reaction_add最终只会执行最后一个。 - 过时方法调用:
send_message、delete_message是旧版Discord.py写法,现在需改用channel.send()和message.delete()。 - 变量名大小写不一致:比如定义了
Text = "Text1",却调用await Channel.send(text),未定义的text会引发报错。 user.server已废弃:Discord.py v1.x之后统一改为user.guild。- 未实例化Bot对象:代码末尾用
client.run(TOKEN),但全程未定义client变量。
修正后的完整代码
import discord from discord.ext import commands import os from dotenv import load_dotenv load_dotenv() TOKEN = os.getenv('DISCORD_TOKEN') # 实例化Bot对象,command_prefix可自定义,无需命令功能也可留空 bot = commands.Bot(command_prefix="!") # 读取黑名单词汇 with open("word_blacklist.txt") as file: blacklist_words = [word.strip().lower() for word in file.readlines()] @bot.event async def on_message(message): # 避免机器人触发自身逻辑 if message.author == bot.user: return message_content = message.content.strip().lower() # 检查内容而非message对象本身 if any(word in message_content for word in blacklist_words): await message.channel.send(f"{message.author.mention} watch your language!") await message.delete() # 使用commands.Bot时必须添加此句,保证命令功能正常运行 await bot.process_commands(message) @bot.event async def on_ready(): print(f"已登录为 {bot.user.name}") # 处理第一个频道的反应角色逻辑 channel1 = bot.get_channel(MY_CHANNEL_ID_1) # 替换为你的频道ID(整数) if channel1: text1 = "Text1" msg1 = await channel1.send(text1) await msg1.add_reaction('✅') # 处理第二个频道的反应角色逻辑 channel2 = bot.get_channel(MY_CHANNEL_ID_2) # 替换为你的频道ID(整数) if channel2: text2 = "Text2" msg2 = await channel2.send(text2) await msg2.add_reaction('🔴') @bot.event async def on_reaction_add(reaction, user): # 忽略机器人自身的反应 if user == bot.user: return # 第一个频道的✅反应处理 if reaction.message.channel.id == MY_CHANNEL_ID_1: if reaction.emoji == '✅': role = discord.utils.get(user.guild.roles, name="Role Name") if role: await user.add_roles(role) # 第二个频道的🔴反应处理 elif reaction.message.channel.id == MY_CHANNEL_ID_2: if reaction.emoji == '🔴': role = discord.utils.get(user.guild.roles, name="Role Name 2") if role: await user.add_roles(role) bot.run(TOKEN)
额外提示
- 将
MY_CHANNEL_ID_1、MY_CHANNEL_ID_2替换为实际的频道ID(注意是整数类型,不是字符串)。 - 若无需命令功能,可改用
discord.Client()实例化,此时不需要await bot.process_commands(message)这句代码。 - 确保Discord.py版本为最新,旧版本可能存在更多兼容性问题,可通过
pip install -U discord.py更新。
内容的提问来源于stack exchange,提问作者PetrP
相关产品推荐
相关产品推荐

