🔥🤖 使用 NodeJS 和 Novu 自动将 MEME 发布到你的 Discord 🚀🚀 TL;DR

2025-06-07

🔥🤖 使用 NodeJS 和 Novu 自动将 MEME 发布到你的 Discord 🚀🚀

TL;DR

TL;DR

在本教程中,您将学习如何使用 Novu 构建一个自动化的 Discord 机器人。该机器人会每小时将某个子版块的表情包发送到您的 Discord 频道 ⏰

自动化


Novu:开源通知基础设施🚀

简单介绍一下我们。Novu 是一个开源通知基础设施。我们主要负责管理所有产品通知。通知可以是应用内通知(类似开发者社区里的铃铛图标)、电子邮件、短信等等。

喜欢


让我们开始吧🔥

创建您的项目文件夹并运行npm init -y以添加package.json文件。



mkdir discord-bot
cd discord-bot
npm init -y


Enter fullscreen mode Exit fullscreen mode

安装 Novu SDK、  Nodemon、  Node Cron和 Fast XML Parser



npm install @novu/node fast-xml-parser node-cron nodemon


Enter fullscreen mode Exit fullscreen mode

Novu 使我们能够在 Node.js 中发送 Discord 消息,Node Cron 有助于安排任务,Fast XML Parser 可以将 XML 文件转换为 JSON,而 Nodemon 是一个 Node.js 工具,可在检测到文件更改后自动重启服务器。

创建一个index.js文件——Web 服务器的入口点。



touch index.js


Enter fullscreen mode Exit fullscreen mode

通过将启动命令添加到package.json文件中的脚本列表中来配置 Nodemon。下面的代码片段使用 Nodemon 启动服务器。



//👇🏻 In server/package.json

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon index.js"
  },


Enter fullscreen mode Exit fullscreen mode

恭喜!🎉您现在可以使用以下命令启动服务器。



npm start


Enter fullscreen mode Exit fullscreen mode

从 Reddit 获取表情包🤖

将下面的代码复制到index.js文件中。



