【问题标题】:Passing context parameter from commands of a discord bot to own function将上下文参数从不和谐机器人的命令传递给自己的函数
【发布时间】:2021-12-09 16:52:30
【问题描述】:

我正在开发一个不和谐的机器人,并且能够使用来自discord.extcommands 向它添加一些命令。这是我当前代码的示例:

client = commands.Bot(command_prefix = '/')

# define commands
@commands.command()
async def start(ctx):
    await ctx.reply('some answer by the bot')

client.add_command(start)

所以这按预期工作,但现在我尝试将ctx 传递给我自己的函数并在那里使用它。这不像我想要的那样工作。目标是在开始某些操作之前检查特定的discord user id

def start_bot(bot_token : str):

    client = commands.Bot(command_prefix = '/')

    # define commands
    @commands.command()
    async def start(ctx):
        start_command(ctx)

    client.add_command(start)

    # run the bot
    client.run(bot_token)

def start_command(ctx):
    
    user_id = ctx.message.author.id
    
    if user_id == 1234:
        print('1234')
        # do some other stuff
    else:
        print('error')
        # do some other stuff

我需要使用awaitasync 吗? 顺便说一句:我的机器人不会崩溃,它只是永远不会在我的 start_command(ctx) 函数中打印我的两条语句之一。

【问题讨论】:

  • 当您将client 定义为您的机器人时,为什么还要使用commands.command()
  • 你的意思是因为我可以使用@client.command()?指this是等价的
  • commands.command 用于Cogs。看起来你没有使用一个,如果我错了,请纠正我。如果你定义了client 并且不使用Cogs 你不能使用commands.command...
  • @Dominik 你错了,Cogs 不需要,他可以用。
  • @Gvinfinity 你不能在Cog之外使用commands.command...看看How do I use cogs

标签: python async-await discord.py bots parameter-passing


【解决方案1】:

我现在自己发现了。使用commands.command() 不是问题。 首先我需要调用我的函数:

@commands.command()
async def start(ctx):
    await start_command(ctx)

而且我的函数需要是async:

async def start_command(ctx):

    welcome_message = 'Welcome!'
    # do some other stuff

    await ctx.send(welcome_message)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-31
    • 2017-12-25
    • 1970-01-01
    • 2018-11-10
    • 2012-08-13
    • 2018-07-21
    • 1970-01-01
    • 2015-04-17
    相关资源
    最近更新 更多