UntisBot/src/index.ts

76 lines
2.1 KiB
TypeScript

import * as dotenv from 'dotenv';
dotenv.config();
import Discord from 'discord.js';
import Enmap from 'enmap';
import fs from 'fs';
import * as WebUntis from 'webuntis';
const untis = new WebUntis.default(
process.env.SCHOOLNAME,
process.env.USERNAME,
process.env.PASSWORD,
process.env.BASEURL
);
console.log('Discord Bot: Logging in');
const client = new Discord.Client();
client.login(process.env.BOT_TOKEN);
client.on('ready', () => console.log(`Discord Bot: Logged in as ${client.user.tag}`));
const seenMessages = new Enmap({ name: "seenMessages" });
const knownLessons = new Enmap({ name: "knownLessons" });
const defaultEmbedColor = 0xFF9A00;
// Periodically attempt to connect to untis and fetch timetable updates
let fetchUpdates = () => {
console.log('Untis: Logging in');
try {
untis.login()
.then(() => {
console.log(`Untis: Logged in`)
fs.readdirSync(`${__dirname}/modules`).filter(file => file.endsWith('.js')).forEach(file => {
require(`${__dirname}/modules/${file}`).run();
});
setTimeout(() => untis.logout().then(() => console.log('Untis: Logged out')), 10000);
});
} catch(e) {
console.error(e);
try {
let embed = new Discord.MessageEmbed()
.setTitle('An error has occurred.')
.setDescription(`\`\`\`js\n${e}\`\`\``)
.setColor(0xff0000);
sendEmbed(embed);
} catch(e) {
console.error(e);
}
}
}
fetchUpdates();
setInterval(fetchUpdates, 60000);
async function sendEmbed(embed: Discord.MessageEmbed) {
const channel = await client.channels.fetch(process.env.CHANNEL) as Discord.DMChannel;
if (!channel) throw `ERROR: Could not find channel`;
if (!embed.timestamp) embed.setTimestamp();
channel.send(embed).catch(console.error);
}
export default {
untis: untis,
bot: client,
defaultEmbedColor: defaultEmbedColor,
sendEmbed: sendEmbed,
db: {
seenMessages: seenMessages,
knownLessons: knownLessons
}
};