Discord 通知集成
本指南将带你配置 Discord webhook,并使用工具方法 sendDiscordNotification,让你能够通过 Discord 及时获取想要的通知信息。
创建 Discord Webhook
- 打开你的 Discord 服务器,先创建一个专用于通知的频道(channel)。
如果是用于内部通知,请开启 Privacy Channel,如果用于公开的通知,让所有成员看到,则关闭。

- 打开频道设置

- 新建 Webhook,复制 Webhook URL


把 Webhook URL 粘贴到环境变量 DISCORD_WEBHOOK_URL。如果你创建了多个 Webhook URL,可以增加环境变量或直接硬编码到代码中。
sendDiscordNotification 介绍与用法
sendDiscordNotification 位于 lib/discord/notifications.ts,调用它需要两个参数:
- webhookUrl:即上一步复制的 Webhook URL,当你未提供显式 URL 时,会回退到
process.env.DISCORD_WEBHOOK_URL。 - payload:这是通知内容,需要你根据要展示的内容设计,下一步会提供示例
lib/discord/notifications.ts
export async function sendDiscordNotification({
webhookUrl,
payload,
}: {
webhookUrl: string;
payload: DiscordWebhookPayload;
}): Promise<{ success: boolean; error?: string }> {
webhookUrl = webhookUrl || process.env.DISCORD_WEBHOOK_URL || '';
if (!webhookUrl) {
const message = "Discord webhook URL not provided";
console.warn(message);
return { success: false, error: message };
}
try {
const response = await fetch(webhookUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(payload),
});
if (!response.ok) {
const errorText = await response.text();
console.error('Discord webhook failed:', response.status, errorText);
return {
success: false,
error: `Discord webhook failed: ${response.status} ${errorText}`,
};
}
console.log('Discord notification sent successfully.');
return { success: true };
} catch (error) {
const errorMessage = getErrorMessage(error);
console.error('Error sending Discord notification:', errorMessage);
return { success: false, error: errorMessage };
}
}发送通知
有了上面的方法,发送功能的核心工作就是设计通知内容。
Discord Payload 支持如下元素:
content:纯文本(最多 2000 字符)。embeds:对象数组,包含title、description、color、fields、footer、thumbnail。fields:每个 embed 最多 25 个;使用inline: true实现列布局。timestamp:embed 页脚的 ISO 字符串。
通常 payload 具体无需自己编写,你只需告知 AI 你的通知需要展示哪些信息,并选中 lib/discord/notifications.ts,AI 会为你完成这项工作。
以下是简单的用法示例:
- 基础文本警报
import { sendDiscordNotification } from '@/lib/discord/notifications';
await sendDiscordNotification({
webhookUrl: '', // 可选;留空以使用 DISCORD_WEBHOOK_URL
payload: {
content: `New User:${user.email}`,
},
});- 富 embed 示例
await sendDiscordNotification({
payload: {
embeds: [
{
title: '新订阅升级',
description: `用户 **${user.name}** 已升级至 **${plan.title}**`,
color: 0x00ff7f,
fields: [
{ name: '所有者', value: user.email, inline: true },
{ name: '套餐', value: plan.title, inline: true },
],
timestamp: new Date().toISOString(),
footer: { text: '计费服务' },
},
],
},
});