/[sudobot]/branches/5.x/src/commands/settings/BlockedTokenCommand.ts
ViewVC logotype

Contents of /branches/5.x/src/commands/settings/BlockedTokenCommand.ts

Parent Directory Parent Directory | Revision Log Revision Log


Revision 577 - (show annotations)
Mon Jul 29 18:52:37 2024 UTC (8 months ago) by rakinar2
File MIME type: application/typescript
File size: 9461 byte(s)
chore: add old version archive branches (2.x to 9.x-dev)
1 /**
2 * This file is part of SudoBot.
3 *
4 * Copyright (C) 2021-2023 OSN Developers.
5 *
6 * SudoBot is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU Affero General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * SudoBot is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Affero General Public License for more details.
15 *
16 * You should have received a copy of the GNU Affero General Public License
17 * along with SudoBot. If not, see <https://www.gnu.org/licenses/>.
18 */
19
20 import { EmbedBuilder, Message, PermissionFlagsBits, SlashCommandBuilder, Snowflake, escapeMarkdown } from "discord.js";
21 import Command, { ArgumentType, BasicCommandContext, CommandMessage, CommandReturn, ValidationRule } from "../../core/Command";
22 import Pagination from "../../utils/Pagination";
23
24 export default class BlockedTokenCommand extends Command {
25 public readonly subcommandsCustom = ["add", "remove", "has", "list"];
26 public readonly name = "blockedtoken";
27 public readonly validationRules: ValidationRule[] = [
28 {
29 types: [ArgumentType.String],
30 requiredErrorMessage: `Please provide a subcommand! The valid subcommands are: \`${this.subcommandsCustom.join("`, `")}\`.`,
31 typeErrorMessage: `Please provide a __valid__ subcommand! The valid subcommands are: \`${this.subcommandsCustom.join("`, `")}\`.`,
32 name: "subcommand"
33 }
34 ];
35
36 public readonly permissions = [PermissionFlagsBits.ManageGuild, PermissionFlagsBits.BanMembers];
37 public readonly permissionMode = "or";
38
39 public readonly description = "Manage blocked tokens.";
40 public readonly detailedDescription = [
41 "Add/remove/check/view the blocked tokens. All arguments, separated by spaces will also be treated as a single token.\n",
42 "**Subcommands**",
43 "* `add <token>` - Add a blocked token",
44 "* `remove <token>` - Remove a blocked token",
45 "* `has <token>` - Check if the given token is blocked",
46 "* `list` - List all the blocked tokens"
47 ].join("\n");
48
49 public readonly argumentSyntaxes = ["<subcommand> [...args]"];
50
51 public readonly slashCommandBuilder = new SlashCommandBuilder()
52 .addSubcommand(subcommand =>
53 subcommand
54 .setName("add")
55 .setDescription("Adds a blocked token")
56 .addStringOption(option => option.setName("token").setDescription("The token to block").setRequired(true))
57 )
58 .addSubcommand(subcommand =>
59 subcommand
60 .setName("remove")
61 .setDescription("Remove blocked token")
62 .addStringOption(option => option.setName("token").setDescription("The token to remove from blocklist").setRequired(true))
63 )
64 .addSubcommand(subcommand =>
65 subcommand
66 .setName("has")
67 .setDescription("Check if a blocked token exists in the blocklist")
68 .addStringOption(option => option.setName("token").setDescription("The token to check").setRequired(true))
69 )
70 .addSubcommand(subcommand => subcommand.setName("list").setDescription("Show the blocked token list"));
71 public readonly aliases = ["blockedtokens"];
72
73 createConfigIfNotExists(guildId: Snowflake) {
74 this.client.configManager.config[guildId!]!.message_filter ??= {
75 enabled: true,
76 delete_message: true,
77 send_logs: true
78 };
79
80 this.client.configManager.config[guildId!]!.message_filter!.data ??= {
81 blocked_tokens: [],
82 blocked_words: []
83 };
84
85 this.client.configManager.config[guildId!]!.message_filter!.data!.blocked_tokens ??= [];
86 }
87
88 getToken(message: CommandMessage, subcommand: string, context: BasicCommandContext) {
89 return context.isLegacy
90 ? (message as Message).content
91 .slice(this.client.configManager.config[message.guildId!]?.prefix.length)
92 .trimStart()
93 .slice(context.argv[0].length)
94 .trimStart()
95 .slice(subcommand.length)
96 .trimStart()
97 : context.options.getString("token", true);
98 }
99
100 async execute(message: CommandMessage, context: BasicCommandContext): Promise<CommandReturn> {
101 const subcommand = (context.isLegacy ? context.parsedNamedArgs.subcommand : context.options.getSubcommand(true))?.toString();
102
103 if (!this.subcommandsCustom.includes(subcommand)) {
104 await this.error(message, `Invalid subcommand provided. The valid subcommands are: \`${this.subcommandsCustom.join("`, `")}\`.`);
105 return;
106 }
107
108 if (context.isLegacy && context.args[1] === undefined && subcommand !== "list") {
109 await this.error(
110 message,
111 `You must specify a token ${subcommand === "add" ? "to block" : subcommand === "remove" ? "to remove" : "to check"}!`
112 );
113 return;
114 }
115
116 if (!this.client.configManager.config[message.guildId!]) {
117 return;
118 }
119
120 await this.deferIfInteraction(message);
121
122 if (context.isLegacy) {
123 context.args.shift();
124 }
125
126 this.createConfigIfNotExists(message.guildId!);
127
128 switch (subcommand) {
129 case "add":
130 {
131 const token = this.getToken(message, subcommand, context);
132
133 if (!this.client.configManager.config[message.guildId!]?.message_filter?.data?.blocked_tokens.includes(token)) {
134 this.client.configManager.config[message.guildId!]?.message_filter?.data?.blocked_tokens.push(token);
135 await this.client.configManager.write();
136 }
137
138 await this.success(message, `The given token(s) have been blocked.`);
139 }
140 break;
141
142 case "has": {
143 const token = this.getToken(message, subcommand, context);
144
145 if (this.client.configManager.config[message.guildId!]?.message_filter?.data?.blocked_tokens.includes(token)) {
146 await this.success(message, `This token is in the blocklist.`);
147 } else {
148 await this.error(message, `This token is not in the blocklist.`);
149 }
150
151 return;
152 }
153
154 case "remove":
155 const token = this.getToken(message, subcommand, context);
156 const index = this.client.configManager.config[message.guildId!]?.message_filter?.data?.blocked_tokens.indexOf(token);
157
158 if (index && index !== -1) {
159 this.client.configManager.config[message.guildId!]?.message_filter?.data?.blocked_tokens.splice(index, 1);
160 await this.client.configManager.write();
161 }
162
163 await this.success(message, `The given token(s) have been unblocked.`);
164 break;
165
166 case "list":
167 {
168 const token: string[] = this.client.configManager.config[message.guildId!]?.message_filter?.data?.blocked_tokens ?? [];
169 const safeTokens: string[][] = [];
170 let length = 0;
171
172 for (const unsafeToken of token) {
173 if (safeTokens.length === 0) safeTokens.push([]);
174
175 const token = escapeMarkdown(unsafeToken);
176
177 if (length + token.length >= 3000) {
178 safeTokens.push([token]);
179 length = token.length;
180 continue;
181 }
182
183 const index = safeTokens.length - 1;
184
185 safeTokens[index].push(token);
186 length += token.length;
187 }
188
189 const pagination = new Pagination(safeTokens, {
190 channelId: message.channelId!,
191 guildId: message.guildId!,
192 limit: 1,
193 timeout: 120_000,
194 userId: message.member!.user.id,
195 client: this.client,
196 embedBuilder({ currentPage, data, maxPages }) {
197 return new EmbedBuilder({
198 author: {
199 name: `Blocked tokens in ${message.guild!.name}`,
200 iconURL: message.guild!.iconURL() ?? undefined
201 },
202 color: 0x007bff,
203 description: "`" + data[0].join("`\n`") + "`",
204 footer: {
205 text: `Page ${currentPage} of ${maxPages}`
206 }
207 });
208 }
209 });
210
211 let reply = await this.deferredReply(message, await pagination.getMessageOptions());
212 await pagination.start(reply);
213 }
214
215 break;
216 }
217 }
218 }

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26