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

如何通过Node.js接收日程型游戏通知并转发至Discord频道?

Alright, let's get this set up step by step— I've built similar integrations for game teams before, so this should work smoothly for your schedule-based game notifications. Here's how to make Node.js receive game alerts and auto-post them to a Discord channel:

1. Prerequisites First

Before diving into code, make sure you have these ready:

  • Node.js installed on your server/local machine
  • A Discord server where you can create a webhook (head to Server Settings → Integrations → Webhooks → New Webhook to generate a URL)
  • Confirm how your game sends notifications: most modern games use HTTP POST webhooks, so we'll build around that assumption. If your game uses a different method (like polling an API endpoint), let me know and I can adjust!
2. Initialize Your Node.js Project

Start by setting up a new project and installing dependencies:

mkdir game-discord-notifier
cd game-discord-notifier
npm init -y
npm install express node-fetch

We'll use express to listen for incoming game notifications, and node-fetch to send messages to Discord's webhook API.

3. Build the Notification Receiver

Create a server.js file with this code— it sets up an endpoint to accept game notifications and forwards them to Discord:

const express = require('express');
const fetch = require('node-fetch');
const app = express();

// Parse JSON payloads from the game
app.use(express.json());

// Replace this with your Discord webhook URL
const DISCORD_WEBHOOK_URL = 'YOUR_DISCORD_WEBHOOK_URL';

// Endpoint the game will send notifications to
app.post('/api/game-alerts', async (req, res) => {
  try {
    const gameAlert = req.body;
    console.log('Received game alert:', gameAlert);

    // Forward to Discord (we'll define this function next)
    await sendToDiscord(gameAlert);

    res.status(200).send('Alert sent to Discord successfully');
  } catch (error) {
    console.error('Failed to process alert:', error);
    res.status(500).send('Error handling game alert');
  }
});

// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Notifier running on port ${PORT}`);
});
4. Format & Send Messages to Discord

Add this sendToDiscord function right above the app.listen line to format notifications properly for Discord:

async function sendToDiscord(alert) {
  // Customize messages based on alert type
  let discordPayload;
  
  switch (alert.type) {
    case 'game_launch':
      discordPayload = {
        content: `🚨 **Game is LIVE!** 🚨\n${alert.message}\nGrab your team and join now!`,
        embeds: [
          {
            title: alert.gameName,
            color: 0x00ff00, // Green for launch alerts
            footer: { text: 'Schedule-Based Game Alert' }
          }
        ]
      };
      break;
    case 'schedule_update':
      discordPayload = {
        content: `📅 **Schedule Updated!** 📅`,
        embeds: [
          {
            description: alert.message,
            fields: [{ name: 'New Details', value: alert.details }],
            color: 0xffa500, // Orange for updates
            timestamp: new Date().toISOString()
          }
        ]
      };
      break;
    default:
      // Fallback for unknown alert types
      discordPayload = {
        content: `🎮 **Game Notification** 🎮\n${alert.message}`
      };
  }

  // Send the formatted message to Discord
  const response = await fetch(DISCORD_WEBHOOK_URL, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(discordPayload)
  });

  if (!response.ok) {
    throw new Error(`Discord API error: ${response.statusText}`);
  }
}
5. Test the Setup
  • Start your server: node server.js
  • Simulate a game notification using curl or Postman:
curl -X POST http://localhost:3000/api/game-alerts \
  -H "Content-Type: application/json" \
  -d '{
    "type": "game_launch",
    "message": "Our new raid mode is live! Limited time only!",
    "gameName": "Mythic Adventures"
  }'

Check your Discord channel— you should see a nicely formatted alert pop up!

6. Optional Enhancements
  • Add authentication: Add an API key check to your /api/game-alerts endpoint to block unauthorized requests.
  • Use environment variables: Store your webhook URL and API keys in a .env file (use the dotenv package) instead of hardcoding.
  • Retry logic: Add retry handling with p-retry in case Discord's API is temporarily down.
  • Logging: Set up proper logging with winston to track all alerts and errors.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 06:56:17