
在 discord 中,用户状态(如在线、离线、空闲、请勿打扰等)是其在线活动的重要指示。discord.py 提供了强大的事件机制,允许机器人监听并响应这些状态的变化。过去,on_presence_update() 事件曾被用于此目的,但现在已被弃用。当前正确且推荐的事件是 on_member_update()。
on_member_update() 事件会在服务器(Guild)中的成员信息发生变化时触发,这包括了他们的状态、昵称、角色等。该事件接收两个参数:
通过比较 before 和 after 对象的属性,我们可以精确地检测到哪些信息发生了改变。
为了让您的 Discord 机器人能够接收到成员状态更新的事件,您必须在机器人客户端中启用特定的 Intents。具体而言,您需要启用 Intents.members 和 Intents.presences。
Intents.members 允许机器人获取成员的详细信息,包括他们的角色、昵称等。 Intents.presences 允许机器人接收成员的在线状态和活动信息。
以下是如何配置 Intents 的示例:
import discord # 启用所有默认 Intents,并额外启用 members 和 presences Intents intents = discord.Intents.default() intents.members = True intents.presences = True # 创建机器人客户端实例时传入配置好的 Intents client = discord.Client(intents=intents) # 或者,如果您使用的是 commands.Bot # from discord.ext import commands # bot = commands.Bot(command_prefix='!', intents=intents)
注意事项:
一旦 Intents 配置完成,您就可以在机器人代码中实现 on_member_update() 事件处理函数。在该函数内部,我们将比较 before.status 和 after.status 来判断用户状态是否发生了变化。
import discord
# 1. 配置 Intents
intents = discord.Intents.default()
intents.members = True
intents.presences = True
client = discord.Client(intents=intents)
TARGET_CHANNEL_ID = YOUR_GENERAL_CHANNEL_ID_HERE # 替换为您的目标频道ID (例如: 123456789012345678)
TARGET_MEMBER_ID = YOUR_TARGET_MEMBER_ID_HERE # 替换为您想要监听的特定成员ID (可选,如果监听所有成员则无需)
@client.event
async def on_ready():
print(f'机器人已登录为 {client.user}')
# 验证目标频道是否存在
target_channel = client.get_channel(TARGET_CHANNEL_ID)
if not target_channel:
print(f"警告: 未找到 ID 为 {TARGET_CHANNEL_ID} 的目标频道。请检查频道 ID。")
@client.event
async def on_member_update(before: discord.Member, after: discord.Member):
# 2. 检查是否是目标成员(如果需要监听特定成员)
if TARGET_MEMBER_ID and after.id != TARGET_MEMBER_ID:
return # 如果不是目标成员,则直接返回
# 3. 检查用户状态是否发生变化
if before.status != after.status:
print(f'{after.display_name} 的状态从 {before.status} 变为 {after.status}')
# 4. 获取目标频道并发送消息
target_channel = client.get_channel(TARGET_CHANNEL_ID)
if target_channel:
message = (
f"**成员状态更新通知:**\n"
f"**成员:** {after.mention} ({after.display_name})\n"
f"**原状态:** {before.status.name.capitalize()}\n"
f"**新状态:** {after.status.name.capitalize()}"
)
try:
await target_channel.send(message)
except discord.Forbidden:
print(f"错误: 机器人没有在频道 {target_channel.name} ({target_channel.id}) 发送消息的权限。")
except Exception as e:
print(f"发送消息时发生未知错误: {e}")
else:
print(f"错误: 无法找到 ID 为 {TARGET_CHANNEL_ID} 的目标频道,无法发送通知。")
# 替换为您的机器人令牌
# client.run('YOUR_BOT_TOKEN_HERE')代码解析:
在将 YOUR_BOT_TOKEN_HERE 替换为您的机器人令牌后,运行此脚本即可启动机器人并开始监听用户状态变化。
python your_bot_file.py
通过本教程,您应该已经掌握了如何使用 Discord.py 的 on_member_update() 事件来实时监听并响应 Discord 服务器中成员的状态变化。正确配置 Intents、比较 before 和 after 状态,以及妥善处理消息发送,是构建一个能够有效监控用户动态的 Discord 机器人的关键。请务必根据您的实际需求调整代码中的频道 ID 和成员 ID,并注意机器人权限的配置。
以上就是Discord.py 教程:实时检测用户状态变化并发送通知的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号