【问题标题】:Space in the Bot Prefix机器人前缀中的空格
【发布时间】:2021-05-02 14:26:54
【问题描述】:

是否可以在服务器的前缀中留出一个空格,因为我想要,用户可以对我的机器人进行 ping 作为前缀 前缀应该是:

def get_prefix(client, message):
try:
    with open('./rsc/databases/prefixes.json', 'r') as f:
        prefixes = json.load(f)

    if str(message.guild.id) in prefixes:
        prefix = prefixes[str(message.guild.id)]
        return [str(prefix), '<@!801443216595353642>', "<@!801443216595353642> "]
    else:
        return ["!", '<@!801443216595353642>', "<@!801443216595353642> "]
except:
    return ["!", '<@!801443216595353642>', "<@!801443216595353642> "]

如果我不在服务器名称后留一个空格,它可以工作,但没有空格:/

因为如果你使用 TAB 完成 ping,它会自动设置空格:/ 所以机器人不会得到命令...

【问题讨论】:

    标签: python discord bots discord.py


    【解决方案1】:

    使用commands 扩展名,前缀中不能有空格,因为您的命令不会被检测到。您必须使用 on_message 事件手动创建命令:

    @client.event
    async def on_message(message):
        prefix = get_prefix(client, message)
        if message.content.startswith(prefix):
            #Your code
    

    【讨论】:

    • 是不是还有别的办法,比如on_message函数把空间删掉了?
    【解决方案2】:

    更新

    您可以在创建机器人时使用commands.when_mentioned_or

    from discord.ext import commands
    
    bot_prefix = commands.when_mentioned_or('!')
    
    bot=commands.Bot(command_prefix=bot_prefix)
    
    @bot.command()
    async def ping(ctx):
        await ctx.send('Pong')
    
    @bot.event
    async def on_message(message):
        await bot.process_commands(message)
    
    bot.run('token')
    

    旧方法

    您可以在处理命令之前检查on_message 事件中的每条消息,并将机器人提及更改为命令前缀。这是通过检查message.content 的开头来完成的,如果它与'&lt;@!botid&gt; ' 匹配,则将其替换为机器人前缀。

    from discord.ext import commands
    
    bot_prefix = '!'
    
    bot=commands.Bot(command_prefix=bot_prefix)
    
    @bot.command()
    async def ping(ctx):
        await ctx.send('Pong')
    
    @bot.event
    async def on_message(message):
        bot_mention_str = bot.user.mention.replace('@', '@!') + ' '
        bot_mention_len = len(bot_mention_str)
    
        if message.content[:bot_mention_len] == bot_mention_str:
            message.content = bot_prefix + message.content[bot_mention_len:]
            await bot.process_commands(message)
        else:
            await bot.process_commands(message)
    
    bot.run('token')
    

    【讨论】:

      猜你喜欢
      • 2020-12-05
      • 2021-04-09
      • 1970-01-01
      • 2017-10-15
      • 2020-10-03
      • 2021-09-03
      • 2021-04-25
      • 2021-06-19
      • 1970-01-01
      相关资源
      最近更新 更多