You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Discord机器人执行Whitelist命令后发送Webhook?

Discord机器人Whitelist命令Webhook发送失败解决方案

问题描述

我有一个Discord机器人的「Whitelist」命令,期望用户触发后机器人发送内容为「New whitelist request」的Webhook,但始终未能实现。当前命令代码如下:

@client.tree.command(guild=TEST_GUILD, description="Whitelist")
async def whitelist(interaction: discord.Interaction):
    # Send the modal with an instance of our `Whitelist` class
    # Since modals require an interaction, they cannot be done as a response to a text command.
    # They can only be done as a response to either an application command or a button press.
    await interaction.response.send_modal(Whitelist())

我曾尝试添加第三方库的Webhook代码,但没有效果:

webhook = DiscordWebhook(url="your webhook url", content="Webhook Message")
response = webhook.execute()

原因分析

  1. 第三方库的DiscordWebhook是同步方法,而Discord.py的命令运行在异步环境中,直接调用同步方法会引发阻塞或报错。
  2. Webhook代码的执行位置可能未被正确触发。

解决方法

方法一:使用异步版第三方Webhook库

如果使用discord-webhook库,改用异步类执行:

from discord_webhook import AsyncDiscordWebhook

@client.tree.command(guild=TEST_GUILD, description="Whitelist")
async def whitelist(interaction: discord.Interaction):
    # 发送模态框
    await interaction.response.send_modal(Whitelist())
    
    # 异步发送Webhook
    webhook = AsyncDiscordWebhook(url="你的Webhook地址", content="New whitelist request")
    await webhook.execute()

方法二:使用Discord.py自带的异步Webhook支持

无需额外安装第三方库,直接用Discord.py内置功能:

from discord import Webhook, AsyncWebhookAdapter
import aiohttp

@client.tree.command(guild=TEST_GUILD, description="Whitelist")
async def whitelist(interaction: discord.Interaction):
    await interaction.response.send_modal(Whitelist())
    
    # 异步发送Webhook
    async with aiohttp.ClientSession() as session:
        webhook = Webhook.from_url("你的Webhook地址", adapter=AsyncWebhookAdapter(session))
        await webhook.send("New whitelist request", wait=False)

注意事项

  • 确认Webhook地址正确,且机器人拥有该Webhook的发送权限。
  • 确保Webhook代码放在命令函数内部,能被正确执行到。
  • 异步环境下必须使用异步方法调用,避免阻塞事件循环。

内容的提问来源于stack exchange,提问作者Quentins_dev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 08:40:07