Python:使用Discord命令发送参数

2024-05-13 23:22:05 发布

您现在位置:Python中文网/ 问答频道 /正文

所以,我目前正在使用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))

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


Tags: 代码answerselfclientvaluedefarg机器人
1条回答
网友
1楼 · 发布于 2024-05-13 23:22:05

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

实现这一点的简单方法是将arg参数的默认值设置为None,然后检查它是否为None,以确定用户是否给出了参数。还请注意,我将其更改为*, arg,您可以阅读关于here的内容。这是因为参数之间用空格分隔,因此如果用户问的问题跨越多个单词,它将只显示第一个单词,否则,通过此项添加,它将显示整个问题

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

执行此操作的更好方法是错误处理命令,您可以在here上阅读更多内容。这具有更大的灵活性,因为您可以处理多个错误,而不会用错误处理代码阻塞主命令块

@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.")
如果你想更好地了解命令系统是如何工作的,你应该考虑阅读official documentation

相关问题 更多 >