Initial commit
This commit is contained in:
commit
f8910e4f30
28 changed files with 3111 additions and 0 deletions
198
src/cmd_handler.ts
Normal file
198
src/cmd_handler.ts
Normal file
|
|
@ -0,0 +1,198 @@
|
|||
//
|
||||
// cmd_handler.ts
|
||||
//
|
||||
// Written by: Oliver Akins (2019/11/06 - 2020/01/31)
|
||||
//
|
||||
|
||||
|
||||
/* Imports */
|
||||
import { Command, Confirmation } from "./utils/Command";
|
||||
import { PERM, FLAG_INDICATOR } from "./constants";
|
||||
import { SORT_COMMANDS } from "./utils/sorting";
|
||||
import { LOAD_CONFIG } from "./utils/Config";
|
||||
import { GET_FLAGS } from "./utils/flags";
|
||||
import { log } from "./utils/webhook";
|
||||
|
||||
|
||||
|
||||
export var commands: Command[] = [];
|
||||
export var confirms: Confirmation[] = [];
|
||||
var global_last_ran: number;
|
||||
var service_last_rans: any = {}
|
||||
|
||||
|
||||
export const REGISTER_COMMAND = (metadata: cmd_metadata): boolean => {
|
||||
// Ensure command gets added correctly
|
||||
try {
|
||||
commands.push(new Command(metadata));
|
||||
SORT_COMMANDS(commands);
|
||||
return true;
|
||||
} catch (error) {
|
||||
return false;
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
|
||||
export const HANDLE_MESSAGE = (ctx: msg_data): string => {
|
||||
|
||||
let config: config = LOAD_CONFIG();
|
||||
let datetime = new Date();
|
||||
let timezone = datetime.toLocaleTimeString("en-us", {timeZoneName:"short"}).split(" ")[2];
|
||||
let date = `${datetime.getFullYear()}-${datetime.getMonth()+1}-${datetime.getDate()}`
|
||||
+ ` @ ${datetime.getHours()}:${datetime.getMinutes()} ${timezone}`;
|
||||
|
||||
|
||||
// Confirmation handling:
|
||||
// Check if we need any confirmations from users
|
||||
for (var index in confirms) {
|
||||
let confirmation = confirms[index];
|
||||
|
||||
let response: CONFIRM_TYPE = confirmation.matches(
|
||||
ctx.user, ctx.channel, ctx.message
|
||||
);
|
||||
|
||||
if (!["no_match", "expired"].includes(response)) {
|
||||
confirms.splice(parseInt(index), 1);
|
||||
let cmd_resp = confirmation.run(response);
|
||||
|
||||
|
||||
// Check if we have a response to log
|
||||
if (cmd_resp) {
|
||||
log({
|
||||
title: `Log Entry (Confirmation Response):`,
|
||||
msg: `Command:\`\`\`\n${ctx.message}\n\`\`\`\n\nResponse:\`\`\`\n${cmd_resp}\n\`\`\``,
|
||||
embed: true,
|
||||
fields: {
|
||||
"Date:": date,
|
||||
"Is Mod:": ctx.level >= PERM.MOD,
|
||||
"Is Admin:": ctx.level >= PERM.ADMIN,
|
||||
"Level:": ctx.level,
|
||||
"Channel:": ctx.channel,
|
||||
"Username": ctx.user,
|
||||
"Platform": ctx.source,
|
||||
"Confirm Type": response
|
||||
},
|
||||
no_stdout: true
|
||||
});
|
||||
};
|
||||
|
||||
return cmd_resp;
|
||||
}
|
||||
|
||||
else if (response === "expired") {
|
||||
confirms.splice(parseInt(index), 1);
|
||||
confirmation.run(response);
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
|
||||
// SECTION: Global command cooldowns
|
||||
if (config.bot.COOLDOWN_TYPE === "GLOBAL" && ctx.cooldown) {
|
||||
if (global_last_ran) {
|
||||
if (Date.now() - global_last_ran < config.bot.COOLDOWN_TIME * 1000) {
|
||||
return null;
|
||||
};
|
||||
};
|
||||
global_last_ran = Date.now();
|
||||
}
|
||||
// !SECTION: Global command cooldowns
|
||||
|
||||
|
||||
|
||||
// SECTION: Service command cooldowns
|
||||
else if (config.bot.COOLDOWN_TYPE === "SERVICE" && ctx.cooldown) {
|
||||
if (service_last_rans[ctx.source]) {
|
||||
if (Date.now() - service_last_rans[ctx.source] < config.bot.COOLDOWN_TIME * 1000) {
|
||||
return null;
|
||||
};
|
||||
};
|
||||
service_last_rans[ctx.source] = Date.now();
|
||||
};
|
||||
// !SECTION: Service command cooldowns
|
||||
|
||||
|
||||
// SECTION: Flag parsing
|
||||
ctx.flags = GET_FLAGS(ctx.message);
|
||||
|
||||
// removing arguments that are indicated as flags
|
||||
let re = new RegExp(`\\${FLAG_INDICATOR}\\w+\\s?`, `g`);
|
||||
ctx.message = ctx.message.replace(re, ``);
|
||||
// !SECTION: Flag parsing
|
||||
|
||||
|
||||
|
||||
// Check all registered commands
|
||||
for (var cmd of commands) {
|
||||
|
||||
|
||||
// NOTE: Checking if message doesn't match
|
||||
if (!cmd.matches(ctx.message.toLowerCase())) { continue; };
|
||||
|
||||
|
||||
// NOTE: Permission checking
|
||||
if (ctx.level < cmd.level) {
|
||||
if (config.bot.INVALID_PERM_ERROR) {
|
||||
return `Invalid Permissions, you must be at least level ${cmd.level}, you are level ${ctx.level}.`;
|
||||
};
|
||||
return null;
|
||||
};
|
||||
|
||||
|
||||
// NOTE: per-command cooldown
|
||||
if (config.bot.COOLDOWN_TYPE === "COMMAND" && ctx.cooldown) {
|
||||
if (cmd.last_ran) {
|
||||
if (Date.now() - cmd.last_ran < config.bot.COOLDOWN_TIME * 1000) {
|
||||
return null;
|
||||
};
|
||||
};
|
||||
cmd.last_ran = Date.now();
|
||||
};
|
||||
|
||||
|
||||
// NOTE: Case sensitivity
|
||||
if (!cmd.case_sensitive) {
|
||||
ctx.message = ctx.message.toLowerCase();
|
||||
};
|
||||
|
||||
|
||||
// NOTE: Argument parsing
|
||||
let args = ctx.message
|
||||
.slice(config.bot.PREFIX.length)
|
||||
.split(" ")
|
||||
.slice(cmd.full_name.split(" ").length);
|
||||
|
||||
|
||||
// Ensure the use supplied enough arguments
|
||||
if (args.length < cmd.mand_args) {
|
||||
return `Not enough arguments, missing argument: \`${cmd.arg_list[args.length]}\``;
|
||||
};
|
||||
|
||||
|
||||
let response = cmd.execute(ctx, args);
|
||||
|
||||
|
||||
log({
|
||||
title: `Log Entry:`,
|
||||
msg: `Command:\`\`\`\n${ctx.message}\n\`\`\`\n\nResponse:\`\`\`\n${response}\n\`\`\``,
|
||||
embed: true,
|
||||
fields: {
|
||||
"Date:": date,
|
||||
"Is Mod:": ctx.level >= PERM.MOD,
|
||||
"Is Admin:": ctx.level >= PERM.ADMIN,
|
||||
"Level:": ctx.level,
|
||||
"Channel:": ctx.channel,
|
||||
"Username": ctx.user,
|
||||
"Platform": ctx.source
|
||||
},
|
||||
no_stdout: true
|
||||
});
|
||||
return response;
|
||||
};
|
||||
return null;
|
||||
};
|
||||
|
||||
|
||||
|
||||
/* Importing all the commands so they can register */
|
||||
38
src/constants.ts
Normal file
38
src/constants.ts
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
//
|
||||
// constants.ts
|
||||
//
|
||||
// Written by: Oliver Akins (2019/11/06 - 2020/07/21)
|
||||
//
|
||||
|
||||
|
||||
export const VERSION: string = "v2020.07.21";
|
||||
|
||||
|
||||
// The indicator used to tell the bot what arguments are flags.
|
||||
// This indicator cannot be used as the start of any non-flag argument
|
||||
export const FLAG_INDICATOR: string = "$"
|
||||
|
||||
|
||||
// The number of seconds for the confirmation timeouts
|
||||
export const CONFIRM_TIMEOUT: number = 5;
|
||||
|
||||
|
||||
export const PERM: perms = {
|
||||
ALL: 0,
|
||||
MOD: 1,
|
||||
ADMIN: 2
|
||||
};
|
||||
|
||||
|
||||
export const LIMIT = {
|
||||
DISCORD: 2000,
|
||||
TWITCH: 500
|
||||
};
|
||||
|
||||
|
||||
export const TEST_CHANNEL = "#tests_channel#";
|
||||
export const TEST_LINKS = "#test_links";
|
||||
export const TEST_USER = "#test_user#";
|
||||
|
||||
|
||||
export const REPO = "https://github.com/Oliver-Akins/chatbot-template";
|
||||
37
src/main.ts
Normal file
37
src/main.ts
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
//
|
||||
// main.ts
|
||||
//
|
||||
// Written by: Oliver Akins (2019/11/06 - 2020/07/21)
|
||||
//
|
||||
|
||||
|
||||
import { run_discord } from "./services/discord_handler";
|
||||
import { run_twitch } from "./services/twitch_handler";
|
||||
import { run_tests } from "./services/test_runner";
|
||||
import { LOAD_CONFIG } from "./utils/Config";
|
||||
|
||||
|
||||
let config = LOAD_CONFIG();
|
||||
let args = process.argv.slice(2);
|
||||
|
||||
|
||||
// Not enough arguments
|
||||
if (args.length < 1) {
|
||||
console.error(`Too few arguments.`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
|
||||
if (args.includes("--test")) {
|
||||
process.exit(run_tests(args.includes("--silent")));
|
||||
};
|
||||
|
||||
|
||||
if (args.includes("--twitch")) {
|
||||
run_twitch();
|
||||
};
|
||||
|
||||
|
||||
if (args.includes("--discord")) {
|
||||
run_discord();
|
||||
};
|
||||
129
src/services/discord_handler.ts
Normal file
129
src/services/discord_handler.ts
Normal file
|
|
@ -0,0 +1,129 @@
|
|||
//
|
||||
// discord_handler.ts
|
||||
//
|
||||
// Written by: Oliver Akins (2019/11/23 - 2019/12/19)
|
||||
//
|
||||
|
||||
|
||||
import { log_error, log } from "../utils/webhook";
|
||||
import { HANDLE_MESSAGE } from "../cmd_handler";
|
||||
import { LOAD_CONFIG } from "../utils/Config";
|
||||
import { PERM } from "../constants";
|
||||
const Eris = require("eris");
|
||||
|
||||
|
||||
|
||||
export const run_discord = (): void => {
|
||||
|
||||
const config: config = LOAD_CONFIG();
|
||||
|
||||
let bot = new Eris(config.DEV ? config.discord.DEV_TOKEN : config.discord.OAUTH_TOKEN);
|
||||
|
||||
|
||||
bot.on("ready", () => {
|
||||
log({ msg: `* Connected to Discord gateway` });
|
||||
});
|
||||
|
||||
|
||||
// Message handler
|
||||
bot.on("messageCreate", (msg: any) => {
|
||||
try {
|
||||
|
||||
// Ensure message to parse
|
||||
if (msg.content.length === 0) { return; };
|
||||
|
||||
|
||||
// SECTION: Exit conditions
|
||||
|
||||
// NOTE: Ensure not a system message
|
||||
if (msg.type !== 0) { return; }
|
||||
|
||||
// NOTE: Ensure channel type is GUILD_TEXT
|
||||
else if (msg.channel.type !== 0) { return; }
|
||||
|
||||
// NOTE: Ensure not a webhook or Clyde
|
||||
else if (msg.author.discriminator === "0000") { return; }
|
||||
|
||||
// NOTE: Ensure not a bot
|
||||
else if (msg.member.bot) { return; }
|
||||
|
||||
// !SECTION: Exit conditions
|
||||
|
||||
|
||||
var is_mod = msg.member.roles.filter(
|
||||
(x: string) => { return config.discord.MOD_ROLES.includes(x); }
|
||||
).length > 0;
|
||||
var is_admin = config.discord.ADMIN.includes(msg.member.id);
|
||||
|
||||
|
||||
var level = PERM.ALL;
|
||||
if (is_mod) { level = PERM.MOD; };
|
||||
if (is_admin) { level = PERM.ADMIN; };
|
||||
|
||||
|
||||
var response: string | void = HANDLE_MESSAGE({
|
||||
channel: `Discord:${msg.member.guild.id}`,
|
||||
level: level,
|
||||
message: msg.content.trim().replace(/\n/g, ""),
|
||||
source: "Discord",
|
||||
user: msg.author.username,
|
||||
cooldown: true,
|
||||
test: false
|
||||
});
|
||||
|
||||
// NOTE: Ensure response isn't null
|
||||
if (response !== null) {
|
||||
|
||||
// NOTE: Reply with string
|
||||
bot.createMessage(msg.channel.id, response)
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
// SECTION: Error Handling
|
||||
catch (error) {
|
||||
log_error({
|
||||
"embeds": [
|
||||
{
|
||||
"title": `${error.name}`,
|
||||
"color": 13238272,
|
||||
"description": `**Error Message:**\n\`\`\`\n${error.message}\n\`\`\``,
|
||||
"fields": [
|
||||
{
|
||||
"name": "**Message Context:**",
|
||||
"value": `\`\`\`\n${JSON.stringify(msg, null, 2)}\n\`\`\``
|
||||
},
|
||||
{
|
||||
"name": "**Message Content:**",
|
||||
"value": `\`\`\`json\n${msg.content}\`\`\``
|
||||
},
|
||||
{
|
||||
"name": "**Is Mod:**",
|
||||
"value": `\`${is_mod}\``,
|
||||
"inline": true
|
||||
},
|
||||
{
|
||||
"name": "**Is Admin:**",
|
||||
"value": `\`${is_admin}\``,
|
||||
"inline": true
|
||||
},
|
||||
{
|
||||
"name": "**Channel:**",
|
||||
"value": `\`${msg.channel.name}\``,
|
||||
"inline": true
|
||||
},
|
||||
{
|
||||
"name": "Source",
|
||||
"value": "Discord",
|
||||
"inline": true
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
});
|
||||
};
|
||||
// !SECTION: Error Handling
|
||||
});
|
||||
|
||||
bot.connect();
|
||||
};
|
||||
72
src/services/test_runner.ts
Normal file
72
src/services/test_runner.ts
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
//
|
||||
// test_runner.ts
|
||||
//
|
||||
// Written by: Oliver Akins (2019/11/17 - 2020/07/21)
|
||||
//
|
||||
|
||||
|
||||
import { TEST_CHANNEL, TEST_USER } from "../constants";
|
||||
import { HANDLE_MESSAGE } from "../cmd_handler";
|
||||
import { LOAD_CONFIG } from "../utils/Config";
|
||||
import { tests } from "../utils/tests";
|
||||
|
||||
|
||||
const config = LOAD_CONFIG();
|
||||
var fail_count = 0;
|
||||
|
||||
|
||||
export const run_tests = (silent: boolean): number => {
|
||||
|
||||
// Run through each test
|
||||
for (var test of tests) {
|
||||
|
||||
|
||||
let response = HANDLE_MESSAGE({
|
||||
message: test.msg_meta.message,
|
||||
level: test.msg_meta.level,
|
||||
user: TEST_USER,
|
||||
cooldown: false,
|
||||
source: test.msg_meta.source,
|
||||
channel: test.msg_meta.channel || TEST_CHANNEL,
|
||||
test: true
|
||||
});
|
||||
|
||||
|
||||
// If the confirmation message is defined, trigger a confirmation
|
||||
if (test.confirm_msg) {
|
||||
response = HANDLE_MESSAGE({
|
||||
message: test.confirm_msg.message,
|
||||
level: test.confirm_msg.level,
|
||||
user: TEST_USER,
|
||||
cooldown: false,
|
||||
source: test.confirm_msg.source,
|
||||
channel: test.msg_meta.channel || TEST_CHANNEL,
|
||||
test: true
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
// Compare outputs
|
||||
if (test.expected_return != response) {
|
||||
fail_count++;
|
||||
if (!silent) {
|
||||
console.log("=====================================================");
|
||||
console.log(`Test ${test.id} failed`);
|
||||
console.log(` Expected: "${test.expected_return}"`);
|
||||
console.log(` Received: "${response}"`);
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
// Check if we are being silent
|
||||
if (!silent && fail_count > 0) {
|
||||
console.log("=====================================================");
|
||||
};
|
||||
|
||||
|
||||
// Output summary
|
||||
console.log(`Tests: ${fail_count} tests failed out of ${tests.length} tests.`);
|
||||
console.log(` ${Math.round(((tests.length - fail_count) / tests.length) * 100)}% passed`);
|
||||
return fail_count;
|
||||
};
|
||||
148
src/services/twitch_handler.ts
Normal file
148
src/services/twitch_handler.ts
Normal file
|
|
@ -0,0 +1,148 @@
|
|||
//
|
||||
// twitch_handler.ts
|
||||
//
|
||||
// Written by: Oliver Akins (2019/12/10 - 2020/07/21)
|
||||
//
|
||||
|
||||
/*
|
||||
tmi.js DOCS: https://github.com/tmijs/docs/blob/gh-pages/_posts/v1.4.2/2019-03-03-Events.md
|
||||
*/
|
||||
|
||||
|
||||
import { log_error, log, push } from "../utils/webhook";
|
||||
import { HANDLE_MESSAGE } from "../cmd_handler";
|
||||
import { LOAD_CONFIG } from "../utils/Config";
|
||||
import { PERM } from "../constants";
|
||||
import * as tmi from "tmi.js";
|
||||
|
||||
|
||||
|
||||
export const run_twitch = (): void => {
|
||||
|
||||
const config: config = LOAD_CONFIG();
|
||||
|
||||
|
||||
// Init Client
|
||||
const client = tmi.Client({
|
||||
options: {
|
||||
debug: config.DEV,
|
||||
clientId: config.twitch.CLIENT_ID
|
||||
},
|
||||
connection: {
|
||||
secure: true,
|
||||
reconnect: true
|
||||
},
|
||||
identity: {
|
||||
username: config.twitch.USERNAME,
|
||||
password: config.twitch.OAUTH_TOKEN
|
||||
},
|
||||
channels: config.twitch.CHANNELS
|
||||
});
|
||||
|
||||
|
||||
|
||||
// SECTION: Handle messages
|
||||
client.on("message", (channel: string, context: tmi.Userstate, message: string, self: boolean) => {
|
||||
try {
|
||||
|
||||
// SECTION: Context checking
|
||||
|
||||
// NOTE: Ensure not self
|
||||
if (self) { return; }
|
||||
|
||||
// NOTE: Ensure text channel, not whisper or anything else weird.
|
||||
else if (context["message-type"] !== "chat") { return; }
|
||||
|
||||
// !SECTION: Context checking
|
||||
|
||||
|
||||
// SECTION: Context parsing
|
||||
var is_admin = config.twitch.ADMIN.includes(context.username);
|
||||
var is_mod = (
|
||||
context.mod ||
|
||||
context.badges ? context.badges.moderator === "1" : false ||
|
||||
context.badges ? context.badges.broadcaster === "1" : false ||
|
||||
is_admin
|
||||
);
|
||||
|
||||
var level = PERM.ALL;
|
||||
if (is_mod) { level = PERM.MOD; };
|
||||
if (is_admin) { level = PERM.ADMIN; };
|
||||
// !SECTION: Context parsing
|
||||
|
||||
|
||||
// NOTE: Get response
|
||||
let response: string = HANDLE_MESSAGE({
|
||||
message: message,
|
||||
channel: `Twitch:${channel}`,
|
||||
level: level,
|
||||
source: "Twitch",
|
||||
user: context.username,
|
||||
cooldown: true,
|
||||
test: false
|
||||
});
|
||||
|
||||
|
||||
// NOTE: Ensure response isn't null
|
||||
if (response) {
|
||||
client.say(
|
||||
channel,
|
||||
response.replace(/`/g, `"`)
|
||||
);
|
||||
};
|
||||
} catch (error) {
|
||||
log_error({
|
||||
"embeds": [
|
||||
{
|
||||
"title": `${error.name}`,
|
||||
"color": 13238272,
|
||||
"description": `**Error Message:**\n\`\`\`\n${error.message}\n\`\`\``,
|
||||
"fields": [
|
||||
{
|
||||
"name": "**Message Context:**",
|
||||
"value": `\`\`\`\n${JSON.stringify(context, null, 2)}\n\`\`\``
|
||||
},
|
||||
{
|
||||
"name": "**Message Content:**",
|
||||
"value": `\`\`\`json\n${message}\`\`\``
|
||||
},
|
||||
{
|
||||
"name": "**Is Mod:**",
|
||||
"value": `\`${is_mod}\``,
|
||||
"inline": true
|
||||
},
|
||||
{
|
||||
"name": "**Is Admin:**",
|
||||
"value": `\`${is_admin}\``,
|
||||
"inline": true
|
||||
},
|
||||
{
|
||||
"name": "**Channel:**",
|
||||
"value": `\`${channel}\``,
|
||||
"inline": true
|
||||
},
|
||||
{
|
||||
"name": "Source",
|
||||
"value": "Twitch",
|
||||
"inline": true
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
});
|
||||
}
|
||||
});
|
||||
// !SECTION
|
||||
|
||||
|
||||
client.on("disconnected", (reason: string) => {
|
||||
log({ msg: `* Disconnected from Twitch w/ reason: ${reason}` });
|
||||
});
|
||||
|
||||
|
||||
client.on("connected", (addr: string, port: number) => {
|
||||
log({ msg: `* Connected to Twitch on \`${addr}:${port}\`` });
|
||||
});
|
||||
|
||||
client.connect().catch((_) => {})
|
||||
};
|
||||
42
src/types/command_metadata.d.ts
vendored
Normal file
42
src/types/command_metadata.d.ts
vendored
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
//
|
||||
// command_metadata.d.ts
|
||||
//
|
||||
// Written by: Oliver Akins (2019/11/06 - 2020/01/04)
|
||||
//
|
||||
|
||||
|
||||
type CONFIRM_TYPE = "confirm"|"deny"|"no_match"|"expired"|"invalid";
|
||||
|
||||
|
||||
|
||||
interface positions {
|
||||
head?: string;
|
||||
head_2?: string;
|
||||
table_head?: string;
|
||||
table_foot?: string;
|
||||
usage?: string;
|
||||
}
|
||||
|
||||
interface alert_structure {
|
||||
info?: positions;
|
||||
warn?: positions;
|
||||
error?: positions;
|
||||
}
|
||||
|
||||
|
||||
|
||||
interface cmd_metadata {
|
||||
executable(context: msg_data, args: string[]): string;
|
||||
flags: {[key: string]: string};
|
||||
requires_confirm: boolean;
|
||||
alerts?: alert_structure;
|
||||
case_sensitive: boolean;
|
||||
description: string;
|
||||
keywords?: string[][];
|
||||
arg_info: string[];
|
||||
opt_args: number;
|
||||
group?: string;
|
||||
args: string[];
|
||||
level: number;
|
||||
name?: string;
|
||||
}
|
||||
58
src/types/config.d.ts
vendored
Normal file
58
src/types/config.d.ts
vendored
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
//
|
||||
// config.d.ts
|
||||
//
|
||||
// Written by: Oliver Akins (2019/11/07 - 2020/07/21)
|
||||
//
|
||||
|
||||
interface auth_options {
|
||||
OAUTH_TOKEN: string;
|
||||
SECRET?: string;
|
||||
CLIENT_ID?: string;
|
||||
ADMIN: string[];
|
||||
}
|
||||
|
||||
interface discord_options extends auth_options {
|
||||
PERMISSIONS_VALUE: string;
|
||||
MOD_ROLES: string;
|
||||
DEV_TOKEN: string;
|
||||
}
|
||||
interface twitch_options extends auth_options {
|
||||
CHANNELS: [string];
|
||||
USERNAME: string;
|
||||
}
|
||||
|
||||
|
||||
interface bot_options {
|
||||
PREFIX: string;
|
||||
COOLDOWN_TIME: number;
|
||||
INVALID_PERM_ERROR: boolean;
|
||||
COOLDOWN_TYPE: "GLOBAL"|"COMMAND"|"SERVICE";
|
||||
}
|
||||
|
||||
|
||||
|
||||
interface web_server_options {
|
||||
ADDRESS: string;
|
||||
ROOT: string;
|
||||
PORT: number;
|
||||
}
|
||||
|
||||
|
||||
|
||||
interface config {
|
||||
DEV: boolean;
|
||||
twitch: twitch_options;
|
||||
discord: discord_options;
|
||||
bot: bot_options;
|
||||
webhooks: {
|
||||
ENABLED: boolean;
|
||||
LOGGING: string;
|
||||
ERROR?: string;
|
||||
TWITCH_MISSED_BITS?: string;
|
||||
};
|
||||
web: web_server_options;
|
||||
extra: { [index: string]: any }
|
||||
}
|
||||
|
||||
|
||||
type WEBHOOK_TYPE = "LOGGING"|"ERROR"|"TWITCH_MISSED_BITS";
|
||||
20
src/types/message_metadata.d.ts
vendored
Normal file
20
src/types/message_metadata.d.ts
vendored
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
//
|
||||
// message_metadata.d.ts
|
||||
//
|
||||
// Written by: Oliver Akins (2019/11/07 - 2020/01/04)
|
||||
//
|
||||
|
||||
|
||||
type platform = "Discord"|"Twitch"
|
||||
|
||||
|
||||
interface msg_data {
|
||||
cooldown: boolean;
|
||||
source: platform;
|
||||
channel: string;
|
||||
message: string;
|
||||
flags?: string[];
|
||||
level: number;
|
||||
test: boolean;
|
||||
user: string;
|
||||
}
|
||||
17
src/types/option.d.ts
vendored
Normal file
17
src/types/option.d.ts
vendored
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
//
|
||||
// option.d.ts
|
||||
//
|
||||
// Written by: Oliver Akins (2019/11/11 - 2020/01/04)
|
||||
//
|
||||
|
||||
|
||||
interface option {
|
||||
aliases: string[];
|
||||
name: string;
|
||||
points: {
|
||||
[key: string]: number
|
||||
};
|
||||
total: number;
|
||||
data_version: string;
|
||||
hidden: boolean;
|
||||
}
|
||||
11
src/types/permission_levels.d.ts
vendored
Normal file
11
src/types/permission_levels.d.ts
vendored
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
//
|
||||
// permission_levels.d.ts
|
||||
//
|
||||
// Written by: Oliver Akins (2019/11/07 - 2019/11/07)
|
||||
//
|
||||
|
||||
interface perms {
|
||||
ALL: number;
|
||||
MOD: number;
|
||||
ADMIN: number;
|
||||
}
|
||||
24
src/types/test_object.d.ts
vendored
Normal file
24
src/types/test_object.d.ts
vendored
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
//
|
||||
// test_object.ts
|
||||
//
|
||||
// Written by: Oliver Akins (2019/11/17 - 2020/01/10)
|
||||
//
|
||||
|
||||
|
||||
interface test_msg_data {
|
||||
source: platform;
|
||||
channel?: string;
|
||||
message: string;
|
||||
level: number;
|
||||
}
|
||||
|
||||
|
||||
interface test {
|
||||
datafile_should_exist: "EXISTS"|"NOT_EXISTS"|"IGNORES";
|
||||
datafile_populated?: boolean;
|
||||
confirm_msg?: test_msg_data;
|
||||
expected_return: string;
|
||||
msg_meta: test_msg_data;
|
||||
links: {[key: string]: string}
|
||||
id: string;
|
||||
}
|
||||
14
src/types/webhooks.d.ts
vendored
Normal file
14
src/types/webhooks.d.ts
vendored
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
//
|
||||
// webhooks.d.ts
|
||||
//
|
||||
// Written by: Oliver Akins (2019/11/11)
|
||||
//
|
||||
|
||||
|
||||
interface log_data {
|
||||
msg: string;
|
||||
title?: string;
|
||||
embed?: boolean;
|
||||
fields?: object;
|
||||
no_stdout?: boolean;
|
||||
}
|
||||
159
src/utils/Command.ts
Normal file
159
src/utils/Command.ts
Normal file
|
|
@ -0,0 +1,159 @@
|
|||
//
|
||||
// Command.ts
|
||||
//
|
||||
// Written by: Oliver Akins (2019/11/06 - 2020/07/21)
|
||||
//
|
||||
|
||||
|
||||
import { LOAD_CONFIG } from "./Config";
|
||||
|
||||
|
||||
export class Command {
|
||||
|
||||
readonly requires_confirm: boolean;
|
||||
readonly case_sensitive: boolean;
|
||||
readonly keywords: string[][];
|
||||
readonly arg_list: string[];
|
||||
readonly arg_info: string[];
|
||||
readonly mand_args: number;
|
||||
readonly full_name: string;
|
||||
readonly opt_args: number;
|
||||
readonly syntax: string;
|
||||
readonly level: number;
|
||||
readonly group: string;
|
||||
readonly flags: object;
|
||||
readonly info: string;
|
||||
readonly name: string;
|
||||
|
||||
readonly alert: alert_structure;
|
||||
|
||||
private _func: (context: msg_data, args: string[]) => string;
|
||||
|
||||
public last_ran: number;
|
||||
|
||||
|
||||
constructor (metadata: cmd_metadata) {
|
||||
this.mand_args = metadata.args.length - metadata.opt_args;
|
||||
this.case_sensitive = metadata.case_sensitive;
|
||||
this.opt_args = metadata.opt_args;
|
||||
this.info = metadata.description;
|
||||
this._func = metadata.executable;
|
||||
this.arg_list = metadata.args;
|
||||
this.group = metadata.group;
|
||||
this.level = metadata.level;
|
||||
this.name = metadata.name;
|
||||
this.keywords = metadata.keywords || [];
|
||||
this.alert = metadata.alerts;
|
||||
this.requires_confirm = metadata.requires_confirm;
|
||||
this.full_name = this.group ? `${this.group} ${this.name}` : `${this.name}`;
|
||||
this.arg_info = metadata.arg_info;
|
||||
this.flags = metadata.flags;
|
||||
|
||||
|
||||
// NOTE: Create syntax dynamically
|
||||
let config: config = LOAD_CONFIG();
|
||||
|
||||
this.syntax = config.bot.PREFIX;
|
||||
this.syntax += this.group ? `${this.group} ${this.name}` : `${this.name}`;
|
||||
if (this.arg_list.length > 0) {
|
||||
this.syntax += ` ${this.arg_list.join(" ")}`;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
// Does the user's message match a command
|
||||
public matches (message: string): boolean {
|
||||
|
||||
const config: config = LOAD_CONFIG();
|
||||
|
||||
|
||||
// Only check for name/group match if the name is specified
|
||||
if (this.name != null) {
|
||||
|
||||
// Construct the regex
|
||||
let regex: string = `^${config.bot.PREFIX}`;
|
||||
if (this.group != null) { regex += `(${this.group}\ )`; };
|
||||
regex += `${this.name}`;
|
||||
|
||||
if (message.match(new RegExp(regex)) != null) {
|
||||
return true;
|
||||
};
|
||||
};
|
||||
|
||||
// Compare the keyword sets to the message
|
||||
for (var keyword_set of this.keywords) {
|
||||
let all_included: boolean = true;
|
||||
|
||||
// Check that each keyword is in the message
|
||||
for (var keyword of keyword_set) {
|
||||
if (!message.includes(keyword)) {
|
||||
all_included = false;
|
||||
break;
|
||||
};
|
||||
};
|
||||
if (all_included) { return true; };
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
|
||||
public execute (ctx: msg_data, args: string[]): string {
|
||||
return this._func(ctx, args)
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
|
||||
|
||||
export class Confirmation {
|
||||
|
||||
readonly username: string;
|
||||
readonly channel: string;
|
||||
|
||||
private data: any;
|
||||
private created: number;
|
||||
private timeout: number;
|
||||
private callback: (type: CONFIRM_TYPE, data?: any) => string;
|
||||
|
||||
|
||||
constructor (
|
||||
username: string,
|
||||
channel: string,
|
||||
timeout: number,
|
||||
cb: (type: CONFIRM_TYPE, data?: any) => string,
|
||||
data?: any
|
||||
) {
|
||||
this.username = username;
|
||||
this.channel = channel;
|
||||
this.created = Date.now();
|
||||
this.callback = cb;
|
||||
this.timeout = timeout * 1000;
|
||||
this.data = data;
|
||||
};
|
||||
|
||||
|
||||
|
||||
public matches (user: string, channel: string, msg: string): CONFIRM_TYPE {
|
||||
|
||||
const config: config = LOAD_CONFIG();
|
||||
|
||||
|
||||
// Timeout checking
|
||||
if (Date.now() - this.created > this.timeout) { return "expired"; }
|
||||
|
||||
// basic user checking
|
||||
else if (this.username !== user) { return "no_match"; }
|
||||
else if (this.channel !== channel) { return "no_match"; }
|
||||
|
||||
// Positive or negative match?
|
||||
else if (msg.match(`^${config.bot.PREFIX}[Yy](es)?$`)) { return "confirm"; }
|
||||
else if (msg.match(`^${config.bot.PREFIX}[Nn](o)?$`)) { return "deny"; }
|
||||
|
||||
// Not valid
|
||||
else { return "invalid"; };
|
||||
};
|
||||
|
||||
public run (type: CONFIRM_TYPE): string {
|
||||
return this.callback(type, this.data)
|
||||
}
|
||||
};
|
||||
96
src/utils/Commands.ts
Normal file
96
src/utils/Commands.ts
Normal file
|
|
@ -0,0 +1,96 @@
|
|||
//
|
||||
// Commands.ts
|
||||
//
|
||||
// Written by: Oliver Akins (2021/02/09)
|
||||
//
|
||||
|
||||
import { Command } from "./Command";
|
||||
|
||||
type commandTree = {[index: string]: Command|commandTree};
|
||||
type invalidArgument = { provided: string, allowed: string[] };
|
||||
|
||||
|
||||
export class Commands {
|
||||
/**
|
||||
* The tree of command objects which have been registered.
|
||||
*/
|
||||
private static commands: commandTree = {};
|
||||
private static channelCommands: {[index: string]: commandTree} = {};
|
||||
|
||||
/**
|
||||
* Finds the command object that matches the message if there is one, this
|
||||
* can return null if no command at all is able to be found. If
|
||||
*
|
||||
* @param cmd
|
||||
*/
|
||||
public findCommand(cmd: string): Command | string {
|
||||
let resp = this.findCommandRecurse(cmd.split(` `), Commands.commands);
|
||||
|
||||
// Check what type of response to provide
|
||||
if (resp instanceof Command) {
|
||||
return resp;
|
||||
} else {
|
||||
return `Invalid argument "${resp.provided}", possible options: ${resp.allowed.join(`, `)}`;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Find the command that is attempting to be ran if there are any channel
|
||||
* specific commands which have been registered.
|
||||
*
|
||||
* @param cmd - The message that we are inspecting for a command
|
||||
* @param channel - The channel that we are looking for commands for
|
||||
*/
|
||||
public findChannelCommand(cmd: string, channel: string): Command | string {
|
||||
|
||||
// Assert that we have a commandsTree for that channel
|
||||
if (!Commands.channelCommands[channel]) {
|
||||
return null;
|
||||
};
|
||||
|
||||
let resp = this.findCommandRecurse(
|
||||
cmd.split(` `),
|
||||
Commands.channelCommands[channel]
|
||||
);
|
||||
|
||||
// Check what type of response to provide
|
||||
if (resp instanceof Command) {
|
||||
return resp;
|
||||
} else {
|
||||
return `Invalid argument "${resp.provided}", possible options: ${resp.allowed.join(`, `)}`;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* The helper function to be able to find the proper command object or the
|
||||
* arguments that are valid at that point.
|
||||
*
|
||||
* @param command - The array of strings that the user has in their message
|
||||
* for parsing the command arguments.
|
||||
* @param tree - The commands object we are checking for properties
|
||||
*/
|
||||
private findCommandRecurse(
|
||||
command: string[],
|
||||
tree: commandTree
|
||||
): Command|invalidArgument {
|
||||
// BASE CASE: The subcommand isn't found or the command ran out of text
|
||||
if (command.length == 0 || tree[command[0]] == null){
|
||||
return {
|
||||
provided: command[0],
|
||||
allowed: Object.keys(tree),
|
||||
};
|
||||
};
|
||||
|
||||
// BASE CASE: The command has been found
|
||||
if (tree[command[0]] instanceof Command) {
|
||||
return tree[command[0]] as Command;
|
||||
};
|
||||
|
||||
// RECURSIVE CASE: check the subcommand tree
|
||||
return this.findCommandRecurse(command.slice(1), tree[command[0]] as commandTree);
|
||||
};
|
||||
|
||||
public static registerCommand() {};
|
||||
}
|
||||
31
src/utils/Config.ts
Normal file
31
src/utils/Config.ts
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
//
|
||||
// Config.ts
|
||||
//
|
||||
// Written by: Oliver Akins (2019/11/07 - 2019/12/29)
|
||||
//
|
||||
|
||||
|
||||
import { readFileSync, writeFile } from "fs"
|
||||
|
||||
|
||||
|
||||
export const LOAD_CONFIG = (): config => {
|
||||
let config = require.resolve("../../config.json");
|
||||
|
||||
let data = readFileSync(config);
|
||||
|
||||
// @ts-ignore
|
||||
return JSON.parse(data);
|
||||
};
|
||||
|
||||
|
||||
|
||||
export const UPDATE_CONFIG = (data: config): void => {
|
||||
writeFile(
|
||||
require.resolve("../../config.json"),
|
||||
JSON.stringify(data, null, 2),
|
||||
() => {
|
||||
console.log("* [Config] Config written to.");
|
||||
}
|
||||
)
|
||||
};
|
||||
38
src/utils/flags.ts
Normal file
38
src/utils/flags.ts
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
//
|
||||
// flags.ts
|
||||
//
|
||||
// Written by: Oliver Akins (2020/01/04 - 2020/01/31)
|
||||
//
|
||||
|
||||
|
||||
import { FLAG_INDICATOR } from "../constants";
|
||||
|
||||
|
||||
|
||||
export const GET_FLAGS = (msg: string): string[] => {
|
||||
|
||||
// Array of flags included in the message
|
||||
let flags: string[] = []
|
||||
|
||||
|
||||
// Check each parameter of the message
|
||||
for (var argument of msg.split(" ")) {
|
||||
|
||||
// Check if the argument is indicated as a flag
|
||||
if (argument.startsWith(FLAG_INDICATOR)) {
|
||||
|
||||
// Check each flag
|
||||
for (var temp_flag of argument.slice(FLAG_INDICATOR.length)) {
|
||||
|
||||
temp_flag = temp_flag.toLowerCase();
|
||||
|
||||
// Only add flags to the array once
|
||||
if (!flags.includes(temp_flag)) {
|
||||
flags.push(temp_flag);
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
return flags;
|
||||
}
|
||||
39
src/utils/sorting.ts
Normal file
39
src/utils/sorting.ts
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
//
|
||||
// sorting.ts
|
||||
//
|
||||
// Written by: Oliver Akins (2019/11/29 - 2019/12/13)
|
||||
//
|
||||
|
||||
|
||||
import { Command } from "./Command";
|
||||
|
||||
|
||||
export const SORT_OPTIONS = (data: option[]): option[] => {
|
||||
return data.sort((a: option, b: option): number => {
|
||||
let a_total: number = a.total;
|
||||
let b_total: number = b.total;
|
||||
|
||||
|
||||
if (a_total < b_total) { return 1; }
|
||||
|
||||
else if (a_total > b_total) { return -1; }
|
||||
|
||||
else { return 0; };
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
|
||||
export const SORT_COMMANDS = (data: Command[]): Command[] => {
|
||||
return data.sort((a: Command, b: Command): number => {
|
||||
let a_name: string = a.full_name;
|
||||
let b_name: string = b.full_name;
|
||||
|
||||
|
||||
if (a_name < b_name) { return -1; }
|
||||
|
||||
else if (a_name > b_name) { return 1; }
|
||||
|
||||
else { return 0; };
|
||||
});
|
||||
};
|
||||
31
src/utils/tests.ts
Normal file
31
src/utils/tests.ts
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
//
|
||||
// tests.ts
|
||||
//
|
||||
// Written by: Oliver Akins (2019/11/17 - 2020/01/10)
|
||||
//
|
||||
|
||||
|
||||
import { PERM, VERSION, TEST_CHANNEL, REPO } from "../constants";
|
||||
import { LOAD_CONFIG } from "./Config";
|
||||
|
||||
|
||||
const config: config = LOAD_CONFIG();
|
||||
|
||||
export const SEND_INVALID_PERM: boolean = config.bot.INVALID_PERM_ERROR
|
||||
export const PREFIX: string = config.bot.PREFIX;
|
||||
|
||||
|
||||
export let tests: test[] = [
|
||||
{
|
||||
id: `general:01`,
|
||||
links: {},
|
||||
datafile_should_exist: `IGNORES`,
|
||||
msg_meta: {
|
||||
source: `Twitch`,
|
||||
message: `potato salad`,
|
||||
level: PERM.ALL,
|
||||
channel: TEST_CHANNEL
|
||||
},
|
||||
expected_return: null
|
||||
}
|
||||
];
|
||||
80
src/utils/webhook.ts
Normal file
80
src/utils/webhook.ts
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
//
|
||||
// webhook.ts
|
||||
//
|
||||
// Written by: Oliver Akins (2019/11/11 - 2019/12/19)
|
||||
//
|
||||
|
||||
|
||||
import * as requests from "request-promise-native";
|
||||
import { LOAD_CONFIG } from "./Config";
|
||||
|
||||
|
||||
const config: config = LOAD_CONFIG();
|
||||
|
||||
|
||||
|
||||
export const log = (context: log_data) => {
|
||||
|
||||
|
||||
// Should we output the data to the console, ensure the data is console-outputable
|
||||
if (config.DEV && !context.no_stdout) {
|
||||
console.log(context.msg);
|
||||
};
|
||||
|
||||
// Are we embedding the response or not?
|
||||
if (context.embed) {
|
||||
let payload = {
|
||||
"content": "Log Entry:",
|
||||
"embeds": [
|
||||
{
|
||||
color: 43520,
|
||||
title: context.title,
|
||||
description: context.msg,
|
||||
fields: []
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
// Add fields
|
||||
for (var field in context.fields) {
|
||||
payload.embeds[0].fields.push({
|
||||
name: field,
|
||||
value: context.fields[field],
|
||||
inline: true
|
||||
});
|
||||
};
|
||||
|
||||
push(payload, "LOGGING")
|
||||
} else {
|
||||
push({
|
||||
"content": context.msg
|
||||
}, "LOGGING");
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
|
||||
export const log_error = (payload: any) => {
|
||||
push(payload, "ERROR");
|
||||
};
|
||||
|
||||
|
||||
|
||||
export const push = (payload: any, webhook: WEBHOOK_TYPE) => {
|
||||
|
||||
// Output to stdout?
|
||||
if (payload.content && !payload.no_stdout && payload.no_stdout != undefined) {
|
||||
console.log(payload.content)
|
||||
};
|
||||
|
||||
// Don't try to execute webhook if they aren't enabled
|
||||
if (!config.webhooks.ENABLED) { return; }
|
||||
|
||||
requests.post({
|
||||
uri: config.webhooks[webhook],
|
||||
body: payload,
|
||||
json: true
|
||||
}).catch((_: any) => {
|
||||
console.error("OHNO, Shit Went DOWWWNNNNNN");
|
||||
});
|
||||
};
|
||||
Loading…
Add table
Add a link
Reference in a new issue