如何使用discord.py检测Discord AutoMod触发事件
解决Discord AutoMod触发事件检测问题
问题背景
在Discord服务器配置AutoMod后,尝试通过discord.py机器人检测AutoMod触发事件,使用on_automod_action_execution事件但未生效,代码如下:
import discord from discord.ext import commands from discord import app_commands intents = discord.Intents.all() bot = commands.Bot(command_prefix=".", intents=intents) @bot.event async def on_ready(): print(f"Logged in as {bot.user.name} ({bot.user.id})") @bot.event async def on_automod_action_execution(action: discord.AutoModAction): try: print("AutoMod Action Executed") print(f"Rule ID: {action.rule_id}") print(f"User ID: {action.user_id}") print(f"Matched Content: {action.matched_content}") print(f"Matched Keyword: {action.matched_keyword}") print(f"Content: {action.content}") except Exception as e: print(f"Failed to handle AutoMod event: {e}")
问题原因及解决方案
1. 事件参数类型错误
on_automod_action_execution事件接收的参数是discord.AutoModActionExecution对象,而非discord.AutoModAction。后者仅代表AutoMod的动作类型,不包含触发时的上下文数据。
2. 版本与权限要求
- discord.py版本:该事件是v2.4.0及以上版本新增功能,需确保使用最新版:
pip install -U discord.py - 开发者门户权限:在Discord开发者平台的机器人页面,开启
Privileged Gateway Intents中的AutoMod Execution权限,否则机器人无法接收该事件。
修正后的代码
import discord from discord.ext import commands from discord import app_commands intents = discord.Intents.all() # 也可显式指定:intents.automod_execution = True bot = commands.Bot(command_prefix=".", intents=intents) @bot.event async def on_ready(): print(f"Logged in as {bot.user.name} ({bot.user.id})") @bot.event async def on_automod_action_execution(payload: discord.AutoModActionExecution): try: print("AutoMod Action Executed") print(f"Rule ID: {payload.rule_id}") print(f"User ID: {payload.user_id}") print(f"Matched Content: {payload.matched_content}") print(f"Matched Keyword: {payload.matched_keyword}") print(f"Original Content: {payload.content}") # 可选:获取规则名称等更多信息 rule = await payload.guild.fetch_automod_rule(payload.rule_id) print(f"Rule Name: {rule.name}") except Exception as e: print(f"Failed to handle AutoMod event: {e}") # 替换为你的机器人令牌 bot.run("YOUR_BOT_TOKEN")
内容的提问来源于stack exchange,提问作者BuddyWinte
相关产品推荐
相关产品推荐

