【问题标题】:Discord.py - Changing prefix with commandDiscord.py - 使用命令更改前缀
【发布时间】:2019-11-09 19:51:02
【问题描述】:

我想创建一个命令,管理员可以更改命令的前缀(例如:而不是使用“。”他们可以将其更改为“-”,并且只有“-”才会起作用)我会能够设置权限以使只有管理员能够使用该命令

我环顾四周,通过文档和互联网,但没有找到任何东西,我也不知道如何做到这一点

【问题讨论】:

    标签: python python-3.x discord.py-rewrite


    【解决方案1】:

    您应该为discord.Bot 使用command_prefix 参数,它接受字符串(表示一个机器人范围的前缀) 或可调用的(表示返回基于前缀的函数的函数条件)

    您的条件依赖于调用message。因此,您可以允许公会定义自己的前缀。我将使用一个 dict 作为一个简单的例子:

    ...
    
    custom_prefixes = {}
    #You'd need to have some sort of persistance here,
    #possibly using the json module to save and load
    #or a database
    default_prefixes = ['.']
    
    async def determine_prefix(bot, message):
        guild = message.guild
        #Only allow custom prefixs in guild
        if guild:
            return custom_prefixes.get(guild.id, default_prefixes)
        else:
            return default_prefixes
    
    bot = commands.Bot(command_prefix = determine_prefix, ...)
    bot.run()
    
    @commands.command()
    @commands.guild_only()
    async def setprefix(self, ctx, *, prefixes=""):
        #You'd obviously need to do some error checking here
        #All I'm doing here is if prefixes is not passed then
        #set it to default 
        custom_prefixes[ctx.guild.id] = prefixes.split() or default_prefixes
        await ctx.send("Prefixes set!")
    

    关于这个使用的一个很好的例子,请参考Rapptz (discord.py 的创建者) 自己的RoboDanny bot,他将其作为教育目的的公共回购举个例子。具体来说,参见prefix_callable 函数,它是我的determine_prefix 示例的更健壮版本。

    【讨论】:

    • 您能否对其进行编辑以使其像在主 bot 文件中而不是在 cog 中一样?我无法将其从 cog 更改为 main,因为我还没有掌握 cogs 的窍门
    • 逻辑就在那里,只要发出命令,我猜你现在正在做什么。此外,请查看 RDanny bot 获取 cog 示例以提供帮助。
    • 我遵循了上面的代码,但是在command_prefix= 位我得到了这个错误(我的command_prefix= 版本是:command_prefix=determine_prefix, commands.when_mentioned)错误是:positional argument follows keyword argument 并且它突出显示(在红色)determine_prefixcommands.when_mentioned 之间的空格
    • 请参阅文档。您使用 when_mentioned 错误。请参阅when_mentioned_or的文档
    猜你喜欢
    • 2021-09-17
    • 2021-02-07
    • 2021-10-30
    • 2021-07-07
    • 2020-08-26
    • 2021-10-02
    • 2021-04-04
    • 1970-01-01
    • 2021-03-06
    相关资源
    最近更新 更多