forked from Lea/UntisBot
78 lines
2.1 KiB
TypeScript
78 lines
2.1 KiB
TypeScript
import { codeBlock } from "@discordjs/builders";
|
|
import { Client, DMChannel, MessageEmbed } from "discord.js";
|
|
import * as dotenv from "dotenv";
|
|
import Enmap from "enmap";
|
|
import fs from "fs";
|
|
import WebUntis, { Lesson } from "webuntis";
|
|
dotenv.config();
|
|
|
|
|
|
const untis = new WebUntis(
|
|
process.env.SCHOOLNAME,
|
|
process.env.USERNAME,
|
|
process.env.PASSWORD,
|
|
process.env.BASEURL,
|
|
);
|
|
|
|
console.log("Discord Bot: Logging in");
|
|
const client = new Client({ intents: [] });
|
|
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: Enmap<string, Lesson> = new Enmap({ name: "knownLessons" });
|
|
|
|
const defaultEmbedColor = 0xFF9A00;
|
|
|
|
|
|
// Periodically attempt to connect to untis and fetch timetable updates
|
|
async function fetchUpdates() {
|
|
console.log("Untis: Logging in");
|
|
try {
|
|
await untis.login();
|
|
console.log("Untis: Logged in");
|
|
|
|
fs.readdirSync(`${__dirname}/modules`).filter(file => file.endsWith(".js")).forEach(file => {
|
|
require(`${__dirname}/modules/${file}`).run();
|
|
});
|
|
|
|
setTimeout(async () => {
|
|
await untis.logout();
|
|
console.log("Untis: Logged out");
|
|
}, 10000);
|
|
} catch (e) {
|
|
console.error(e);
|
|
try {
|
|
const embed = new MessageEmbed()
|
|
.setTitle("An error has occurred.")
|
|
.setDescription(codeBlock("js", `${e}`))
|
|
.setColor(0xff0000);
|
|
sendEmbed(embed);
|
|
} catch (err) {
|
|
console.error(err);
|
|
}
|
|
}
|
|
}
|
|
|
|
fetchUpdates();
|
|
setInterval(fetchUpdates, 60000);
|
|
|
|
|
|
async function sendEmbed(embed: MessageEmbed) {
|
|
const channel = await client.channels.fetch(process.env.CHANNEL) as DMChannel;
|
|
if (!channel) throw "ERROR: Could not find channel";
|
|
|
|
if (!embed.timestamp) embed.setTimestamp();
|
|
channel.send({ embeds: [embed] }).catch(console.error);
|
|
}
|
|
|
|
export default {
|
|
untis,
|
|
bot: client,
|
|
defaultEmbedColor,
|
|
sendEmbed,
|
|
db: {
|
|
seenMessages,
|
|
knownLessons,
|
|
},
|
|
}; |