Py-cord中on_member_join()事件报错:缺少必填参数member
问题
我正在使用Py-cord开发Discord机器人,编写了如下代码实现成员加入日志记录功能:
import discord from discord import Option from datetime import datetime intents = discord.Intents.default() intents.members = True intents.presences = True intents.messages = True intents.message_content = True bot = discord.Bot( intents=intents, debug_guilds=[GUILD-IDs] ) @bot.event async def on_member_join(member): print(f'{datetime.utcnow()} {member} has joined {member.guild.name}, Server ID: {member.guild.id}') with open('join-log.txt', 'a') as joinlog: joinlog.writelines(f'{datetime.utcnow()} {member} has joined {member.guild.name}, Server ID: {member.guild.id}\n') bot.run("TOKEN")
但触发该事件时出现如下报错:
Traceback (most recent call last): File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 382, in _run_event await coro(*args, **kwargs) TypeError: on_member_join() missing 1 required positional argument: 'member'
奇怪的是,逻辑相同的on_member_remove()函数却能正常运行,请问这是什么问题?
问题原因与解决方法
这个报错的核心是事件触发时,on_member_join函数未接收到预期的member参数,以下是可行的解决方向:
1. 替换事件装饰器
尝试将@bot.event替换为@bot.listen(),部分场景下listen装饰器的事件绑定逻辑更稳定:
@bot.listen() async def on_member_join(member): print(f'{datetime.utcnow()} {member} has joined {member.guild.name}, Server ID: {member.guild.id}') with open('join-log.txt', 'a') as joinlog: joinlog.writelines(f'{datetime.utcnow()} {member} has joined {member.guild.name}, Server ID: {member.guild.id}\n')
2. 确认导入的是Py-cord而非discord.py
若同时安装了discord.py和Py-cord,Python可能错误导入discord.py,导致事件签名不匹配。可在代码开头添加版本验证:
import discord print(discord.__version__) # Py-cord版本通常为2.x,discord.py多为1.x或2.x但命名逻辑不同
如果导入的是discord.py,卸载后重新安装Py-cord:
pip uninstall discord.py pip install py-cord
3. 检查重复定义
确认代码中没有重复定义on_member_join函数,重复定义会覆盖原函数,导致事件绑定到错误的函数上。
4. 验证Intents配置
虽然已开启intents.members,仍需确认Discord开发者后台的Privileged Gateway Intents中,Server Members Intent已启用,同时保证代码中的Intents配置正确:
intents = discord.Intents.default() intents.members = True # 其他必要的intents保持不变
内容的提问来源于stack exchange,提问作者Luckyjazz
相关产品推荐
相关产品推荐

