我的Python Discord Bot目前有点麻烦。我要在机器人中编程的代码部分是一个简单的骰子滚动命令,但是无论我尝试什么,我似乎都无法弄清楚如何解决它。
我要编写的命令是“!roll d(骰子上的边数)(骰子数),然后应返回指定骰子掷出的边数。例如,有人输入“ !roll d20 4”应返回“您的骰子掷骰数为:13、6、18、3”的行。这是目前为止我到目前为止的代码:
@client.command()
async def roll(ctx, sides, amount):
try:
sides = sides.split("d")
rolls = []
for number in range(amount):
result = random.randint(sides[1])
rolls.append(result)
rolls = ", ".join(rolls)
await ctx.send("Your dice rolls were: " + rolls)
except:
await ctx.send("Incorrect format for sides of dice (try something like \"!roll d6 1\").")
当我运行程序时,即使尝试将主部分移到“ try”部分之外,我也不会收到任何错误,但是我没有收到任何错误,但仍然没有收到预期的结果,例如:
try:
sides = sides.split("d")
check = True
except:
await ctx.send("Incorrect format for sides of dice (try something like \"!roll d6 1\").")
if check == True:
blah blah rest of code
答案 0 :(得分:1)
我在您的代码中发现4个错误:
except
。像except Exception as e:
print(e)
将给您错误消息。如果您想要更多,还可以打印回溯以查明错误代码。
random.randint
带有2个自变量start
和end
,都为int
。
现在您只通过了一个,甚至还没有通过int
。
sides[1]
将为您提供一个字符串,即使该字符串包含数字,但该类型仍然是字符串,因为.split
返回一个字符串列表。因此,例如,您调用了!roll d3 5
,则sides
将是列表["d", "3"]
,其中sides[1]
将是字符串"3"
您的rolls
将是一个整数列表,因为random.randint
返回一个int
,而您正在使用rolls .append(result)
,因此rolls
将是整数列表。
因此您不能使用", ".join(rolls)
,因为您将整数连接到字符串", "
相反,您需要调用", ".join(str(number) for number in rolls)
,或者可以将每个追加调用立即转换为字符串。
amount
将作为字符串传递,因此您不能使用range(amount)
,它必须为range(int(amount))
因此,完整的代码如下:
async def roll(ctx, sides, amount):
try:
sides = int(sides.split("d")[1])
rolls_list = []
for number in range(int(amount)):
# 1 is the minimum number the dice can have
rolls_list.append(random.randint(1, sides))
rolls = ", ".join(str(number) for number in rolls_list)
await ctx.send("Your dice rolls were: " + rolls)
except Exception as e:
# You should catch different exceptions for each problem and then handle them
# Exception is too broad
print(e)
await ctx.send("Incorrect format for sides of dice (try something like \"!roll d6 1\").")
您还应该检查一些输入错误,例如整数是否为负数amount