78 lines
2.4 KiB
JavaScript
78 lines
2.4 KiB
JavaScript
require('dotenv').config();
|
|
const { Client } = require('matrix-js-sdk');
|
|
const fs = require('fs');
|
|
|
|
const client = new Client({
|
|
accessToken: process.env.MATRIX_ACCESS_TOKEN,
|
|
matrix_homeserver: {
|
|
baseUrl: process.env.MATRIX_HOME_SERVER,
|
|
}
|
|
});
|
|
|
|
function loadQuotes() {
|
|
return new Promise((resolve) => {
|
|
setTimeout(() => {
|
|
const quotesFile = './quotes.json';
|
|
if (fs.existsSync(quotesFile)) {
|
|
try {
|
|
resolve(JSON.parse(fs.readFileSync(quotesFile, 'utf8')));
|
|
} catch (err) {
|
|
resolve([]);
|
|
}
|
|
} else {
|
|
resolve([]);
|
|
}
|
|
}, 0);
|
|
});
|
|
}
|
|
|
|
loadQuotes().then((quotes) => {
|
|
if (quotes.length === 0) {
|
|
console.error('No quotes found! Please ensure quotes.json is present.');
|
|
process.exit(1);
|
|
}
|
|
|
|
let joinedRooms = new Set();
|
|
|
|
client.on('RoomMember#joined', (member) => {
|
|
const room = member.room;
|
|
if (!joinedRooms.has(room.roomId)) {
|
|
joinedRooms.add(room.roomId);
|
|
console.log(`Joined room: ${room.roomId}`);
|
|
|
|
room.on('EventMessage', async (event) => {
|
|
const messageContent = event.getContent();
|
|
|
|
if (!messageContent || !messageContent.body) return;
|
|
|
|
const body = messageContent.body.toLowerCase();
|
|
const botCommand = (process.env.BOT_COMMAND || '!quote').toLowerCase();
|
|
|
|
if (body.includes(botCommand)) {
|
|
const randomQuote = quotes[Math.floor(Math.random() * quotes.length)];
|
|
try {
|
|
await room.sendMessage(randomQuote);
|
|
console.log(`Sent quote to ${room.roomId}`);
|
|
} catch (err) {
|
|
console.error('Failed to send message:', err.message);
|
|
}
|
|
}
|
|
});
|
|
|
|
room.on('RoomMember#left', () => {
|
|
joinedRooms.delete(room.roomId);
|
|
console.log(`Left room: ${room.roomId}`);
|
|
});
|
|
}
|
|
});
|
|
|
|
client.init().then(() => {
|
|
console.log('Bot is online');
|
|
}).catch(err => {
|
|
console.error('Failed to initialize client:', err.message);
|
|
process.exit(1);
|
|
});
|
|
}).catch(err => {
|
|
console.error('Failed to load quotes:', err.message);
|
|
});
|