diff options
author | RaindropsSys <contact@minteck.org> | 2023-05-12 16:43:00 +0200 |
---|---|---|
committer | RaindropsSys <contact@minteck.org> | 2023-05-12 16:43:00 +0200 |
commit | 32bed03d78e8bc20ae2e81d9379bf63f4a58caba (patch) | |
tree | 3bcf08f8ff48af67e7cd7a4e1c776c27a8f4c159 | |
parent | 2f160cbdf67f40c71ddafe62eb502fc443ab9e90 (diff) | |
download | butterscotch-32bed03d78e8bc20ae2e81d9379bf63f4a58caba.tar.gz butterscotch-32bed03d78e8bc20ae2e81d9379bf63f4a58caba.tar.bz2 butterscotch-32bed03d78e8bc20ae2e81d9379bf63f4a58caba.zip |
Updated 19 files and added 2 files (automated)
-rw-r--r-- | .gitignore | 3 | ||||
-rw-r--r-- | commands/help.js | 4 | ||||
-rw-r--r-- | commands/usage.js | 8 | ||||
-rw-r--r-- | discord.js | 90 | ||||
-rw-r--r-- | handler.js | 36 | ||||
-rw-r--r-- | help/ask.json | 3 | ||||
-rw-r--r-- | help/cute.json | 3 | ||||
-rw-r--r-- | help/fortune.json | 3 | ||||
-rw-r--r-- | help/front.json | 3 | ||||
-rw-r--r-- | help/help.json | 3 | ||||
-rw-r--r-- | help/ip.json | 3 | ||||
-rw-r--r-- | help/math.json | 3 | ||||
-rw-r--r-- | help/nsfw.json | 3 | ||||
-rw-r--r-- | help/ping.json | 3 | ||||
-rw-r--r-- | help/roll.json | 3 | ||||
-rw-r--r-- | help/status.json | 3 | ||||
-rw-r--r-- | help/usage.json | 6 | ||||
-rw-r--r-- | help/what.json | 3 | ||||
-rw-r--r-- | index.js | 28 | ||||
-rw-r--r-- | matrix.js | 166 | ||||
-rw-r--r-- | package.json | 2 |
21 files changed, 246 insertions, 133 deletions
@@ -1 +1,2 @@ -credentials.json
\ No newline at end of file +credentials.json +cache
\ No newline at end of file diff --git a/commands/help.js b/commands/help.js index d27bd03..bf2971c 100644 --- a/commands/help.js +++ b/commands/help.js @@ -34,6 +34,10 @@ module.exports = (parameter, wrapper) => { txt += "* **Description:** " + help['description'] + "\n"; } + if (parameter === "ask" || parameter === "math") { + txt += "* Limited to 400 commands a month\n"; + } + wrapper.send(txt); } else { wrapper.send("π’ Sorry, no help is available for this command, try again later."); diff --git a/commands/usage.js b/commands/usage.js new file mode 100644 index 0000000..d4289ab --- /dev/null +++ b/commands/usage.js @@ -0,0 +1,8 @@ +module.exports = (parameter, wrapper) => { + let usedCredits = { + month:ratelimits["month"][wrapper.sender][new Date().toISOString().split("-").splice(0, 2).join("-")] + } + + wrapper.send("π More expensive commands have a monthly credit system to prevent abuse and to make sure everyone gets a fair share at trying out the bot. These credits are reset every month on the 1st.\n\n\n" + + "* **Knowledge credits:** " + usedCredits["month"] + "/" + maxCredits["month"] + " (" + Math.round(((maxCredits["month"] - usedCredits["month"]) / maxCredits["month"]) * 100) + "% used)"); +}
\ No newline at end of file @@ -1,42 +1,52 @@ -const { Client, GatewayIntentBits } = require('discord.js'); -const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent] }); - -client.on('ready', () => { - console.log(`Logged in as ${client.user.tag}!`); -}); - -client.on('messageCreate', (msg) => { - if (!msg.guild || msg.author.bot) return; - - let message = msg.content; - - if (message.startsWith(".") && !message.startsWith("..") && message.trim() !== "." && message.trim() !== ".c.") { - let command; - - try { - command = message.replaceAll(/ +/g, " "); - if (command.startsWith(". ")) command = "." + command.substring(2); - command = command.split(" ")[0].substring(1).replaceAll("/", "-"); - let parameter = message.split(" ").splice(1).join(" "); - - require('./handler')({ - command, - parameter, - source: "discord", - message: msg, - channel: msg.channel, - client - }); - } catch (e) { - msg.channel.send("β Hmm, something isn't quite right! I was trying to process your message and something wrong happened. I think you need to report this so it can be fixed!\n\n```plaintext\n" + e.stack + "\n```"); - } - } else if (message.includes("<@" + client.user.id + ">")) { - msg.channel.send("π Hello! I think you forgot my prefix is `.`, use `.help` to get help."); - } else { - if (!lastMessages[msg.channel.id]) lastMessages[msg.channel.id] = []; - lastMessages[msg.channel.id].unshift(message); - lastMessages[msg.channel.id] = lastMessages[msg.channel.id].splice(0, 5); +function startDiscord() { + try { + const { Client, GatewayIntentBits } = require('discord.js'); + const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent] }); + + client.on('ready', () => { + console.log(`Logged in as ${client.user.tag}!`); + }); + + client.on('messageCreate', (msg) => { + if (!msg.guild || msg.author.bot) return; + + let message = msg.content; + + if (message.startsWith(".") && !message.startsWith("..") && message.trim() !== "." && message.trim() !== ".c.") { + let command; + + try { + command = message.replaceAll(/ +/g, " "); + if (command.startsWith(". ")) command = "." + command.substring(2); + command = command.split(" ")[0].substring(1).replaceAll("/", "-"); + let parameter = message.split(" ").splice(1).join(" "); + + require('./handler')({ + command, + parameter, + source: "discord", + message: msg, + channel: msg.channel, + client + }); + } catch (e) { + msg.channel.send("β Hmm, something isn't quite right! I was trying to process your message and something wrong happened. I think you need to report this so it can be fixed!\n\n```plaintext\n" + e.stack + "\n```"); + } + } else if (message.includes("<@" + client.user.id + ">")) { + msg.channel.send("π Hello! I think you forgot my prefix is `.`, use `.help` to get help."); + } else { + if (!lastMessages[msg.channel.id]) lastMessages[msg.channel.id] = []; + lastMessages[msg.channel.id].unshift(message); + lastMessages[msg.channel.id] = lastMessages[msg.channel.id].splice(0, 5); + } + }); + + client.login(require('./credentials.json').discord); + } catch (e) { + setTimeout(() => { + startDiscord(); + }, 300000); } -}); +} -client.login(require('./credentials.json').discord);
\ No newline at end of file +startDiscord();
\ No newline at end of file @@ -67,8 +67,44 @@ module.exports = (config) => { } if (fs.existsSync("./commands/" + command + ".js")) { + if (typeof ratelimits["month"][wrapper.sender] === "undefined") ratelimits["month"][wrapper.sender] = {}; + if (typeof ratelimits["month"][wrapper.sender][new Date().toISOString().split("-").splice(0, 2).join("-")] === "undefined") ratelimits["month"][wrapper.sender][new Date().toISOString().split("-").splice(0, 2).join("-")] = maxCredits["month"]; + + if (command === "math" || command === "ask") { + if (ratelimits["month"][wrapper.sender][new Date().toISOString().split("-").splice(0, 2).join("-")] <= 0) { + if (config['source'] === "matrix") { + matrixSend(config['room'].roomId, "π« Sorry, you do not have any knowledge credits left, run `.usage` for more details."); + } else if (config['source'] === "discord") { + config['channel'].send("π« Sorry, you do not have any knowledge credits left for now, run `.usage` for more details."); + } + return; + } else { + ratelimits["month"][wrapper.sender][new Date().toISOString().split("-").splice(0, 2).join("-")]--; + } + + if (ratelimits["month"][wrapper.sender][new Date().toISOString().split("-").splice(0, 2).join("-")] < 0) ratelimits["month"][wrapper.sender][new Date().toISOString().split("-").splice(0, 2).join("-")] = 0; + } + require("./commands/" + command + ".js")(parameter, wrapper); } else if (aliases[command]) { + if (typeof ratelimits["month"][wrapper.sender] === "undefined") ratelimits["month"][wrapper.sender] = {}; + if (typeof ratelimits["month"][wrapper.sender][new Date().toISOString().split("-").splice(0, 2).join("-")] === "undefined") ratelimits["month"][wrapper.sender][new Date().toISOString().split("-").splice(0, 2).join("-")] = maxCredits["month"]; + + if (command === "math" || command === "ask") { + if (ratelimits["month"][wrapper.sender][new Date().toISOString().split("-").splice(0, 2).join("-")] <= 0) { + if (config['source'] === "matrix") { + matrixSend(config['room'].roomId, "π« Sorry, you do not have any knowledge credits left, run `.usage` for more details."); + } else if (config['source'] === "discord") { + config['channel'].send("π« Sorry, you do not have any knowledge credits left for now, run `.usage` for more details."); + } + return; + } else { + ratelimits["month"][wrapper.sender][new Date().toISOString().split("-").splice(0, 2).join("-")]--; + } + + if (ratelimits["month"][wrapper.sender][new Date().toISOString().split("-").splice(0, 2).join("-")] < 0) ratelimits["month"][wrapper.sender][new Date().toISOString().split("-").splice(0, 2).join("-")] = 0; + } + require("./commands/" + aliases[command] + ".js")(parameter, wrapper); } else { if (config['source'] === "matrix") { diff --git a/help/ask.json b/help/ask.json index 1061b8d..e4d2cf2 100644 --- a/help/ask.json +++ b/help/ask.json @@ -1,5 +1,6 @@ { "description": "Ask anything, anytime.", "parameters": " <query>", - "aliases": [ "wolfram", "knowledge", "question", "wa", "a" ] + "aliases": [ "wolfram", "knowledge", "question", "wa", "a" ], + "exempt": false }
\ No newline at end of file diff --git a/help/cute.json b/help/cute.json index 7610389..4d5cda7 100644 --- a/help/cute.json +++ b/help/cute.json @@ -1,5 +1,6 @@ { "description": "Sends an adorable pony, either random or with a query.", "parameters": " [query]", - "aliases": [ "cutie", "derpibooru", "db", "adorable", "c" ] + "aliases": [ "cutie", "derpibooru", "db", "adorable", "c" ], + "exempt": false }
\ No newline at end of file diff --git a/help/fortune.json b/help/fortune.json index 43a13d5..05382ac 100644 --- a/help/fortune.json +++ b/help/fortune.json @@ -1,5 +1,6 @@ { "description": "Unwraps a fortune cookie, but it's from Equestria.", "parameters": " [filter]", - "aliases": [ "pony", "ponyfortune", "fo", "cookie" ] + "aliases": [ "pony", "ponyfortune", "fo", "cookie" ], + "exempt": false }
\ No newline at end of file diff --git a/help/front.json b/help/front.json index 3034ed7..a78d600 100644 --- a/help/front.json +++ b/help/front.json @@ -1,5 +1,6 @@ { "description": "Shows a summary of the fronting schedule.", "parameters": "", - "aliases": [ "schedule", "planner", "f", "plan" ] + "aliases": [ "schedule", "planner", "f", "plan" ], + "exempt": false }
\ No newline at end of file diff --git a/help/help.json b/help/help.json index 165d755..75551b0 100644 --- a/help/help.json +++ b/help/help.json @@ -1,5 +1,6 @@ { "description": "Get some help about the bot.", "parameters": " [command]", - "aliases": [ "h", "?", "list", "commands" ] + "aliases": [ "h", "?", "list", "commands" ], + "exempt": true }
\ No newline at end of file diff --git a/help/ip.json b/help/ip.json index 5d6ffb4..db28408 100644 --- a/help/ip.json +++ b/help/ip.json @@ -1,5 +1,6 @@ { "description": "Looks up an IP address's location.", "parameters": " <address>", - "aliases": [ "lookup", "ipv4", "ipv6", "i" ] + "aliases": [ "lookup", "ipv4", "ipv6", "i" ], + "exempt": false }
\ No newline at end of file diff --git a/help/math.json b/help/math.json index f430e4a..db072f1 100644 --- a/help/math.json +++ b/help/math.json @@ -1,5 +1,6 @@ { "description": "Solves a math problem with a lot of detail.", "parameters": " <problem>", - "aliases": [ "problem", "m", "equation", "explain" ] + "aliases": [ "problem", "m", "equation", "explain" ], + "exempt": false }
\ No newline at end of file diff --git a/help/nsfw.json b/help/nsfw.json index 7132dca..47496ee 100644 --- a/help/nsfw.json +++ b/help/nsfw.json @@ -1,5 +1,6 @@ { "description": "Sends an explicit image, either random or with a query.", "parameters": " [query]", - "aliases": [ "explicit", "porn" ] + "aliases": [ "explicit", "porn" ], + "exempt": false }
\ No newline at end of file diff --git a/help/ping.json b/help/ping.json index 2279e3e..c41039e 100644 --- a/help/ping.json +++ b/help/ping.json @@ -1,5 +1,6 @@ { "description": "Shows how long it takes to do stuff.", "parameters": "", - "aliases": [ "hello", "pong", "doot", "boop" ] + "aliases": [ "hello", "pong", "doot", "boop" ], + "exempt": true }
\ No newline at end of file diff --git a/help/roll.json b/help/roll.json index d42fb24..f6a1437 100644 --- a/help/roll.json +++ b/help/roll.json @@ -1,5 +1,6 @@ { "description": "Roll a dice, or many dices.", "parameters": " <x>d<y>", - "aliases": [ "dice", "d", "r" ] + "aliases": [ "dice", "d", "r" ], + "exempt": false }
\ No newline at end of file diff --git a/help/status.json b/help/status.json index 12d0ea2..5313cd6 100644 --- a/help/status.json +++ b/help/status.json @@ -1,5 +1,6 @@ { "description": "Shows the status of Equestria.dev's systems.", "parameters": "", - "aliases": [ "s", "statuspage", "state", "servers" ] + "aliases": [ "s", "statuspage", "state", "servers" ], + "exempt": false }
\ No newline at end of file diff --git a/help/usage.json b/help/usage.json new file mode 100644 index 0000000..c62caa5 --- /dev/null +++ b/help/usage.json @@ -0,0 +1,6 @@ +{ + "description": "Shows how many command credits you have left.", + "parameters": "", + "aliases": [ "credit", "credits", "quota", "q" ], + "exempt": true +}
\ No newline at end of file diff --git a/help/what.json b/help/what.json index 3df0c2f..c25edb8 100644 --- a/help/what.json +++ b/help/what.json @@ -1,5 +1,6 @@ { "description": "Shows the last 5 messages sent to this room.", "parameters": "", - "aliases": [ "history", "w", "msg" ] + "aliases": [ "history", "w", "msg" ], + "exempt": false }
\ No newline at end of file @@ -1,7 +1,33 @@ const fs = require("fs"); -global.lastMessages = {}; +if (!fs.existsSync("cache")) fs.mkdirSync("cache"); +if (!fs.existsSync("cache/lastMessages.json")) fs.writeFileSync("cache/lastMessages.json", "{}"); +if (!fs.existsSync("cache/ratelimits.json")) fs.writeFileSync("cache/ratelimits.json", `{"month":{},"day":{},"hour":{},"minute":{}}`); + +global.lastMessages = JSON.parse(fs.readFileSync("cache/lastMessages.json").toString()); global.aliases = {}; +global.ratelimits = JSON.parse(fs.readFileSync("cache/ratelimits.json").toString()); + +let lastSavedLastMessages = JSON.stringify(lastMessages); +let lastSavedRateLimits = JSON.stringify(ratelimits); + +global.maxCredits = { + month: 400 +}; + +setInterval(() => { + if (JSON.stringify(ratelimits) !== lastSavedRateLimits) { + console.log("Saving ratelimits"); + fs.writeFileSync("cache/ratelimits.json", JSON.stringify(ratelimits)); + lastSavedRateLimits = JSON.stringify(ratelimits); + } + + if (JSON.stringify(lastMessages) !== lastSavedLastMessages) { + console.log("Saving lastMessages"); + fs.writeFileSync("cache/lastMessages.json", JSON.stringify(lastMessages)); + lastSavedLastMessages = JSON.stringify(lastMessages); + } +}, 1000); for (let helpFile of fs.readdirSync("./help")) { let command = helpFile.substring(0, helpFile.length - 5); @@ -1,94 +1,104 @@ -const sdk = require("matrix-js-sdk"); -const showdown = require('showdown'); +function startMatrix() { + try { + const sdk = require("matrix-js-sdk"); + const showdown = require('showdown'); -global.matrixSend = (room, message, data) => { - return new Promise((res, rej) => { - client.sendEvent(room, "m.room.message", { - msgtype: "m.text", - body: data ?? message, - format: "org.matrix.custom.html", - formatted_body: markdown(message), - }, "", (err, response) => { - if (err) rej(err); - res(response); - }); - }) -} + global.matrixSend = (room, message, data) => { + return new Promise((res, rej) => { + client.sendEvent(room, "m.room.message", { + msgtype: "m.text", + body: data ?? message, + format: "org.matrix.custom.html", + formatted_body: markdown(message), + }, "", (err, response) => { + if (err) rej(err); + res(response); + }); + }) + } -global.markdown = (text) => { - let converter = new showdown.Converter(); - return converter.makeHtml(text); -} + global.markdown = (text) => { + let converter = new showdown.Converter(); + return converter.makeHtml(text); + } -const client = sdk.createClient({ - baseUrl: "https://chat.equestria.dev", - userId: require('./credentials.json').username, - accessToken: require('./credentials.json').token -}); + const client = sdk.createClient({ + baseUrl: "https://chat.equestria.dev", + userId: require('./credentials.json').username, + accessToken: require('./credentials.json').token + }); -(async () => { - await client.startClient({ initialSyncLimit: 0 }); + (async () => { + await client.startClient({ initialSyncLimit: 0 }); - client.once("sync", async function (state, prevState, res) { - if (state === "PREPARED") { - console.log("Ready!"); + client.once("sync", async function (state, prevState, res) { + if (state === "PREPARED") { + console.log("Ready!"); - client.setPresence({ - presence: "online" + client.setPresence({ + presence: "online" + }); + } else { + console.log(state); + process.exit(1); + } }); - } else { - console.log(state); - process.exit(1); - } - }); - client.on("Room.timeline", function (event, room) { - if (event.getType() !== "m.room.message") { - return; - } + client.on("Room.timeline", function (event, room) { + if (event.getType() !== "m.room.message") { + return; + } - if (new Date().getTime() - event.event.origin_server_ts < 1000 && event.sender.userId !== require('./credentials.json').username) { - let message = event.event.content.body; + if (new Date().getTime() - event.event.origin_server_ts < 1000 && event.sender.userId !== require('./credentials.json').username) { + let message = event.event.content.body; - if (event.event.content.formatted_body && event.event.content.formatted_body.startsWith("<mx-reply>")) { - message = event.event.content.formatted_body.split("</mx-reply>")[1]; - } + if (event.event.content.formatted_body && event.event.content.formatted_body.startsWith("<mx-reply>")) { + message = event.event.content.formatted_body.split("</mx-reply>")[1]; + } - if (message.startsWith(".") && !message.startsWith("..") && message.trim() !== "." && message.trim() !== ".c.") { - let command; + if (message.startsWith(".") && !message.startsWith("..") && message.trim() !== "." && message.trim() !== ".c.") { + let command; - try { - command = message.replaceAll(/ +/g, " "); - if (command.startsWith(". ")) command = "." + command.substring(2); - command = command.split(" ")[0].substring(1).replaceAll("/", "-"); - let parameter = message.split(" ").splice(1).join(" "); + try { + command = message.replaceAll(/ +/g, " "); + if (command.startsWith(". ")) command = "." + command.substring(2); + command = command.split(" ")[0].substring(1).replaceAll("/", "-"); + let parameter = message.split(" ").splice(1).join(" "); - require('./handler')({ - command, - parameter, - source: "matrix", - event, - room, - client - }); - } catch (e) { - matrixSend(room.roomId, "β Hmm, something isn't quite right! I was trying to process your message and something wrong happened. I think you need to report this so it can be fixed!\n\n<details><summary>Show stack trace</summary>\n\n```plaintext\n" + e.stack + "\n```\n\n</details>"); + require('./handler')({ + command, + parameter, + source: "matrix", + event, + room, + client + }); + } catch (e) { + matrixSend(room.roomId, "β Hmm, something isn't quite right! I was trying to process your message and something wrong happened. I think you need to report this so it can be fixed!\n\n<details><summary>Show stack trace</summary>\n\n```plaintext\n" + e.stack + "\n```\n\n</details>"); + } + } else if (message.includes(require('./credentials.json').username) || (event.event.content.formatted_body && event.event.content.formatted_body.includes(require('./credentials.json').username))) { + matrixSend(room.roomId, "π Hello! I think you forgot my prefix is `.`, use `.help` to get help."); + } else { + if (!lastMessages[room.roomId]) lastMessages[room.roomId] = []; + lastMessages[room.roomId].unshift(event.event.content.body); + lastMessages[room.roomId] = lastMessages[room.roomId].splice(0, 5); + } } - } else if (message.includes(require('./credentials.json').username) || (event.event.content.formatted_body && event.event.content.formatted_body.includes(require('./credentials.json').username))) { - matrixSend(room.roomId, "π Hello! I think you forgot my prefix is `.`, use `.help` to get help."); - } else { - if (!lastMessages[room.roomId]) lastMessages[room.roomId] = []; - lastMessages[room.roomId].unshift(event.event.content.body); - lastMessages[room.roomId] = lastMessages[room.roomId].splice(0, 5); - } - } - }); + }); - client.on("RoomMember.membership", function (event, member) { - if (member.membership === "invite" && member.userId === require('./credentials.json').username) { - client.joinRoom(member.roomId).then(function () { - console.log("Auto-joined %s", member.roomId); + client.on("RoomMember.membership", function (event, member) { + if (member.membership === "invite" && member.userId === require('./credentials.json').username) { + client.joinRoom(member.roomId).then(function () { + console.log("Auto-joined %s", member.roomId); + }); + } }); - } - }); -})();
\ No newline at end of file + })(); + } catch (e) { + setTimeout(() => { + startDiscord(); + }, 300000); + } +} + +startMatrix();
\ No newline at end of file diff --git a/package.json b/package.json index ff31902..a966b2d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "scripts": { - "start": "nodemon index.js" + "start": "nodemon -i ./cache index.js" }, "dependencies": { "axios": "^1.4.0", |