ahegao 1.69.27 → 1.69.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,80 @@
1
+ import { Channel, Client, Collection, Guild, GuildBasedChannel, GuildMember, InteractionReplyOptions, Message, MessagePayload, MessageReference, TextBasedChannel, TextChannel, ThreadChannel, User } from "discord.js";
2
+ import { CommandType, SendOptions } from "./discord_types";
3
+ import { MESSAGE_TYPE, RECIPIENT_TYPE } from "./discord_fields";
4
+ import { ExtendedInteraction, MessageType } from "../utils/discord-util";
5
+ export declare class BaseDiscordClient extends Client {
6
+ readonly commands: Collection<string, CommandType>;
7
+ private noAccessGuilds;
8
+ private noAccessChannels;
9
+ private noAccessMessages;
10
+ private userCache;
11
+ private channelCache;
12
+ private slashCommands;
13
+ private readyToPostReactionQueue;
14
+ readonly name: string;
15
+ readonly nameLower: string;
16
+ protected styledName: string;
17
+ protected styledNameLower: string;
18
+ protected fgColor: import("chalk").Chalk;
19
+ readonly defaultEmbedColor: number;
20
+ startMessage: string;
21
+ private starting;
22
+ private started;
23
+ constructor(name: string);
24
+ get userId(): string;
25
+ setDefaultStartMessage(): void;
26
+ setFgColor(chalkColor: any): void;
27
+ isStartedOrStarting(): boolean;
28
+ onBeforeStart(): Promise<void>;
29
+ onAfterStart(): Promise<void>;
30
+ onAfterCacheInit(): Promise<void>;
31
+ getPreviousMessageOfChannel(channel: TextBasedChannel, indexFromLast?: number): Promise<Message<boolean>>;
32
+ start(token: string, resourcesPath: string): Promise<void>;
33
+ onStartFail(): void;
34
+ onError(error: Error): void;
35
+ importFile(filePath: string): Promise<any>;
36
+ private registerToDiscord;
37
+ protected registerBotEvents(resourcesPath: string): Promise<void>;
38
+ log(message?: any): void;
39
+ private onReady;
40
+ protected registerEverything(resourcesPath: string): Promise<void>;
41
+ protected registerSlashCommands(resourcesPath: string): Promise<void>;
42
+ protected registerEvents(resourcesPath: string): Promise<void>;
43
+ edit(message: Message<boolean>, newContent: string): Promise<Message<boolean>>;
44
+ send(recipient: RECIPIENT_TYPE, message: MESSAGE_TYPE, options?: SendOptions): Promise<Message<boolean>>;
45
+ onEditedToReal(message: Message<boolean>): Promise<void>;
46
+ getUwuChance(): number;
47
+ getAiInterpretationChance(): number;
48
+ getAiRandomScenarioChance(): number;
49
+ sendToById(message: MESSAGE_TYPE, channelId: string, options?: SendOptions): Promise<Message<boolean>>;
50
+ trySendToById(messages: string[], channelId: string, options?: SendOptions): Promise<boolean>;
51
+ sendToByName(message: string | MessagePayload, guildId: string, channelName: string): Promise<Message<boolean>>;
52
+ dmUserById(userId: string, message: MESSAGE_TYPE): Promise<Message<boolean>>;
53
+ getOrCreateChannelByGuildName(guild: Guild, channelName: string): Promise<TextBasedChannel>;
54
+ findChannelByGuildName(guild: Guild, channelName: string): Promise<TextBasedChannel>;
55
+ findChannelByGuildIdName(guildId: string, channelName: string): Promise<TextBasedChannel>;
56
+ findGuildById(guildId: string): Promise<Guild>;
57
+ findMemberByGuildIdAndId(guildId: string, userId: string): Promise<GuildMember>;
58
+ findMemberByGuildAndId(guild: Guild, userId: string): Promise<GuildMember>;
59
+ findUserById(userId: string): Promise<User>;
60
+ findChannelById(channelId: string): Promise<Channel>;
61
+ memberHasRole(member: GuildMember, roleId: string): boolean;
62
+ trySetNickname(member: GuildMember, newName: string): Promise<boolean>;
63
+ followUp(interaction: ExtendedInteraction, options: string | MessagePayload | InteractionReplyOptions): Promise<Message<boolean>>;
64
+ renameGuildById(guildId: string, name: string): Promise<boolean>;
65
+ renameChannelById(channelId: string, name: string): Promise<boolean>;
66
+ renameMemberByGuildIdAndId(guildId: string, memberId: string, name: string): Promise<boolean>;
67
+ referenceToString(reference: MessageReference): Promise<string>;
68
+ delete(message: MessageType): Promise<boolean>;
69
+ setChannelMessagesTo(channel: TextChannel | ThreadChannel, msgs: string[]): Promise<void>;
70
+ stopIfDev(interaction: ExtendedInteraction): boolean;
71
+ stopIfNotTextChannel(interaction: ExtendedInteraction, channel: Channel): channel is Exclude<any, TextChannel>;
72
+ getUserNameById(userId: string): Promise<string>;
73
+ get loadingMessage(): string;
74
+ forEveryServer(doThis: (guild: Guild) => void | Promise<void>): Promise<void>;
75
+ forEveryMember(doThis: (member: GuildMember, guild: Guild) => void | Promise<void>): Promise<void>;
76
+ forEveryChannel(doThis: (channel: GuildBasedChannel, guild: Guild) => void | Promise<void>): Promise<void>;
77
+ getAllMembers(): Promise<Set<GuildMember>>;
78
+ getAllUsers(): Promise<Set<User>>;
79
+ getAllChannels(): Promise<Set<GuildBasedChannel>>;
80
+ }
@@ -0,0 +1,613 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.BaseDiscordClient = void 0;
37
+ const util_1 = require("../utils/util");
38
+ const discord_js_1 = require("discord.js");
39
+ const discord_fields_1 = require("./discord_fields");
40
+ const discord_util_1 = require("../utils/discord-util");
41
+ const fields_1 = require("./fields");
42
+ const mathjs_1 = require("mathjs");
43
+ class BaseDiscordClient extends discord_js_1.Client {
44
+ constructor(name) {
45
+ super({
46
+ intents: 4194303,
47
+ closeTimeout: 120000,
48
+ waitGuildTimeout: 120000,
49
+ });
50
+ this.commands = new discord_js_1.Collection();
51
+ this.noAccessGuilds = new Set();
52
+ this.noAccessChannels = new Set();
53
+ this.noAccessMessages = new Set();
54
+ this.userCache = new Map();
55
+ this.channelCache = new Map();
56
+ this.slashCommands = [];
57
+ this.readyToPostReactionQueue = true;
58
+ this.fgColor = util_1.chalk.whiteBright;
59
+ this.defaultEmbedColor = 0xff0077;
60
+ this.starting = false;
61
+ this.started = false;
62
+ // super({ intents: [32767, GatewayIntentBits.MessageContent, GatewayIntentBits.GuildMessages, GatewayIntentBits.DirectMessages] })
63
+ this.name = name;
64
+ this.styledName = this.fgColor(this.name);
65
+ this.nameLower = name.toLocaleLowerCase();
66
+ this.styledNameLower = this.fgColor(this.nameLower);
67
+ this.setFgColor(this.fgColor);
68
+ this.startMessage = this.fgColor(`-${this.name} Sounds-`);
69
+ }
70
+ get userId() {
71
+ return this.user.id;
72
+ }
73
+ setDefaultStartMessage() {
74
+ this.startMessage = this.fgColor(`-${this.name} Sounds-`);
75
+ }
76
+ setFgColor(chalkColor) {
77
+ this.fgColor = chalkColor;
78
+ this.styledName = this.fgColor(this.name);
79
+ this.styledNameLower = this.fgColor(this.nameLower);
80
+ }
81
+ isStartedOrStarting() {
82
+ return this.starting || this.started;
83
+ }
84
+ async onBeforeStart() {
85
+ }
86
+ async onAfterStart() {
87
+ }
88
+ async onAfterCacheInit() {
89
+ // setupSpamPortals(this)
90
+ }
91
+ async getPreviousMessageOfChannel(channel, indexFromLast = 1) {
92
+ let messages = Array.from(channel.messages.cache.values());
93
+ if (messages.length < indexFromLast + 1) {
94
+ messages = Array.from((await channel.messages.fetch({ limit: indexFromLast + 1 })).values());
95
+ }
96
+ if (messages.length > 0) {
97
+ if (indexFromLast < messages.length) {
98
+ return messages[messages.length - indexFromLast];
99
+ }
100
+ return messages[messages.length - 1];
101
+ }
102
+ return null;
103
+ }
104
+ async start(token, resourcesPath) {
105
+ if (this.started) {
106
+ return;
107
+ }
108
+ await this.onBeforeStart();
109
+ this.starting = true;
110
+ await this.registerBotEvents(resourcesPath);
111
+ await this.login(token);
112
+ await this.onAfterStart();
113
+ this.starting = false;
114
+ this.started = true;
115
+ // extendThreadsTo7Days(this)
116
+ }
117
+ onStartFail() {
118
+ this.starting = false;
119
+ this.started = false;
120
+ this.log(`Failed to start ${this.styledName}`);
121
+ }
122
+ onError(error) {
123
+ this.starting = false;
124
+ this.started = false;
125
+ this.log(`Error: ${error.name}\n${error.stack ? `${error.stack}\n` : ""}${error.cause ? `${error.cause}\n` : ""}${error.message}`);
126
+ }
127
+ async importFile(filePath) {
128
+ var _a;
129
+ return (_a = (await Promise.resolve(`${filePath}`).then(s => __importStar(require(s))))) === null || _a === void 0 ? void 0 : _a.default;
130
+ }
131
+ async registerToDiscord({ commands, guildId }) {
132
+ var _a;
133
+ if (guildId) {
134
+ await ((_a = this.guilds.cache.get(guildId)) === null || _a === void 0 ? void 0 : _a.commands.set(commands));
135
+ this.log(`Registering ${commands.length} ${discord_fields_1.STYLED_SLASH_COMMANDS} to ${guildId}`);
136
+ }
137
+ else {
138
+ await this.application.commands.set(commands);
139
+ // this.log(`Registering ${commands.length} global slash commands`)
140
+ }
141
+ }
142
+ async registerBotEvents(resourcesPath) {
143
+ this.on("ready", () => this.onReady(resourcesPath));
144
+ }
145
+ log(message) {
146
+ // print(`${toStamp((Date.now() / 1000 % SECONDS_IN_DAY + SERVER_TIMEZONE_OFFSET_H * 3600) % SECONDS_IN_DAY)} ${this.styledName}: ${message}`)
147
+ (0, util_1.print)(message);
148
+ }
149
+ async onReady(resourcesPath) {
150
+ await this.registerEverything(resourcesPath);
151
+ await this.registerToDiscord({
152
+ commands: this.slashCommands,
153
+ guildId: process.env.guildId
154
+ });
155
+ this.log(this.startMessage);
156
+ }
157
+ async registerEverything(resourcesPath) {
158
+ await this.registerSlashCommands(resourcesPath);
159
+ await this.registerEvents(resourcesPath);
160
+ }
161
+ async registerSlashCommands(resourcesPath) {
162
+ const slashCommandsPath = (0, util_1.makeUnixPath)(resourcesPath, "slash_commands");
163
+ this.log(`Registering ${this.styledNameLower}...`);
164
+ const registeredCommands = new Set();
165
+ //Slash Commands
166
+ const slashCommandRegisterer = async (filePath) => {
167
+ const command = await this.importFile(filePath);
168
+ if (!command.name)
169
+ return;
170
+ if (command.options != null) {
171
+ for (const option of command.options) {
172
+ if (option == null) {
173
+ throw this.log(`Command ${command.name} option is null!`);
174
+ continue;
175
+ }
176
+ if (option.name.length < 1 || option.name.length > 100) {
177
+ throw new Error(`Command ${command.name} name is not 1<->100 length! ${option.name.length}`);
178
+ }
179
+ if (option.description.length < 1 || option.description.length > 100) {
180
+ throw new Error(`Command ${command.description} description is not 1<->100 length! ${option.description.length}`);
181
+ }
182
+ }
183
+ }
184
+ if (registeredCommands.has(command.name)) {
185
+ this.log(`${discord_fields_1.STYLED_WARNING}: Duplicate ${discord_fields_1.STYLED_SLASH_COMMAND} ${command.name}. ${util_1.chalk.underline(util_1.chalk.whiteBright("Skipping!"))}`);
186
+ return;
187
+ }
188
+ // this.log(`Registering ${STYLED_SLASH_COMMAND} ${command.name}`)
189
+ this.commands.set(command.name, command);
190
+ this.slashCommands.push(command);
191
+ registeredCommands.add(command.name);
192
+ };
193
+ const myCommandFilesPath = (0, util_1.makeUnixPath)(slashCommandsPath, this.nameLower, "*{.ts,.js}");
194
+ (0, util_1.dogPaths)(`myCommandFilesPath: "${myCommandFilesPath}"`);
195
+ const myCommandFiles = await (0, fields_1.globPromise)(myCommandFilesPath);
196
+ for (const slashCommand of myCommandFiles) {
197
+ await slashCommandRegisterer(slashCommand);
198
+ }
199
+ const sharedCommandFilesPath = (0, util_1.makeUnixPath)(slashCommandsPath, "shared", "*{.ts,.js}");
200
+ (0, util_1.dogPaths)(`sharedCommandFilesPath: "${sharedCommandFilesPath}"`);
201
+ const sharedCommandFiles = await (0, fields_1.globPromise)(sharedCommandFilesPath);
202
+ for (const slashCommand of sharedCommandFiles) {
203
+ await slashCommandRegisterer(slashCommand);
204
+ }
205
+ const slashCommandsCount = myCommandFiles.length + sharedCommandFiles.length;
206
+ this.log(`Registered ${myCommandFiles.length + sharedCommandFiles.length} ${(0, util_1.if1Else)(slashCommandsCount, discord_fields_1.STYLED_SLASH_COMMAND, discord_fields_1.STYLED_SLASH_COMMANDS)}.`);
207
+ }
208
+ async registerEvents(resourcesPath) {
209
+ const eventsPath = (0, util_1.makeUnixPath)(resourcesPath, "events");
210
+ //Event
211
+ const eventRegisterer = async (filePath) => {
212
+ const event = await this.importFile(filePath);
213
+ if (!event.enabled) {
214
+ return;
215
+ }
216
+ this.on(event.event, (...args) => event.run(this, ...args));
217
+ // this.log(`Registering ${STYLED_EVENT} ${event.event}`)
218
+ };
219
+ const myEventFilesPath = (0, util_1.makeUnixPath)(eventsPath, this.nameLower, "*{.ts,.js}");
220
+ (0, util_1.dogPaths)(`myEventFilesPath: "${myEventFilesPath}"`);
221
+ const myEventFiles = await (0, fields_1.globPromise)(myEventFilesPath);
222
+ for (const event of myEventFiles) {
223
+ await eventRegisterer(event);
224
+ }
225
+ const sharedEventFilesPath = (0, util_1.makeUnixPath)(eventsPath, "shared", "*{.ts,.js}");
226
+ (0, util_1.dogPaths)(`sharedEventFilesPath: "${sharedEventFilesPath}"`);
227
+ const sharedEventFiles = await (0, fields_1.globPromise)(sharedEventFilesPath);
228
+ for (const event of sharedEventFiles) {
229
+ await eventRegisterer(event);
230
+ }
231
+ const eventsCount = myEventFiles.length + sharedEventFiles.length;
232
+ this.log(`Registered ${eventsCount} ${(0, util_1.if1Else)(eventsCount, discord_fields_1.STYLED_EVENT, discord_fields_1.STYLED_EVENTS)}.`);
233
+ }
234
+ async edit(message, newContent) {
235
+ if (newContent.length > fields_1.DISCORD_MESSAGE_LENGTH_LIMIT) {
236
+ newContent = newContent.slice(0, 1996) + "...";
237
+ this.log(`Tried to edit a message to length ${newContent.length}; Slicing to ${fields_1.DISCORD_MESSAGE_LENGTH_LIMIT}...\n${newContent}`);
238
+ }
239
+ message = await message.edit(newContent);
240
+ return message;
241
+ }
242
+ async send(recipient, message, options = discord_fields_1.DEFAULT_SEND_OPTIONS) {
243
+ var _a, _b;
244
+ if (recipient == null) {
245
+ this.log(util_1.chalk.redBright(`Tried to send a message; no ["send"]! Recipient: ${typeof recipient} | ${recipient}`));
246
+ return null;
247
+ }
248
+ if (recipient == null) {
249
+ this.log(`bot.send: Null recipient:\n${message}`);
250
+ return null;
251
+ }
252
+ let content = ((0, util_1.isString)(message) ? message : (_a = message) !== null && _a !== void 0 ? _a : null);
253
+ if (content == null) {
254
+ return await recipient(message);
255
+ }
256
+ if (content.length <= 0) {
257
+ this.log(`Tried to send empty message`);
258
+ return null;
259
+ }
260
+ const dummyMessageEditToReal = (_b = options.dummyMessageEditToReal) !== null && _b !== void 0 ? _b : discord_fields_1.DEFAULT_DUMMY_MESSAGE_EDIT_TO_REAL;
261
+ if (options.uwuAllowed) {
262
+ if ((0, mathjs_1.random)() < this.getUwuChance()) {
263
+ const match = content.match(fields_1.LINK_REGEX);
264
+ if (match == null) {
265
+ content = content
266
+ .replaceAll(/[rl]/g, "w")
267
+ .replaceAll(/[RL]/g, "W")
268
+ .replaceAll("no", "nyo")
269
+ .replaceAll("No", "Nyo")
270
+ .replaceAll(/(oa|ro)/g, "aw")
271
+ .replaceAll(/(Oa|Ro)/g, "Aw")
272
+ // .replaceAll(/lem/g, "mlem")
273
+ // .replaceAll(/Lem/g, "Mlem")
274
+ .replaceAll("ni", "nyai")
275
+ .replaceAll("Ni", "Nyai")
276
+ .replaceAll("pon", "pown")
277
+ .replaceAll("Pon", "Pown")
278
+ .replace(/([.!?])(\s|$)/g, (_, punc, space) => `${punc} ${(0, discord_util_1.getRandomUwuFace)()}${space}`);
279
+ }
280
+ }
281
+ }
282
+ if ((0, discord_util_1.tooLongForDiscord)(content)) {
283
+ this.log(`Tried to send a message of length ${content}; Slicing to 2000`);
284
+ content = content.slice(0, 1996) + "...";
285
+ }
286
+ if (Math.random() <= 0.01523) {
287
+ if ((0, discord_util_1.tooLongForDiscord)(content.length + discord_fields_1.VERIFIED_BY_DISCORD_ADMINS_EASTER_EGG_MESSAGE.length + 1)) {
288
+ content += `\n${discord_fields_1.VERIFIED_BY_DISCORD_ADMINS_EASTER_EGG_MESSAGE}`;
289
+ }
290
+ }
291
+ let liveMsg = null;
292
+ if (dummyMessageEditToReal) {
293
+ liveMsg = await recipient((0, util_1.skyify)(content));
294
+ if (liveMsg != null) {
295
+ liveMsg = await this.edit(liveMsg, content);
296
+ this.onEditedToReal(liveMsg);
297
+ }
298
+ }
299
+ else {
300
+ liveMsg = await recipient(content);
301
+ }
302
+ return liveMsg;
303
+ }
304
+ async onEditedToReal(message) {
305
+ }
306
+ getUwuChance() {
307
+ return 0;
308
+ }
309
+ getAiInterpretationChance() {
310
+ return 0;
311
+ }
312
+ getAiRandomScenarioChance() {
313
+ return 0;
314
+ }
315
+ async sendToById(message, channelId, options = discord_fields_1.DEFAULT_SEND_OPTIONS) {
316
+ let channel = await this.findChannelById(channelId);
317
+ if (channel instanceof discord_js_1.TextChannel) {
318
+ return this.send(channel, message, options);
319
+ }
320
+ // else
321
+ // {
322
+ // this.log(`NULL OR NON TextChannel CHANNEL IN BOT SEND: whereTo:${channelId}\n${new Error().stack.slice(0, 1000)}`)
323
+ // }
324
+ return null;
325
+ }
326
+ async trySendToById(messages, channelId, options = discord_fields_1.DEFAULT_SEND_OPTIONS) {
327
+ for (let message of messages) {
328
+ const trimmedMessage = message.trim();
329
+ if (trimmedMessage.length <= 0) {
330
+ continue;
331
+ }
332
+ if (trimmedMessage.length > fields_1.DISCORD_MESSAGE_LENGTH_LIMIT) {
333
+ this.log(`${discord_fields_1.STYLED_WARNING}: Tried to send a message that's too long ${trimmedMessage.length}. Trimming!`);
334
+ message = message.slice(0, 1999);
335
+ }
336
+ const sentMessage = await this.sendToById(message, channelId, options);
337
+ if (sentMessage == undefined) {
338
+ return false;
339
+ }
340
+ }
341
+ return true;
342
+ }
343
+ async sendToByName(message, guildId, channelName) {
344
+ let channel = await this.findChannelByGuildIdName(guildId, channelName);
345
+ if (channel != null)
346
+ return this.send(channel, message);
347
+ else {
348
+ const error = new Error();
349
+ if (error.stack != null) {
350
+ this.log(`NULL CHANNEL IN BOT SEND: whereTo:${channelName}, guildId:${guildId}\n${error.stack.slice(0, 1000)}`);
351
+ }
352
+ }
353
+ return null;
354
+ }
355
+ async dmUserById(userId, message) {
356
+ try {
357
+ const user = this.users.cache.get(userId);
358
+ return this.send(user, (0, util_1.isString)(message) ? message.slice(0, 1999) : message).catch(err => { (0, util_1.print)(err); });
359
+ // this.findUserById(userId).then((user: User) =>
360
+ // {
361
+ // this.send(user, message)
362
+ // user.send(message.slice(0, 1999))
363
+ // })
364
+ }
365
+ catch (err) {
366
+ this.log(`pmUserById ERROR: id:${userId}, \n${err.stack.slice(0, 1000)}`);
367
+ }
368
+ return null;
369
+ }
370
+ async getOrCreateChannelByGuildName(guild, channelName) {
371
+ let channel = await this.findChannelByGuildName(guild, channelName);
372
+ if (channel == null) {
373
+ try {
374
+ channel = await guild.channels.create({ name: channelName });
375
+ }
376
+ catch (err) {
377
+ this.log(util_1.chalk.redBright(`Could not create channel in guild: ${guild.id} ${guild.name}, channel: ${channelName}\n${err}`));
378
+ }
379
+ }
380
+ return channel;
381
+ }
382
+ async findChannelByGuildName(guild, channelName) {
383
+ for (const channel of guild.channels.cache.values()) {
384
+ if (channel.name == channelName) {
385
+ return channel;
386
+ }
387
+ }
388
+ const fetchedChannels = await guild.channels.fetch();
389
+ if (fetchedChannels != null) {
390
+ for (const channel of fetchedChannels.values()) {
391
+ if (channel.name == channelName) {
392
+ return channel;
393
+ }
394
+ }
395
+ }
396
+ return null;
397
+ }
398
+ async findChannelByGuildIdName(guildId, channelName) {
399
+ const guild = await this.findGuildById(guildId);
400
+ if (guild == null) {
401
+ return null;
402
+ }
403
+ const channel = await this.findChannelByGuildName(guild, channelName);
404
+ if (channel == null) {
405
+ this.log(`Channel ${channelName} not found!`);
406
+ }
407
+ return channel;
408
+ }
409
+ async findGuildById(guildId) {
410
+ if (this.noAccessGuilds.has(guildId)) {
411
+ return null;
412
+ }
413
+ let guild = null;
414
+ try {
415
+ guild = this.guilds.cache.get(guildId);
416
+ if (guild == null) {
417
+ guild = await this.guilds.fetch(guildId);
418
+ }
419
+ }
420
+ catch (ignored) { }
421
+ if (guild == null) {
422
+ this.noAccessGuilds.add(guildId);
423
+ }
424
+ return guild;
425
+ }
426
+ async findMemberByGuildIdAndId(guildId, userId) {
427
+ const guild = await this.findGuildById(guildId);
428
+ if (guild != null) {
429
+ return this.findMemberByGuildAndId(guild, userId);
430
+ }
431
+ return undefined;
432
+ }
433
+ async findMemberByGuildAndId(guild, userId) {
434
+ let member = guild.members.cache.get(userId);
435
+ if (member != null) {
436
+ return member;
437
+ }
438
+ try {
439
+ return await guild.members.fetch(userId);
440
+ }
441
+ catch (err) {
442
+ return undefined;
443
+ }
444
+ }
445
+ async findUserById(userId) {
446
+ const user = this.userCache.get(userId);
447
+ if (user != null) {
448
+ return user;
449
+ }
450
+ return this.users.cache.has(userId) ? this.users.cache.get(userId) : await this.users.fetch(userId);
451
+ }
452
+ async findChannelById(channelId) {
453
+ if (this.noAccessChannels.has(channelId)) {
454
+ return null;
455
+ }
456
+ let channel = this.channelCache.get(channelId);
457
+ if (channel != null) {
458
+ return channel;
459
+ }
460
+ channel = this.channels.cache.get(channelId);
461
+ if (channel != null) {
462
+ return channel;
463
+ }
464
+ else {
465
+ try {
466
+ return (await this.channels.fetch(channelId));
467
+ }
468
+ catch (err) {
469
+ this.noAccessChannels.add(channelId);
470
+ }
471
+ }
472
+ return null;
473
+ }
474
+ memberHasRole(member, roleId) {
475
+ return member.roles.cache.has(roleId);
476
+ }
477
+ async trySetNickname(member, newName) {
478
+ try {
479
+ const oldName = member.nickname;
480
+ await member.setNickname(newName);
481
+ this.log(`${oldName} changed to ${newName}`);
482
+ }
483
+ catch (_a) {
484
+ this.log(`Couldn't set name!`);
485
+ return false;
486
+ }
487
+ return true;
488
+ }
489
+ async followUp(interaction, options) {
490
+ this.log(`Interaction: ${(0, discord_util_1.wrapTitle)(interaction.commandName)} followUp: ${(0, util_1.isString)(options) ? options : `\n${(0, util_1.stringify)(options)}`}`);
491
+ try {
492
+ return await interaction.followUp(options);
493
+ }
494
+ catch (_a) {
495
+ (0, util_1.print)(util_1.chalk.redBright(`Error following up interaction; probably timed out! Oh well! Followup message:\n${options}`));
496
+ }
497
+ return null;
498
+ }
499
+ async renameGuildById(guildId, name) {
500
+ const guild = await this.findGuildById(guildId);
501
+ if (guild == null) {
502
+ return false;
503
+ }
504
+ (0, discord_util_1.renameGuildOrChannel)(guild, name);
505
+ return true;
506
+ }
507
+ async renameChannelById(channelId, name) {
508
+ const channel = await this.findChannelById(channelId);
509
+ if (!(channel instanceof discord_js_1.TextChannel)) {
510
+ return false;
511
+ }
512
+ await (0, discord_util_1.renameGuildOrChannel)(channel, name);
513
+ return true;
514
+ }
515
+ async renameMemberByGuildIdAndId(guildId, memberId, name) {
516
+ const member = await this.findMemberByGuildIdAndId(guildId, memberId);
517
+ if (member == null) {
518
+ return false;
519
+ }
520
+ await (0, discord_util_1.renameMember)(member, name);
521
+ return true;
522
+ }
523
+ async referenceToString(reference) {
524
+ var _a;
525
+ let referenceString = "";
526
+ if (reference != null) {
527
+ try {
528
+ const referenceChannel = await this.findChannelById(reference.channelId);
529
+ const referenceMessage = await referenceChannel.messages.fetch((_a = reference.messageId) !== null && _a !== void 0 ? _a : "");
530
+ referenceString = (0, discord_util_1.messageToReplyString)(referenceMessage);
531
+ }
532
+ catch (err) {
533
+ this.log(util_1.chalk.redBright(err));
534
+ }
535
+ }
536
+ return referenceString;
537
+ }
538
+ async delete(message) {
539
+ if (message == null) {
540
+ return false;
541
+ }
542
+ try {
543
+ await message.delete();
544
+ return true;
545
+ }
546
+ catch (err) {
547
+ this.log(`Error deleting message:\n${err}`);
548
+ }
549
+ return false;
550
+ }
551
+ async setChannelMessagesTo(channel, msgs) {
552
+ await (0, discord_util_1.forEachMessage)(channel, async (msg) => {
553
+ (0, util_1.print)(`Deleting old message ${msg.content}`);
554
+ await this.delete(msg);
555
+ });
556
+ for (const msg of msgs) {
557
+ const liveMsg = await this.send(channel, msg, discord_fields_1.AI_NOT_ALLOWED);
558
+ (0, util_1.print)(`Posted new message ${liveMsg.content}`);
559
+ }
560
+ }
561
+ stopIfDev(interaction) {
562
+ if ((0, discord_util_1.isDev)()) {
563
+ this.followUp(interaction, discord_util_1.COMMAND_NOT_ALLOWED_IN_DEV_MESSAGE);
564
+ return true;
565
+ }
566
+ return false;
567
+ }
568
+ stopIfNotTextChannel(interaction, channel) {
569
+ if (interaction.channel == null) {
570
+ return false;
571
+ }
572
+ if ((0, discord_util_1.isNotTextChannel)(interaction.channel)) {
573
+ this.followUp(interaction, discord_util_1.ONLY_TEXT_CHANNEL_SUPPORTED);
574
+ return false;
575
+ }
576
+ return true;
577
+ }
578
+ async getUserNameById(userId) {
579
+ return (0, discord_util_1.getUserName)(await this.findUserById(userId));
580
+ }
581
+ get loadingMessage() {
582
+ return `Loading~`;
583
+ }
584
+ async forEveryServer(doThis) {
585
+ await this.guilds.fetch();
586
+ for (const guild of this.guilds.cache.values()) {
587
+ await doThis(guild);
588
+ }
589
+ }
590
+ async forEveryMember(doThis) {
591
+ await this.forEveryServer(guild => (0, discord_util_1.forEveryMemberInGuild)(guild, member => doThis(member, guild)));
592
+ }
593
+ async forEveryChannel(doThis) {
594
+ await this.forEveryServer(guild => (0, discord_util_1.forEveryChannelInGuild)(guild, channel => doThis(channel, guild)));
595
+ }
596
+ async getAllMembers() {
597
+ const members = new Set();
598
+ await this.forEveryMember(member => { members.add(member); });
599
+ return members;
600
+ }
601
+ async getAllUsers() {
602
+ const users = new Set();
603
+ await this.forEveryMember(member => { users.add(member.user); });
604
+ return users;
605
+ }
606
+ async getAllChannels() {
607
+ const channels = new Set();
608
+ await this.forEveryChannel(channel => { channels.add(channel); });
609
+ return channels;
610
+ }
611
+ }
612
+ exports.BaseDiscordClient = BaseDiscordClient;
613
+ //# sourceMappingURL=discord_classes.js.map