discord.py中是否存在类似onFirendRequestAccepted的好友请求接受事件触发器?
关于Discord.py中监听好友请求被接受的事件
首先直接给结论:Discord.py 并没有原生提供一个名为 on_friend_request_accepted 的直接事件触发器,但我们可以通过监听关系更新/添加事件来实现完全相同的效果——毕竟当好友请求被接受时,你和对方的关系状态会从"待确认"转变为"好友"。
具体实现步骤
开启关系意图
要接收关系相关的事件,你必须在实例化Bot/Client时开启relationships意图,否则Discord API不会推送这类事件给你的客户端。监听关系添加事件
在Discord.py v2.x版本中,可以使用on_relationship_add事件来捕获新建立的关系(包括好友请求被接受的情况)。下面是一个完整的示例代码:
import discord from discord.ext import commands # 配置意图,必须开启relationships intents = discord.Intents.default() intents.relationships = True intents.message_content = True # 如果你的函数需要处理消息,可根据需求添加 bot = commands.Bot(command_prefix="!", intents=intents) async def your_target_function(user: discord.User): """你想要在好友请求被接受时执行的指定函数""" print(f"正在执行指定逻辑,用户:{user.name}#{user.discriminator}") # 这里可以添加你的业务代码,比如发送欢迎消息、记录好友列表等 try: await user.send("嘿!很高兴和你成为好友😉") except discord.Forbidden: print(f"无法给用户 {user.name} 发送消息,可能对方关闭了陌生人消息权限") @bot.event async def on_relationship_add(relationship): # 只处理"好友"类型的关系 if relationship.type == discord.RelationshipType.friend: # 可以通过direction区分是你加别人被接受,还是你接受了别人的请求 # RelationshipDirection.outgoing 表示是你主动发送的请求被对方接受 if relationship.direction == discord.RelationshipDirection.outgoing: print(f"你的好友请求被 {relationship.user.name}#{relationship.user.discriminator} 接受了!") await your_target_function(relationship.user) @bot.event async def on_ready(): print(f"已登录为 {bot.user.display_name},等待好友请求事件...") # 替换成你的token bot.run("YOUR_BOT_OR_USER_TOKEN")
注意事项
- 如果你使用的是用户token(而非机器人应用的token)来运行客户端,这属于Discord服务条款中禁止的"自机器人"行为,可能会导致账号被封禁,请谨慎操作。
- 部分用户可能关闭了陌生人消息权限,所以在给新好友发送消息时最好添加异常捕获,避免程序报错。
内容的提问来源于stack exchange,提问作者Dmitry Arkhipenko
相关产品推荐
相关产品推荐

