0

我想让我的 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 仍然不响应命令。我怎样才能让它工作?

4

1 回答 1

1

使用on_message事件的时候,一定要记得添加process_commands函数,像这样:

@client.event
async def on_message(message):
    #Do Something
    await client.process_commands(message)
于 2021-04-12T12:54:30.883 回答