added discord bot

This commit is contained in:
Evan
2024-12-14 20:10:38 -08:00
committed by evanpelle
parent 70fefe347b
commit 37a71c2ef0
4 changed files with 471 additions and 22 deletions
+60
View File
@@ -0,0 +1,60 @@
import { SecretManagerServiceClient } from '@google-cloud/secret-manager';
import { Client, Events, GatewayIntentBits } from 'discord.js';
export class DiscordBot {
private client: Client;
private secretManager: SecretManagerServiceClient;
constructor() {
this.client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
],
});
this.secretManager = new SecretManagerServiceClient();
this.setupEventHandlers();
}
private setupEventHandlers(): void {
this.client.once(Events.ClientReady, (c) => {
console.log(`Ready! Logged in as ${c.user.tag}`);
});
this.client.on(Events.MessageCreate, async (message) => {
if (message.author.bot) return;
if (message.content === '!ping') {
await message.reply('Pong! 🏓');
}
if (message.content === '!hello') {
await message.reply(`Hello ${message.author.username}! 👋`);
}
});
}
private async getToken(): Promise<string | undefined> {
const name = 'projects/openfrontio/secrets/discord-bot-token/versions/latest';
const [version] = await this.secretManager.accessSecretVersion({ name });
return version.payload?.data?.toString().trim();
}
public async start(): Promise<void> {
try {
const token = await this.getToken();
if (!token) {
throw new Error('Failed to retrieve Discord token');
}
await this.client.login(token);
} catch (error) {
console.error('Failed to start bot:', error);
throw error;
}
}
public stop(): void {
this.client.destroy();
}
}
+8
View File
@@ -10,6 +10,7 @@ import { LogSeverity, slog } from './StructuredLog';
import { Client } from './Client';
import { GamePhase, GameServer } from './GameServer';
import { archive } from './Archive';
import { DiscordBot } from './DiscordBot';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
@@ -24,6 +25,13 @@ app.use(express.json())
const gm = new GameManager(getConfig())
const bot = new DiscordBot();
try {
await bot.start();
} catch (error) {
console.error('Failed to start bot:', error);
}
// New GET endpoint to list lobbies
app.get('/lobbies', (req, res) => {
const now = Date.now()