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

discord.py中Slash命令custdice参数缺类型注解致Bot无法启动求助

问题解决:Discord斜杠命令带参数无法启动的修复

你的代码存在几个关键问题,直接导致机器人无法启动,逐个修复即可:

1. 斜杠命令参数必须添加类型注解

Discord.py 的@bot.tree.command()要求参数必须声明明确类型,否则机器人无法解析参数规则、完成命令注册。你需要给int1和int2加上int类型注解,让Discord识别这是整数类型参数。

2. 异步函数禁止使用同步阻塞的time.sleep()

time.sleep()会卡住整个机器人的异步事件循环,必须替换为异步版本的asyncio.sleep()。

3. 确保导入依赖模块

代码里用到的randint需要导入random模块,asyncio.sleep需要导入asyncio模块,缺失导入也会导致启动失败。

修正后的完整代码

import asyncio
import random
from discord.ext import commands

@bot.tree.command(name="custdice", description="自定义范围掷骰子")
async def custdice(interaction, int1: int, int2: int):
    # 斜杠命令需通过interaction.response发送初始响应
    msg = await interaction.response.send_message("You have rolled a dice! Rolling in progress... :game_die:")
    await asyncio.sleep(1.5)
    await msg.edit(content=f"You have rolled a dice! Rolling in progress... :game_die:\n\nThe number you rolled is {random.randint(int1, int2)}!")

额外注意事项

  • 命令修改后需要同步到Discord服务器,可在机器人启动时加入同步代码:
@bot.event
async def on_ready():
    # 全局同步(生效需约1小时),测试建议用指定服务器同步
    # await bot.tree.sync(guild=discord.Object(id=你的服务器ID))
    await bot.tree.sync()
    print(f"Logged in as {bot.user}")
  • 若仍无法启动,直接查看控制台报错信息,通常会明确指出具体问题(比如参数类型错误、模块缺失),这是新手排查问题的核心依据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 09:35:21