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

使用Discord.py调用change_presence时报NoneType无该属性如何解决

问题原因
  • 你定义的Bot类已经继承了commands.Bot,而commands.Bot本身就是discord.Client的子类,原生包含所有客户端操作方法,完全不需要额外声明独立的discord.Client实例。
  • 你在__init__中创建的self.client是一个没有经过登录流程的空客户端实例,它没有和Discord服务器建立有效websocket连接,内部的ws属性为None,调用它的change_presence方法自然就触发了属性不存在的报错。
解决方案

两步修改即可解决问题:

  1. 删除__init__方法中self.client = discord.Client()这行多余代码
  2. 将on_ready方法中调用self.client.change_presence的逻辑,改为直接调用Bot实例自身的change_presence方法

修改后的核心代码参考:

class Bot(commands.Bot):
    def __init__(self):
        super().__init__(command_prefix=_prefix_callable,
                         help_attrs=dict(hidden=True))
        self.token = credentials['token']

        for extension in INITIAL_EXTENSIONS:
            try:
                self.load_extension(extension)
            except Exception as e:
                print('Failed to load extension {}\n{}: {}'.format(extension, type(e).__name__, e))

    async def on_ready(self):
        print('Logged in as:')
        print('Username: ' + self.user.name)
        print('ID: ' + str(self.user.id))
        print('------')
        # 直接调用自身的状态修改方法即可
        await self.change_presence(status=discord.Status.idle, activity=discord.Game(name="can help"))

    async def close(self):
        await super().close()

    def run(self):
        super().run(self.token, reconnect=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 18:45:03