|
|
let fs = require('fs'); let sdk = require("matrix-js-sdk"); let message = require("./message.js"); let utility = require("./utility.js");
class Bot { constructor(config, buildInfo) { this.config = config; this.buildInfo = buildInfo; this.connected = false; }
sendStatusStartup() { let promises = [Promise.resolve(true)] if (this.connected) { this.config.statusRooms.forEach(roomId => { console.log("Notifying %s", roomId, "of startup"); promises.push(this.client.sendMessage( roomId, message.createBasic("Started with version: " + this.buildInfo) ).then(function () { console.log("Notified %s", roomId, "of startup"); })); }); } else { console.log("Attempting to send startup message while disconnected"); } return Promise.all(promises); }
sendStatusShutdown() { let promises = [Promise.resolve(true)] if (this.connected) { this.config.statusRooms.forEach(roomId => { console.log("Notifying %s", roomId, "of Shutdown"); promises.push(this.client.sendMessage( roomId, message.createBasic("Shutting down") ).then(function () { console.log("Notified %s", roomId, "of shutdown"); })); }); } else { console.log("Attempting to send shutdown message while disconnected"); } return Promise.all(promises); } }
function getBuildInfo(buildInfoPath) { try { return fs.readFileSync(buildInfoPath, "utf8"); } catch (err) { if (err.code === 'ENOENT') { return "UNKNOWN_" + utility.toISODateString(new Date()); } else { console.log("Unexpected Error! " + err); } } }
function create(configFile) { let config = require(configFile); console.log("Running with config:"); console.log(config); let buildInfo = getBuildInfo("../build.info") console.log("Running version:"); console.log(buildInfo); return new Bot(config, buildInfo); }
function init(bot) { console.log("Creating Matrix Client") bot.client = sdk.createClient({ baseUrl: bot.config.baseUrl, accessToken: bot.config.accessToken, userId: bot.config.userId });
bot.client.on("sync", async function (state, previousState, data) { switch (state) { case "PREPARED": bot.connected = true; await bot.sendStatusStartup(); break; } });
bot.client.on("RoomMember.membership", function (event, member) { if (member.membership === "invite" && bot.config.admin.indexOf(ember.userId) >= 0) { bot.client.joinRoom(member.roomId).done(function () { console.log("Auto-joined %s", member.roomId); }); } });
/* Capture Exit Conditions */
["SIGINT", "SIGTERM"].forEach((signature) => { process.on(signature, async () => { await bot.sendStatusShutdown() .then(function () { console.log("Gracefully stopping Matrix SDK Client") bot.client.stopClient(); }); process.exit(0); }); });
process.on('exit', async function () { console.log("Shutting Down"); });
return bot; }
function run(bot) { // console.log("Initializing Crypto");
// await bot.client.initCrypto();
console.log("Starting Matrix SDK Client"); bot.client.startClient(); }
exports.create = create; exports.init = init; exports.run = run;
|