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

discord.py调用get()方法返回None触发AttributeError如何解决?

问题原因及修复方案

核心报错原因

你遇到的AttributeError: 'NoneType' object has no attribute 'connect'报错,本质是discord.utils.get没有匹配到你指定名称的语音频道,返回了None值,你尝试调用None的connect方法才触发报错。

具体错误点排查

  • 频道名称拼接错误:循环拼接频道名时,首次拼接会额外增加一个前导空格,比如你要找的Just Chatting实际拼接出来是 Just Chatting,和真实频道名不匹配
  • 语法错误:Python列表没有contains方法,判断元素是否存在应该用in关键字
  • 异步方法调用错误:connect、play都是异步方法,必须加await关键字调用,不能直接同步执行
  • 事件循环阻塞:time.sleep是同步阻塞方法,会卡死discord机器人的事件循环,必须替换为asyncio.sleep
  • 缺少消息意图配置:新版discord.py默认关闭消息内容读取权限,不开启的话无法读取用户的消息内容
  • 没有判断频道类型:get方法默认匹配所有类型的频道,如果你指定的是文字频道,也会导致无法调用connect方法

修正后的完整代码

import discord
from discord.utils import get
import asyncio

# 开启必要的机器人权限
intents = discord.Intents.default()
intents.message_content = True
intents.voice_states = True

class MyClient(discord.Client):
    # 登录成功触发
    async def on_ready(self):
        print("Privet")
    # 收到消息触发
    async def on_message(self, message):
        if message.author == self.user:
            return

        if message.content.lower().startswith("vadim") and message.content.lower().endswith("blyat"):
            messagearray = message.content.split(" ")
            messagearray.pop() # 移除末尾的blyat
            messagearray.remove("vadim") # 移除开头的vadim

            # 修正列表存在性判断语法
            if messagearray[0].lower() == "play" and len(messagearray) != 1 and "&channel" in messagearray:
                channel_name_start_idx = messagearray.index("&channel") + 1
                # 修正频道名拼接,去掉多余的前导空格
                where = " ".join(messagearray[channel_name_start_idx:])
                print(where)

                # 限定只查找语音频道,避免匹配到文字频道
                channel = get(message.guild.voice_channels, name=where)
                if not channel:
                    await message.channel.send("找不到指定的语音频道blyat")
                    return

                # 异步调用connect方法,判断是否已经连接
                if not message.guild.voice_client:
                    voice_client = await channel.connect()
                else:
                    await message.guild.voice_client.move_to(channel)
                    voice_client = message.guild.voice_client

                # 播放国歌,播放结束后自动断开
                voice_client.play(discord.FFmpegPCMAudio('National Anthem of USSR.mp3'))
                while voice_client.is_playing():
                    await asyncio.sleep(1)
                await voice_client.disconnect()

client = MyClient(intents=intents)
# 此处替换为你的机器人Token,注意不是客户端ID
client.run("你的机器人Token")

额外注意事项

  • 运行前需要安装FFmpeg,并配置到系统环境变量中,否则无法播放音频
  • 你需要在Discord开发者后台给机器人开启Message Content Intent权限,否则无法读取用户消息内容
  • client.run参数填写的是机器人的Token,不是客户端ID,填错会导致机器人无法登录
  • 机器人需要加入服务器,并且拥有进入指定语音频道、播放音频的权限

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 16:36:03