diff --git a/backend/src/plugins/Censor/util/applyFiltersToMsg.ts b/backend/src/plugins/Censor/util/applyFiltersToMsg.ts index 6e83acc6..045276f2 100644 --- a/backend/src/plugins/Censor/util/applyFiltersToMsg.ts +++ b/backend/src/plugins/Censor/util/applyFiltersToMsg.ts @@ -9,6 +9,7 @@ import { censorMessage } from "./censorMessage"; import escapeStringRegexp from "escape-string-regexp"; import { logger } from "../../../logger"; import { allowTimeout } from "../../../RegExpRunner"; +import { MessageEmbed, Invite } from "discord.js"; export async function applyFiltersToMsg( pluginData: GuildPluginData, @@ -20,7 +21,7 @@ export async function applyFiltersToMsg( let messageContent = savedMessage.data.content || ""; if (savedMessage.data.attachments) messageContent += " " + JSON.stringify(savedMessage.data.attachments); if (savedMessage.data.embeds) { - const embeds = (savedMessage.data.embeds as Embed[]).map(e => cloneDeep(e)); + const embeds = (savedMessage.data.embeds as MessageEmbed[]).map(e => cloneDeep(e)); for (const embed of embeds) { if (embed.type === "video") { // Ignore video descriptions as they're not actually shown on the embed @@ -69,20 +70,20 @@ export async function applyFiltersToMsg( } if (isGuildInvite(invite)) { - if (inviteGuildWhitelist && !inviteGuildWhitelist.includes(invite.guild.id)) { + if (inviteGuildWhitelist && !inviteGuildWhitelist.includes(invite.guild!.id)) { censorMessage( pluginData, savedMessage, - `invite guild (**${invite.guild.name}** \`${invite.guild.id}\`) not found in whitelist`, + `invite guild (**${invite.guild!.name}** \`${invite.guild!.id}\`) not found in whitelist`, ); return true; } - if (inviteGuildBlacklist && inviteGuildBlacklist.includes(invite.guild.id)) { + if (inviteGuildBlacklist && inviteGuildBlacklist.includes(invite.guild!.id)) { censorMessage( pluginData, savedMessage, - `invite guild (**${invite.guild.name}** \`${invite.guild.id}\`) found in blacklist`, + `invite guild (**${invite.guild!.name}** \`${invite.guild!.id}\`) found in blacklist`, ); return true; } diff --git a/backend/src/plugins/Censor/util/censorMessage.ts b/backend/src/plugins/Censor/util/censorMessage.ts index df0011ca..9591e81d 100644 --- a/backend/src/plugins/Censor/util/censorMessage.ts +++ b/backend/src/plugins/Censor/util/censorMessage.ts @@ -4,6 +4,7 @@ import { SavedMessage } from "../../../data/entities/SavedMessage"; import { LogType } from "../../../data/LogType"; import { stripObjectToScalars, resolveUser } from "../../../utils"; import { disableCodeBlocks, deactivateMentions } from "knub/dist/helpers"; +import { TextChannel } from "discord.js"; export async function censorMessage( pluginData: GuildPluginData, @@ -13,7 +14,8 @@ export async function censorMessage( pluginData.state.serverLogs.ignoreLog(LogType.MESSAGE_DELETE, savedMessage.id); try { - await pluginData.client.deleteMessage(savedMessage.channel_id, savedMessage.id, "Censored"); + const channel = pluginData.guild.channels.resolve(savedMessage.channel_id) as TextChannel + await channel.messages.delete(savedMessage.id); } catch { return; } diff --git a/backend/src/plugins/ChannelArchiver/commands/ArchiveChannelCmd.ts b/backend/src/plugins/ChannelArchiver/commands/ArchiveChannelCmd.ts index 373f2aa4..b85aeb2f 100644 --- a/backend/src/plugins/ChannelArchiver/commands/ArchiveChannelCmd.ts +++ b/backend/src/plugins/ChannelArchiver/commands/ArchiveChannelCmd.ts @@ -51,7 +51,7 @@ export const ArchiveChannelCmd = channelArchiverCmd({ let previousId: string | undefined; const startTime = Date.now(); - const progressMsg = await msg.channel.createMessage("Creating archive..."); + const progressMsg = await msg.channel.send("Creating archive..."); const progressUpdateInterval = setInterval(() => { const secondsSinceStart = Math.round((Date.now() - startTime) / 1000); progressMsg @@ -61,16 +61,16 @@ export const ArchiveChannelCmd = channelArchiverCmd({ while (archivedMessages < maxMessagesToArchive) { const messagesToFetch = Math.min(MAX_MESSAGES_PER_FETCH, maxMessagesToArchive - archivedMessages); - const messages = await args.channel.getMessages(messagesToFetch, previousId); - if (messages.length === 0) break; + const messages = await args.channel.messages.fetch({ limit: messagesToFetch, before: previousId }); + if (messages.size === 0) break; - for (const message of messages) { - const ts = moment.utc(message.timestamp).format("YYYY-MM-DD HH:mm:ss"); + for (const message of messages.values()) { + const ts = moment.utc(message.createdTimestamp).format("YYYY-MM-DD HH:mm:ss"); let content = `[${ts}] [${message.author.id}] [${message.author.username}#${ message.author.discriminator }]: ${message.content || ""}`; - if (message.attachments.length) { + if (message.attachments.size) { if (args["attachment-channel"]) { const rehostedAttachmentUrl = await rehostAttachment(message.attachments[0], args["attachment-channel"]); content += `\n-- Attachment: ${rehostedAttachmentUrl}`; @@ -104,9 +104,6 @@ export const ArchiveChannelCmd = channelArchiverCmd({ result += `\n\n${archiveLines.join("\n")}\n`; progressMsg.delete().catch(noop); - msg.channel.createMessage("Archive created!", { - file: Buffer.from(result), - name: `archive-${args.channel.name}-${moment.utc().format("YYYY-MM-DD-HH-mm-ss")}.txt`, - }); + msg.channel.send({ content: "Archive created!", files: [{attachment: Buffer.from(result), name: `archive-${args.channel.name}-${moment.utc().format("YYYY-MM-DD-HH-mm-ss")}.txt`}], split: false }); }, }); diff --git a/backend/src/plugins/ChannelArchiver/rehostAttachment.ts b/backend/src/plugins/ChannelArchiver/rehostAttachment.ts index 09aa338f..56ef2924 100644 --- a/backend/src/plugins/ChannelArchiver/rehostAttachment.ts +++ b/backend/src/plugins/ChannelArchiver/rehostAttachment.ts @@ -1,10 +1,11 @@ import { downloadFile } from "../../utils"; import fs from "fs"; +import { MessageAttachment, MessageOptions, TextChannel } from "discord.js"; const fsp = fs.promises; const MAX_ATTACHMENT_REHOST_SIZE = 1024 * 1024 * 8; -export async function rehostAttachment(attachment: Attachment, targetChannel: TextChannel): Promise { +export async function rehostAttachment(attachment: MessageAttachment, targetChannel: TextChannel): Promise { if (attachment.size > MAX_ATTACHMENT_REHOST_SIZE) { return "Attachment too big to rehost"; } @@ -17,11 +18,9 @@ export async function rehostAttachment(attachment: Attachment, targetChannel: Te } try { - const rehostMessage = await targetChannel.createMessage(`Rehost of attachment ${attachment.id}`, { - name: attachment.filename, - file: await fsp.readFile(downloaded.path), - }); - return rehostMessage.attachments[0].url; + const content: MessageOptions = { content: `Rehost of attachment ${attachment.id}`, files: [{ name: attachment.name ? attachment.name : undefined, attachment: await fsp.readFile(downloaded.path)}]} + const rehostMessage = await targetChannel.send({ content, split: false }); + return rehostMessage.attachments.values()[0].url; } catch { return "Failed to rehost attachment"; } diff --git a/backend/src/plugins/CompanionChannels/CompanionChannelsPlugin.ts b/backend/src/plugins/CompanionChannels/CompanionChannelsPlugin.ts index 91d2358a..d3a89865 100644 --- a/backend/src/plugins/CompanionChannels/CompanionChannelsPlugin.ts +++ b/backend/src/plugins/CompanionChannels/CompanionChannelsPlugin.ts @@ -1,11 +1,9 @@ import { zeppelinGuildPlugin } from "../ZeppelinPluginBlueprint"; -import { CompanionChannelsPluginType, ConfigSchema, TCompanionChannelOpts } from "./types"; -import { VoiceChannelJoinEvt } from "./events/VoiceChannelJoinEvt"; -import { VoiceChannelSwitchEvt } from "./events/VoiceChannelSwitchEvt"; -import { VoiceChannelLeaveEvt } from "./events/VoiceChannelLeaveEvt"; +import { CompanionChannelsPluginType, ConfigSchema } from "./types"; import { trimPluginDescription } from "../../utils"; import { LogsPlugin } from "../Logs/LogsPlugin"; import { CooldownManager } from "knub"; +import { VoiceStateUpdateEvt } from "./events/VoiceStateUpdateEvt"; const defaultOptions = { config: { @@ -29,7 +27,7 @@ export const CompanionChannelsPlugin = zeppelinGuildPlugin = { export async function getCompanionChannelOptsForVoiceChannelId( pluginData: GuildPluginData, userId: string, - voiceChannel: VoiceChannel, + voiceChannel: VoiceChannel | StageChannel, ): Promise { const config = await pluginData.config.getMatchingConfig({ userId, channelId: voiceChannel.id }); return Object.values(config.entries) diff --git a/backend/src/plugins/CompanionChannels/functions/handleCompanionPermissions.ts b/backend/src/plugins/CompanionChannels/functions/handleCompanionPermissions.ts index 0806da09..022b01d7 100644 --- a/backend/src/plugins/CompanionChannels/functions/handleCompanionPermissions.ts +++ b/backend/src/plugins/CompanionChannels/functions/handleCompanionPermissions.ts @@ -5,6 +5,7 @@ import { GuildPluginData } from "knub"; import { isDiscordRESTError, MINUTES } from "../../../utils"; import { LogsPlugin } from "../../Logs/LogsPlugin"; import { LogType } from "../../../data/LogType"; +import { VoiceChannel, TextChannel, Permissions, StageChannel } from "discord.js"; const ERROR_COOLDOWN_KEY = "errorCooldown"; const ERROR_COOLDOWN = 5 * MINUTES; @@ -12,20 +13,8 @@ const ERROR_COOLDOWN = 5 * MINUTES; export async function handleCompanionPermissions( pluginData: GuildPluginData, userId: string, - voiceChannel: VoiceChannel, - oldChannel?: VoiceChannel, -); -export async function handleCompanionPermissions( - pluginData: GuildPluginData, - userId: string, - voiceChannel: null, - oldChannel: VoiceChannel, -); -export async function handleCompanionPermissions( - pluginData: GuildPluginData, - userId: string, - voiceChannel: VoiceChannel | null, - oldChannel?: VoiceChannel, + voiceChannel: VoiceChannel | StageChannel | null, + oldChannel?: VoiceChannel | StageChannel | null, ) { if (pluginData.state.errorCooldownManager.isOnCooldown(ERROR_COOLDOWN_KEY)) { return; @@ -65,18 +54,16 @@ export async function handleCompanionPermissions( for (const channelId of permsToDelete) { const channel = pluginData.guild.channels.cache.get(channelId); if (!channel || !(channel instanceof TextChannel)) continue; - await channel.deletePermission(userId, `Companion Channel for ${oldChannel!.id} | User Left`); + await channel.permissionOverwrites.get(userId)?.delete(`Companion Channel for ${oldChannel!.id} | User Left`); } for (const [channelId, permissions] of permsToSet) { const channel = pluginData.guild.channels.cache.get(channelId); if (!channel || !(channel instanceof TextChannel)) continue; - await channel.editPermission( + await channel.updateOverwrite( userId, - permissions, - 0, - "member", - `Companion Channel for ${voiceChannel!.id} | User Joined`, + new Permissions(BigInt(permissions)).serialize(), + {reason: `Companion Channel for ${voiceChannel!.id} | User Joined`}, ); } } catch (e) { diff --git a/backend/src/plugins/Counters/commands/AddCounterCmd.ts b/backend/src/plugins/Counters/commands/AddCounterCmd.ts index f67fd6a6..26c4da25 100644 --- a/backend/src/plugins/Counters/commands/AddCounterCmd.ts +++ b/backend/src/plugins/Counters/commands/AddCounterCmd.ts @@ -2,10 +2,11 @@ import { typedGuildCommand } from "knub"; import { CountersPluginType } from "../types"; import { commandTypeHelpers as ct } from "../../../commandTypes"; import { sendErrorMessage } from "../../../pluginUtils"; -import { resolveChannel, waitForReply } from "knub/dist/helpers"; +import { waitForReply } from "knub/dist/helpers"; import { resolveUser, UnknownUser } from "../../../utils"; import { changeCounterValue } from "../functions/changeCounterValue"; +import { TextChannel } from "discord.js"; export const AddCounterCmd = typedGuildCommand()({ trigger: ["counters add", "counter add", "addcounter"], @@ -66,14 +67,14 @@ export const AddCounterCmd = typedGuildCommand()({ let channel = args.channel; if (!channel && counter.per_channel) { - message.channel.createMessage(`Which channel's counter value would you like to add to?`); + message.channel.send(`Which channel's counter value would you like to add to?`); const reply = await waitForReply(pluginData.client, message.channel, message.author.id); if (!reply || !reply.content) { sendErrorMessage(pluginData, message.channel, "Cancelling"); return; } - const potentialChannel = resolveChannel(pluginData.guild, reply.content); + const potentialChannel = pluginData.guild.channels.resolve(reply.content); if (!potentialChannel || !(potentialChannel instanceof TextChannel)) { sendErrorMessage(pluginData, message.channel, "Channel is not a text channel, cancelling"); return; @@ -84,7 +85,7 @@ export const AddCounterCmd = typedGuildCommand()({ let user = args.user; if (!user && counter.per_user) { - message.channel.createMessage(`Which user's counter value would you like to add to?`); + message.channel.send(`Which user's counter value would you like to add to?`); const reply = await waitForReply(pluginData.client, message.channel, message.author.id); if (!reply || !reply.content) { sendErrorMessage(pluginData, message.channel, "Cancelling"); @@ -102,7 +103,7 @@ export const AddCounterCmd = typedGuildCommand()({ let amount = args.amount; if (!amount) { - message.channel.createMessage("How much would you like to add to the counter's value?"); + message.channel.send("How much would you like to add to the counter's value?"); const reply = await waitForReply(pluginData.client, message.channel, message.author.id); if (!reply || !reply.content) { sendErrorMessage(pluginData, message.channel, "Cancelling"); @@ -123,19 +124,19 @@ export const AddCounterCmd = typedGuildCommand()({ const counterName = counter.name || args.counterName; if (channel && user) { - message.channel.createMessage( + message.channel.send( `Added ${amount} to **${counterName}** for <@!${user.id}> in <#${channel.id}>. The value is now ${newValue}.`, ); } else if (channel) { - message.channel.createMessage( + message.channel.send( `Added ${amount} to **${counterName}** in <#${channel.id}>. The value is now ${newValue}.`, ); } else if (user) { - message.channel.createMessage( + message.channel.send( `Added ${amount} to **${counterName}** for <@!${user.id}>. The value is now ${newValue}.`, ); } else { - message.channel.createMessage(`Added ${amount} to **${counterName}**. The value is now ${newValue}.`); + message.channel.send(`Added ${amount} to **${counterName}**. The value is now ${newValue}.`); } }, }); diff --git a/backend/src/plugins/Counters/commands/CountersListCmd.ts b/backend/src/plugins/Counters/commands/CountersListCmd.ts index a9316268..5e35a28a 100644 --- a/backend/src/plugins/Counters/commands/CountersListCmd.ts +++ b/backend/src/plugins/Counters/commands/CountersListCmd.ts @@ -41,7 +41,7 @@ export const CountersListCmd = typedGuildCommand()({ hintLines.push(`Use \`${getGuildPrefix(pluginData)}counters reset_all \` to reset a counter entirely`); } - message.channel.createMessage( + message.channel.send( trimMultilineString(` ${counterLines.join("\n\n")} diff --git a/backend/src/plugins/Counters/commands/ResetAllCounterValuesCmd.ts b/backend/src/plugins/Counters/commands/ResetAllCounterValuesCmd.ts index 2bf6e714..6b632f95 100644 --- a/backend/src/plugins/Counters/commands/ResetAllCounterValuesCmd.ts +++ b/backend/src/plugins/Counters/commands/ResetAllCounterValuesCmd.ts @@ -2,11 +2,8 @@ import { typedGuildCommand } from "knub"; import { CountersPluginType } from "../types"; import { commandTypeHelpers as ct } from "../../../commandTypes"; import { sendErrorMessage, sendSuccessMessage } from "../../../pluginUtils"; -import { resolveChannel, waitForReply } from "knub/dist/helpers"; -import { confirm, MINUTES, noop, resolveUser, trimMultilineString, UnknownUser } from "../../../utils"; -import { changeCounterValue } from "../functions/changeCounterValue"; -import { setCounterValue } from "../functions/setCounterValue"; +import { confirm, MINUTES, noop, trimMultilineString } from "../../../utils"; import { resetAllCounterValues } from "../functions/resetAllCounterValues"; import { counterIdLock } from "../../../utils/lockNameHelpers"; @@ -49,7 +46,7 @@ export const ResetAllCounterValuesCmd = typedGuildCommand()( } const loadingMessage = await message.channel - .createMessage(`Resetting counter **${counterName}**. This might take a while. Please don't reload the config.`) + .send(`Resetting counter **${counterName}**. This might take a while. Please don't reload the config.`) .catch(() => null); const lock = await pluginData.locks.acquire(counterIdLock(counterId), 10 * MINUTES); diff --git a/backend/src/plugins/Counters/commands/ResetCounterCmd.ts b/backend/src/plugins/Counters/commands/ResetCounterCmd.ts index ed858a0f..736f66f8 100644 --- a/backend/src/plugins/Counters/commands/ResetCounterCmd.ts +++ b/backend/src/plugins/Counters/commands/ResetCounterCmd.ts @@ -2,10 +2,11 @@ import { typedGuildCommand } from "knub"; import { CountersPluginType } from "../types"; import { commandTypeHelpers as ct } from "../../../commandTypes"; import { sendErrorMessage } from "../../../pluginUtils"; -import { resolveChannel, waitForReply } from "knub/dist/helpers"; +import { waitForReply } from "knub/dist/helpers"; import { resolveUser, UnknownUser } from "../../../utils"; import { setCounterValue } from "../functions/setCounterValue"; +import { TextChannel } from "discord.js"; export const ResetCounterCmd = typedGuildCommand()({ trigger: ["counters reset", "counter reset", "resetcounter"], @@ -61,14 +62,14 @@ export const ResetCounterCmd = typedGuildCommand()({ let channel = args.channel; if (!channel && counter.per_channel) { - message.channel.createMessage(`Which channel's counter value would you like to reset?`); + message.channel.send(`Which channel's counter value would you like to reset?`); const reply = await waitForReply(pluginData.client, message.channel, message.author.id); if (!reply || !reply.content) { sendErrorMessage(pluginData, message.channel, "Cancelling"); return; } - const potentialChannel = resolveChannel(pluginData.guild, reply.content); + const potentialChannel = pluginData.guild.channels.resolve(reply.content); if (!potentialChannel || !(potentialChannel instanceof TextChannel)) { sendErrorMessage(pluginData, message.channel, "Channel is not a text channel, cancelling"); return; @@ -79,7 +80,7 @@ export const ResetCounterCmd = typedGuildCommand()({ let user = args.user; if (!user && counter.per_user) { - message.channel.createMessage(`Which user's counter value would you like to reset?`); + message.channel.send(`Which user's counter value would you like to reset?`); const reply = await waitForReply(pluginData.client, message.channel, message.author.id); if (!reply || !reply.content) { sendErrorMessage(pluginData, message.channel, "Cancelling"); @@ -99,13 +100,13 @@ export const ResetCounterCmd = typedGuildCommand()({ const counterName = counter.name || args.counterName; if (channel && user) { - message.channel.createMessage(`Reset **${counterName}** for <@!${user.id}> in <#${channel.id}>`); + message.channel.send(`Reset **${counterName}** for <@!${user.id}> in <#${channel.id}>`); } else if (channel) { - message.channel.createMessage(`Reset **${counterName}** in <#${channel.id}>`); + message.channel.send(`Reset **${counterName}** in <#${channel.id}>`); } else if (user) { - message.channel.createMessage(`Reset **${counterName}** for <@!${user.id}>`); + message.channel.send(`Reset **${counterName}** for <@!${user.id}>`); } else { - message.channel.createMessage(`Reset **${counterName}**`); + message.channel.send(`Reset **${counterName}**`); } }, }); diff --git a/backend/src/plugins/Counters/commands/SetCounterCmd.ts b/backend/src/plugins/Counters/commands/SetCounterCmd.ts index b90bdfb8..1158b5a6 100644 --- a/backend/src/plugins/Counters/commands/SetCounterCmd.ts +++ b/backend/src/plugins/Counters/commands/SetCounterCmd.ts @@ -2,11 +2,11 @@ import { typedGuildCommand } from "knub"; import { CountersPluginType } from "../types"; import { commandTypeHelpers as ct } from "../../../commandTypes"; import { sendErrorMessage } from "../../../pluginUtils"; -import { resolveChannel, waitForReply } from "knub/dist/helpers"; +import { waitForReply } from "knub/dist/helpers"; import { resolveUser, UnknownUser } from "../../../utils"; -import { changeCounterValue } from "../functions/changeCounterValue"; import { setCounterValue } from "../functions/setCounterValue"; +import { TextChannel } from "discord.js"; export const SetCounterCmd = typedGuildCommand()({ trigger: ["counters set", "counter set", "setcounter"], @@ -67,14 +67,14 @@ export const SetCounterCmd = typedGuildCommand()({ let channel = args.channel; if (!channel && counter.per_channel) { - message.channel.createMessage(`Which channel's counter value would you like to change?`); + message.channel.send(`Which channel's counter value would you like to change?`); const reply = await waitForReply(pluginData.client, message.channel, message.author.id); if (!reply || !reply.content) { sendErrorMessage(pluginData, message.channel, "Cancelling"); return; } - const potentialChannel = resolveChannel(pluginData.guild, reply.content); + const potentialChannel = pluginData.guild.channels.resolve(reply.content); if (!potentialChannel || !(potentialChannel instanceof TextChannel)) { sendErrorMessage(pluginData, message.channel, "Channel is not a text channel, cancelling"); return; @@ -85,7 +85,7 @@ export const SetCounterCmd = typedGuildCommand()({ let user = args.user; if (!user && counter.per_user) { - message.channel.createMessage(`Which user's counter value would you like to change?`); + message.channel.send(`Which user's counter value would you like to change?`); const reply = await waitForReply(pluginData.client, message.channel, message.author.id); if (!reply || !reply.content) { sendErrorMessage(pluginData, message.channel, "Cancelling"); @@ -103,7 +103,7 @@ export const SetCounterCmd = typedGuildCommand()({ let value = args.value; if (!value) { - message.channel.createMessage("What would you like to set the counter's value to?"); + message.channel.send("What would you like to set the counter's value to?"); const reply = await waitForReply(pluginData.client, message.channel, message.author.id); if (!reply || !reply.content) { sendErrorMessage(pluginData, message.channel, "Cancelling"); @@ -128,13 +128,13 @@ export const SetCounterCmd = typedGuildCommand()({ const counterName = counter.name || args.counterName; if (channel && user) { - message.channel.createMessage(`Set **${counterName}** for <@!${user.id}> in <#${channel.id}> to ${value}`); + message.channel.send(`Set **${counterName}** for <@!${user.id}> in <#${channel.id}> to ${value}`); } else if (channel) { - message.channel.createMessage(`Set **${counterName}** in <#${channel.id}> to ${value}`); + message.channel.send(`Set **${counterName}** in <#${channel.id}> to ${value}`); } else if (user) { - message.channel.createMessage(`Set **${counterName}** for <@!${user.id}> to ${value}`); + message.channel.send(`Set **${counterName}** for <@!${user.id}> to ${value}`); } else { - message.channel.createMessage(`Set **${counterName}** to ${value}`); + message.channel.send(`Set **${counterName}** to ${value}`); } }, }); diff --git a/backend/src/plugins/Counters/commands/ViewCounterCmd.ts b/backend/src/plugins/Counters/commands/ViewCounterCmd.ts index 6fed0607..bafbcb76 100644 --- a/backend/src/plugins/Counters/commands/ViewCounterCmd.ts +++ b/backend/src/plugins/Counters/commands/ViewCounterCmd.ts @@ -2,9 +2,10 @@ import { typedGuildCommand } from "knub"; import { CountersPluginType } from "../types"; import { commandTypeHelpers as ct } from "../../../commandTypes"; import { sendErrorMessage } from "../../../pluginUtils"; -import { resolveChannel, waitForReply } from "knub/dist/helpers"; +import { waitForReply } from "knub/dist/helpers"; import { resolveUser, UnknownUser } from "../../../utils"; +import { TextChannel } from "discord.js"; export const ViewCounterCmd = typedGuildCommand()({ trigger: ["counters view", "counter view", "viewcounter", "counter"], @@ -60,14 +61,14 @@ export const ViewCounterCmd = typedGuildCommand()({ let channel = args.channel; if (!channel && counter.per_channel) { - message.channel.createMessage(`Which channel's counter value would you like to view?`); + message.channel.send(`Which channel's counter value would you like to view?`); const reply = await waitForReply(pluginData.client, message.channel, message.author.id); if (!reply || !reply.content) { sendErrorMessage(pluginData, message.channel, "Cancelling"); return; } - const potentialChannel = resolveChannel(pluginData.guild, reply.content); + const potentialChannel = pluginData.guild.channels.resolve(reply.content); if (!potentialChannel || !(potentialChannel instanceof TextChannel)) { sendErrorMessage(pluginData, message.channel, "Channel is not a text channel, cancelling"); return; @@ -78,7 +79,7 @@ export const ViewCounterCmd = typedGuildCommand()({ let user = args.user; if (!user && counter.per_user) { - message.channel.createMessage(`Which user's counter value would you like to view?`); + message.channel.send(`Which user's counter value would you like to view?`); const reply = await waitForReply(pluginData.client, message.channel, message.author.id); if (!reply || !reply.content) { sendErrorMessage(pluginData, message.channel, "Cancelling"); @@ -99,13 +100,13 @@ export const ViewCounterCmd = typedGuildCommand()({ const counterName = counter.name || args.counterName; if (channel && user) { - message.channel.createMessage(`**${counterName}** for <@!${user.id}> in <#${channel.id}> is ${finalValue}`); + message.channel.send(`**${counterName}** for <@!${user.id}> in <#${channel.id}> is ${finalValue}`); } else if (channel) { - message.channel.createMessage(`**${counterName}** in <#${channel.id}> is ${finalValue}`); + message.channel.send(`**${counterName}** in <#${channel.id}> is ${finalValue}`); } else if (user) { - message.channel.createMessage(`**${counterName}** for <@!${user.id}> is ${finalValue}`); + message.channel.send(`**${counterName}** for <@!${user.id}> is ${finalValue}`); } else { - message.channel.createMessage(`**${counterName}** is ${finalValue}`); + message.channel.send(`**${counterName}** is ${finalValue}`); } }, }); diff --git a/backend/src/plugins/LocateUser/LocateUserPlugin.ts b/backend/src/plugins/LocateUser/LocateUserPlugin.ts index ed5c6567..b6bf2538 100644 --- a/backend/src/plugins/LocateUser/LocateUserPlugin.ts +++ b/backend/src/plugins/LocateUser/LocateUserPlugin.ts @@ -7,7 +7,7 @@ import { fillActiveAlertsList } from "./utils/fillAlertsList"; import { WhereCmd } from "./commands/WhereCmd"; import { FollowCmd } from "./commands/FollowCmd"; import { DeleteFollowCmd, ListFollowCmd } from "./commands/ListFollowCmd"; -import { ChannelJoinAlertsEvt, ChannelLeaveAlertsEvt, ChannelSwitchAlertsEvt } from "./events/SendAlertsEvts"; +import { VoiceStateUpdateAlertEvt } from "./events/SendAlertsEvts"; import { GuildBanRemoveAlertsEvt } from "./events/BanRemoveAlertsEvt"; import { trimPluginDescription } from "../../utils"; import Timeout = NodeJS.Timeout; @@ -53,9 +53,7 @@ export const LocateUserPlugin = zeppelinGuildPlugin()({ // prettier-ignore events: [ - ChannelJoinAlertsEvt, - ChannelSwitchAlertsEvt, - ChannelLeaveAlertsEvt, + VoiceStateUpdateAlertEvt, GuildBanRemoveAlertsEvt ], diff --git a/backend/src/plugins/LocateUser/commands/FollowCmd.ts b/backend/src/plugins/LocateUser/commands/FollowCmd.ts index 08c105ed..3dcfae9b 100644 --- a/backend/src/plugins/LocateUser/commands/FollowCmd.ts +++ b/backend/src/plugins/LocateUser/commands/FollowCmd.ts @@ -46,7 +46,7 @@ export const FollowCmd = locateUserCmd({ sendSuccessMessage( pluginData, msg.channel, - `Every time ${args.member.mention} joins or switches VC in the next ${humanizeDuration( + `Every time <@${args.member.id}> joins or switches VC in the next ${humanizeDuration( time, )} i will notify and move you.\nPlease make sure to be in a voice channel, otherwise i cannot move you!`, ); @@ -54,7 +54,7 @@ export const FollowCmd = locateUserCmd({ sendSuccessMessage( pluginData, msg.channel, - `Every time ${args.member.mention} joins or switches VC in the next ${humanizeDuration( + `Every time <@${args.member.id}> joins or switches VC in the next ${humanizeDuration( time, )} i will notify you`, ); diff --git a/backend/src/plugins/LocateUser/commands/WhereCmd.ts b/backend/src/plugins/LocateUser/commands/WhereCmd.ts index 0662e880..5cbdac4a 100644 --- a/backend/src/plugins/LocateUser/commands/WhereCmd.ts +++ b/backend/src/plugins/LocateUser/commands/WhereCmd.ts @@ -14,6 +14,6 @@ export const WhereCmd = locateUserCmd({ }, async run({ message: msg, args, pluginData }) { - sendWhere(pluginData, args.member, msg.channel, `${msg.member.mention} | `); + sendWhere(pluginData, args.member, msg.channel, `<@${msg.member.id}> | `); }, }); diff --git a/backend/src/plugins/LocateUser/events/BanRemoveAlertsEvt.ts b/backend/src/plugins/LocateUser/events/BanRemoveAlertsEvt.ts index cc6c155f..bc4e8d0f 100644 --- a/backend/src/plugins/LocateUser/events/BanRemoveAlertsEvt.ts +++ b/backend/src/plugins/LocateUser/events/BanRemoveAlertsEvt.ts @@ -4,7 +4,7 @@ export const GuildBanRemoveAlertsEvt = locateUserEvt({ event: "guildBanAdd", async listener(meta) { - const alerts = await meta.pluginData.state.alerts.getAlertsByUserId(meta.args.user.id); + const alerts = await meta.pluginData.state.alerts.getAlertsByUserId(meta.args.ban.user.id); alerts.forEach(alert => { meta.pluginData.state.alerts.delete(alert.id); }); diff --git a/backend/src/plugins/LocateUser/events/SendAlertsEvts.ts b/backend/src/plugins/LocateUser/events/SendAlertsEvts.ts index 353a2c26..f506069c 100644 --- a/backend/src/plugins/LocateUser/events/SendAlertsEvts.ts +++ b/backend/src/plugins/LocateUser/events/SendAlertsEvts.ts @@ -1,38 +1,27 @@ +import { TextChannel } from "discord.js"; import { locateUserEvt } from "../types"; import { sendAlerts } from "../utils/sendAlerts"; -export const ChannelJoinAlertsEvt = locateUserEvt({ - event: "voiceChannelJoin", +export const VoiceStateUpdateAlertEvt = locateUserEvt({ + event: "voiceStateUpdate", async listener(meta) { - if (meta.pluginData.state.usersWithAlerts.includes(meta.args.member.id)) { - sendAlerts(meta.pluginData, meta.args.member.id); - } - }, -}); + const memberId = meta.args.oldState.member ? meta.args.oldState.member.id : meta.args.newState.member!.id; -export const ChannelSwitchAlertsEvt = locateUserEvt({ - event: "voiceChannelSwitch", + if (meta.args.newState.channel != null) { + if (meta.pluginData.state.usersWithAlerts.includes(memberId)) { + sendAlerts(meta.pluginData, memberId); + } + } else { + const triggeredAlerts = await meta.pluginData.state.alerts.getAlertsByUserId(memberId); + const voiceChannel = meta.args.oldState.channel!; - async listener(meta) { - if (meta.pluginData.state.usersWithAlerts.includes(meta.args.member.id)) { - sendAlerts(meta.pluginData, meta.args.member.id); - } - }, -}); - -export const ChannelLeaveAlertsEvt = locateUserEvt({ - event: "voiceChannelLeave", - - async listener(meta) { - const triggeredAlerts = await meta.pluginData.state.alerts.getAlertsByUserId(meta.args.member.id); - const voiceChannel = meta.args.oldChannel as VoiceChannel; - - triggeredAlerts.forEach(alert => { - const txtChannel = meta.pluginData.client.getChannel(alert.channel_id) as TextableChannel; - txtChannel.createMessage( - `🔴 <@!${alert.requestor_id}> the user <@!${alert.user_id}> disconnected out of \`${voiceChannel.name}\``, + triggeredAlerts.forEach(alert => { + const txtChannel = meta.pluginData.guild.channels.resolve(alert.channel_id) as TextChannel; + txtChannel.send( + `🔴 <@!${alert.requestor_id}> the user <@!${alert.user_id}> disconnected out of \`<#!${voiceChannel.id}>\``, ); }); + } }, }); diff --git a/backend/src/plugins/LocateUser/utils/createOrReuseInvite.ts b/backend/src/plugins/LocateUser/utils/createOrReuseInvite.ts index 8ba7f2e1..2853c7f0 100644 --- a/backend/src/plugins/LocateUser/utils/createOrReuseInvite.ts +++ b/backend/src/plugins/LocateUser/utils/createOrReuseInvite.ts @@ -1,9 +1,11 @@ -export async function createOrReuseInvite(vc: VoiceChannel) { - const existingInvites = await vc.getInvites(); +import { VoiceChannel } from "discord.js"; - if (existingInvites.length !== 0) { +export async function createOrReuseInvite(vc: VoiceChannel) { + const existingInvites = await vc.fetchInvites(); + + if (existingInvites.size !== 0) { return existingInvites[0]; } else { - return vc.createInvite(undefined); + return vc.createInvite(); } } diff --git a/backend/src/plugins/LocateUser/utils/moveMember.ts b/backend/src/plugins/LocateUser/utils/moveMember.ts index 6966d10f..4289b2a1 100644 --- a/backend/src/plugins/LocateUser/utils/moveMember.ts +++ b/backend/src/plugins/LocateUser/utils/moveMember.ts @@ -1,18 +1,19 @@ import { GuildPluginData } from "knub"; import { LocateUserPluginType } from "../types"; import { sendErrorMessage } from "../../../pluginUtils"; +import { GuildMember, TextChannel } from "discord.js"; export async function moveMember( pluginData: GuildPluginData, toMoveID: string, - target: Member, - errorChannel: TextableChannel, + target: GuildMember, + errorChannel: TextChannel, ) { - const modMember: Member = await pluginData.client.getRESTGuildMember(pluginData.guild.id, toMoveID); - if (modMember.voiceState.channelID != null) { + const modMember: GuildMember = await pluginData.guild.members.fetch(toMoveID); + if (modMember.voice.channelID != null) { try { await modMember.edit({ - channelID: target.voiceState.channelID, + channel: target.voice.channelID }); } catch { sendErrorMessage(pluginData, errorChannel, "Failed to move you. Are you in a voice channel?"); diff --git a/backend/src/plugins/LocateUser/utils/sendAlerts.ts b/backend/src/plugins/LocateUser/utils/sendAlerts.ts index bb47168a..882e4344 100644 --- a/backend/src/plugins/LocateUser/utils/sendAlerts.ts +++ b/backend/src/plugins/LocateUser/utils/sendAlerts.ts @@ -4,6 +4,7 @@ import { resolveMember } from "../../../utils"; import { sendWhere } from "./sendWhere"; import { moveMember } from "./moveMember"; +import { TextChannel } from "discord.js"; export async function sendAlerts(pluginData: GuildPluginData, userId: string) { const triggeredAlerts = await pluginData.state.alerts.getAlertsByUserId(userId); @@ -12,7 +13,7 @@ export async function sendAlerts(pluginData: GuildPluginData { const prepend = `<@!${alert.requestor_id}>, an alert requested by you has triggered!\nReminder: \`${alert.body}\`\n`; - const txtChannel = pluginData.client.getChannel(alert.channel_id) as TextableChannel; + const txtChannel = pluginData.guild.channels.resolve(alert.channel_id) as TextChannel; sendWhere(pluginData, member, txtChannel, prepend); if (alert.active) { moveMember(pluginData, alert.requestor_id, member, txtChannel); diff --git a/backend/src/plugins/LocateUser/utils/sendWhere.ts b/backend/src/plugins/LocateUser/utils/sendWhere.ts index 8b9678a7..4fb151b6 100644 --- a/backend/src/plugins/LocateUser/utils/sendWhere.ts +++ b/backend/src/plugins/LocateUser/utils/sendWhere.ts @@ -3,19 +3,20 @@ import { createOrReuseInvite } from "./createOrReuseInvite"; import { GuildPluginData } from "knub"; import { LocateUserPluginType } from "../types"; import { sendErrorMessage } from "../../../pluginUtils"; +import { GuildMember, Invite, TextChannel, VoiceChannel } from "discord.js"; export async function sendWhere( pluginData: GuildPluginData, - member: Member, - channel: TextableChannel, + member: GuildMember, + channel: TextChannel, prepend: string, ) { - const voice = member.voiceState.channelID - ? (pluginData.guild.channels.cache.get(member.voiceState.channelID) as VoiceChannel) + const voice = member.voice.channelID + ? (pluginData.guild.channels.resolve(member.voice.channelID) as VoiceChannel) : null; if (voice == null) { - channel.createMessage(prepend + "That user is not in a channel"); + channel.send(prepend + "That user is not in a channel"); } else { let invite: Invite; try { @@ -24,9 +25,10 @@ export async function sendWhere( sendErrorMessage(pluginData, channel, "Cannot create an invite to that channel!"); return; } - channel.createMessage({ - content: prepend + `${member.mention} is in the following channel: \`${voice.name}\` ${getInviteLink(invite)}`, - allowedMentions: { users: true }, + channel.send({ + content: prepend + `<@${member.id}> is in the following channel: \`${voice.name}\` ${getInviteLink(invite)}`, + allowedMentions: { parse: ["users"] }, + split: false, }); } } diff --git a/backend/src/plugins/Logs/events/LogsGuildBanEvts.ts b/backend/src/plugins/Logs/events/LogsGuildBanEvts.ts index ef61f5e3..ab7d7498 100644 --- a/backend/src/plugins/Logs/events/LogsGuildBanEvts.ts +++ b/backend/src/plugins/Logs/events/LogsGuildBanEvts.ts @@ -3,20 +3,21 @@ import { stripObjectToScalars, UnknownUser } from "../../../utils"; import { LogType } from "../../../data/LogType"; import { safeFindRelevantAuditLogEntry } from "../../../utils/safeFindRelevantAuditLogEntry"; +import { GuildAuditLogs } from "discord.js"; export const LogsGuildBanAddEvt = logsEvt({ event: "guildBanAdd", async listener(meta) { const pluginData = meta.pluginData; - const user = meta.args.user; + const user = meta.args.ban.user; const relevantAuditLogEntry = await safeFindRelevantAuditLogEntry( pluginData, - ErisConstants.AuditLogActions.MEMBER_BAN_ADD, + GuildAuditLogs.Actions.MEMBER_BAN_ADD as number, user.id, ); - const mod = relevantAuditLogEntry ? relevantAuditLogEntry.user : new UnknownUser(); + const mod = relevantAuditLogEntry ? relevantAuditLogEntry.executor : new UnknownUser(); pluginData.state.guildLogs.log( LogType.MEMBER_BAN, @@ -34,14 +35,14 @@ export const LogsGuildBanRemoveEvt = logsEvt({ async listener(meta) { const pluginData = meta.pluginData; - const user = meta.args.user; + const user = meta.args.ban.user; const relevantAuditLogEntry = await safeFindRelevantAuditLogEntry( pluginData, - ErisConstants.AuditLogActions.MEMBER_BAN_REMOVE, + GuildAuditLogs.Actions.MEMBER_BAN_REMOVE as number, user.id, ); - const mod = relevantAuditLogEntry ? relevantAuditLogEntry.user : new UnknownUser(); + const mod = relevantAuditLogEntry ? relevantAuditLogEntry.executor : new UnknownUser(); pluginData.state.guildLogs.log( LogType.MEMBER_UNBAN, diff --git a/backend/src/plugins/Logs/events/LogsGuildMemberAddEvt.ts b/backend/src/plugins/Logs/events/LogsGuildMemberAddEvt.ts index b7a731f7..71448dbb 100644 --- a/backend/src/plugins/Logs/events/LogsGuildMemberAddEvt.ts +++ b/backend/src/plugins/Logs/events/LogsGuildMemberAddEvt.ts @@ -13,14 +13,14 @@ export const LogsGuildMemberAddEvt = logsEvt({ const member = meta.args.member; const newThreshold = moment.utc().valueOf() - 1000 * 60 * 60; - const accountAge = humanizeDuration(moment.utc().valueOf() - member.createdAt, { + const accountAge = humanizeDuration(moment.utc().valueOf() - member.user.createdTimestamp, { largest: 2, round: true, }); pluginData.state.guildLogs.log(LogType.MEMBER_JOIN, { member: stripObjectToScalars(member, ["user", "roles"]), - new: member.createdAt >= newThreshold ? " :new:" : "", + new: member.user.createdTimestamp >= newThreshold ? " :new:" : "", account_age: accountAge, }); diff --git a/backend/src/plugins/Logs/events/LogsUserUpdateEvts.ts b/backend/src/plugins/Logs/events/LogsUserUpdateEvts.ts index 396cbbc8..170e8543 100644 --- a/backend/src/plugins/Logs/events/LogsUserUpdateEvts.ts +++ b/backend/src/plugins/Logs/events/LogsUserUpdateEvts.ts @@ -5,6 +5,7 @@ import { LogType } from "../../../data/LogType"; import isEqual from "lodash.isequal"; import diff from "lodash.difference"; import { safeFindRelevantAuditLogEntry } from "../../../utils/safeFindRelevantAuditLogEntry"; +import { GuildAuditLogs } from "discord.js"; export const LogsGuildMemberUpdateEvt = logsEvt({ event: "guildMemberUpdate", @@ -12,17 +13,17 @@ export const LogsGuildMemberUpdateEvt = logsEvt({ async listener(meta) { const pluginData = meta.pluginData; const oldMember = meta.args.oldMember; - const member = meta.args.member; + const member = meta.args.newMember; if (!oldMember) return; const logMember = stripObjectToScalars(member, ["user", "roles"]); - if (member.nick !== oldMember.nick) { + if (member.nickname !== oldMember.nickname) { pluginData.state.guildLogs.log(LogType.MEMBER_NICK_CHANGE, { member: logMember, - oldNick: oldMember.nick != null ? oldMember.nick : "", - newNick: member.nick != null ? member.nick : "", + oldNick: oldMember.nickname != null ? oldMember.nickname : "", + newNick: member.nickname != null ? member.nickname : "", }); } @@ -49,10 +50,10 @@ export const LogsGuildMemberUpdateEvt = logsEvt({ if (!skip) { const relevantAuditLogEntry = await safeFindRelevantAuditLogEntry( pluginData, - ErisConstants.AuditLogActions.MEMBER_ROLE_UPDATE, + GuildAuditLogs.Actions.MEMBER_ROLE_UPDATE as number, member.id, ); - const mod = relevantAuditLogEntry ? relevantAuditLogEntry.user : new UnknownUser(); + const mod = relevantAuditLogEntry ? relevantAuditLogEntry.executor : new UnknownUser(); if (addedRoles.length && removedRoles.length) { // Roles added *and* removed diff --git a/backend/src/plugins/Logs/events/LogsVoiceChannelEvts.ts b/backend/src/plugins/Logs/events/LogsVoiceChannelEvts.ts index 55d115ec..ef0ba7af 100644 --- a/backend/src/plugins/Logs/events/LogsVoiceChannelEvts.ts +++ b/backend/src/plugins/Logs/events/LogsVoiceChannelEvts.ts @@ -1,46 +1,34 @@ import { logsEvt } from "../types"; import { stripObjectToScalars } from "../../../utils"; import { LogType } from "../../../data/LogType"; -/** Merge into single event -export const LogsVoiceJoinEvt = logsEvt({ - event: "voiceChannelJoin", - - async listener(meta) { - meta.pluginData.state.guildLogs.log(LogType.VOICE_CHANNEL_JOIN, { - member: stripObjectToScalars(meta.args.member, ["user", "roles"]), - channel: stripObjectToScalars(meta.args.newChannel), - }); - }, -}); - -export const LogsVoiceLeaveEvt = logsEvt({ - event: "voiceChannelLeave", - - async listener(meta) { - meta.pluginData.state.guildLogs.log(LogType.VOICE_CHANNEL_LEAVE, { - member: stripObjectToScalars(meta.args.member, ["user", "roles"]), - channel: stripObjectToScalars(meta.args.oldChannel), - }); - }, -}); - -export const LogsVoiceSwitchEvt = logsEvt({ - event: "voiceChannelSwitch", - - async listener(meta) { - meta.pluginData.state.guildLogs.log(LogType.VOICE_CHANNEL_MOVE, { - member: stripObjectToScalars(meta.args.member, ["user", "roles"]), - oldChannel: stripObjectToScalars(meta.args.oldChannel), - newChannel: stripObjectToScalars(meta.args.newChannel), - }); - }, -}); -**/ export const LogsVoiceStateUpdateEvt = logsEvt({ event: "voiceStateUpdate", async listener(meta) { - console.error(`Fixme @LogsVoiceChannelEvts.ts`); + const oldChannel = meta.args.oldState.channel; + const newChannel = meta.args.newState.channel; + const member = meta.args.newState.member ?? meta.args.oldState.member!; + + if (!newChannel) { // Leave evt + meta.pluginData.state.guildLogs.log(LogType.VOICE_CHANNEL_LEAVE, { + member: stripObjectToScalars(member, ["user", "roles"]), + oldChannel: stripObjectToScalars(oldChannel), + newChannel: stripObjectToScalars(newChannel), + }); + } else if (!oldChannel) { // Join Evt + meta.pluginData.state.guildLogs.log(LogType.VOICE_CHANNEL_JOIN, { + member: stripObjectToScalars(member, ["user", "roles"]), + oldChannel: stripObjectToScalars(oldChannel), + newChannel: stripObjectToScalars(newChannel), + }); + } else { + meta.pluginData.state.guildLogs.log(LogType.VOICE_CHANNEL_MOVE, { + member: stripObjectToScalars(member, ["user", "roles"]), + oldChannel: stripObjectToScalars(oldChannel), + newChannel: stripObjectToScalars(newChannel), + }); + } + }, }); diff --git a/backend/src/plugins/Logs/util/getLogMessage.ts b/backend/src/plugins/Logs/util/getLogMessage.ts index 89542467..06baebc5 100644 --- a/backend/src/plugins/Logs/util/getLogMessage.ts +++ b/backend/src/plugins/Logs/util/getLogMessage.ts @@ -12,15 +12,15 @@ import { import { SavedMessage } from "../../../data/entities/SavedMessage"; import { renderTemplate, TemplateParseError } from "../../../templateFormatter"; import { logger } from "../../../logger"; -import moment from "moment-timezone"; import { TimeAndDatePlugin } from "../../TimeAndDate/TimeAndDatePlugin"; +import { MessageOptions } from "discord.js"; export async function getLogMessage( pluginData: GuildPluginData, type: LogType, data: any, opts?: Pick, -): Promise { +): Promise { const config = pluginData.config.get(); const format = opts?.format?.[LogType[type]] || config.format[LogType[type]] || ""; if (format === "" || format == null) return null; diff --git a/backend/src/plugins/Logs/util/log.ts b/backend/src/plugins/Logs/util/log.ts index 8e4840aa..ea65690d 100644 --- a/backend/src/plugins/Logs/util/log.ts +++ b/backend/src/plugins/Logs/util/log.ts @@ -6,6 +6,7 @@ import { createChunkedMessage, get, noop } from "../../../utils"; import { getLogMessage } from "./getLogMessage"; import { allowTimeout } from "../../../RegExpRunner"; import { SavedMessage } from "../../../data/entities/SavedMessage"; +import { MessageMentionTypes, TextChannel } from "discord.js"; const excludedUserProps = ["user", "member", "mod"]; const excludedRoleProps = ["message.member.roles", "member.roles"]; @@ -46,8 +47,8 @@ export async function log(pluginData: GuildPluginData, type: Log for (const value of Object.values(data || {})) { if (value instanceof SavedMessage) { const member = pluginData.guild.members.cache.get(value.user_id); - for (const role of member?.roles || []) { - if (opts.excluded_roles.includes(role)) { + for (const role of member?.roles.cache || []) { + if (opts.excluded_roles.includes(role[0])) { continue logChannelLoop; } } @@ -128,7 +129,7 @@ export async function log(pluginData: GuildPluginData, type: Log if (message) { // For non-string log messages (i.e. embeds) batching or chunking is not possible, so send them immediately if (typeof message !== "string") { - await channel.createMessage(message).catch(noop); + await channel.send(message).catch(noop); return; } @@ -136,6 +137,7 @@ export async function log(pluginData: GuildPluginData, type: Log const batched = opts.batched ?? true; const batchTime = opts.batch_time ?? 1000; const cfg = pluginData.config.get(); + const parse: MessageMentionTypes[] | undefined = cfg.allow_user_mentions ? ["users"] : undefined; if (batched) { // If we're batching log messages, gather all log messages within the set batch_time into a single message @@ -144,14 +146,14 @@ export async function log(pluginData: GuildPluginData, type: Log setTimeout(async () => { const batchedMessage = pluginData.state.batches.get(channel.id)!.join("\n"); pluginData.state.batches.delete(channel.id); - createChunkedMessage(channel, batchedMessage, { users: cfg.allow_user_mentions }).catch(noop); + createChunkedMessage(channel, batchedMessage, { parse }).catch(noop); }, batchTime); } pluginData.state.batches.get(channel.id)!.push(message); } else { // If we're not batching log messages, just send them immediately - await createChunkedMessage(channel, message, { users: cfg.allow_user_mentions }).catch(noop); + await createChunkedMessage(channel, message, { parse }).catch(noop); } } } diff --git a/backend/src/plugins/Logs/util/onMessageDelete.ts b/backend/src/plugins/Logs/util/onMessageDelete.ts index eae416fd..a7437713 100644 --- a/backend/src/plugins/Logs/util/onMessageDelete.ts +++ b/backend/src/plugins/Logs/util/onMessageDelete.ts @@ -6,6 +6,7 @@ import moment from "moment-timezone"; import { GuildPluginData } from "knub"; import { FORMAT_NO_TIMESTAMP, LogsPluginType } from "../types"; import { TimeAndDatePlugin } from "../../TimeAndDate/TimeAndDatePlugin"; +import { MessageAttachment } from "discord.js"; export async function onMessageDelete(pluginData: GuildPluginData, savedMessage: SavedMessage) { const user = await resolveUser(pluginData.client, savedMessage.user_id); @@ -14,7 +15,7 @@ export async function onMessageDelete(pluginData: GuildPluginData, @@ -14,13 +15,13 @@ export async function onMessageUpdate( // To log a message update, either the message content or a rich embed has to change let logUpdate = false; - const oldEmbedsToCompare = ((oldSavedMessage.data.embeds || []) as Embed[]) + const oldEmbedsToCompare = ((oldSavedMessage.data.embeds || []) as MessageEmbed[]) .map(e => cloneDeep(e)) - .filter(e => (e as Embed).type === "rich"); + .filter(e => (e as MessageEmbed).type === "rich"); - const newEmbedsToCompare = ((savedMessage.data.embeds || []) as Embed[]) + const newEmbedsToCompare = ((savedMessage.data.embeds || []) as MessageEmbed[]) .map(e => cloneDeep(e)) - .filter(e => (e as Embed).type === "rich"); + .filter(e => (e as MessageEmbed).type === "rich"); for (const embed of [...oldEmbedsToCompare, ...newEmbedsToCompare]) { if (embed.thumbnail) { diff --git a/backend/src/plugins/MessageSaver/commands/SaveMessagesToDB.ts b/backend/src/plugins/MessageSaver/commands/SaveMessagesToDB.ts index 114da844..226a8a2b 100644 --- a/backend/src/plugins/MessageSaver/commands/SaveMessagesToDB.ts +++ b/backend/src/plugins/MessageSaver/commands/SaveMessagesToDB.ts @@ -14,7 +14,7 @@ export const SaveMessagesToDBCmd = messageSaverCmd({ }, async run({ message: msg, args, pluginData }) { - await msg.channel.createMessage("Saving specified messages..."); + await msg.channel.send("Saving specified messages..."); const { savedCount, failed } = await saveMessagesToDB(pluginData, args.channel, args.ids.trim().split(" ")); if (failed.length) { diff --git a/backend/src/plugins/MessageSaver/commands/SavePinsToDB.ts b/backend/src/plugins/MessageSaver/commands/SavePinsToDB.ts index 2ecbf8e0..5d9484ed 100644 --- a/backend/src/plugins/MessageSaver/commands/SavePinsToDB.ts +++ b/backend/src/plugins/MessageSaver/commands/SavePinsToDB.ts @@ -13,13 +13,13 @@ export const SavePinsToDBCmd = messageSaverCmd({ }, async run({ message: msg, args, pluginData }) { - await msg.channel.createMessage(`Saving pins from <#${args.channel.id}>...`); + await msg.channel.send(`Saving pins from <#${args.channel.id}>...`); - const pins = await args.channel.getPins(); + const pins = await args.channel.messages.fetchPinned(); const { savedCount, failed } = await saveMessagesToDB( pluginData, args.channel, - pins.map(m => m.id), + pins.keyArray(), ); if (failed.length) { diff --git a/backend/src/plugins/MessageSaver/events/SaveMessagesEvts.ts b/backend/src/plugins/MessageSaver/events/SaveMessagesEvts.ts index 51e34ff1..c9b093cd 100644 --- a/backend/src/plugins/MessageSaver/events/SaveMessagesEvts.ts +++ b/backend/src/plugins/MessageSaver/events/SaveMessagesEvts.ts @@ -1,3 +1,4 @@ +import { Message } from "discord.js"; import { messageSaverEvt } from "../types"; export const MessageCreateEvt = messageSaverEvt({ @@ -7,7 +8,7 @@ export const MessageCreateEvt = messageSaverEvt({ async listener(meta) { // Only save regular chat messages - if (meta.args.message.type !== 0) { + if (meta.args.message.type !== "DEFAULT" && meta.args.message.type !== "REPLY") { return; } @@ -21,11 +22,11 @@ export const MessageUpdateEvt = messageSaverEvt({ allowSelf: true, async listener(meta) { - if (meta.args.message.type !== 0) { + if (meta.args.newMessage.type !== "DEFAULT" && meta.args.newMessage.type !== "REPLY") { return; } - await meta.pluginData.state.savedMessages.saveEditFromMsg(meta.args.message); + await meta.pluginData.state.savedMessages.saveEditFromMsg(meta.args.newMessage as Message); }, }); @@ -36,7 +37,7 @@ export const MessageDeleteEvt = messageSaverEvt({ async listener(meta) { const msg = meta.args.message as Message; - if (msg.type != null && msg.type !== 0) { + if (msg.type != null && meta.args.message.type !== "DEFAULT" && meta.args.message.type !== "REPLY") { return; } diff --git a/backend/src/plugins/MessageSaver/saveMessagesToDB.ts b/backend/src/plugins/MessageSaver/saveMessagesToDB.ts index 8e1635b9..dd0f3b80 100644 --- a/backend/src/plugins/MessageSaver/saveMessagesToDB.ts +++ b/backend/src/plugins/MessageSaver/saveMessagesToDB.ts @@ -1,5 +1,6 @@ import { MessageSaverPluginType } from "./types"; import { GuildPluginData } from "knub"; +import { TextChannel, Message } from "discord.js"; export async function saveMessagesToDB( pluginData: GuildPluginData, @@ -14,7 +15,7 @@ export async function saveMessagesToDB( let thisMsg: Message; try { - thisMsg = await channel.getMessage(id); + thisMsg = await channel.messages.fetch(id); if (!thisMsg) { failed.push(id);