簡體   English   中英

Discord.py檢查輸入是否為int

[英]Discord.py check if input is int

我正在嘗試使用discord.py為我的機器人編寫一個抽獎命令,並希望它使用戶可以執行以下命令來啟動抽獎:

!raffle時間冠軍頭銜EG:!raffle 60 1派

我遇到的問題是創建驗證以檢查前兩個輸入是否為數字以及標題是否為空白。 目前,這是命令的代碼:

@bot.command(pass_context=True)
async def raffle(ctx, time, winners, title):    

    if time != int or winners != int or title != "":
        await bot.say("{} raffle has been started for {} seconds and there will be {} winner(s)!".format(title, time, winners))
    else:
        await bot.say("Seems you went wrong! Raffle format is: !raffle time winners title")
        return

但是,我沒有運氣,並遇到以下錯誤:

Ignoring exception in command raffle
Traceback (most recent call last):
  File "C:\Users\kairj\AppData\Local\Programs\Python\Python36-32\lib\site-packages\discord\ext\commands\bot.py", line 846, in process_commands
    yield from command.invoke(ctx)
  File "C:\Users\kairj\AppData\Local\Programs\Python\Python36-32\lib\site-packages\discord\ext\commands\core.py", line 367, in invoke
    yield from self.prepare(ctx)
  File "C:\Users\kairj\AppData\Local\Programs\Python\Python36-32\lib\site-packages\discord\ext\commands\core.py", line 345, in prepare
    yield from self._parse_arguments(ctx)
  File "C:\Users\kairj\AppData\Local\Programs\Python\Python36-32\lib\site-packages\discord\ext\commands\core.py", line 304, in _parse_arguments
    transformed = yield from self.transform(ctx, param)
  File "C:\Users\kairj\AppData\Local\Programs\Python\Python36-32\lib\site-packages\discord\ext\commands\core.py", line 212, in transform
    raise MissingRequiredArgument('{0.name} is a required argument that is missing.'.format(param))
discord.ext.commands.errors.MissingRequiredArgument: time is a required argument that is missing.

任何幫助都將非常有用,因為我確信這是某個地方的簡單錯誤!

提前致謝

嘗試使用isinstance代替:

if not isinstance(time, int)

您定義的實際上是兩個檢查。 第一個是要確保命令中有3個參數,第二個是要確保前兩個參數是整數。

第一個實際上是內部由ext.commands處理的。 要捕獲它,您將需要定義一個on_command_error事件方法。

@bot.event
def on_command_error(exc, ctx):
    if isinstance(exc, commands.errors.MissingRequiredArgument):
        # Send a message here
        return

    # If nothing is caught, reraise the error so that it goes to console.
    raise exc

第二個是檢查整數,就像@Luke McPuke所說的那樣

if not isinstance(time, int)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM