Update config loading logic. Refactor isModerator

This commit is contained in:
Charlie Laabs
2019-12-23 15:38:14 -06:00
parent d9a412ed75
commit fa18227ccc

View File

@@ -22,6 +22,12 @@ interface MessagesDB {
messages: MessageRecord[]; messages: MessageRecord[];
} }
interface MarkbotConfig {
prefix: string;
game: string;
token?: string;
}
const version: string = JSON.parse(fs.readFileSync('./package.json', 'utf8')).version || '0.0.0'; const version: string = JSON.parse(fs.readFileSync('./package.json', 'utf8')).version || '0.0.0';
const client = new Discord.Client(); const client = new Discord.Client();
@@ -52,6 +58,7 @@ const markovOpts = {
minScorePerWord: 0, minScorePerWord: 0,
maxTries: 10000, maxTries: 10000,
}; };
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
function uniqueBy<Record extends { [key: string]: any }>( function uniqueBy<Record extends { [key: string]: any }>(
arr: Record[], arr: Record[],
@@ -126,28 +133,29 @@ function loadConfig(): void {
fs.renameSync('./markovDB.json', './config/markovDB.json'); fs.renameSync('./markovDB.json', './config/markovDB.json');
} }
let token = 'missing';
try { try {
const cfg = JSON.parse(fs.readFileSync('./config/config.json', 'utf8')); const cfg: MarkbotConfig = JSON.parse(fs.readFileSync('./config/config.json', 'utf8'));
PREFIX = cfg.prefix; PREFIX = cfg.prefix || '!mark';
GAME = cfg.game; GAME = cfg.game || '!mark help';
client.login(cfg.token); token = cfg.token || process.env.TOKEN || token;
} catch (e) { } catch (e) {
console.warn( console.error('Failed to read config.json.');
'Failed to use config.json. using default configuration with token environment variable' throw e;
); }
PREFIX = '!mark'; try {
GAME = '"!mark help" for help'; client.login(token);
client.login(process.env.TOKEN); } catch (e) {
console.error('Failed to login with token:', token);
} }
} }
/** /**
* Checks if the author of a message as moderator-like permissions. * Checks if the author of a message as moderator-like permissions.
* @param {Message} message Message object to get the sender of the message. * @param {GuildMember} member Sender of the message
* @return {Boolean} True if the sender is a moderator. * @return {Boolean} True if the sender is a moderator.
*/ */
function isModerator(message: Discord.Message): boolean { function isModerator(member: Discord.GuildMember): boolean {
const { member } = message;
return ( return (
member.hasPermission('ADMINISTRATOR') || member.hasPermission('ADMINISTRATOR') ||
member.hasPermission('MANAGE_CHANNELS') || member.hasPermission('MANAGE_CHANNELS') ||
@@ -346,7 +354,7 @@ client.on('message', message => {
}); });
} }
if (command === 'train') { if (command === 'train') {
if (isModerator(message)) { if (isModerator(message.member)) {
console.log('Training...'); console.log('Training...');
fileObj = { fileObj = {
messages: [], messages: [],