initial update

This commit is contained in:
murm 2023-03-15 10:09:09 -04:00
parent 3272429cf6
commit db9b70bf66
280 changed files with 11772 additions and 11966 deletions

View file

@ -1,5 +1,5 @@
import { debug } from "../utils/logger.js";
export default async (client, message) => {
debug(message);
import { debug } from "../utils/logger.js";
export default async (client, message) => {
debug(message);
};

View file

@ -1,5 +1,5 @@
import { error } from "../utils/logger.js";
export default async (client, message) => {
error(message);
import { error } from "../utils/logger.js";
export default async (client, message) => {
error(message);
};

View file

@ -1,6 +0,0 @@
import { log } from "../utils/logger.js";
// run when the bot is added to a guild
export default async (client, guild) => {
log(`[GUILD JOIN] ${guild.name} (${guild.id}) added the bot.`);
};

View file

@ -1,6 +0,0 @@
import { log } from "../utils/logger.js";
// run when the bot is removed from a guild
export default async (client, guild) => {
log(`[GUILD LEAVE] ${guild.name} (${guild.id}) removed the bot.`);
};

View file

@ -1,89 +0,0 @@
import database from "../utils/database.js";
import * as logger from "../utils/logger.js";
import { commands, messageCommands } from "../utils/collections.js";
import { clean } from "../utils/misc.js";
import { upload } from "../utils/tempimages.js";
// run when a slash command is executed
export default async (client, interaction) => {
if (interaction?.type !== 2) return;
// check if command exists and if it's enabled
const command = interaction.data.name;
let cmd = commands.get(command);
if (!cmd) {
cmd = messageCommands.get(command);
if (!cmd) return;
}
if (cmd.dbRequired && !database) {
await interaction["createMessage"]({ content: "This command is unavailable on stateless instances of esmBot.", flags: 64 });
return;
}
const invoker = interaction.member ?? interaction.user;
// actually run the command
logger.log("log", `${invoker.username} (${invoker.id}) ran application command ${command}`);
try {
if (database) {
await database.addCount(command);
}
// eslint-disable-next-line no-unused-vars
const commandClass = new cmd(client, { type: "application", interaction });
const result = await commandClass.run();
const replyMethod = interaction.acknowledged ? "editOriginal" : "createMessage";
if (typeof result === "string") {
await interaction[replyMethod]({
content: result,
flags: commandClass.success ? 0 : 64
});
} else if (typeof result === "object") {
if (result.contents && result.name) {
const fileSize = 8388119;
if (result.contents.length > fileSize) {
if (process.env.TEMPDIR && process.env.TEMPDIR !== "") {
await upload(client, result, interaction, true);
} else {
await interaction[replyMethod]({
content: "The resulting image was more than 8MB in size, so I can't upload it.",
flags: 64
});
}
} else {
await interaction[replyMethod](result.text ? result.text : { files: [result] });
}
} else {
await interaction[replyMethod](Object.assign({
flags: result.flags ?? (commandClass.success ? 0 : 64)
}, result));
}
} else {
logger.warn(`Unknown return type for command ${command}: ${result} (${typeof result})`);
await interaction[replyMethod](Object.assign({
flags: commandClass.success ? 0 : 64
}, result));
}
} catch (error) {
const replyMethod = interaction.acknowledged ? "editOriginal" : "createMessage";
if (error.toString().includes("Request entity too large")) {
await interaction[replyMethod]({ content: "The resulting file was too large to upload. Try again with a smaller image if possible.", flags: 64 });
} else if (error.toString().includes("Job ended prematurely")) {
await interaction[replyMethod]({ content: "Something happened to the image servers before I could receive the image. Try running your command again.", flags: 64 });
} else {
logger.error(`Error occurred with application command ${command} with arguments ${JSON.stringify(interaction.data.optionsArray)}: ${error.stack || error}`);
try {
let err = error;
if (error?.constructor?.name == "Promise") err = await error;
await interaction[replyMethod]({
content: "Uh oh! I ran into an error while running this command. Please report the content of the attached file at the following link or on the esmBot Support server: <https://github.com/esmBot/esmBot/issues>",
files: [{
contents: `Message: ${clean(err)}\n\nStack Trace: ${clean(err.stack)}`,
name: "error.txt"
}]
});
} catch (e) {
logger.error(`While attempting to send the previous error message, another error occurred: ${e.stack || e}`);
}
}
}
};

View file

@ -1,184 +0,0 @@
import database from "../utils/database.js";
import { log, error as _error } from "../utils/logger.js";
import { prefixCache, aliases, disabledCache, disabledCmdCache, commands } from "../utils/collections.js";
import parseCommand from "../utils/parseCommand.js";
import { clean } from "../utils/misc.js";
import { upload } from "../utils/tempimages.js";
import { ThreadChannel } from "oceanic.js";
let mentionRegex;
// run when someone sends a message
export default async (client, message) => {
// ignore other bots
if (message.author.bot) return;
// don't run command if bot can't send messages
let permChannel = message.channel;
if (permChannel instanceof ThreadChannel && !permChannel.parent) {
try {
permChannel = await client.rest.channels.get(message.channel.parentID);
} catch {
return;
}
}
if (message.guildID && !permChannel.permissionsOf(client.user.id.toString()).has("SEND_MESSAGES")) return;
if (!mentionRegex) mentionRegex = new RegExp(`^<@!?${client.user.id}> `);
let guildDB;
let text;
const mentionResult = message.content.match(mentionRegex);
if (mentionResult) {
text = message.content.substring(mentionResult[0].length).trim();
} else if (message.guildID && database) {
const cachedPrefix = prefixCache.get(message.guildID);
if (cachedPrefix && message.content.startsWith(cachedPrefix)) {
text = message.content.substring(cachedPrefix.length).trim();
} else {
guildDB = await database.getGuild(message.guildID);
if (message.content.startsWith(guildDB.prefix)) {
text = message.content.substring(guildDB.prefix.length).trim();
prefixCache.set(message.guildID, guildDB.prefix);
} else {
return;
}
}
} else if (message.content.startsWith(process.env.PREFIX)) {
text = message.content.substring(process.env.PREFIX.length).trim();
} else if (!message.guildID) {
text = message.content;
} else {
return;
}
// separate commands and args
const preArgs = text.split(/\s+/g);
const command = preArgs.shift().toLowerCase();
const aliased = aliases.get(command);
// check if command exists and if it's enabled
const cmd = commands.get(aliased ?? command);
if (!cmd) return;
// block certain commands from running in DMs
if (!cmd.directAllowed && !message.guildID) return;
if (cmd.dbRequired && !database) {
await client.rest.channels.createMessage(message.channelID, {
content: "This command is unavailable on stateless instances of esmBot."
});
return;
}
// don't run if message is in a disabled channel
if (message.guildID && database) {
let disabled = disabledCache.get(message.guildID);
if (!disabled) {
if (!guildDB) guildDB = await database.getGuild(message.guildID);
disabledCache.set(message.guildID, guildDB.disabled);
disabled = guildDB.disabled;
}
if (disabled.includes(message.channelID) && command != "channel") return;
let disabledCmds = disabledCmdCache.get(message.guildID);
if (!disabledCmds) {
if (!guildDB) guildDB = await database.getGuild(message.guildID);
disabledCmdCache.set(message.guildID, guildDB.disabled_commands ?? guildDB.disabledCommands);
disabledCmds = guildDB.disabled_commands ?? guildDB.disabledCommands;
}
if (disabledCmds.includes(aliased ?? command)) return;
}
// actually run the command
log("log", `${message.author.username} (${message.author.id}) ran classic command ${command}`);
const reference = {
messageReference: {
channelID: message.channelID,
messageID: message.id,
guildID: message.guildID ?? undefined,
failIfNotExists: false
},
allowedMentions: {
repliedUser: false
}
};
try {
// parse args
const parsed = parseCommand(preArgs);
if (database) {
await database.addCount(aliases.get(command) ?? command);
}
const startTime = new Date();
// eslint-disable-next-line no-unused-vars
const commandClass = new cmd(client, { type: "classic", message, args: parsed._, content: text.replace(command, "").trim(), specialArgs: (({ _, ...o }) => o)(parsed) }); // we also provide the message content as a parameter for cases where we need more accuracy
const result = await commandClass.run();
const endTime = new Date();
if ((endTime - startTime) >= 180000) reference.allowedMentions.repliedUser = true;
if (typeof result === "string") {
reference.allowedMentions.repliedUser = true;
await client.rest.channels.createMessage(message.channelID, Object.assign({
content: result
}, reference));
} else if (typeof result === "object") {
if (result.contents && result.name) {
let fileSize = 8388119;
if (message.guildID) {
switch (message.guild.premiumTier) {
case 2:
fileSize = 52428308;
break;
case 3:
fileSize = 104856616;
break;
}
}
if (result.contents.length > fileSize) {
if (process.env.TEMPDIR && process.env.TEMPDIR !== "") {
await upload(client, result, message);
} else {
await client.rest.channels.createMessage(message.channelID, {
content: "The resulting image was more than 8MB in size, so I can't upload it."
});
}
} else {
await client.rest.channels.createMessage(message.channelID, Object.assign({
content: result.text ? result.text : undefined,
files: [result]
}, reference));
}
} else {
await client.rest.channels.createMessage(message.channelID, Object.assign(result, reference));
}
}
} catch (error) {
if (error.toString().includes("Request entity too large")) {
await client.rest.channels.createMessage(message.channelID, Object.assign({
content: "The resulting file was too large to upload. Try again with a smaller image if possible."
}, reference));
} else if (error.toString().includes("Job ended prematurely")) {
await client.rest.channels.createMessage(message.channelID, Object.assign({
content: "Something happened to the image servers before I could receive the image. Try running your command again."
}, reference));
} else if (error.toString().includes("Timed out")) {
await client.rest.channels.createMessage(message.channelID, Object.assign({
content: "The request timed out before I could download that image. Try uploading your image somewhere else or reducing its size."
}, reference));
} else {
_error(`Error occurred with command message ${message.content}: ${error.stack || error}`);
try {
let err = error;
if (error?.constructor?.name == "Promise") err = await error;
await client.rest.channels.createMessage(message.channelID, Object.assign({
content: "Uh oh! I ran into an error while running this command. Please report the content of the attached file at the following link or on the esmBot Support server: <https://github.com/esmBot/esmBot/issues>",
files: [{
contents: `Message: ${clean(err)}\n\nStack Trace: ${clean(err.stack)}`,
name: "error.txt"
}]
}, reference));
} catch (e) {
_error(`While attempting to send the previous error message, another error occurred: ${e.stack || e}`);
}
}
}
};

View file

@ -1,38 +1,38 @@
import { activityChanger, checkBroadcast } from "../utils/misc.js";
import { send } from "../utils/handler.js";
import { generateList, createPage } from "../utils/help.js";
import { logger } from "../utils/logger.js";
import { readFileSync } from "fs";
const { types } = JSON.parse(readFileSync(new URL("../config/commands.json", import.meta.url)));
let ready = false;
export default async (client) => {
if (ready) return;
// send slash command data
if (types.application) {
try {
await send(client);
} catch (e) {
logger.log("error", e);
logger.log("error", "Failed to send command data to Discord, slash/message commands may be unavailable.");
}
}
// generate docs
if (process.env.OUTPUT && process.env.OUTPUT !== "") {
generateList();
await createPage(process.env.OUTPUT);
logger.log("info", "The help docs have been generated.");
}
await checkBroadcast(client);
activityChanger(client);
ready = true;
if (process.env.PM2_USAGE) process.send("ready");
logger.log("info", "Started esmBot.");
import { activityChanger, checkBroadcast } from "../utils/misc.js";
import { send } from "../utils/handler.js";
import { generateList, createPage } from "../utils/help.js";
import { logger } from "../utils/logger.js";
import { readFileSync } from "fs";
const { types } = JSON.parse(readFileSync(new URL("../config/commands.json", import.meta.url)));
let ready = false;
export default async (client) => {
if (ready) return;
// send slash command data
if (types.application) {
try {
await send(client);
} catch (e) {
logger.log("error", e);
logger.log("error", "Failed to send command data to Discord, slash/message commands may be unavailable.");
}
}
// generate docs
if (process.env.OUTPUT && process.env.OUTPUT !== "") {
generateList();
await createPage(process.env.OUTPUT);
logger.log("info", "The help docs have been generated.");
}
await checkBroadcast(client);
activityChanger(client);
ready = true;
if (process.env.PM2_USAGE) process.send("ready");
logger.log("info", "Started esmBot.");
};

135
events/roommessage.js Normal file
View file

@ -0,0 +1,135 @@
import database from "../utils/database.js";
import { log, error as _error, logger } from "../utils/logger.js";
import { prefixCache, aliases, disabledCache, disabledCmdCache, commands } from "../utils/collections.js";
import parseCommand from "../utils/parseCommand.js";
import { clean } from "../utils/misc.js";
import sizeOf from "image-size";
// import { upload } from "../utils/tempimages.js";
// import { ThreadChannel } from "oceanic.js";
let mentionRegex;
// run when someone sends a message
export default async function (matrixClient, event, room, toStartOfTimeline) {
// console.log(matrixClient)
if (event.getType() == "m.room.message") {
if (toStartOfTimeline) {
return; // don't act on paginated results
}
if (event.event.sender == process.env.MATRIX_USERNAME) return;
// console.log(event.event);
let text;
text = event.event.content.body;
// if a reply, strip the reply from the formatting
text = text.replace(/.*\n\n/g, "")
if (text.startsWith(process.env.PREFIX)) {
text = text.substring(process.env.PREFIX.length).trim();
} else {
return;
}
// separate commands and args
const preArgs = text.split(/\s+/g);
const command = preArgs.shift().toLowerCase();
const aliased = aliases.get(command);
const cmd = commands.get(aliased ?? command);
if (!cmd) return;
// command time :peachtime:
log("log", `${event.sender.name} (${event.event.sender}) ran command ${command}`);
const reference = {
messageReference: {
channelID: event.event.room_id,
messageID: event.event.event_id,
guildID: undefined,
failIfNotExists: false
},
allowedMentions: {
repliedUser: false
}
};
try {
// parse args
const parsed = parseCommand(preArgs);
// if (database) {
// await database.addCount(aliases.get(command) ?? command);
// }
const startTime = new Date();
// eslint-disable-next-line no-unused-vars
const commandClass = new cmd(matrixClient, { type: "classic", message: event.event, args: parsed._, content: text.replace(command, "").trim(), specialArgs: (({ _, ...o }) => o)(parsed) }); // we also provide the message content as a parameter for cases where we need more accuracy
const result = await commandClass.run();
const endTime = new Date();
if ((endTime - startTime) >= 180000) reference.allowedMentions.repliedUser = true;
if (typeof result === "string") {
const content = {
body: result,
msgtype: "m.text",
};
matrixClient.sendEvent(event.event.room_id, "m.room.message", content, "", (err, res) => {
console.log(err);
});
} else if (typeof result === "object") {
// console.log(result)
if (result.contents && result.name) {
let fileSize = 52428308;
if (result.contents.length > fileSize) {
if (process.env.TEMPDIR && process.env.TEMPDIR !== "") {
await upload(client, result, message);
} else {
const content = {
body: "imag too big :(",
msgtype: "m.text",
};
matrixClient.sendEvent(event.event.room_id, "m.room.message", content, "", (err, res) => {
console.log(err);
});
}
} else {
const mxcUri = await matrixClient.uploadContent(result.contents);
console.log(mxcUri.content_uri)
// TODO: make info object get width, height, and mime from natives so i dont need to read the buffer
const imgsize = sizeOf(result.contents)
await matrixClient.sendImageMessage(event.event.room_id, mxcUri.content_uri, {h: imgsize.height, w: imgsize.width, mimetype: `image/${imgsize.type}`, size: result.contents.length, thumbnail_info: {h: imgsize.height, w: imgsize.width, mimetype: `image/${imgsize.type}`, size: result.contents.length}}, result.name)
}
} else {
// await client.rest.channels.createMessage(message.channelID, Object.assign(result, reference));
}
} else {
console.log(typeof result)
}
} catch (error) {
logger.log("error", error.stack)
// if (error.toString().includes("Request entity too large")) {
// await client.rest.channels.createMessage(event.event.room_id, Object.assign({
// content: "The resulting file was too large to upload. Try again with a smaller image if possible."
// }, reference));
// } else if (error.toString().includes("Job ended prematurely")) {
// await client.rest.channels.createMessage(event.event.room_id, Object.assign({
// content: "Something happened to the image servers before I could receive the image. Try running your command again."
// }, reference));
// } else if (error.toString().includes("Timed out")) {
// await client.rest.channels.createMessage(event.event.room_id, Object.assign({
// content: "The request timed out before I could download that image. Try uploading your image somewhere else or reducing its size."
// }, reference));
// } else {
// _error(`Error occurred with command message ${event.event.content.body}: ${error.stack || error}`);
// try {
// let err = error;
// if (error?.constructor?.name == "Promise") err = await error;
// await client.rest.channels.createMessage(event.event.room_id, Object.assign({
// content: "Uh oh! I ran into an error while running this command. Please report the content of the attached file at the following link or on the esmBot Support server: <https://github.com/esmBot/esmBot/issues>",
// files: [{
// contents: `Message: ${clean(err)}\n\nStack Trace: ${clean(err.stack)}`,
// name: "error.txt"
// }]
// }, reference));
// } catch (e) {
// _error(`While attempting to send the previous error message, another error occurred: ${e.stack || e}`);
// }
// }
}
return;
}
return;
};

View file

@ -1,17 +0,0 @@
import { players, errHandle } from "../utils/soundplayer.js";
export default async (client, id) => {
for (const player of players.values()) {
if (id !== player.voiceChannel.guild.shard.id) return;
try {
await player.player.connection.connect({
guildId: player.voiceChannel.guildID,
channelId: player.voiceChannel.id,
shardId: player.voiceChannel.guild.shard.id,
deaf: true
});
} catch (e) {
errHandle(e, client, player.player, player.playingMessage, player.voiceChannel, { type: "classic" }, true);
}
}
};

View file

@ -1,115 +0,0 @@
import { players, queues, skipVotes } from "../utils/soundplayer.js";
import AwaitRejoin from "../utils/awaitrejoin.js";
import { random } from "../utils/misc.js";
import { logger } from "../utils/logger.js";
const isWaiting = new Map();
export default async (client, member, oldChannel) => {
if (!oldChannel) return;
const connection = players.get(oldChannel.guildID);
if (oldChannel.id === connection?.voiceChannel.id) {
if (oldChannel.voiceMembers.filter((i) => i.id !== client.user.id && !i.bot).length === 0) {
if (isWaiting.has(oldChannel.id)) return;
isWaiting.set(oldChannel.id, true);
connection.player.setPaused(true);
const waitMessage = await client.rest.channels.createMessage(connection.originalChannel.id, {
content: "🔊 Waiting 10 seconds for someone to return..."
});
const awaitRejoin = new AwaitRejoin(oldChannel, true, member.id);
awaitRejoin.once("end", async (rejoined, newMember, cancel) => {
isWaiting.delete(oldChannel.id);
if (rejoined) {
if (cancel) return;
connection.player.setPaused(false);
if (member.id !== newMember.id) {
players.set(connection.voiceChannel.guildID, { player: connection.player, type: connection.type, host: newMember.id, voiceChannel: connection.voiceChannel, originalChannel: connection.originalChannel, loop: connection.loop, shuffle: connection.shuffle, playMessage: connection.playMessage });
waitMessage.edit({
content: `🔊 ${newMember.mention} is the new voice channel host.`
});
} else {
try {
await waitMessage.delete();
} catch {
logger.warn(`Failed to delete wait message ${waitMessage.id}`);
}
}
} else {
try {
if (waitMessage.channel.messages.has(waitMessage.id)) await waitMessage.delete();
} catch {
logger.warn(`Failed to delete wait message ${waitMessage.id}`);
}
if (cancel) return;
try {
connection.player.node.leaveChannel(connection.originalChannel.guildID);
} catch {
logger.warn(`Failed to leave voice channel ${connection.originalChannel.guildID}`);
}
players.delete(connection.originalChannel.guildID);
queues.delete(connection.originalChannel.guildID);
skipVotes.delete(connection.originalChannel.guildID);
client.rest.channels.createMessage(connection.originalChannel.id, {
content: `🔊 The voice channel session in \`${connection.voiceChannel.name}\` has ended.`
});
}
});
} else if (member.id === connection.host) {
if (isWaiting.has(oldChannel.id)) return;
isWaiting.set(oldChannel.id, true);
const waitMessage = await client.rest.channels.createMessage(connection.originalChannel.id, {
content: "🔊 Waiting 10 seconds for the host to return..."
});
const awaitRejoin = new AwaitRejoin(oldChannel, false, member.id);
awaitRejoin.once("end", async (rejoined) => {
isWaiting.delete(oldChannel.id);
if (rejoined) {
try {
if (waitMessage.channel.messages.has(waitMessage.id)) await waitMessage.delete();
} catch {
logger.warn(`Failed to delete wait message ${waitMessage.id}`);
}
} else {
const members = oldChannel.voiceMembers.filter((i) => i.id !== client.user.id && !i.bot);
if (members.length === 0) {
try {
if (waitMessage.channel.messages.has(waitMessage.id)) await waitMessage.delete();
} catch {
logger.warn(`Failed to delete wait message ${waitMessage.id}`);
}
try {
connection.player.node.leaveChannel(connection.originalChannel.guildID);
} catch {
logger.warn(`Failed to leave voice channel ${connection.originalChannel.guildID}`);
}
players.delete(connection.originalChannel.guildID);
queues.delete(connection.originalChannel.guildID);
skipVotes.delete(connection.originalChannel.guildID);
client.rest.channels.createMessage(connection.originalChannel.id, {
content: `🔊 The voice channel session in \`${connection.voiceChannel.name}\` has ended.`
});
} else {
const randomMember = random(members);
players.set(connection.voiceChannel.guildID, { player: connection.player, type: connection.type, host: randomMember.id, voiceChannel: connection.voiceChannel, originalChannel: connection.originalChannel, loop: connection.loop, shuffle: connection.shuffle, playMessage: connection.playMessage });
waitMessage.edit({
content: `🔊 ${randomMember.mention} is the new voice channel host.`
});
}
}
});
} else if (member.id === client.user.id) {
isWaiting.delete(oldChannel.id);
try {
connection.player.node.leaveChannel(connection.originalChannel.guildID);
} catch {
logger.warn(`Failed to leave voice channel ${connection.originalChannel.guildID}`);
}
players.delete(connection.originalChannel.guildID);
queues.delete(connection.originalChannel.guildID);
skipVotes.delete(connection.originalChannel.guildID);
await client.rest.channels.createMessage(connection.originalChannel.id, {
content: `🔊 The voice channel session in \`${connection.voiceChannel.name}\` has ended.`
});
}
}
};

View file

@ -1,5 +0,0 @@
import leaveHandler from "./voiceChannelLeave.js";
export default async (client, member, newChannel, oldChannel) => {
await leaveHandler(client, member, oldChannel);
};

View file

@ -1,5 +1,5 @@
import { warn } from "../utils/logger.js";
export default async (client, message) => {
warn(message);
import { warn } from "../utils/logger.js";
export default async (client, message) => {
warn(message);
};