Files
matrix-quotes-bot/index.js

83 lines
2.6 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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`);
try {
await client.startClient();
console.log('✅ Client initialized\n');
let joinedRooms = new Set();
let lastSentMessage = null;
client.on('RoomMember#joined', (member) => {
const room = member.room;
if (!joinedRooms.has(room.roomId)) {
joinedRooms.add(room.roomId);
console.log(`✅ Joined: ${room.roomId}`);
room.on('EventMessage', async (event) => {
const content = event.getContent();
if (!content || !content.body) return;
const body = content.body.toLowerCase();
const cmd = (process.env.BOT_COMMAND || '!quote').toLowerCase();
if (body.includes(cmd)) {
if (!lastSentMessage || Date.now() - lastSentMessage > 300) {
const quote = quotes[Math.floor(Math.random() * quotes.length)];
await room.sendMessage(quote);
console.log(`🎃 Quote: ${quote}`);
lastSentMessage = Date.now();
}
}
});
room.on('RoomMember#left', () => {
joinedRooms.delete(room.roomId);
console.log(`ℹ️ Left: ${room.roomId}`);
});
}
});
console.log('🤖 Bot is running!');
console.log(' Invite to a Matrix room and type !quote to get an Ancestor quote.\n');
} catch (err) {
console.error('Fatal error:', err.message);
process.exit(1);
}
setInterval(() => {}, 60000);
})();