discord.py中on_message_pin与on_message_unpin事件失效求助
问题排查与修复方案
1. 事件参数类型错误
discord.py 中 on_message_pin 和 on_message_unpin 事件的参数并非直接是 message 对象,而是**discord.RawMessagePinEvent** 和 discord.RawMessageUnpinEvent(事件载荷)。你直接使用 message 作为参数,会导致事件触发时无法匹配函数签名,代码自然不会执行。
正确的做法是通过载荷中的 channel_id 和 message_id 来获取对应的消息对象:
修复后的 on_message_pin 示例:
@bot.event async def on_message_pin(payload): """Logowanie przypinania wiadomości.""" channel = bot.get_channel(payload.channel_id) if not channel: return message = await channel.fetch_message(payload.message_id) print(f"Przypinanie wiadomości: {message.id} w kanale {channel.id}") webhook_url = get_webhook_url(payload.guild_id) if webhook_url: print(f"Wysyłanie logu do webhooka: {webhook_url}") embed = discord.Embed(title="📌 Przypięto wiadomość", color=discord.Color.green()) embed.add_field(name="Kto przypiął:", value=message.author.mention, inline=False) embed.add_field(name="Kanał:", value=f"{channel.mention}", inline=False) embed.add_field(name="Link do wiadomości:", value=f"[Kliknij tutaj](https://discord.com/channels/{payload.guild_id}/{channel.id}/{message.id})", inline=False) async with aiohttp.ClientSession() as session: webhook = Webhook.from_url(webhook_url, session=session) await webhook.send(embed=embed) print("Log wiadomości przypiętej został wysłany.")
2. on_message_unpin 存在语法错误
你的 on_message_unpin 函数中的文档字符串未用引号包裹,这会直接导致语法错误,使得该事件函数无法被正确加载:
# 错误写法 async def on_message_unpin(message): Logowanie odpinania wiadomości.
需修正为带引号的文档字符串:
# 正确写法 async def on_message_unpin(payload): """Logowanie odpinania wiadomości."""
3. 补充验证:确保Intents配置正确
虽然你提到已配置Intents,但需确认已启用 guild_messages 和 message_content 权限,初始化代码示例:
intents = discord.Intents.default() intents.guild_messages = True intents.message_content = True bot = commands.Bot(command_prefix="!", intents=intents)
完整修复后的 on_message_unpin 代码
@bot.event async def on_message_unpin(payload): """Logowanie odpinania wiadomości.""" channel = bot.get_channel(payload.channel_id) if not channel: return message = await channel.fetch_message(payload.message_id) print(f"Odpinanie wiadomości: {message.id} w kanale {channel.id}") webhook_url = get_webhook_url(payload.guild_id) if webhook_url: print(f"Wysyłanie logu do webhooka: {webhook_url}") embed = discord.Embed(title="🚫 Odpinanie wiadomości", color=discord.Color.red()) embed.add_field(name="Kto odpiął:", value=message.author.mention, inline=False) embed.add_field(name="Kanał:", value=f"{channel.mention}", inline=False) embed.add_field(name="Link do wiadomości:", value=f"[Kliknij tutaj](https://discord.com/channels/{payload.guild_id}/{channel.id}/{message.id})", inline=False) async with aiohttp.ClientSession() as session: webhook = Webhook.from_url(webhook_url, session=session) await webhook.send(embed=embed) print("Log wiadomości odpiętej został wysłany.")
内容的提问来源于stack exchange,提问作者user28857236
相关产品推荐
相关产品推荐

