在同一参数中使用整数或字符串的Discord命令

2024-09-28 13:45:18 发布

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

我在制造一个不和机器人。此bot具有Economy命令。我的“撤回”命令只对作为参数的字符串有效。我想用参数“ALL”取所有的钱,用整数取确切的数量。代码如下:

@commands.command()
 async def withdraw(self, ctx, cantidad):
     if type(cantidad) == int and cantidad == 0:
        await ctx.send("Put a valid value")
        return                                  
                                                    
     userStr = str(ctx.message.author)           
     current_bank_balance = database.get_user_bank(userStr)                                                           
     
     if current_bank_balance == 0:                     
         await ctx.send("You dont have money")
         return                                        
                                                          
     if cantidad == "all" or cantidad == "ALL":        
         database.withdraw(userStr, current_bank_balance)
         await ctx.send(f"You withdraw {current_bank_balance} money")
     else:                   
         database.withdraw(userStr, cantidad)
         await ctx.send(f"You withdraw {cantidad} money")    

当您调用draw all时,bot会将所有的钱都带到“银行”,但如果您调用draw 60,则这不起作用


Tags: 命令yousendifbotcurrentawaitdatabase
2条回答
     @commands.command()
     async def withdraw(self, ctx, cantidad = None):
         if cantidad == None:
             await ctx.send("You need to enter an amount")
             return
         if type(cantidad) == int and cantidad == 0:
            await ctx.send("Put a valid value")
            return                                  
                                                        
         userStr = str(ctx.author)           
         current_bank_balance = database.get_user_bank(userStr)                                                           
         
         if int(current_bank_balance) == 0:                     
             await ctx.send("You dont have money")
             return                                        
                                                              
         if str(cantidad.lower()) == 'all': """This will work for 'all' 'All' 'ALl' 'AlL' etc"""
             database.withdraw(userStr, current_bank_balance)
             await ctx.send(f"You withdraw {current_bank_balance} money")

         else:                   
             database.withdraw(userStr, int(cantidad))
             await ctx.send(f"You withdraw {cantidad} money") 

我不确定这是否有效,但试试看

这是一个简单的解决办法

if type(cantidad) == int and cantidad == 0:

在这一行中,int指的是函数int(),所以你检查cantidad的类型是否为int(),你可以将int改为类型(1),它应该可以工作,或者你可以使用try-except语句

if type(cantidad) == type(1) and cantidad == 0:
try:
    cantidad=int(cantidad)
    #do the stuff if it a number
except ValueError: #if cantidad is not a number
    #do the stuff if it a string

相关问题 更多 >

    热门问题