如何通过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:
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!
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.
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}`); });
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}`); } }
- 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!
- Add authentication: Add an API key check to your
/api/game-alertsendpoint to block unauthorized requests. - Use environment variables: Store your webhook URL and API keys in a
.envfile (use thedotenvpackage) instead of hardcoding. - Retry logic: Add retry handling with
p-retryin case Discord's API is temporarily down. - Logging: Set up proper logging with
winstonto track all alerts and errors.
内容的提问来源于stack exchange,提问作者Michael

