[英]Discord Bot using python sending multiple responses to one command
[英]Python: Sending an argument with a command in 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
,您可以在此處閱讀。 這是因為 arguments 是用空格分隔的,所以如果用戶問的問題跨越多個單詞,它只會顯示第一個單詞,否則會顯示整個問題。
@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.")
如果您想更好地了解命令系統的工作原理,您應該考慮閱讀官方文檔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.