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

Python Discord斜杠命令机器人启动报AttributeError求助

问题解决:Discord机器人斜杠命令初始化报错

错误原因

你使用的discord_slash库已停止维护,且与新版Discord.py(v2.0+)不兼容。该库初始化时会在非异步上下文直接访问bot.loop,而Discord.py v2.0+已禁止这种操作,因此触发AttributeError。

解决方案

改用Discord.py原生的斜杠命令支持(官方维护,兼容性更好),同时调整代码结构适配新版API:

修改后的完整代码

import discord
import serial
from discord.ext import commands
from discord import app_commands

intents = discord.Intents.all()
bot = commands.Bot(command_prefix=".", intents=intents)

ledstate = False
serport = None  # 先初始化变量,后续再赋值

@bot.event
async def on_ready():
    global serport
    # 机器人就绪后再初始化串口,避免提前阻塞启动流程
    serport = serial.Serial("COM3", baudrate=9600, timeout=1)
    print(f"{bot.user.name} 已就绪")
    # 同步斜杠命令(测试阶段建议指定服务器ID,全局同步需等待1小时左右生效)
    await bot.tree.sync(guild=discord.Object(id=你的服务器ID))  # 替换为你的服务器ID,或去掉guild参数做全局同步

@bot.tree.command(name="led_on", description="打开所有LED")  # 官方斜杠命令名称不允许含空格,改用下划线
async def an(interaction: discord.Interaction):
    if serport is not None:
        serport.write(b'a')
        await interaction.response.send_message("所有LED已打开")
    else:
        await interaction.response.send_message("串口未初始化,无法执行操作")

# 替换为你的机器人TOKEN
bot.run("你的TOKEN")

关键修改点说明

  1. 移除第三方依赖:删掉discord_slash,改用Discord.py内置的discord.app_commands模块,无需额外安装库
  2. 修正命令命名:官方斜杠命令名称不支持空格,改用led_on格式
  3. 调整初始化时机:把串口初始化移到on_ready事件中,避免机器人启动时被串口操作阻塞
  4. 同步命令方式:在on_ready中调用bot.tree.sync()完成斜杠命令同步,测试阶段指定服务器ID可快速生效
  5. 替换交互对象:原生斜杠命令使用discord.Interaction替代旧的ctx,通过interaction.response.send_message()回复消息

额外注意事项

  • 确保Discord.py版本在v2.0以上,可通过pip install -U discord.py升级
  • 串口操作是同步逻辑,若需处理大量IO,建议用线程封装避免阻塞机器人事件循环

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 19:30:32