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

Python discord.py on_member_join事件报NoneType无send属性错误

discord.py 新成员入群欢迎功能报错修复

问题背景

基于discord.py开发Discord机器人时,其余消息响应功能运行正常,新增on_member_join新成员入群欢迎功能持续报错,因担心版本升级破坏现有逻辑,暂未更新discord.py库版本。

问题复现代码与报错

初始实现代码:

intents = discord.Intents.all()

bot = discord.Client(intents=intents)

@bot.event
async def on_member_join(member):
    print("Recognised that a member called " + member.name + " joined")
    channel = bot.get_channel("The ID I don't want to share") # get the channel
    await channel.send("Passed")

触发首个报错:

Ignoring exception in on_member_join
Traceback (most recent call last):
  File "C:\Users\Nutzer\AppData\Local\Programs\Python\Python37-32\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "c:/Users/Nutzer/Documents/Programming/discord/main.py", line 125, in on_member_join
    await channel.send("Passed")
AttributeError: 'NoneType' object has no attribute 'send'

尝试更换旧版消息发送写法后触发第二个报错:

Ignoring exception in on_member_join
Traceback (most recent call last):
  File "C:\Users\Nutzer\AppData\Local\Programs\Python\Python37-32\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "c:/Users/Nutzer/Documents/Programming/discord/main.py", line 124, in on_member_join
    await bot.send_message(bot.get_channel("The ID I don't want to share"), 'OI MATES, gather around for ' + member.name + " joined our server.")
AttributeError: 'Client' object has no attribute 'send_message'

问题根因

  • 'NoneType' object has no attribute 'send':bot.get_channel()仅接受整数类型的频道ID入参,传入字符串格式ID时方法无法匹配到对应频道实例,返回None,对None调用send()方法必然抛出属性错误。
  • 'Client' object has no attribute 'send_message':bot.send_message()是discord.py 0.16.x及更早async分支的旧API,1.0+重写版本已经完全移除该顶层方法,消息发送统一改为调用频道、用户等实例自身的send()方法,当前运行环境使用的是重写版本,不存在该方法。
  • 隐性拦截点:代码中配置了Intents.all(),但如果未在Discord开发者后台开启对应特权网关Intent开关,on_member_join事件本身不会被触发,即使代码逻辑正确也无法运行。

修复方案(无需升级discord.py版本,无现有逻辑兼容问题)

  • 修正频道ID传参类型:将字符串格式的频道ID转为整数后传入bot.get_channel(),禁止给ID加引号。
  • 废弃旧版bot.send_message()写法,统一使用重写版的实例send()方法,该写法与当前已正常运行的消息处理逻辑API完全一致,不会产生兼容问题。
  • 校验开发者后台Intent配置:
    • 进入Discord开发者平台对应机器人的应用页面
    • 打开Bot设置 tab,下滑到Privileged Gateway Intents板块
    • 开启Server Members Intent开关并保存
    • 若机器人已加入超过100台服务器,需完成Discord官方资质验证才可使用该权限
  • 修正后可正常运行的代码参考:
@bot.event
async def on_member_join(member):
    print(f"Recognised that a member called {member.name} joined")
    # 替换为自身服务器的整数类型欢迎频道ID
    channel = bot.get_channel(123456789012345678)
    # 增加兜底判断,避免ID配置错误时直接抛出异常
    if channel:
        await channel.send(f"OI MATES, gather around for {member.name} joined our server.")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 11:21:26