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

Discord.py无法从discord.app_commands导入SlashCommand问题求助

Discord Moderation Bot 导入错误解决方案

问题

开发包含/mute、/timeout和/ban斜杠命令的Discord基础 moderation bot时,运行代码始终报错:

Import Error: cannot import 'SlashCommand' from 'discord.app_commands'

原代码如下:

import discord
from discord import app_commands
from discord.app_commands import SlashCommand
from discord import Client, Intents

intents = discord.Intents.all()
intents.message_content = True

client = Client(intents=intents)

mute_command = SlashCommand(client, name="mute", description="Mutes a member for a specific reason.")

@mute_command.callback
async def mute(ctx: Interaction, member: discord.Member, reason=None):
    # Check if user has permission to mute
    if not ctx.author.guild_permissions.manage_roles:
        await ctx.send("You don't have permissions to mute members!")
        return

    # Check if bot can mute the member (consider bot hierarchy and roles)
    if member.top_role >= ctx.me.top_role:
        await ctx.send("I can't mute users with higher or equal roles!")
        return

    # Get the role for muted members (create one if it doesn't exist)
    muted_role = discord.utils.get(ctx.guild.roles, name="Muted")
    if not muted_role:
        muted_role = await ctx.guild.create_role(name="Muted")
        await muted_role.edit(permissions=discord.Permissions(speak=False))  # Remove speak permission

    # Mute the member by adding the muted role
    await member.add_roles(muted_role, reason=reason)
    await ctx.send(f"{member.mention} has been muted!")

    # Optional: Send a direct message to the muted user (with reason)
    if reason:
        await member.send(f"You have been muted in {ctx.guild.name} for: {reason}")
    else:
        await member.send(f"You have been muted in {ctx.guild.name}.")

@client.event
async def on_ready():
    await client.application_command.sync()  # Use client.application_command

    # This function runs when the bot is ready
    print(f'Logged in as {client.user} (ID: {client.user.id})')

# I swapped out "MY_TOKEN" for my bot token
client.run("MY_TOKEN")

已尝试的调试方法:

  • 更新至Python 3.12.3
  • 更新、重装及强制重装Discord.py 2.3.2
  • 使用discord_py_slash_command
  • 使用discord.interactions模块

错误原因

discord.py 2.x版本已移除SlashCommand类,该类属于旧版命令体系。同时原代码存在其他问题:

  • 未导入Interaction类导致类型注解报错
  • 命令同步写法错误(client.application_command.sync()不是正确调用方式)
  • 斜杠命令未按规范使用交互响应方法

修正后的代码

import discord
from discord import app_commands, Client, Intents, Interaction

intents = discord.Intents.all()
intents.message_content = True

client = Client(intents=intents)

@app_commands.command(name="mute", description="Mutes a member for a specific reason.")
async def mute(ctx: Interaction, member: discord.Member, reason: str = None):
    # 检查用户是否有禁言权限
    if not ctx.author.guild_permissions.manage_roles:
        await ctx.response.send_message("你没有禁言成员的权限!")
        return

    # 检查机器人是否有权限禁言该成员
    if member.top_role >= ctx.me.top_role:
        await ctx.response.send_message("我无法禁言角色等级高于或等于我的用户!")
        return

    # 获取或创建禁言角色
    muted_role = discord.utils.get(ctx.guild.roles, name="Muted")
    if not muted_role:
        muted_role = await ctx.guild.create_role(name="Muted")
        # 对所有频道应用禁言权限
        for channel in ctx.guild.channels:
            await channel.set_permissions(muted_role, speak=False, send_messages=False)

    # 为成员添加禁言角色
    await member.add_roles(muted_role, reason=reason)
    await ctx.response.send_message(f"{member.mention} 已被禁言!")

    # 可选:给被禁言用户发送私信告知原因
    try:
        if reason:
            await member.send(f"你在 {ctx.guild.name} 被禁言,原因:{reason}")
        else:
            await member.send(f"你在 {ctx.guild.name} 被禁言。")
    except discord.Forbidden:
        # 忽略用户关闭私信的情况
        pass

@client.event
async def on_ready():
    # 同步斜杠命令到Discord服务器
    await client.tree.sync()
    print(f'已登录为 {client.user} (ID: {client.user.id})')

# 替换为你的机器人令牌
client.run("MY_TOKEN")

关键修正点

  • 移除无效的SlashCommand导入,改用@app_commands.command()装饰器定义斜杠命令
  • 导入Interaction类并修正类型注解
  • 将ctx.send()改为ctx.response.send_message()(斜杠命令必须先响应交互)
  • 修正命令同步逻辑为await client.tree.sync()
  • 优化禁言角色权限设置,对所有频道应用禁言规则
  • 添加私信发送的异常处理,避免因用户关闭私信导致报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 17:43:13