首页 > 解决方案 > Discord 机器人掷骰错误。为什么我的代码没有达到预期的结果?

问题描述

我目前在使用 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

标签: python-3.xdiscord.py-rewrite

解决方案


我在您的代码中发现了 4 个错误:

  1. 您说您没有收到任何错误,那是因为您使用的是 bare except。像这样简单的东西
except Exception as e:
  print(e)

会给你错误信息。如果您想要更多,您还可以打印回溯以查明错误代码。

  1. random.randint接受 2 个参数start并且end两者都是int.

    现在你只通过一个,它甚至不是一个int.

    sides[1]即使字符串包含一个数字,也会给你一个字符串,但类型仍然是一个字符串,因为.split返回一个字符串列表。因此,例如,您调用!roll d3 5sides将是一个列表["d", "3"],其中sides[1]将是一个字符串"3"

  2. rolls将成为整数列表,因为random.randint返回一个int并且您正在使用的rolls .append(result)rolls是整数列表。

    所以你不能使用", ".join(rolls),因为你会将整数加入字符串", "

    相反,您需要调用", ".join(str(number) for number in rolls),或者您可以立即将每个附加调用转换为字符串。

  3. 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


推荐阅读