const { XMLParser } = require("fast-xml-parser");
const parser = new XMLParser();
//👇🏻 Regex for retrieving memes image URL
const urlPattern = /https:\/\/i\.redd\.it[^"]*/g;

const getMemes = async () => {
    const matchedUrls = [];
    try {
        //👇🏻 fetch XML data
        const fetchMeme = await fetch(
            "https://www.reddit.com/r/ProgrammerHumor/.rss"
        );
        const XMLdata = await fetchMeme.text();
        //👇🏻 convert XML data to JSON format
        const jsonObj = parser.parse(XMLdata);
        const content = jsonObj.feed.entry;
        //👇🏻 map through the memes data
        const contentArray = content.map((obj) => obj.content);
        contentArray.forEach((htmlString) => {
            const matches = htmlString.match(urlPattern);
            if (matches) {
                // Add memes into an array
                matchedUrls.push(...matches);
            }
        });
        return matchedUrls;
    } catch (err) {
        console.error(err);
    }
};

//👇🏻 log memes array to the console (for testing purposes)
const logMemes = async () => {
    const memes = await getMemes();
    console.log(memes);
};

logMemes();


Enter fullscreen mode Exit fullscreen mode

上面的代码片段从ProgrammerHumor subreddit 获取 XML 数据(RSS 提要),使用 XMLParser 将其转换为 JSON 格式,然后从返回的大量数据中仅检索模因。


使用 Novu 将 Reddit 转至 Discord ✨

在这里,您将学习如何使用Novu向您的 Discord 频道发送消息  - Novu 是一种开源通知基础设施,可让您从单个仪表板发送应用内、短信、聊天、推送和电子邮件通知。

在我们继续之前,创建您的 Discord 服务器并右键单击您需要添加机器人的频道。

继续

选择Edit Channel > IntegrationsWebhooks 来创建一个新的 webhook URL。

Webhook

复制Copy Webhook URL并粘贴到计算机上的某个位置;我们很快就会用到它。

钩

创建 Novu 项目

运行下面的代码片段来创建您的 Novu 帐户。



npx novu init


Enter fullscreen mode Exit fullscreen mode

输入您的应用程序名称并登录 Novu 仪表板。以下代码片段包含运行后需要遵循的步骤npx novu init



Now let's setup your account and send your first notification
? What is your application name? Discord Bot
? Now lets setup your environment. How would you like to proceed? Create a free cloud account (Recommended)
? Create your account with: Sign-in with GitHub
? I accept the Terms and Conditions (https://novu.co/terms) and have read the Privacy Policy (https://novu.co/privacy) Yes
✔ Created your account successfully.


Enter fullscreen mode Exit fullscreen mode

访问演示页面,从页面复制您的订阅者 ID,然后单击Skip Tutorial按钮。

Novu1

接下来,在您的 Novu 集成商店中激活 Discord 聊天频道。

最后,创建一个触发聊天通知的工作流。

Novu2

从上面的代码片段中,我添加了一个变量 -{{content}}作为聊天消息内容,以使我们能够发送动态消息。

请记住从您的仪表板复制您的 API 密钥,我们将在下一节中使用它。

Discord 消息

向 Discord 频道发送消息

将以下导入添加到文件顶部index.js



const { Novu, ChatProviderIdEnum } = require("@novu/node");
const novu = new Novu("<YOUR_API_KEY>");
const subscriberId = "<YOUR_SUBSCRIBER_ID>";


Enter fullscreen mode Exit fullscreen mode

创建一个将 webhook URL 附加到您的订阅者详细信息的函数。



const sendChatMessage = async () => {
    await novu.subscribers.setCredentials(
        subscriberId,
        ChatProviderIdEnum.Discord,
        {
            webhookUrl: "<DISCORD_WEBHOOK_URL>",
        }
    );
};


Enter fullscreen mode Exit fullscreen mode

最后,更新函数以循环遍历从 subreddit 检索到的模因并将其发送到 Discord 频道。



const sendChatMessage = async () => {
    await novu.subscribers.setCredentials(
        subscriberId,
        ChatProviderIdEnum.Discord,
        {
            webhookUrl: "<DISCORD_WEBHOOK_URL>",
        }
    );
    //👇🏻 gets the memes
    const memes = await getMemes();
    //👇🏻 loops through the memes
    memes.forEach(async (meme) => {
        //👇🏻 sends the meme via Novu
        await novu
            .trigger("discord", {
                to: {
                    subscriberId,
                },
                payload: { content: meme },
            })
            .then((res) => console.log(res.data.data));
    });
};

//👇🏻 execute the function
sendChatMessage();


Enter fullscreen mode Exit fullscreen mode

上面的代码片段从前一个函数中获取模因 - getMemes(),循环遍历数组并通过 Novu 发送它们。

恭喜!模因应该会与您的 Discord 频道一起显示,如下所示。

自动化


使用 Node Cron 每小时检查一次 MEME ⏰

在这里,您将学习如何使用Node Cron安排任务- 基于 GNU crontab 的纯 JavaScript 为 Node.js 编写的微型任务调度程序。

将包导入到index.js文件中。



const cron = require("node-cron");


Enter fullscreen mode Exit fullscreen mode

然后,sendChatMessage使用 Node Cron 调用该函数。



//👇🏻 schedules the task hourly
const hourlyTask = cron.schedule("0 * * * *", sendChatMessage);

console.log("Scheduled task to run every hour.");


Enter fullscreen mode Exit fullscreen mode

上面的代码片段sendChatMessage每小时执行一次该函数,使其能够从 subreddit 获取最新和随机的模因。

恭喜您取得了如此大的进步!🎉您可以 在此处了解有关使用 Node Cron 进行调度和自动化的更多信息。


最后的注释📜

到目前为止,您已经学习了如何:

  • 将 XML 数据转换为 JSON 类型,
  • 使用 Novu 发送聊天消息,
  • 使用 Node Cron 自动执行任务,
  • 并使用 Node.js 构建一个自动化的 Discord 机器人。

机器人是旨在执行自动化任务或与人交谈的计算机程序 - Discord 机器人在诸如审核、自定义命令、管理成员请求等任务中非常有用。

今天,如果您有一个 Discord 频道,您需要一个机器人来帮助自动完成大部分审核任务。

本教程的源代码可以在这里找到:  https://github.com/novuhq/blog/tree/main/meme-discord-bot-with-novu-reddit

感谢您的阅读!

喜欢

文章来源:https://dev.to/novu/automate-memes-posting-to-your-discord-with-nodejs-and-novu-28hi
PREV
使用 NextJS 构建竞价系统
NEXT
如何在 Ubuntu 上设置 Appwrite