You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Discord.py Rewrite向commands传列表时出现参数缺失、未定义报错如何解决?

问题根因

  • 你将类属性messages放入了命令的参数列表,discord.py会默认把命令方法中除ctx外的所有参数识别为需要用户输入的内容,因此触发MissingRequiredArgument报错
  • 删除参数后直接调用messages会触发未定义错误,类属性必须通过实例的self关键字访问
  • 原代码还存在导入不完整、类继承拼写错误的基础问题

修正后完整代码

import discord
import random
from discord.ext import commands

class RandomMessage(commands.Cog):
    def __init__(self, client):
        self.client = client
        # 消息列表作为实例属性存储
        self.messages = ["This is one message", "And this is another"]

    @commands.command()
    async def randmsg(self, ctx):
        await ctx.send(random.choice(self.messages))
    
    @commands.command()
    async def addmsg(self, ctx, *, message):
        self.messages.append(message)
        await ctx.send(f"{message} was added to the list of messages.")

def setup(client):
    client.add_cog(RandomMessage(client))

修改说明

  1. 补全导入:新增random模块导入、修正discord.ext导入语句为from discord.ext import commands
  2. 修正基类拼写:commands.cog改为大写开头的commands.Cog,这是discord.py规定的Cog基类写法
  3. 移除命令参数中的messages,所有对消息列表的读写都通过self.messages访问
  4. 把原类属性messages移到__init__中作为实例属性,更符合常规使用习惯,保留原来的类属性写法也可正常使用,访问方式不变

内容的提问来源于stack exchange,提问作者Ned-Arthur

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 21:27:03