【问题标题】:Changing prefixes makes the bot not respond to commands [Discord.py] [duplicate]更改前缀会使机器人不响应命令 [Discord.py] [重复]
【发布时间】:2021-07-07 13:02:32
【问题描述】:

我想让我的 Discord Bot 具有不断变化的前缀。这就是我的意思是用户(必须具有管理员权限)按照他们想要的方式设置前缀。默认前缀是&,但如果他们希望它是!,他们会使用&spr 命令,就像&spr ! 这样前缀将更改为!。这本身就很好用。然而,为了让它工作,它需要一个起始前缀,所以我这样设置它:

@client.event
async def on_guild_join(guild):
    with open('prefixes.json', 'r') as pr:
        prefixes = json.load(pr)

    prefixes[str(guild.id)] = '&'

    with open('prefixes.json', 'w') as pr:
        json.dump(prefixes, pr, indent = 4)

当机器人像这样加入服务器时,它会写入一个 json 文件:

{
    "SERVER1 ID": "&",
    "SERVER2 ID": "&",
    "SERVER3 ID": "&",
    "SERVER4 ID": "&",
    "SERVER5 ID": "&"
}

我还有一个函数,在代码的开头,它检索前缀:

def getPrefix(client, message):
    with open('prefixes.json', 'r') as pr:
        prefixes = json.load(pr)

    return prefixes[str(message.guild.id)]

并将其交给客户:

client = commands.Bot(command_prefix = getPrefix, help_command = None)

一切正常。但是,我意识到,因为它在加入服务器时将前缀添加到 json 文件中,所以如果机器人在离线时加入服务器,它不会添加它。这意味着机器人无法响应任何命令,因为它没有前缀。为了解决这个问题,我创建了一个设置事件:

@client.event
async def on_message(message):
    if message.author == client.user:
        return

    if message.content.startswith('&setup'):

        with open('prefixes.json', 'r') as pr:
            prefixes = json.load(pr)

        prefixes[str(message.guild.id)] = '&'

        with open('prefixes.json', 'w') as pr:
            json.dump(prefixes, pr, indent = 4)

它按计划将前缀&添加到json文件中。但是,即使在 json 文件中设置了前缀,机器人仍然不响应命令。我怎样才能让它发挥作用?

【问题讨论】:

  • 你在使用命令吗?即有什么谎言@bot.command()
  • @Łukasz Kwieciński 是的,感谢您再次帮助我。

标签: python discord discord.py


【解决方案1】:

当您使用on_message 事件时,您必须始终记得添加process_commands 函数,如下所示:

@client.event
async def on_message(message):
    #Do Something
    await client.process_commands(message)

【讨论】:

  • 谢谢。现在可以了。我会记住的。
猜你喜欢
  • 2021-10-30
  • 2021-10-06
  • 1970-01-01
  • 2019-11-09
  • 2022-01-21
  • 1970-01-01
  • 2021-11-10
  • 2022-01-10
  • 2023-03-20
相关资源
最近更新 更多