The default StubStore.getRoom() always returns null, so every received
message bailed at the room lookup ('got m.room.message for unknown room').
A MemoryStore keeps joined rooms available for lookup.
147 lines
5.3 KiB
JavaScript
147 lines
5.3 KiB
JavaScript
import * as dotenv from 'dotenv';
|
||
import { MatrixClient } from 'matrix-js-sdk';
|
||
import { MemoryStore } from 'matrix-js-sdk/lib/store/memory.js';
|
||
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,
|
||
store: new MemoryStore(),
|
||
});
|
||
|
||
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 {
|
||
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');
|
||
|
||
const joinedRooms = client.getRooms();
|
||
console.log(`🏠 Current rooms: ${joinedRooms.length}`);
|
||
joinedRooms.forEach((r) => {
|
||
console.log(` - ${r.roomId} membership="${r.getMyMembership()}"`);
|
||
});
|
||
console.log('');
|
||
|
||
const cmd = (process.env.BOT_COMMAND || '!quote').toLowerCase();
|
||
console.log(`🔊 Listening for command: "${cmd}"`);
|
||
|
||
// Auto-accept invites so the bot can be invited into rooms.
|
||
client.on('RoomMember.membership', (event, member) => {
|
||
if (member.userId === userId && member.membership === 'invite') {
|
||
const roomId = event.getRoomId();
|
||
console.log(`📩 Invited to ${roomId}, joining...`);
|
||
client.joinRoom(roomId).catch((err) => {
|
||
console.error('Failed to join room:', err.message);
|
||
});
|
||
}
|
||
});
|
||
|
||
// Respond to messages in any room this bot is a member of.
|
||
client.on('event', (event) => {
|
||
const type = event.getType();
|
||
const eventRoomId = event.getRoomId();
|
||
|
||
// Encrypted rooms: the bot has no E2EE support, so command text
|
||
// never arrives as plaintext and cannot be read or answered.
|
||
if (type === 'm.room.encrypted') {
|
||
console.log(`🔒 [${eventRoomId}] encrypted message received. ` +
|
||
`The bot cannot read E2EE rooms; invite it to an unencrypted room instead.`);
|
||
return;
|
||
}
|
||
|
||
if (type !== 'm.room.message') return;
|
||
|
||
const sender = event.getSender();
|
||
if (sender === userId) return; // skip replies from ourselves
|
||
|
||
const room = eventRoomId ? client.getRoom(eventRoomId) : null;
|
||
if (!room) {
|
||
console.log(`ℹ️ [debug] got m.room.message for unknown room: ${eventRoomId}`);
|
||
return;
|
||
}
|
||
|
||
const membership = room.getMyMembership();
|
||
if (membership !== 'join') {
|
||
console.log(`ℹ️ [debug] [${room.roomId}] m.room.message while membership="${membership}" — not replying`);
|
||
return;
|
||
}
|
||
|
||
const content = event.getContent();
|
||
if (!content || typeof content.body !== 'string') {
|
||
console.log(`ℹ️ [debug] [${room.roomId}] m.room.message without text body`);
|
||
return;
|
||
}
|
||
|
||
const lower = content.body.toLowerCase().trim();
|
||
const matches = lower === cmd || lower.startsWith(cmd + ' ');
|
||
console.log(`💬 [${room.roomId}] <${sender}> "${content.body}" (listening for "${cmd}", match=${matches})`);
|
||
if (!matches) return;
|
||
|
||
const quote = quotes[Math.floor(Math.random() * quotes.length)];
|
||
client.sendTextMessage(room.roomId, quote)
|
||
.then(() => console.log(`🎃 [${room.roomId}] ${quote}`))
|
||
.catch((err) => console.error('Failed to send quote:', err.message));
|
||
});
|
||
|
||
console.log('🤖 Bot is running!');
|
||
console.log(` Invite this bot to a room and type ${process.env.BOT_COMMAND || '!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);
|
||
})(); |