Notification-Bot: Discord-Benachrichtigungen für Streams
- Neues Notification-Plugin mit eigenem Discord-Bot - Admin-Modal im Streaming-Tab für Channel-Konfiguration - Automatische Benachrichtigungen bei Stream-Start/Ende - Stream-Links mit Passwort-Hinweis in Discord-Embeds - Konfigurierbare Events pro Channel (stream_start, stream_end) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
parent
b25ae7990b
commit
1cf79ef917
5 changed files with 672 additions and 0 deletions
|
|
@ -14,6 +14,7 @@ import lolstatsPlugin from './plugins/lolstats/index.js';
|
|||
import streamingPlugin, { attachWebSocket } from './plugins/streaming/index.js';
|
||||
import watchTogetherPlugin, { attachWatchTogetherWs } from './plugins/watch-together/index.js';
|
||||
import gameLibraryPlugin from './plugins/game-library/index.js';
|
||||
import notificationsPlugin from './plugins/notifications/index.js';
|
||||
|
||||
// ── Config ──
|
||||
const PORT = Number(process.env.PORT ?? 8080);
|
||||
|
|
@ -25,6 +26,7 @@ const ALLOWED_GUILD_IDS = (process.env.ALLOWED_GUILD_IDS ?? '')
|
|||
// Per-bot tokens (DISCORD_TOKEN is legacy fallback for jukebox/soundboard)
|
||||
const TOKEN_JUKEBOX = process.env.DISCORD_TOKEN_JUKEBOX ?? process.env.DISCORD_TOKEN ?? '';
|
||||
const TOKEN_RADIO = process.env.DISCORD_TOKEN_RADIO ?? '';
|
||||
const TOKEN_NOTIFICATIONS = process.env.DISCORD_TOKEN_NOTIFICATIONS ?? '';
|
||||
|
||||
// ── Persistence ──
|
||||
loadState();
|
||||
|
|
@ -43,6 +45,9 @@ if (TOKEN_JUKEBOX) clients.push({ name: 'Jukebox', client: clientJukebox, token:
|
|||
const clientRadio = createClient();
|
||||
if (TOKEN_RADIO) clients.push({ name: 'Radio', client: clientRadio, token: TOKEN_RADIO });
|
||||
|
||||
const clientNotifications = createClient();
|
||||
if (TOKEN_NOTIFICATIONS) clients.push({ name: 'Notifications', client: clientNotifications, token: TOKEN_NOTIFICATIONS });
|
||||
|
||||
// ── Plugin Contexts ──
|
||||
const ctxJukebox: PluginContext = { client: clientJukebox, dataDir: DATA_DIR, adminPwd: ADMIN_PWD, allowedGuildIds: ALLOWED_GUILD_IDS };
|
||||
const ctxRadio: PluginContext = { client: clientRadio, dataDir: DATA_DIR, adminPwd: ADMIN_PWD, allowedGuildIds: ALLOWED_GUILD_IDS };
|
||||
|
|
@ -149,6 +154,10 @@ async function boot(): Promise<void> {
|
|||
const ctxGameLibrary: PluginContext = { client: clientGameLibrary, dataDir: DATA_DIR, adminPwd: ADMIN_PWD, allowedGuildIds: ALLOWED_GUILD_IDS };
|
||||
registerPlugin(gameLibraryPlugin, ctxGameLibrary);
|
||||
|
||||
// notifications bot — uses its own Discord token for sending messages
|
||||
const ctxNotifications: PluginContext = { client: clientNotifications, dataDir: DATA_DIR, adminPwd: ADMIN_PWD, allowedGuildIds: ALLOWED_GUILD_IDS };
|
||||
registerPlugin(notificationsPlugin, ctxNotifications);
|
||||
|
||||
// Init all plugins
|
||||
for (const p of getPlugins()) {
|
||||
const pCtx = getPluginCtx(p.name)!;
|
||||
|
|
|
|||
261
server/src/plugins/notifications/index.ts
Normal file
261
server/src/plugins/notifications/index.ts
Normal file
|
|
@ -0,0 +1,261 @@
|
|||
import type express from 'express';
|
||||
import crypto from 'node:crypto';
|
||||
import { Client, EmbedBuilder, TextChannel, ChannelType } from 'discord.js';
|
||||
import type { Plugin, PluginContext } from '../../core/plugin.js';
|
||||
import { getState, setState } from '../../core/persistence.js';
|
||||
|
||||
const NB = '[Notifications]';
|
||||
|
||||
// ── Types ──
|
||||
|
||||
interface NotifyChannelConfig {
|
||||
channelId: string;
|
||||
channelName: string;
|
||||
guildId: string;
|
||||
guildName: string;
|
||||
events: string[]; // e.g. ['stream_start', 'stream_end']
|
||||
}
|
||||
|
||||
interface NotificationConfig {
|
||||
channels: NotifyChannelConfig[];
|
||||
}
|
||||
|
||||
// ── Module-level state ──
|
||||
|
||||
let _client: Client | null = null;
|
||||
let _ctx: PluginContext | null = null;
|
||||
let _publicUrl = '';
|
||||
|
||||
// ── Admin Auth (JWT-like with HMAC) ──
|
||||
|
||||
type AdminPayload = { iat: number; exp: number };
|
||||
|
||||
function readCookie(req: express.Request, name: string): string | undefined {
|
||||
const header = req.headers.cookie;
|
||||
if (!header) return undefined;
|
||||
const match = header.split(';').map(s => s.trim()).find(s => s.startsWith(`${name}=`));
|
||||
return match?.split('=').slice(1).join('=');
|
||||
}
|
||||
|
||||
function b64url(str: string): string {
|
||||
return Buffer.from(str).toString('base64url');
|
||||
}
|
||||
|
||||
function verifyAdminToken(adminPwd: string, token: string | undefined): boolean {
|
||||
if (!adminPwd || !token) return false;
|
||||
const parts = token.split('.');
|
||||
if (parts.length !== 2) return false;
|
||||
const [body, sig] = parts;
|
||||
const expected = crypto.createHmac('sha256', adminPwd).update(body).digest('base64url');
|
||||
if (expected !== sig) return false;
|
||||
try {
|
||||
const payload = JSON.parse(Buffer.from(body, 'base64url').toString('utf8')) as AdminPayload;
|
||||
return typeof payload.exp === 'number' && Date.now() < payload.exp;
|
||||
} catch { return false; }
|
||||
}
|
||||
|
||||
function signAdminToken(adminPwd: string): string {
|
||||
const payload: AdminPayload = { iat: Date.now(), exp: Date.now() + 7 * 24 * 3600_000 };
|
||||
const body = b64url(JSON.stringify(payload));
|
||||
const sig = crypto.createHmac('sha256', adminPwd).update(body).digest('base64url');
|
||||
return `${body}.${sig}`;
|
||||
}
|
||||
|
||||
// ── Exported notification functions (called by other plugins) ──
|
||||
|
||||
export async function notifyStreamStart(info: {
|
||||
streamId: string;
|
||||
broadcasterName: string;
|
||||
title: string;
|
||||
hasPassword: boolean;
|
||||
}): Promise<void> {
|
||||
if (!_client?.isReady()) return;
|
||||
const config = getState<NotificationConfig>('notifications_config', { channels: [] });
|
||||
const targets = config.channels.filter(c => c.events.includes('stream_start'));
|
||||
if (targets.length === 0) return;
|
||||
|
||||
const streamUrl = _publicUrl ? `${_publicUrl}?viewStream=${info.streamId}` : null;
|
||||
|
||||
const embed = new EmbedBuilder()
|
||||
.setColor(0x57F287) // green
|
||||
.setTitle('🔴 Stream gestartet')
|
||||
.addFields(
|
||||
{ name: 'Titel', value: info.title, inline: true },
|
||||
{ name: 'Streamer', value: info.broadcasterName, inline: true },
|
||||
)
|
||||
.setTimestamp();
|
||||
|
||||
if (info.hasPassword) {
|
||||
embed.addFields({ name: '🔒', value: 'Passwortgeschützt', inline: true });
|
||||
}
|
||||
if (streamUrl) {
|
||||
embed.addFields({ name: 'Link', value: `[Stream öffnen](${streamUrl})` });
|
||||
}
|
||||
|
||||
for (const target of targets) {
|
||||
try {
|
||||
const channel = await _client.channels.fetch(target.channelId);
|
||||
if (channel?.type === ChannelType.GuildText) {
|
||||
await (channel as TextChannel).send({ embeds: [embed] });
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`${NB} Failed to send to ${target.channelId}:`, err);
|
||||
}
|
||||
}
|
||||
console.log(`${NB} Stream-start notification sent to ${targets.length} channel(s)`);
|
||||
}
|
||||
|
||||
export async function notifyStreamEnd(info: {
|
||||
broadcasterName: string;
|
||||
title: string;
|
||||
viewerCount: number;
|
||||
duration: string; // human readable e.g. "1h 23m"
|
||||
}): Promise<void> {
|
||||
if (!_client?.isReady()) return;
|
||||
const config = getState<NotificationConfig>('notifications_config', { channels: [] });
|
||||
const targets = config.channels.filter(c => c.events.includes('stream_end'));
|
||||
if (targets.length === 0) return;
|
||||
|
||||
const embed = new EmbedBuilder()
|
||||
.setColor(0xED4245) // red
|
||||
.setTitle('⏹️ Stream beendet')
|
||||
.addFields(
|
||||
{ name: 'Titel', value: info.title, inline: true },
|
||||
{ name: 'Streamer', value: info.broadcasterName, inline: true },
|
||||
{ name: 'Zuschauer', value: String(info.viewerCount), inline: true },
|
||||
{ name: 'Dauer', value: info.duration, inline: true },
|
||||
)
|
||||
.setTimestamp();
|
||||
|
||||
for (const target of targets) {
|
||||
try {
|
||||
const channel = await _client.channels.fetch(target.channelId);
|
||||
if (channel?.type === ChannelType.GuildText) {
|
||||
await (channel as TextChannel).send({ embeds: [embed] });
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`${NB} Failed to send to ${target.channelId}:`, err);
|
||||
}
|
||||
}
|
||||
console.log(`${NB} Stream-end notification sent to ${targets.length} channel(s)`);
|
||||
}
|
||||
|
||||
// ── Plugin ──
|
||||
|
||||
const notificationsPlugin: Plugin = {
|
||||
name: 'notifications',
|
||||
version: '1.0.0',
|
||||
description: 'Discord Notification Bot',
|
||||
|
||||
async init(ctx) {
|
||||
_ctx = ctx;
|
||||
_client = ctx.client;
|
||||
_publicUrl = process.env.PUBLIC_URL?.replace(/\/$/, '') ?? '';
|
||||
console.log(`${NB} Initialized${_publicUrl ? ` (PUBLIC_URL=${_publicUrl})` : ' (no PUBLIC_URL set)'}`);
|
||||
},
|
||||
|
||||
async onReady(ctx) {
|
||||
console.log(`${NB} Bot ready as ${ctx.client.user?.tag}`);
|
||||
},
|
||||
|
||||
registerRoutes(app, ctx) {
|
||||
const requireAdmin = (req: express.Request, res: express.Response, next: () => void): void => {
|
||||
if (!ctx.adminPwd) { res.status(503).json({ error: 'Admin nicht konfiguriert' }); return; }
|
||||
if (!verifyAdminToken(ctx.adminPwd, readCookie(req, 'admin'))) { res.status(401).json({ error: 'Nicht eingeloggt' }); return; }
|
||||
next();
|
||||
};
|
||||
|
||||
// Admin status
|
||||
app.get('/api/notifications/admin/status', (req, res) => {
|
||||
if (!ctx.adminPwd) { res.json({ admin: false }); return; }
|
||||
res.json({ admin: verifyAdminToken(ctx.adminPwd, readCookie(req, 'admin')) });
|
||||
});
|
||||
|
||||
// Admin login
|
||||
app.post('/api/notifications/admin/login', (req, res) => {
|
||||
if (!ctx.adminPwd) { res.status(503).json({ error: 'Admin nicht konfiguriert' }); return; }
|
||||
const { password } = req.body ?? {};
|
||||
if (password !== ctx.adminPwd) { res.status(401).json({ error: 'Falsches Passwort' }); return; }
|
||||
const token = signAdminToken(ctx.adminPwd);
|
||||
res.setHeader('Set-Cookie', `admin=${token}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${7 * 86400}`);
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
// Admin logout
|
||||
app.post('/api/notifications/admin/logout', (_req, res) => {
|
||||
res.setHeader('Set-Cookie', 'admin=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0');
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
// List available text channels (requires admin)
|
||||
app.get('/api/notifications/channels', requireAdmin, async (_req, res) => {
|
||||
if (!ctx.client.isReady()) {
|
||||
res.status(503).json({ error: 'Bot nicht verbunden' });
|
||||
return;
|
||||
}
|
||||
const result: Array<{ channelId: string; channelName: string; guildId: string; guildName: string }> = [];
|
||||
for (const guild of ctx.client.guilds.cache.values()) {
|
||||
// Filter by allowed guilds if configured
|
||||
if (ctx.allowedGuildIds.length > 0 && !ctx.allowedGuildIds.includes(guild.id)) continue;
|
||||
for (const channel of guild.channels.cache.values()) {
|
||||
if (channel.type === ChannelType.GuildText) {
|
||||
result.push({
|
||||
channelId: channel.id,
|
||||
channelName: channel.name,
|
||||
guildId: guild.id,
|
||||
guildName: guild.name,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
res.json({ channels: result });
|
||||
});
|
||||
|
||||
// Get current config
|
||||
app.get('/api/notifications/config', requireAdmin, (_req, res) => {
|
||||
const config = getState<NotificationConfig>('notifications_config', { channels: [] });
|
||||
res.json(config);
|
||||
});
|
||||
|
||||
// Save config
|
||||
app.post('/api/notifications/config', requireAdmin, (req, res) => {
|
||||
const { channels } = req.body ?? {};
|
||||
if (!Array.isArray(channels)) { res.status(400).json({ error: 'channels array erforderlich' }); return; }
|
||||
// Validate each channel config
|
||||
const validChannels: NotifyChannelConfig[] = channels.map((c: any) => ({
|
||||
channelId: String(c.channelId || ''),
|
||||
channelName: String(c.channelName || ''),
|
||||
guildId: String(c.guildId || ''),
|
||||
guildName: String(c.guildName || ''),
|
||||
events: Array.isArray(c.events) ? c.events.filter((e: string) => ['stream_start', 'stream_end'].includes(e)) : [],
|
||||
})).filter((c: NotifyChannelConfig) => c.channelId && c.events.length > 0);
|
||||
setState('notifications_config', { channels: validChannels });
|
||||
console.log(`${NB} Config saved: ${validChannels.length} channel(s)`);
|
||||
res.json({ ok: true, channels: validChannels });
|
||||
});
|
||||
|
||||
// Bot status (public)
|
||||
app.get('/api/notifications/status', (_req, res) => {
|
||||
res.json({
|
||||
online: ctx.client.isReady(),
|
||||
botTag: ctx.client.user?.tag ?? null,
|
||||
configuredChannels: getState<NotificationConfig>('notifications_config', { channels: [] }).channels.length,
|
||||
});
|
||||
});
|
||||
},
|
||||
|
||||
getSnapshot() {
|
||||
return {
|
||||
notifications: {
|
||||
online: _client?.isReady() ?? false,
|
||||
botTag: _client?.user?.tag ?? null,
|
||||
},
|
||||
};
|
||||
},
|
||||
|
||||
async destroy() {
|
||||
console.log(`${NB} Destroyed`);
|
||||
},
|
||||
};
|
||||
|
||||
export default notificationsPlugin;
|
||||
|
|
@ -3,6 +3,7 @@ import { WebSocketServer, WebSocket } from 'ws';
|
|||
import crypto from 'node:crypto';
|
||||
import type { Plugin, PluginContext } from '../../core/plugin.js';
|
||||
import { sseBroadcast } from '../../core/sse.js';
|
||||
import { notifyStreamStart, notifyStreamEnd } from '../notifications/index.js';
|
||||
|
||||
// ── Types ──
|
||||
|
||||
|
|
@ -73,6 +74,19 @@ function endStream(streamId: string, reason: string): void {
|
|||
broadcaster.broadcastStreamId = undefined;
|
||||
}
|
||||
|
||||
// Send Discord notification
|
||||
const durationMs = Date.now() - new Date(stream.startedAt).getTime();
|
||||
const durationMin = Math.floor(durationMs / 60000);
|
||||
const durationH = Math.floor(durationMin / 60);
|
||||
const durationM = durationMin % 60;
|
||||
const durationStr = durationH > 0 ? `${durationH}h ${durationM}m` : `${durationM}m`;
|
||||
notifyStreamEnd({
|
||||
broadcasterName: stream.broadcasterName,
|
||||
title: stream.title,
|
||||
viewerCount: stream.viewerCount,
|
||||
duration: durationStr,
|
||||
}).catch(err => console.error('[Streaming] Notification error:', err));
|
||||
|
||||
streams.delete(streamId);
|
||||
broadcastStreamStatus();
|
||||
console.log(`[Streaming] Stream "${stream.title}" ended: ${reason}`);
|
||||
|
|
@ -130,6 +144,13 @@ function handleSignalingMessage(client: WsClient, msg: any): void {
|
|||
}
|
||||
}
|
||||
console.log(`[Streaming] ${name} started "${title}" (${streamId.slice(0, 8)})`);
|
||||
// Send Discord notification
|
||||
notifyStreamStart({
|
||||
streamId,
|
||||
broadcasterName: name,
|
||||
title,
|
||||
hasPassword: password.length > 0,
|
||||
}).catch(err => console.error('[Streaming] Notification error:', err));
|
||||
break;
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue