首页 > 解决方案 > Python:在 Discord 中使用命令发送参数

问题描述

所以,我目前正在使用 Python 开发 Discord 机器人,但我似乎已经被我的代码卡住了。当我向我发送我意识到的“.fate”命令时,我没有给出任何论据,机器人已经向我发送了回复。

这是我的代码:

import random

class Questions(commands.Cog):
  def __init__(self, client):
    self.client = client
  
  @commands.command()
  async def fate(self, ctx, arg):
    answer = ['Yes.', 'No.', 'Maybe.','In the near future.', 'Ask again later.','Reply hazy try again.', 'Most likely.', 'Better not tell you now.', 'Concentrate and ask again.', 'Cannot predict now.', 'Very doubtful.']
    value = random.choice(answer)
    await ctx.send(f'{arg} {value}')
    else:
       await ctx.send('You need to give an argument, wise one.')

def setup(client):
  client.add_cog(Questions(client))

我不确定我需要在代码中添加什么才能使参数起作用。有人能帮我吗?

标签: pythondiscord.py

解决方案


我认为你想要做的是一个 8ball 命令。

实现此目的的一种简单方法是将 arg 参数的默认值设置为 None,然后检查它是否为 None 以确定用户是否给出了参数。另请注意,我将其更改为您可以在此处*, arg阅读的内容。这是因为参数由空格分隔,因此如果用户提出的问题跨越多个单词,则只会显示第一个单词,否则将显示整个问题。

@commands.command()
async def fate(self, ctx, *, arg=None):
    if arg is None:
        await ctx.send('You need to give an argument, wise one.')
        return
    answer = ['Yes.', 'No.', 'Maybe.','In the near future.', 'Ask again later.','Reply hazy try again.', 'Most likely.', 'Better not tell you now.', 'Concentrate and ask again.', 'Cannot predict now.', 'Very doubtful.']
    value = random.choice(answer)
    await ctx.send(f'{arg} {value}')

更好的方法是通过错误处理命令,您可以在此处阅读更多内容。这具有更大的灵活性,因为您可以处理多个错误并且不会用错误处理代码阻塞主命令块。

@fate.error
async def fate_error(self, ctx, error):
    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send("You need to give an argument, wise one.")

如果您想更好地了解命令系统的工作原理,您应该考虑阅读官方文档。


推荐阅读