【问题标题】:Discord.py Rewrite pass list into commandsDiscord.py 将传递列表重写为命令
【发布时间】:2021-09-24 08:37:54
【问题描述】:

我正在使用 Python 3.9.6 和 Discord.py 制作 Discord 机器人。我正在研究带有 2 个命令的 cog;一个从函数外部的列表中发送随机字符串消息,另一个将字符串添加到消息列表中。当我尝试传入消息变量时,一切似乎都很好,但是当我在 Discord 中测试命令时,会出现此错误消息:

discord.ext.commands.errors.MissingRequiredArgument: messages is a required argument that is missing.

我认为这意味着机器人期望用户提供messages,因此我尝试删除messages 参数。但是,当我这样做时,会出现此错误:

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'messages' is not defined

messages 在 VSCode 中有一条黄色下划线:

"messages" is not defined Pylance(reportUnidentifiedVariable)

我不知道还能尝试什么。

这是齿轮的代码:

import discord
from discord.ext

class RandomMessage(commands.cog):
    def __init__(self, client):
        self.client = client

    messages = ["This is one message", "And this is another"]

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

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

【问题讨论】:

    标签: python discord.py


    【解决方案1】:

    正如您自己编写的那样,如果您将 messages 添加为参数,则它需要用户输入。要引用messages 变量,您需要使用self.messages 调用它,因为它在一个类中。 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.")
    

    【讨论】:

      猜你喜欢
      • 2019-05-23
      • 2020-10-19
      • 2021-07-15
      • 2020-05-03
      • 2020-11-06
      • 2021-03-30
      • 2020-09-11
      • 2019-07-10
      • 2021-04-04
      相关资源
      最近更新 更多