【问题标题】:Reload discord bot after prefix change (Discord.py)前缀更改后重新加载不和谐机器人 (Discord.py)
【发布时间】:2022-01-21 11:57:51
【问题描述】:

问题是我想用一个命令动态地改变我的前缀。前缀在 json 文件中更新,但唯一的问题是机器人需要重新加载才能接受新的前缀。所以我需要一种方法让机器人在 config.json 中更新后立即读取新前缀。

JSON 文件: "command_prefix": "."

更新前缀 CMD:(该命令在我的核心 cog 中)

# PREFIX CHANGE COMMAND
    @commands.group(name="prefix", invoke_without_command=True)
    @commands.has_permissions(administrator=True)
    async def prefix(self, ctx):
        current_prefix = get_config_file("command_prefix")

        await ctx.channel.send(f'Current prefix is: **{current_prefix}** \n If you want to change the prefix use subcommand: _set_')

    @prefix.command(name="set")
    @commands.has_permissions(administrator=True)
    async def set(self, ctx, mode):
        mode != None

        with open('config.json', 'r') as f:
            config = json.load(f)

        config["command_prefix"] = mode

        with open('config.json', 'w') as f:
            json.dump(config, f, indent=4)
        
        f.close()
        
        await ctx.channel.send(f'Prefix has been changed to `{mode}`')

【问题讨论】:

    标签: python discord discord.py prefix


    【解决方案1】:

    当您首次初始化机器人时,它会创建一个前缀并仅在您重新创建机器人之前使用该前缀。如果您希望机器人具有不同的前缀或对其进行更新,则需要对 command_prefix 参数进行回调。

    首先创建get_prefix函数。

    async def get_prefix(bot, message): # you can also do it by guild with message argument
        return get_config_file("prefix_command")
    

    然后在 Bot 实例中

    bot = commands.Bot(command_prefix=get_prefix)
    

    注意:这两者都将在您创建机器人的主文件中。每次更新前缀时它都会立即更改。

    【讨论】:

    • 这是我的机器人实例bot = commands.Bot( command_prefix=get_config_file("command_prefix"), help_command=None, intents = intents, )
    • 是的,您目前正在获取前缀,而不是采用动态方式。用我上面显示的代码替换get_config_file("command_prefix")
    • 如果我理解正确的话,我需要在主文件中创建函数吗?但是我没有 bot 参数,因为我的 bot 在 core.py 文件中
    • @FabianHasieber 我假设 Bot 实例是在主文件中创建的。该函数应该在 Bot 实例所在的任何位置
    • 不,这不是您创建机器人的地方。通常它在main.py。您从哪里获得令牌并运行机器人?这就是所有东西都应该放置的地方
    猜你喜欢
    • 2021-10-30
    • 2021-03-10
    • 2017-09-13
    • 2023-03-20
    • 2021-07-07
    • 2017-10-15
    • 2021-06-19
    • 2021-02-15
    • 2023-01-07
    相关资源
    最近更新 更多