是否可以为不同的命令集设置两个不同的前缀? [不和谐.py]

时间:2021-05-02 23:52:28

标签: python discord discord.py

我自己尝试过,但似乎不起作用。这是我唯一能想到的方法。

bot1 = commands.Bot(command_prefix='!')
bot2 = commands.Bot(command_prefix='?')

...

bot1.run('token')
bot2.run('token')

编辑: 这是我想要执行的命令类型的示例

py = commands.Bot(command_prefix='py')
js = commands.Bot(command_prefix='js')

@py.command("if")
async def py_if(ctx):
  ctx.send("if <cond>:")

@js.command("if")
async def js_if(ctx):
  ctx.send("if (<cond>){  }")

py.run('token')
js.run('token')

在此示例中,多个前缀将允许您为特定语言使用不同的前缀。

2 个答案:

答案 0 :(得分:1)

我在 discord.py 文档中找到了这个:

<块引用>

命令前缀是消息内容最初必须包含的内容才能调用命令。这个前缀可以是一个字符串来指示前缀应该是什么,或者是一个可调用的,它接受机器人作为它的第一个参数和 discord.Message 作为它的第二个参数并返回前缀。这是为了方便“动态”命令前缀。此可调用对象可以是常规函数或协程。

此外,您可以使用前缀字符串的集合。例如:

import random

bot = commands.Bot(command_prefix=('!', '?'))


@bot.command(name='random')
async def my_random(ctx):
    await ctx.send(random.random())


bot.run(TOKEN)

Visit documentation

编辑:来自文档链接:

<块引用>

命令前缀也可以是一个可迭代的字符串,表示应该对前缀进行多次检查,第一个匹配的将是调用前缀。您可以通过 Context.prefix 获取此前缀。为避免混淆,不允许使用空的可迭代对象。

答案 1 :(得分:1)

bot1.run('token')
bot2.run('token')

你不能这样做。 bot1.run('token') 是一个阻塞调用。 bot2.run('token') 不会被执行。因此只有 bot1 会上线。


正如 Roman 所说的 bot = commands.Bot(command_prefix=('!', '?')),您可以为同一个命令使用多个前缀。

@py.command("if")
async def py_if(ctx):
  ctx.send("if <cond>:")

@js.command("if")
async def js_if(ctx):
  ctx.send("if (<cond>){  }")

如果你想把一个命令绑定到一个特定的前缀,你必须做这样的事情

bot = commands.Bot(command_prefix=('!', '?'))

@bot.command("myCommand")
async def myCommand(ctx):
  if ctx.prefix == "!":
    await ctx.send("Command was invoked with ! prefix")

bot.run('token')

https://discordpy.readthedocs.io/en/stable/ext/commands/api.html?highlight=prefix#discord.ext.commands.Context.prefix

或:

bot = commands.Bot(command_prefix=('!', '?'))

def check_prefix(ctx):  
  return ctx.prefix == "!"    

@bot.command("myCommand")
@commands.check(check_prefix)
async def myCommand(ctx):
  await ctx.send("Command was invoked with ! prefix")

bot.run('token')
相关问题