Discord.py handle_response函数缺失必选位置参数问题求助
问题解决方法
错误原因
报错handle_response() missing 1 required positional argument: 'user_message'的核心是调用handle_response时传递的参数数量和函数定义不匹配,同时你的handle_response函数本身还有几处问题:
- 直接对
message对象调用.lower(),若传递的是discord.Message对象会触发错误,应该取message.content再转小写; if message.author=="Desper"末尾缺少冒号,属于语法错误;str(message.author)会返回带用户标签的完整字符串(格式为用户名#数字),直接匹配"Desper"大概率不生效,应该用message.author.name获取纯用户名。
修正方案
方案一:传递完整的Message对象
- 修正
handle_response函数:
def handle_response(message) -> str: p_message = message.content.lower() # 获取不带数字标签的纯用户名 username = message.author.name if p_message == 'hello': if username == "Desper": return 'hey desper' return 'Hey there!'
- 在
on_message事件中调用函数:
@client.event async def on_message(message): if message.author == client.user: return # 直接把message对象传入函数 response = handle_response(message) await message.channel.send(response)
方案二:单独传递用户名和消息内容
如果不想传递整个Message对象,可以拆分参数:
- 修正
handle_response函数:
def handle_response(user_message, username) -> str: p_message = user_message.lower() if p_message == 'hello': if username == "Desper": return 'hey desper' return 'Hey there!'
- 在
on_message事件中调用函数:
@client.event async def on_message(message): if message.author == client.user: return username = message.author.name user_message = str(message.content) # 按函数定义传入消息内容和用户名两个参数 response = handle_response(user_message, username) await message.channel.send(response)
额外提示
- 调用
handle_response时必须保证参数数量和函数定义一致,这是解决报错的关键; - 使用
message.author.name获取纯用户名,比str(message.author)更适合直接匹配用户名。
内容的提问来源于stack exchange,提问作者Sliced Water
相关产品推荐
相关产品推荐

