import * as dotenv from 'dotenv'; import { MatrixClient } from 'matrix-js-sdk'; import fs from 'fs'; dotenv.config(); console.log('🚀 Starting Ancestor Quote Bot...\n'); const client = new MatrixClient({ accessToken: process.env.MATRIX_ACCESS_TOKEN, baseUrl: process.env.MATRIX_HOME_SERVER, }); function loadQuotes() { try { const quotesFile = './quotes.json'; if (fs.existsSync(quotesFile)) { return JSON.parse(fs.readFileSync(quotesFile, 'utf8')); } } catch (err) { console.error('Error loading quotes:', err.message); } return []; } (async () => { const quotes = loadQuotes(); if (quotes.length === 0) { console.error('❌ No quotes found! Please ensure quotes.json is present.'); process.exit(1); } console.log(`✅ Loaded ${quotes.length} Ancestor quotes`); const token = process.env.MATRIX_ACCESS_TOKEN; const server = process.env.MATRIX_HOME_SERVER; if (!token || !server) { console.error('❌ Missing required environment variables!'); console.error(' Required: MATRIX_ACCESS_TOKEN, MATRIX_HOME_SERVER'); console.error(' See .env.example for guidance.'); process.exit(1); } console.log(`🏠 Server: ${server}`); try { // The SDK needs to know the bot's own user ID to build request URLs // (e.g. /user/$userId/filter). It would otherwise use the literal // "$userId" placeholder, which the homeserver rejects. Fetch it via // the whoami endpoint before connecting. const whoami = await client.whoami(); const userId = whoami.user_id; if (!userId || !userId.startsWith('@')) { console.error(`❌ whoami returned invalid user ID: ${userId}`); process.exit(1); } client.credentials.userId = userId; console.log(`👤 Bot Identity: ${userId}`); await client.startClient(); console.log('✅ MatrixClient connected and authenticated\n'); let lastSentMessage = null; client.on('RoomMember#joined', async (member) => { const room = member.room; console.log(`✅ Room: ${room.getCanonicalRoomName() || room.roomId}`); room.on('EventMessage', async (event, stateEvent) => { const content = event.getContent(); if (!content || !content.body) return; const body = content.body.toLowerCase().trim(); const cmd = (process.env.BOT_COMMAND || '!quote').toLowerCase(); if (body === cmd || body.startsWith(cmd)) { if (!lastSentMessage || Date.now() - lastSentMessage > 300) { const quote = quotes[Math.floor(Math.random() * quotes.length)]; try { await room.sendMessage(quote); console.log(`🎃 Quote: ${quote}`); lastSentMessage = Date.now(); } catch (err) { console.error('Failed to send quote:', err.message); } } } }); member.room.on('RoomMember#left', () => { console.log(`â„šī¸ Left: ${room.getCanonicalRoomName() || room.roomId}`); }); }); console.log('🤖 Bot is running!'); console.log(' Invite this bot to a Matrix room and type !quote to get an Ancestor quote.\n'); } catch (err) { console.error('❌ Fatal error starting bot:', err.message); console.error(err.stack); process.exit(1); } process.on('unhandledRejection', (reason, promise) => { console.error('🚨 Unhandled rejection:', reason?.message || reason); process.exit(1); }); setInterval(() => {}, 60000); })();