python-3.x - 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
解决方案
我在您的代码中发现了 4 个错误:
- 您说您没有收到任何错误,那是因为您使用的是 bare
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
推荐阅读
- rust - Gtk 小部件即使在保存数据时也返回 None
- javascript - 如果表单有效,则单击按钮呈现新组件
- javascript - 与 ARRAYFORMULA 一起使用的自定义表格功能
- python - 如何生成与父进程具有相同参数的 Python 多进程?
- azure-functions - Azure Functions 消耗计划和冷启动成本
- mysql - 在每列都必须支持排序的排行榜表中存储数据的最佳方式是什么?
- r - 添加具有独特颜色和大小的自定义轴标签
- html - CSS -webkit-box-shadow 在 Microsoft Edge 中不起作用
- json - 如何在 PowerShell 中解析嵌套的 JSON?
- keycloak - Keycloak startTLS openldap 用户凭据失败