将不和谐机器人命令的上下文参数传递给自己的函数
Passing context parameter from commands of a discord bot to own function
我正在开发一个 discord 机器人,并且能够使用来自 discord.ext
的 commands
添加一些命令。这是我当前代码的示例:
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
我需要使用 await
和 async
吗?
顺便说一句:我的机器人没有崩溃,它只是从不在我的 start_command(ctx)
函数中打印我的 2 个语句之一。
现在我自己找到了。使用 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)
我正在开发一个 discord 机器人,并且能够使用来自 discord.ext
的 commands
添加一些命令。这是我当前代码的示例:
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
我需要使用 await
和 async
吗?
顺便说一句:我的机器人没有崩溃,它只是从不在我的 start_command(ctx)
函数中打印我的 2 个语句之一。
现在我自己找到了。使用 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)