python - 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))
我不确定我需要在代码中添加什么才能使参数起作用。有人能帮我吗?
解决方案
我认为你想要做的是一个 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.")
如果您想更好地了解命令系统的工作原理,您应该考虑阅读官方文档。
推荐阅读
- python - discord.py 成员角色的 If Else 语句
- typescript - Typescript 条件分型奇怪的错误案例
- crystal-reports - 当内容从字段打印到屏幕时,垂直调整组标题以适应内容
- azure-devops - 在 Azure DevOps 发布管道阶段处理多个服务器
- excel - excel:错误1004。参考无效不知道为什么
- powershell - 如何通过格式化将powershell脚本输出发送到打印机?
- json - 使用 create-react-app 并且我无法解析简单的 JSON 文件
- javascript - Javascript 输出没有改变?
- reactjs - 如何在 react.js 中更改组件背景颜色更改状态?
- operating-system - 为什么 32 位操作系统有 4 GB RAM 的限制?