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

使用Discord.py app_commands修改机器人在线状态新手求助

解决Discord.py斜杠命令机器人在线状态修改问题

你的代码存在几处问题导致在线状态无法正常设置,以下是具体修正方案:

问题分析

  1. 缺失核心模块导入:你的Bot类继承自commands.Bot,但代码未导入discord.ext.commands模块,会直接引发报错。
  2. 错误的方法调用:setup_hook中你使用self.Bot.change_presence,但self本身就是Bot实例,正确写法是直接调用self.change_presence。
  3. 时机适配问题:setup_hook是机器人启动初期的钩子函数,此时机器人可能尚未完全连接Discord网关,在on_ready事件中设置状态更稳妥,该事件会在机器人完全就绪后触发。

修正后的完整代码

import discord
from discord import app_commands
from discord.ext import commands  # 补充缺失的必要导入

class Bot(commands.Bot):
    def __init__(self):
        intents = discord.Intents.all()
        super().__init__(command_prefix=";", intents=intents)
    
    async def setup_hook(self):
        await self.tree.sync()
        print("Synced slash commands for Kurumi")
    
    async def on_ready(self):
        # 机器人完全就绪后设置在线状态
        await self.change_presence(
            activity=discord.Activity(
                type=discord.ActivityType.listening, 
                name="Commands"
            )
        )
        print(f"已登录为 {self.user}")

client = Bot()
# 替换为你的机器人Token并启用运行
# client.run("你的机器人Token")

补充说明

如果坚持要在setup_hook中设置状态,仅需将self.Bot.change_presence改为self.change_presence即可,但on_ready事件更适配这类就绪后的初始化操作,能避免网关未连接导致的异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 01:54:27