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

discord.py使用get_channel_id作为频道ID报错AttributeError如何解决

问题排查与修复方案

核心错误原因

你遇到的AttributeError: 'NoneType' object has no attribute 'send'是因为client.get_channel返回了空值,具体由以下几个问题共同导致:

  • 未正确调用get_channel_id函数:channel = client.get_channel(id=get_channel_id) 直接传入了函数对象本身,没有执行函数获取返回值,也没有传入函数要求的入参。
  • 类型不匹配:存入welcome.json的频道ID是字符串格式,但client.get_channel要求传入整数类型的雪花ID,传入字符串会直接返回None。
  • 函数缩进错误:get_channel_id中json.load(f)行没有缩进在with open代码块内,会直接触发语法错误。
  • 入参设计不合理:on_member_join事件仅能拿到member对象,不存在message对象,无法匹配get_channel_id要求的message入参。
  • 意图权限未开启:on_member_join事件需要开启members意图才能触发,未开启时事件根本不会执行,同时需要在Discord开发者后台的机器人设置页打开Server Members Intent开关。

修正后代码

1. 初始化与通用部分

import discord
import json
import datetime

# 开启必要意图
intents = discord.Intents.default()
intents.members = True # 必须开启,否则on_member_join不会触发
client = discord.Client(intents=intents)

2. 优化后的ID获取函数

def get_channel_id(guild_id):
    with open('./json/welcome.json', 'r') as f:
        channel_id_map = json.load(f)
    # 转换为整数类型返回,适配get_channel的入参要求
    return int(channel_id_map[str(guild_id)])

3. 成员加入事件

@client.event
async def on_member_join(member):
    embed = discord.Embed(colour=0x767429, description=f"Welcome to my server! You are the {len(list(member.guild.members))}th member ")
    embed.set_thumbnail(url=f"{member.avatar_url}")
    embed.set_author(name=f"{member.name}", icon_url=f"{member.avatar_url}")
    embed.set_footer(text=f"{member.guild}", icon_url=f"{member.guild.icon_url}")
    embed.timestamp = datetime.datetime.utcnow()

    # 正确调用函数传入服务器ID,获取频道对象
    channel = client.get_channel(id=get_channel_id(member.guild.id))
    # 增加非空判断,避免异常ID导致程序崩溃
    if channel:
        await channel.send(embed=embed)

4. 欢迎频道设置命令

优化为支持直接@频道设置,无需手动输入ID,减少输入错误:

@client.command()
async def welcomechannel(ctx, channel: discord.TextChannel):
    with open('./json/welcome.json', 'r') as f:
        id_map = json.load(f)
    id_map[str(ctx.guild.id)] = channel.id
    with open('./json/welcome.json', 'w') as f:
        json.dump(id_map, f, indent=4)
    await ctx.send(f'Welcome channel changed to {channel.mention}')

注意事项

首次使用前需要先在对应服务器执行welcomechannel @目标频道命令完成配置,否则读取JSON时会抛出KeyError,也可以根据需要在get_channel_id中增加异常捕获逻辑处理未配置的情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 20:27:05