程序问答   发布时间:2022-06-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Bot 前缀中的空格大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决Bot 前缀中的空格?

开发过程中遇到Bot 前缀中的空格的问题如何解决?下面主要结合日常开发的经验,给出你关于Bot 前缀中的空格的解决方法建议,希望对你解决Bot 前缀中的空格有所启发或帮助;

是否可以在服务器的前缀中留出一个空格,因为我希望用户可以对我的机器人进行 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> "]
except:
    return ["!","<@!801443216595353642> "]

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

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

解决方法

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

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

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

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')

大佬总结

以上是大佬教程为你收集整理的Bot 前缀中的空格全部内容,希望文章能够帮你解决Bot 前缀中的空格所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: