You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Discord.py开发1~6数字投注Bot 正确猜数仍提示失败问题求助

问题修复方案

核心错误原因

  • 类型不匹配:discord.py命令传入的参数a默认是字符串格式,你生成的随机结果r是整数格式,二者直接用==比较永远返回False,这是投注正确也判定失败的根本原因。
  • 随机范围错误:你要实现1~6的数字投注,代码里却写了random.randint(1, 2),只能生成1、2两个数字,不符合需求。
  • 冗余逻辑:你已经通过play命令的a参数接收了用户投注的数字,还额外发送了Type the number you bet on 的提示,这段逻辑完全无效。
  • 重复实例化:先创建discord.Client()对象又立刻覆盖为commands.Bot对象,属于多余代码。

修复后代码

import discord
import random
from discord.ext import commands

# 删掉重复的client初始化,直接初始化命令机器人
client = commands.Bot(command_prefix='%')

@client.event
async def on_ready():
    print('we are ready')

@client.command()
async def play(ctx, a: int): # 直接指定参数类型为int,discord.py会自动做类型转换,输入非数字会返回错误提示
    r = random.randint(1, 6) # 修改随机范围为1~6
    if a == r:
        await ctx.send(f'你赢了!生成结果是{r},你选择的是{a}')
    else:
        await ctx.send(f'你输了!生成结果是{r},你选择的是{a}')

额外优化说明

如果你需要兼容用户输入非数字的情况不报错,可以改成手动捕获转换异常,示例:

@client.command()
async def play(ctx, a):
    try:
        bet_num = int(a)
    except ValueError:
        await ctx.send('请输入有效的1~6整数数字')
        return
    if bet_num <1 or bet_num>6:
        await ctx.send('投注数字只能是1~6之间的整数')
        return
    r = random.randint(1,6)
    if bet_num == r:
        await ctx.send(f'你赢了!生成结果是{r},你选择的是{bet_num}')
    else:
        await ctx.send(f'你输了!生成结果是{r},你选择的是{bet_num}')

内容的提问来源于stack exchange,提问作者Fame Star

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 23:33:00