Files
matrix-quotes-bot/index.js

113 lines
3.9 KiB
JavaScript
Raw Normal View History

import * as dotenv from 'dotenv';
import { MatrixClient } from 'matrix-js-sdk';
import fs from 'fs';
dotenv.config();
2026-09-12 23:57:45 -04:00
console.log('🚀 Starting Ancestor Quote Bot...\n');
const client = new MatrixClient({
2026-09-12 23:57:45 -04:00
accessToken: process.env.MATRIX_ACCESS_TOKEN,
baseUrl: process.env.MATRIX_HOME_SERVER,
2026-09-12 23:57:45 -04:00
});
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;
2026-09-13 14:39:02 -04:00
client.on('RoomMember#joined', async (member) => {
const room = member.room;
console.log(`✅ Room: ${room.getCanonicalRoomName() || room.roomId}`);
2026-09-13 14:39:02 -04:00
room.on('EventMessage', async (event, stateEvent) => {
const content = event.getContent();
if (!content || !content.body) return;
2026-09-13 14:39:02 -04:00
const body = content.body.toLowerCase().trim();
const cmd = (process.env.BOT_COMMAND || '!quote').toLowerCase();
2026-09-13 14:39:02 -04:00
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();
2026-09-13 14:39:02 -04:00
} catch (err) {
console.error('Failed to send quote:', err.message);
}
}
2026-09-13 14:39:02 -04:00
}
});
2026-09-13 14:39:02 -04:00
member.room.on('RoomMember#left', () => {
console.log(`ℹ️ Left: ${room.getCanonicalRoomName() || room.roomId}`);
2026-09-13 14:39:02 -04:00
});
});
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);
})();