Discord.py使用on_member_update实现成员离线发告别消息的问题咨询
解决方案
1. 修复on_member_update事件不触发问题
on_member_update事件无响应是因为没有启用对应的特权网关意图,按以下步骤操作:
- 打开Discord开发者平台的机器人应用配置页,进入「Bot」栏目,找到Privileged Gateway Intents区域,开启
Presence Intent和Server Members Intent两个开关 - 代码初始化客户端时,显式声明启用对应意图,示例如下:
import discord from discord.ext import commands # 配置意图 intents = discord.Intents.default() intents.presences = True # 允许获取成员在线状态 intents.members = True # 允许接收成员属性更新事件 intents.message_content = True # 保留on_message事件所需权限 client = commands.Bot(command_prefix="!", intents=intents)
2. 功能代码修复优化
你原来的代码存在几处可优化的点,调整后的完整实现如下:
# 初始化全局频道变量,避免未收到消息时报错 message_channel = None @client.event async def on_message(message): global message_channel # 忽略机器人自身发送的消息 if message.author.bot: return message_channel = message.channel # 必须添加该行,否则其他指令功能会失效 await client.process_commands(message) @client.event async def on_member_update(before, after): global message_channel print(before.status, after.status) # 直接调用内置状态枚举,避免字符串转换出错 if before.status == discord.Status.online and after.status == discord.Status.offline: print("检测到用户下线") if message_channel is None: print("未找到可用发送频道,跳过消息推送") return try: # after本身就是成员对象,无需调用.user属性,用mention可以艾特对应用户 await message_channel.send(f"Goodbye, {after.mention}") except Exception as e: print(f"告别消息发送失败: {str(e)}")
可选优化:固定消息频道
如果你的机器人只在单个服务器使用,可以直接绑定指定频道ID,不需要依赖接收消息来获取频道,稳定性更高:
# 替换为你要发送消息的频道数字ID TARGET_CHANNEL_ID = 123456789012345678 @client.event async def on_member_update(before, after): if before.status == discord.Status.online and after.status == discord.Status.offline: channel = client.get_channel(TARGET_CHANNEL_ID) if channel: await channel.send(f"Goodbye, {after.mention}")
内容的提问来源于stack exchange,提问作者Daggerpov
相关产品推荐
相关产品推荐

