【问题标题】:Setting valid prefixes for the discord bot in discord.py在 discord.py 中为 discord 机器人设置有效前缀
【发布时间】:2021-06-09 01:03:28
【问题描述】:

所以我在 discord.py 中创建了一个不和谐机器人,当我创建一个用于设置机器人前缀的命令时,我想到了这个想法:“我如何知道用户是否为机器人输入了有效字符字首?”
例如,这里有一些机器人前缀的有效字符:'!'、'$'、'%'、'&'等...
以下是一些无效字符:'╒'、'Γ'、'▓'、'µ'、'╦'等...

这是我的代码:

@commands.command(aliases=['prefixSet']) # also I'm creating this command in a cog
@commands.has_permissions(administrator=True) # setting permission
    async def change_prefix(self, context, prefix):
        valid_prefix = ['!', '@', '#', '$', '%', '^', '&', '*','-', '_', '+', '=', '~']
        if prefix in valid_prefix:
            with open('prefixes.json', 'r') as f:
                prefixes = json.load(f)

            prefixes[str(context.guild.id)] = prefix

            with open('prefixes.json', 'w') as f:
                json.dump(prefixes, f, indent=4)
        else:
            context.send('Abnormal symbol for new prefix, try something else.')

基本上,如果用户输入的字符确实存在于@ 987654325@ list 然后它将接受该字符作为新前缀,否则它不会。
但是当我用这个'╒'字符测试它时,它仍然接受这个字符作为新的前缀,所以你们有什么解决办法吗?

【问题讨论】:

    标签: python discord.py


    【解决方案1】:

    不确定这是否会起作用,但是,您可能应该为您的 else 提供一个 return 语句,这样如果机器人没有提供有效的前缀,它就不会更改服务器的前缀。所以像这样的东西可能会起作用。另外我们不说context,我们说ctx

    @commands.command(aliases=['prefixSet']) # also I'm creating this command in a cog
    @commands.has_permissions(administrator=True) # setting permission
        async def change_prefix(self, ctx, prefix):
            valid_prefix = ['!', '@', '#', '$', '%', '^', '&', '*','-', '_', '+', '=', '~']
            if prefix not in valid_prefix: #if they don't give a valid prefix
                await ctx.send('That is not a valid prefix!')
                return #the bot won't change the prefix if it's invalid
            if prefix in valid_prefix: #if they give a valid prefix
                with open('prefixes.json', 'r') as f:
                    prefixes = json.load(f)
    
                prefixes[str(context.guild.id)] = prefix
    
                with open('prefixes.json', 'w') as f:
                    json.dump(prefixes, f, indent=4)
                await ctx.send(f'Prefix changed to {prefix}')
    

    我不是 100% 肯定这会起作用,如果您有任何错误或有任何问题,请随时提问:D

    【讨论】:

      猜你喜欢
      • 2021-09-03
      • 2021-04-25
      • 2021-02-12
      • 2021-07-18
      • 2021-05-24
      • 2021-01-01
      • 2020-11-25
      • 2020-04-07
      • 1970-01-01
      相关资源
      最近更新 更多