3
0
Fork 0
mirror of https://github.com/ZeppelinBot/Zeppelin.git synced 2025-03-15 05:41:51 +00:00

Finish preliminary rework, ready to test

This commit is contained in:
Dark 2021-06-02 04:07:50 +02:00
parent 57893e7f76
commit d0a1beb809
No known key found for this signature in database
GPG key ID: 2CD6ACB6B0A87B8A
177 changed files with 854 additions and 707 deletions

2
.gitignore vendored
View file

@ -77,3 +77,5 @@ npm-audit.txt
# Debug files
*.debug.ts
*.debug.js
.vscode/

View file

@ -211,7 +211,8 @@ export class GuildSavedMessages extends BaseGuildRepository {
const newMessage = { ...oldMessage, data: newData };
await this.messages.update(
//@ts-ignore
await this.messages.update( // FIXME?
{ id },
{
data: newData,

View file

@ -53,13 +53,13 @@ export const AddRolesAction = automodAction({
await Promise.all(
members.map(async member => {
const memberRoles = new Set(member.roles);
const memberRoles = new Set(member.roles.cache.keyArray());
for (const roleId of rolesToAssign) {
memberRoles.add(roleId);
ignoreRoleChange(pluginData, member.id, roleId);
}
if (memberRoles.size === member.roles.length) {
if (memberRoles.size === member.roles.cache.size) {
// No role changes
return;
}
@ -70,7 +70,6 @@ export const AddRolesAction = automodAction({
await member.edit({
roles: rolesArr,
});
member.roles = rolesArr; // Make sure we know of the new roles internally as well
memberRoleLock.unlock();
}),

View file

@ -57,13 +57,13 @@ export const RemoveRolesAction = automodAction({
await Promise.all(
members.map(async member => {
const memberRoles = new Set(member.roles);
const memberRoles = new Set(member.roles.cache.keyArray());
for (const roleId of rolesToRemove) {
memberRoles.delete(roleId);
ignoreRoleChange(pluginData, member.id, roleId);
}
if (memberRoles.size === member.roles.length) {
if (memberRoles.size === member.roles.cache.size) {
// No role changes
return;
}
@ -74,7 +74,6 @@ export const RemoveRolesAction = automodAction({
await member.edit({
roles: rolesArr,
});
member.roles = rolesArr; // Make sure we know of the new roles internally as well
memberRoleLock.unlock();
}),

View file

@ -23,11 +23,11 @@ export function getTextMatchPartialSummary(
} else if (type === "username") {
return `username: ${context.user!.username}`;
} else if (type === "nickname") {
return `nickname: ${context.member!.nick}`;
return `nickname: ${context.member!.nickname}`;
} else if (type === "visiblename") {
const visibleName = context.member?.nick || context.user!.username;
const visibleName = context.member?.nickname || context.user!.username;
return `visible name: ${visibleName}`;
} else if (type === "customstatus") {
return `custom status: ${context.member!.game!.state}`;
return `custom status: ${context.member!.presence.activities.find(a => a.type === "CUSTOM_STATUS")?.name}`;
}
}

View file

@ -20,7 +20,7 @@ export const MemberJoinTrigger = automodTrigger<unknown>()({
if (triggerConfig.only_new) {
const threshold = Date.now() - convertDelayStringToMS(triggerConfig.new_threshold)!;
return context.member.createdAt >= threshold ? {} : null;
return context.member.user.createdTimestamp >= threshold ? {} : null;
}
return {};

View file

@ -2,6 +2,7 @@ import { botControlCmd } from "../types";
import { isOwnerPreFilter, sendErrorMessage, sendSuccessMessage } from "../../../pluginUtils";
import { commandTypeHelpers as ct } from "../../../commandTypes";
import { ApiPermissions } from "@shared/apiPermissions";
import { TextChannel } from "discord.js";
export const AddDashboardUserCmd = botControlCmd({
trigger: ["add_dashboard_user"],
@ -18,7 +19,7 @@ export const AddDashboardUserCmd = botControlCmd({
async run({ pluginData, message: msg, args }) {
const guild = await pluginData.state.allowedGuilds.find(args.guildId);
if (!guild) {
sendErrorMessage(pluginData, msg.channel, "Server is not using Zeppelin");
sendErrorMessage(pluginData, msg.channel as TextChannel, "Server is not using Zeppelin");
return;
}
@ -39,7 +40,7 @@ export const AddDashboardUserCmd = botControlCmd({
);
sendSuccessMessage(
pluginData,
msg.channel,
msg.channel as TextChannel,
`The following users were given dashboard access for **${guild.name}**:\n\n${userNameList}`,
);
},

View file

@ -3,6 +3,7 @@ import { isOwnerPreFilter, sendErrorMessage, sendSuccessMessage } from "../../..
import { commandTypeHelpers as ct } from "../../../commandTypes";
import { isSnowflake } from "../../../utils";
import { ApiPermissions } from "@shared/apiPermissions";
import { TextChannel } from "discord.js";
export const AllowServerCmd = botControlCmd({
trigger: ["allow_server", "allowserver", "add_server", "addserver"],
@ -19,17 +20,17 @@ export const AllowServerCmd = botControlCmd({
async run({ pluginData, message: msg, args }) {
const existing = await pluginData.state.allowedGuilds.find(args.guildId);
if (existing) {
sendErrorMessage(pluginData, msg.channel, "Server is already allowed!");
sendErrorMessage(pluginData, msg.channel as TextChannel, "Server is already allowed!");
return;
}
if (!isSnowflake(args.guildId)) {
sendErrorMessage(pluginData, msg.channel, "Invalid server ID!");
sendErrorMessage(pluginData, msg.channel as TextChannel, "Invalid server ID!");
return;
}
if (args.userId && !isSnowflake(args.userId)) {
sendErrorMessage(pluginData, msg.channel, "Invalid user ID!");
sendErrorMessage(pluginData, msg.channel as TextChannel, "Invalid user ID!");
return;
}
@ -40,6 +41,6 @@ export const AllowServerCmd = botControlCmd({
await pluginData.state.apiPermissionAssignments.addUser(args.guildId, args.userId, [ApiPermissions.EditConfig]);
}
sendSuccessMessage(pluginData, msg.channel, "Server is now allowed to use Zeppelin!");
sendSuccessMessage(pluginData, msg.channel as TextChannel, "Server is now allowed to use Zeppelin!");
},
});

View file

@ -2,6 +2,7 @@ import { botControlCmd } from "../types";
import { isOwnerPreFilter, sendErrorMessage, sendSuccessMessage } from "../../../pluginUtils";
import { commandTypeHelpers as ct } from "../../../commandTypes";
import { noop } from "../../../utils";
import { TextChannel } from "discord.js";
export const DisallowServerCmd = botControlCmd({
trigger: ["disallow_server", "disallowserver", "remove_server", "removeserver"],
@ -17,12 +18,15 @@ export const DisallowServerCmd = botControlCmd({
async run({ pluginData, message: msg, args }) {
const existing = await pluginData.state.allowedGuilds.find(args.guildId);
if (!existing) {
sendErrorMessage(pluginData, msg.channel, "That server is not allowed in the first place!");
sendErrorMessage(pluginData, msg.channel as TextChannel, "That server is not allowed in the first place!");
return;
}
await pluginData.state.allowedGuilds.remove(args.guildId);
await pluginData.client.leaveGuild(args.guildId).catch(noop);
sendSuccessMessage(pluginData, msg.channel, "Server removed!");
await pluginData.client.guilds.cache
.get(args.guildId)
?.leave()
.catch(noop);
sendSuccessMessage(pluginData, msg.channel as TextChannel, "Server removed!");
},
});

View file

@ -2,6 +2,7 @@ import { botControlCmd } from "../types";
import { sendErrorMessage, sendSuccessMessage } from "../../../pluginUtils";
import { commandTypeHelpers as ct } from "../../../commandTypes";
import { resolveInvite, verboseUserMention } from "../../../utils";
import { TextChannel } from "discord.js";
const REQUIRED_MEMBER_COUNT = 5000;
@ -18,7 +19,7 @@ export const EligibleCmd = botControlCmd({
if ((await pluginData.state.apiPermissionAssignments.getByUserId(args.user.id)).length) {
sendSuccessMessage(
pluginData,
msg.channel,
msg.channel as TextChannel,
`${verboseUserMention(args.user)} is an existing bot operator. They are eligible!`,
);
return;
@ -26,17 +27,17 @@ export const EligibleCmd = botControlCmd({
const invite = await resolveInvite(pluginData.client, args.inviteCode, true);
if (!invite || !invite.guild) {
sendErrorMessage(pluginData, msg.channel, "Could not resolve server from invite");
sendErrorMessage(pluginData, msg.channel as TextChannel, "Could not resolve server from invite");
return;
}
if (invite.guild.features.includes("PARTNERED")) {
sendSuccessMessage(pluginData, msg.channel, `Server is partnered. It is eligible!`);
sendSuccessMessage(pluginData, msg.channel as TextChannel, `Server is partnered. It is eligible!`);
return;
}
if (invite.guild.features.includes("VERIFIED")) {
sendSuccessMessage(pluginData, msg.channel, `Server is verified. It is eligible!`);
sendSuccessMessage(pluginData, msg.channel as TextChannel, `Server is verified. It is eligible!`);
return;
}
@ -44,7 +45,7 @@ export const EligibleCmd = botControlCmd({
if (memberCount >= REQUIRED_MEMBER_COUNT) {
sendSuccessMessage(
pluginData,
msg.channel,
msg.channel as TextChannel,
`Server has ${memberCount} members, which is equal or higher than the required ${REQUIRED_MEMBER_COUNT}. It is eligible!`,
);
return;
@ -52,7 +53,7 @@ export const EligibleCmd = botControlCmd({
sendErrorMessage(
pluginData,
msg.channel,
msg.channel as TextChannel,
`Server **${invite.guild.name}** (\`${invite.guild.id}\`) is not eligible`,
);
},

View file

@ -1,6 +1,7 @@
import { botControlCmd } from "../types";
import { isOwnerPreFilter, sendErrorMessage, sendSuccessMessage } from "../../../pluginUtils";
import { commandTypeHelpers as ct } from "../../../commandTypes";
import { TextChannel } from "discord.js";
export const LeaveServerCmd = botControlCmd({
trigger: ["leave_server", "leave_guild"],
@ -14,21 +15,21 @@ export const LeaveServerCmd = botControlCmd({
},
async run({ pluginData, message: msg, args }) {
if (!pluginData.client.guilds.has(args.guildId)) {
sendErrorMessage(pluginData, msg.channel, "I am not in that guild");
if (!pluginData.client.guilds.cache.has(args.guildId)) {
sendErrorMessage(pluginData, msg.channel as TextChannel, "I am not in that guild");
return;
}
const guildToLeave = pluginData.client.guilds.get(args.guildId)!;
const guildToLeave = await pluginData.client.guilds.fetch(args.guildId)!;
const guildName = guildToLeave.name;
try {
await pluginData.client.leaveGuild(args.guildId);
await pluginData.client.guilds.cache.get(args.guildId)?.leave();
} catch (e) {
sendErrorMessage(pluginData, msg.channel, `Failed to leave guild: ${e.message}`);
sendErrorMessage(pluginData, msg.channel as TextChannel, `Failed to leave guild: ${e.message}`);
return;
}
sendSuccessMessage(pluginData, msg.channel, `Left guild **${guildName}**`);
sendSuccessMessage(pluginData, msg.channel as TextChannel, `Left guild **${guildName}**`);
},
});

View file

@ -4,6 +4,7 @@ import { commandTypeHelpers as ct } from "../../../commandTypes";
import { createChunkedMessage, resolveUser } from "../../../utils";
import { AllowedGuild } from "../../../data/entities/AllowedGuild";
import { ApiPermissionAssignment } from "../../../data/entities/ApiPermissionAssignment";
import { TextChannel } from "discord.js";
export const ListDashboardPermsCmd = botControlCmd({
trigger: ["list_dashboard_permissions", "list_dashboard_perms", "list_dash_permissionss", "list_dash_perms"],
@ -19,7 +20,7 @@ export const ListDashboardPermsCmd = botControlCmd({
async run({ pluginData, message: msg, args }) {
if (!args.user && !args.guildId) {
sendErrorMessage(pluginData, msg.channel, "Must specify at least guildId, user, or both.");
sendErrorMessage(pluginData, msg.channel as TextChannel, "Must specify at least guildId, user, or both.");
return;
}
@ -27,7 +28,7 @@ export const ListDashboardPermsCmd = botControlCmd({
if (args.guildId) {
guild = await pluginData.state.allowedGuilds.find(args.guildId);
if (!guild) {
sendErrorMessage(pluginData, msg.channel, "Server is not using Zeppelin");
sendErrorMessage(pluginData, msg.channel as TextChannel, "Server is not using Zeppelin");
return;
}
}
@ -36,7 +37,7 @@ export const ListDashboardPermsCmd = botControlCmd({
if (args.user) {
existingUserAssignment = await pluginData.state.apiPermissionAssignments.getByUserId(args.user.id);
if (existingUserAssignment.length === 0) {
sendErrorMessage(pluginData, msg.channel, "The user has no assigned permissions.");
sendErrorMessage(pluginData, msg.channel as TextChannel, "The user has no assigned permissions.");
return;
}
}
@ -59,7 +60,7 @@ export const ListDashboardPermsCmd = botControlCmd({
if (finalMessage === "") {
sendErrorMessage(
pluginData,
msg.channel,
msg.channel as TextChannel,
`The user ${userInfo} has no assigned permissions on the specified server.`,
);
return;
@ -70,7 +71,11 @@ export const ListDashboardPermsCmd = botControlCmd({
const existingGuildAssignment = await pluginData.state.apiPermissionAssignments.getByGuildId(guild.id);
if (existingGuildAssignment.length === 0) {
sendErrorMessage(pluginData, msg.channel, `The server ${guildInfo} has no assigned permissions.`);
sendErrorMessage(
pluginData,
msg.channel as TextChannel,
`The server ${guildInfo} has no assigned permissions.`,
);
return;
}
@ -83,6 +88,6 @@ export const ListDashboardPermsCmd = botControlCmd({
}
}
await sendSuccessMessage(pluginData, msg.channel, finalMessage.trim(), {});
await sendSuccessMessage(pluginData, msg.channel as TextChannel, finalMessage.trim(), {});
},
});

View file

@ -3,6 +3,7 @@ import { isOwnerPreFilter, sendErrorMessage, sendSuccessMessage } from "../../..
import { commandTypeHelpers as ct } from "../../../commandTypes";
import { ApiPermissions } from "@shared/apiPermissions";
import { resolveUser, UnknownUser } from "../../../utils";
import { TextChannel } from "discord.js";
export const ListDashboardUsersCmd = botControlCmd({
trigger: ["list_dashboard_users"],
@ -18,7 +19,7 @@ export const ListDashboardUsersCmd = botControlCmd({
async run({ pluginData, message: msg, args }) {
const guild = await pluginData.state.allowedGuilds.find(args.guildId);
if (!guild) {
sendErrorMessage(pluginData, msg.channel, "Server is not using Zeppelin");
sendErrorMessage(pluginData, msg.channel as TextChannel, "Server is not using Zeppelin");
return;
}
@ -30,7 +31,7 @@ export const ListDashboardUsersCmd = botControlCmd({
sendSuccessMessage(
pluginData,
msg.channel,
msg.channel as TextChannel,
`The following users have dashboard access for **${guild.name}**:\n\n${userNameList}`,
{},
);

View file

@ -1,6 +1,7 @@
import { botControlCmd } from "../types";
import { isOwnerPreFilter } from "../../../pluginUtils";
import { getActiveReload, setActiveReload } from "../activeReload";
import { TextChannel } from "discord.js";
export const ReloadGlobalPluginsCmd = botControlCmd({
trigger: "bot_reload_global_plugins",
@ -13,7 +14,7 @@ export const ReloadGlobalPluginsCmd = botControlCmd({
if (getActiveReload()) return;
setActiveReload((message.channel as TextChannel).guild?.id, message.channel.id);
await message.channel.createMessage("Reloading global plugins...");
await message.channel.send("Reloading global plugins...");
pluginData.getKnubInstance().reloadGlobalContext();
},

View file

@ -1,6 +1,7 @@
import { botControlCmd } from "../types";
import { isOwnerPreFilter, sendErrorMessage, sendSuccessMessage } from "../../../pluginUtils";
import { commandTypeHelpers as ct } from "../../../commandTypes";
import { TextChannel } from "discord.js";
export const ReloadServerCmd = botControlCmd({
trigger: ["reload_server", "reload_guild"],
@ -14,19 +15,19 @@ export const ReloadServerCmd = botControlCmd({
},
async run({ pluginData, message: msg, args }) {
if (!pluginData.client.guilds.has(args.guildId)) {
sendErrorMessage(pluginData, msg.channel, "I am not in that guild");
if (!pluginData.client.guilds.cache.has(args.guildId)) {
sendErrorMessage(pluginData, msg.channel as TextChannel, "I am not in that guild");
return;
}
try {
await pluginData.getKnubInstance().reloadGuild(args.guildId);
} catch (e) {
sendErrorMessage(pluginData, msg.channel, `Failed to reload guild: ${e.message}`);
sendErrorMessage(pluginData, msg.channel as TextChannel, `Failed to reload guild: ${e.message}`);
return;
}
const guild = pluginData.client.guilds.get(args.guildId);
sendSuccessMessage(pluginData, msg.channel, `Reloaded guild **${guild?.name || "???"}**`);
const guild = await pluginData.client.guilds.fetch(args.guildId);
sendSuccessMessage(pluginData, msg.channel as TextChannel, `Reloaded guild **${guild?.name || "???"}**`);
},
});

View file

@ -2,6 +2,7 @@ import { botControlCmd } from "../types";
import { isOwnerPreFilter, sendErrorMessage, sendSuccessMessage } from "../../../pluginUtils";
import { commandTypeHelpers as ct } from "../../../commandTypes";
import { ApiPermissions } from "@shared/apiPermissions";
import { TextChannel } from "discord.js";
export const RemoveDashboardUserCmd = botControlCmd({
trigger: ["remove_dashboard_user"],
@ -18,7 +19,7 @@ export const RemoveDashboardUserCmd = botControlCmd({
async run({ pluginData, message: msg, args }) {
const guild = await pluginData.state.allowedGuilds.find(args.guildId);
if (!guild) {
sendErrorMessage(pluginData, msg.channel, "Server is not using Zeppelin");
sendErrorMessage(pluginData, msg.channel as TextChannel, "Server is not using Zeppelin");
return;
}
@ -39,7 +40,7 @@ export const RemoveDashboardUserCmd = botControlCmd({
);
sendSuccessMessage(
pluginData,
msg.channel,
msg.channel as TextChannel,
`The following users were removed from the dashboard for **${guild.name}**:\n\n${userNameList}`,
);
},

View file

@ -3,6 +3,7 @@ import { isOwnerPreFilter } from "../../../pluginUtils";
import { commandTypeHelpers as ct } from "../../../commandTypes";
import escapeStringRegexp from "escape-string-regexp";
import { createChunkedMessage, getUser, sorter } from "../../../utils";
import { TextChannel } from "discord.js";
export const ServersCmd = botControlCmd({
trigger: ["servers", "guilds"],
@ -23,7 +24,7 @@ export const ServersCmd = botControlCmd({
const showList = Boolean(args.all || args.initialized || args.uninitialized || args.search);
const search = args.search ? new RegExp([...args.search].map(s => escapeStringRegexp(s)).join(".*"), "i") : null;
const joinedGuilds = Array.from(pluginData.client.guilds.values());
const joinedGuilds = Array.from(pluginData.client.guilds.cache.values());
const loadedGuilds = pluginData.getKnubInstance().getLoadedGuilds();
const loadedGuildsMap = loadedGuilds.reduce((map, guildData) => map.set(guildData.guildId, guildData), new Map());
@ -50,16 +51,16 @@ export const ServersCmd = botControlCmd({
const owner = getUser(pluginData.client, g.ownerID);
return `\`${paddedId}\` **${g.name}** (${g.memberCount} members) (owner **${owner.username}#${owner.discriminator}** \`${owner.id}\`)`;
});
createChunkedMessage(msg.channel, lines.join("\n"));
createChunkedMessage(msg.channel as TextChannel, lines.join("\n"));
} else {
msg.channel.createMessage("No servers matched the filters");
msg.channel.send("No servers matched the filters");
}
} else {
const total = joinedGuilds.length;
const initialized = joinedGuilds.filter(g => loadedGuildsMap.has(g.id)).length;
const unInitialized = total - initialized;
msg.channel.createMessage(
msg.channel.send(
`I am on **${total} total servers**, of which **${initialized} are initialized** and **${unInitialized} are not initialized**`,
);
}

View file

@ -14,7 +14,7 @@ export async function censorMessage(
pluginData.state.serverLogs.ignoreLog(LogType.MESSAGE_DELETE, savedMessage.id);
try {
const channel = pluginData.guild.channels.resolve(savedMessage.channel_id) as TextChannel
const channel = pluginData.guild.channels.resolve(savedMessage.channel_id) as TextChannel;
await channel.messages.delete(savedMessage.id);
} catch {
return;

View file

@ -104,6 +104,15 @@ export const ArchiveChannelCmd = channelArchiverCmd({
result += `\n\n${archiveLines.join("\n")}\n`;
progressMsg.delete().catch(noop);
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 });
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,
});
},
});

View file

@ -18,7 +18,10 @@ export async function rehostAttachment(attachment: MessageAttachment, targetChan
}
try {
const content: MessageOptions = { content: `Rehost of attachment ${attachment.id}`, files: [{ name: attachment.name ? attachment.name : undefined, attachment: await fsp.readFile(downloaded.path)}]}
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 {

View file

@ -60,11 +60,9 @@ export async function handleCompanionPermissions(
for (const [channelId, permissions] of permsToSet) {
const channel = pluginData.guild.channels.cache.get(channelId);
if (!channel || !(channel instanceof TextChannel)) continue;
await channel.updateOverwrite(
userId,
new Permissions(BigInt(permissions)).serialize(),
{reason: `Companion Channel for ${voiceChannel!.id} | User Joined`},
);
await channel.updateOverwrite(userId, new Permissions(BigInt(permissions)).serialize(), {
reason: `Companion Channel for ${voiceChannel!.id} | User Joined`,
});
}
} catch (e) {
if (isDiscordRESTError(e) && e.code === 50001) {

View file

@ -128,13 +128,9 @@ export const AddCounterCmd = typedGuildCommand<CountersPluginType>()({
`Added ${amount} to **${counterName}** for <@!${user.id}> in <#${channel.id}>. The value is now ${newValue}.`,
);
} else if (channel) {
message.channel.send(
`Added ${amount} to **${counterName}** in <#${channel.id}>. The value is now ${newValue}.`,
);
message.channel.send(`Added ${amount} to **${counterName}** in <#${channel.id}>. The value is now ${newValue}.`);
} else if (user) {
message.channel.send(
`Added ${amount} to **${counterName}** for <@!${user.id}>. The value is now ${newValue}.`,
);
message.channel.send(`Added ${amount} to **${counterName}** for <@!${user.id}>. The value is now ${newValue}.`);
} else {
message.channel.send(`Added ${amount} to **${counterName}**. The value is now ${newValue}.`);
}

View file

@ -30,6 +30,6 @@ export async function addRoleAction(
const rolesToAdd = Array.isArray(action.role) ? action.role : [action.role];
await target.edit({
roles: Array.from(new Set([...target.roles, ...rolesToAdd])),
roles: Array.from(new Set([...target.roles.cache.array(), ...rolesToAdd])),
});
}

View file

@ -3,6 +3,7 @@ import { CustomEventsPluginType } from "../types";
import * as t from "io-ts";
import { renderTemplate } from "../../../templateFormatter";
import { ActionError } from "../ActionError";
import { TextChannel } from "discord.js";
export const MessageAction = t.type({
type: t.literal("message"),
@ -21,5 +22,5 @@ export async function messageAction(
if (!targetChannel) throw new ActionError("Unknown target channel");
if (!(targetChannel instanceof TextChannel)) throw new ActionError("Target channel is not a text channel");
await targetChannel.createMessage({ content: action.content });
await targetChannel.send({ content: action.content });
}

View file

@ -5,6 +5,7 @@ import { renderTemplate } from "../../../templateFormatter";
import { resolveMember } from "../../../utils";
import { ActionError } from "../ActionError";
import { canActOn } from "../../../pluginUtils";
import { VoiceChannel } from "discord.js";
export const MoveToVoiceChannelAction = t.type({
type: t.literal("move_to_vc"),
@ -33,8 +34,8 @@ export async function moveToVoiceChannelAction(
if (!targetChannel) throw new ActionError("Unknown target channel");
if (!(targetChannel instanceof VoiceChannel)) throw new ActionError("Target channel is not a voice channel");
if (!target.voiceState.channelID) return;
if (!target.voice.channelID) return;
await target.edit({
channelID: targetChannel.id,
channel: targetChannel.id,
});
}

View file

@ -30,11 +30,8 @@ export async function setChannelPermissionOverridesAction(
}
for (const override of action.overrides) {
await channel.editPermission(
override.id,
override.allow,
override.deny,
override.type,
await channel.overwritePermissions(
[{ id: override.id, allow: BigInt(override.allow), deny: BigInt(override.deny), type: override.type }],
`Custom event: ${event.name}`,
);
}

View file

@ -10,6 +10,7 @@ import { messageAction } from "../actions/messageAction";
import { makeRoleMentionableAction } from "../actions/makeRoleMentionableAction";
import { makeRoleUnmentionableAction } from "../actions/makeRoleUnmentionableAction";
import { setChannelPermissionOverridesAction } from "../actions/setChannelPermissionOverrides";
import { Message, TextChannel } from "discord.js";
export async function runEvent(
pluginData: GuildPluginData<CustomEventsPluginType>,
@ -38,7 +39,7 @@ export async function runEvent(
} catch (e) {
if (e instanceof ActionError) {
if (event.trigger.type === "command") {
sendErrorMessage(pluginData, (eventData.msg as Message).channel, e.message);
sendErrorMessage(pluginData, (eventData.msg as Message).channel as TextChannel, e.message);
} else {
// TODO: Where to log action errors from other kinds of triggers?
}

View file

@ -2,6 +2,7 @@ import { zeppelinGlobalPlugin } from "../ZeppelinPluginBlueprint";
import { BasePluginType, typedGlobalEventListener, GlobalPluginData } from "knub";
import * as t from "io-ts";
import { AllowedGuilds } from "../../data/AllowedGuilds";
import { Guild } from "discord.js";
interface GuildAccessMonitorPluginType extends BasePluginType {
config: {};
@ -27,7 +28,7 @@ export const GuildAccessMonitorPlugin = zeppelinGlobalPlugin<GuildAccessMonitorP
events: [
typedGlobalEventListener<GuildAccessMonitorPluginType>()({
event: "guildAvailable",
event: "guildCreate",
listener({ pluginData, args: { guild } }) {
checkGuild(pluginData, guild);
},
@ -39,7 +40,7 @@ export const GuildAccessMonitorPlugin = zeppelinGlobalPlugin<GuildAccessMonitorP
},
afterLoad(pluginData) {
for (const guild of pluginData.client.guilds.values()) {
for (const guild of pluginData.client.guilds.cache.values()) {
checkGuild(pluginData, guild);
}
},

View file

@ -54,9 +54,7 @@ export const FollowCmd = locateUserCmd({
sendSuccessMessage(
pluginData,
msg.channel,
`Every time <@${args.member.id}> joins or switches VC in the next ${humanizeDuration(
time,
)} i will notify you`,
`Every time <@${args.member.id}> joins or switches VC in the next ${humanizeDuration(time)} i will notify you`,
);
}
},

View file

@ -20,8 +20,8 @@ export const VoiceStateUpdateAlertEvt = locateUserEvt({
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}>\``,
);
});
);
});
}
},
});

View file

@ -13,7 +13,7 @@ export async function moveMember(
if (modMember.voice.channelID != null) {
try {
await modMember.edit({
channel: target.voice.channelID
channel: target.voice.channelID,
});
} catch {
sendErrorMessage(pluginData, errorChannel, "Failed to move you. Are you in a voice channel?");

View file

@ -10,13 +10,15 @@ export const LogsVoiceStateUpdateEvt = logsEvt({
const newChannel = meta.args.newState.channel;
const member = meta.args.newState.member ?? meta.args.oldState.member!;
if (!newChannel) { // Leave evt
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
} else if (!oldChannel) {
// Join Evt
meta.pluginData.state.guildLogs.log(LogType.VOICE_CHANNEL_JOIN, {
member: stripObjectToScalars(member, ["user", "roles"]),
oldChannel: stripObjectToScalars(oldChannel),
@ -29,6 +31,5 @@ export const LogsVoiceStateUpdateEvt = logsEvt({
newChannel: stripObjectToScalars(newChannel),
});
}
},
});

View file

@ -16,11 +16,7 @@ export const SavePinsToDBCmd = messageSaverCmd({
await msg.channel.send(`Saving pins from <#${args.channel.id}>...`);
const pins = await args.channel.messages.fetchPinned();
const { savedCount, failed } = await saveMessagesToDB(
pluginData,
args.channel,
pins.keyArray(),
);
const { savedCount, failed } = await saveMessagesToDB(pluginData, args.channel, pins.keyArray());
if (failed.length) {
sendSuccessMessage(

View file

@ -45,6 +45,7 @@ import { onModActionsEvent } from "./functions/onModActionsEvent";
import { offModActionsEvent } from "./functions/offModActionsEvent";
import { updateCase } from "./functions/updateCase";
import { Queue } from "../../Queue";
import { GuildMember, Message } from "discord.js";
const defaultOptions = {
config: {
@ -158,13 +159,13 @@ export const ModActionsPlugin = zeppelinGuildPlugin<ModActionsPluginType>()({
public: {
warnMember(pluginData) {
return (member: Member, reason: string, warnOptions?: WarnOptions) => {
return (member: GuildMember, reason: string, warnOptions?: WarnOptions) => {
warnMember(pluginData, member, reason, warnOptions);
};
},
kickMember(pluginData) {
return (member: Member, reason: string, kickOptions?: KickOptions) => {
return (member: GuildMember, reason: string, kickOptions?: KickOptions) => {
kickMember(pluginData, member, reason, kickOptions);
};
},

View file

@ -59,7 +59,7 @@ export const AddCaseCmd = modActionsCmd({
return;
}
const reason = formatReasonWithAttachments(args.reason, msg.attachments);
const reason = formatReasonWithAttachments(args.reason, msg.attachments.array());
// Create the case
const casesPlugin = pluginData.getPlugin(CasesPlugin);

View file

@ -6,7 +6,7 @@ import { isBanned } from "../functions/isBanned";
import { readContactMethodsFromArgs } from "../functions/readContactMethodsFromArgs";
import { formatReasonWithAttachments } from "../functions/formatReasonWithAttachments";
import { banUserId } from "../functions/banUserId";
import { getMemberLevel, waitForReaction } from "knub/dist/helpers";
import { getMemberLevel } from "knub/dist/helpers";
import humanizeDuration from "humanize-duration";
import { CasesPlugin } from "../../../plugins/Cases/CasesPlugin";
import { CaseTypes } from "../../../data/CaseTypes";
@ -49,7 +49,7 @@ export const BanCmd = modActionsCmd({
}
const time = args["time"] ? args["time"] : null;
const reason = formatReasonWithAttachments(args.reason, msg.attachments);
const reason = formatReasonWithAttachments(args.reason, msg.attachments.array());
const memberToBan = await resolveMember(pluginData.client, pluginData.guild, user.id);
// The moderator who did the action is the message author or, if used, the specified -mod
let mod = msg.member;
@ -76,11 +76,11 @@ export const BanCmd = modActionsCmd({
}
// Ask the mod if we should update the existing ban
const alreadyBannedMsg = await msg.channel.createMessage("User is already banned, update ban?");
const reply = await waitForReaction(pluginData.client, alreadyBannedMsg, ["✅", "❌"], msg.author.id);
const alreadyBannedMsg = await msg.channel.send("User is already banned, update ban?");
const reply = false; // await waitForReaction(pluginData.client, alreadyBannedMsg, ["✅", "❌"], msg.author.id); FIXME waiting on waitForButton
alreadyBannedMsg.delete().catch(noop);
if (!reply || reply.name === "❌") {
if (!reply /* || reply.name === "❌"*/) {
sendErrorMessage(pluginData, msg.channel, "User already banned, update cancelled by moderator");
lock.unlock();
return;
@ -124,11 +124,11 @@ export const BanCmd = modActionsCmd({
}
} else {
// Ask the mod if we should upgrade to a forceban as the user is not on the server
const notOnServerMsg = await msg.channel.createMessage("User not found on the server, forceban instead?");
const reply = await waitForReaction(pluginData.client, notOnServerMsg, ["✅", "❌"], msg.author.id);
const notOnServerMsg = await msg.channel.send("User not found on the server, forceban instead?");
const reply = false; // await waitForReaction(pluginData.client, notOnServerMsg, ["✅", "❌"], msg.author.id); Waiting for waitForButton
notOnServerMsg.delete().catch(noop);
if (!reply || reply.name === "❌") {
if (!reply /*|| reply.name === "❌"*/) {
sendErrorMessage(pluginData, msg.channel, "User not on server, ban cancelled by moderator");
lock.unlock();
return;

View file

@ -24,6 +24,6 @@ export const CaseCmd = modActionsCmd({
const casesPlugin = pluginData.getPlugin(CasesPlugin);
const embed = await casesPlugin.getCaseEmbed(theCase.id, msg.author.id);
msg.channel.createMessage(embed);
msg.channel.send(embed);
},
});

View file

@ -9,6 +9,7 @@ import { getChunkedEmbedFields } from "../../../utils/getChunkedEmbedFields";
import { getDefaultPrefix } from "knub/dist/commands/commandUtils";
import { getGuildPrefix } from "../../../utils/getGuildPrefix";
import { createPaginatedMessage } from "../../../utils/createPaginatedMessage";
import { MessageEmbedOptions, User } from "discord.js";
const opts = {
mod: ct.userId({ option: true }),
@ -55,10 +56,10 @@ export const CasesModCmd = modActionsCmd({
const lastCaseNum = page * casesPerPage;
const title = `Most recent cases ${firstCaseNum}-${lastCaseNum} of ${totalCases} by ${modName}`;
const embed: EmbedOptions = {
const embed: MessageEmbedOptions = {
author: {
name: title,
icon_url: mod instanceof User ? mod.avatarURL || mod.defaultAvatarURL : undefined,
iconURL: mod instanceof User ? mod.avatarURL() || mod.defaultAvatarURL : undefined,
},
fields: [
...getChunkedEmbedFields(emptyEmbedValue, lines.join("\n")),

View file

@ -16,6 +16,7 @@ import { getGuildPrefix } from "../../../utils/getGuildPrefix";
import { getChunkedEmbedFields } from "../../../utils/getChunkedEmbedFields";
import { asyncMap } from "../../../utils/async";
import { CaseTypes } from "../../../data/CaseTypes";
import { MessageEmbedOptions, User } from "discord.js";
const opts = {
expand: ct.bool({ option: true, isSwitch: true, shortcut: "e" }),
@ -75,13 +76,13 @@ export const CasesUserCmd = modActionsCmd({
: `${user.username}#${user.discriminator}`;
if (cases.length === 0) {
msg.channel.createMessage(`No cases found for **${userName}**`);
msg.channel.send(`No cases found for **${userName}**`);
} else {
const casesToDisplay = args.hidden ? cases : normalCases;
if (args.expand) {
if (casesToDisplay.length > 8) {
msg.channel.createMessage("Too many cases for expanded view. Please use compact view instead.");
msg.channel.send("Too many cases for expanded view. Please use compact view instead.");
return;
}
@ -89,7 +90,7 @@ export const CasesUserCmd = modActionsCmd({
const casesPlugin = pluginData.getPlugin(CasesPlugin);
for (const theCase of casesToDisplay) {
const embed = await casesPlugin.getCaseEmbed(theCase.id);
msg.channel.createMessage(embed);
msg.channel.send(embed);
}
} else {
// Compact view (= regular message with a preview of each case)
@ -121,13 +122,13 @@ export const CasesUserCmd = modActionsCmd({
const chunkStart = i * linesPerChunk + 1;
const chunkEnd = Math.min((i + 1) * linesPerChunk, lines.length);
const embed: EmbedOptions = {
const embed: MessageEmbedOptions = {
author: {
name:
lineChunks.length === 1
? `Cases for ${userName} (${lines.length} total)`
: `Cases ${chunkStart}${chunkEnd} of ${lines.length} for ${userName}`,
icon_url: user instanceof User ? user.avatarURL || user.defaultAvatarURL : undefined,
icon_url: user instanceof User ? user.avatarURL() || user.defaultAvatarURL : undefined,
},
fields: [
...getChunkedEmbedFields(emptyEmbedValue, linesInChunk.join("\n")),
@ -135,7 +136,7 @@ export const CasesUserCmd = modActionsCmd({
],
};
msg.channel.createMessage({ embed });
msg.channel.send({ embed });
}
}
}

View file

@ -10,6 +10,7 @@ import { LogType } from "../../../data/LogType";
import moment from "moment-timezone";
import { TimeAndDatePlugin } from "../../TimeAndDate/TimeAndDatePlugin";
import { Case } from "../../../data/entities/Case";
import { TextChannel } from "discord.js";
export const DeleteCaseCmd = modActionsCmd({
trigger: ["delete_case", "deletecase"],
@ -49,7 +50,7 @@ export const DeleteCaseCmd = modActionsCmd({
if (!args.force) {
const cases = pluginData.getPlugin(CasesPlugin);
const embedContent = await cases.getCaseEmbed(theCase);
message.channel.createMessage({
message.channel.send({
content: "Delete the following case? Answer 'Yes' to continue, 'No' to cancel.",
embed: embedContent.embed,
});
@ -62,7 +63,7 @@ export const DeleteCaseCmd = modActionsCmd({
);
const normalizedReply = (reply?.content || "").toLowerCase().trim();
if (normalizedReply !== "yes" && normalizedReply !== "y") {
message.channel.createMessage("Cancelled. Case was not deleted.");
message.channel.send("Cancelled. Case was not deleted.");
cancelled++;
continue;
}

View file

@ -61,14 +61,17 @@ export const ForcebanCmd = modActionsCmd({
mod = args.mod;
}
const reason = formatReasonWithAttachments(args.reason, msg.attachments);
const reason = formatReasonWithAttachments(args.reason, msg.attachments.array());
ignoreEvent(pluginData, IgnoredEventType.Ban, user.id);
pluginData.state.serverLogs.ignoreLog(LogType.MEMBER_BAN, user.id);
try {
// FIXME: Use banUserId()?
await pluginData.guild.banMember(user.id, 1, reason != null ? encodeURIComponent(reason) : undefined);
await pluginData.guild.bans.create(user.id, {
days: 1,
reason: reason != null ? encodeURIComponent(reason) : undefined,
});
} catch {
sendErrorMessage(pluginData, msg.channel, "Failed to forceban member");
return;

View file

@ -15,6 +15,7 @@ import { LogType } from "../../../data/LogType";
import { performance } from "perf_hooks";
import { humanizeDurationShort } from "../../../humanizeDurationShort";
import { load } from "js-yaml";
import { TextChannel } from "discord.js";
export const MassbanCmd = modActionsCmd({
trigger: "massban",
@ -35,14 +36,14 @@ export const MassbanCmd = modActionsCmd({
}
// Ask for ban reason (cleaner this way instead of trying to cram it into the args)
msg.channel.createMessage("Ban reason? `cancel` to cancel");
msg.channel.send("Ban reason? `cancel` to cancel");
const banReasonReply = await waitForReply(pluginData.client, msg.channel as TextChannel, msg.author.id);
if (!banReasonReply || !banReasonReply.content || banReasonReply.content.toLowerCase().trim() === "cancel") {
sendErrorMessage(pluginData, msg.channel, "Cancelled");
return;
}
const banReason = formatReasonWithAttachments(banReasonReply.content, msg.attachments);
const banReason = formatReasonWithAttachments(banReasonReply.content, msg.attachments.array());
// Verify we can act on each of the users specified
for (const userId of args.userIds) {
@ -60,7 +61,7 @@ export const MassbanCmd = modActionsCmd({
pluginData.state.massbanQueue.length === 0
? "Banning..."
: `Massban queued. Waiting for previous massban to finish (max wait ${maxWaitTimeFormatted}).`;
const loadingMsg = await msg.channel.createMessage(initialLoadingText);
const loadingMsg = await msg.channel.send(initialLoadingText);
const waitTimeStart = performance.now();
const waitingInterval = setInterval(() => {
@ -95,7 +96,10 @@ export const MassbanCmd = modActionsCmd({
ignoreEvent(pluginData, IgnoredEventType.Ban, userId, 120 * 1000);
pluginData.state.serverLogs.ignoreLog(LogType.MEMBER_BAN, userId, 120 * 1000);
await pluginData.guild.banMember(userId, 1, banReason != null ? encodeURIComponent(banReason) : undefined);
await pluginData.guild.bans.create(userId, {
days: 1,
reason: banReason != null ? encodeURIComponent(banReason) : undefined,
});
await casesPlugin.createCase({
userId,

View file

@ -10,6 +10,7 @@ import { waitForReply } from "knub/dist/helpers";
import { ignoreEvent } from "../functions/ignoreEvent";
import { CasesPlugin } from "../../Cases/CasesPlugin";
import { LogType } from "../../../data/LogType";
import { TextChannel } from "discord.js";
export const MassunbanCmd = modActionsCmd({
trigger: "massunban",
@ -30,14 +31,14 @@ export const MassunbanCmd = modActionsCmd({
}
// Ask for unban reason (cleaner this way instead of trying to cram it into the args)
msg.channel.createMessage("Unban reason? `cancel` to cancel");
msg.channel.send("Unban reason? `cancel` to cancel");
const unbanReasonReply = await waitForReply(pluginData.client, msg.channel as TextChannel, msg.author.id);
if (!unbanReasonReply || !unbanReasonReply.content || unbanReasonReply.content.toLowerCase().trim() === "cancel") {
sendErrorMessage(pluginData, msg.channel, "Cancelled");
return;
}
const unbanReason = formatReasonWithAttachments(unbanReasonReply.content, msg.attachments);
const unbanReason = formatReasonWithAttachments(unbanReasonReply.content, msg.attachments.array());
// Ignore automatic unban cases and logs for these users
// We'll create our own cases below and post a single "mass unbanned" log instead
@ -48,7 +49,7 @@ export const MassunbanCmd = modActionsCmd({
});
// Show a loading indicator since this can take a while
const loadingMsg = await msg.channel.createMessage("Unbanning...");
const loadingMsg = await msg.channel.send("Unbanning...");
// Unban each user and count failed unbans (if any)
const failedUnbans: Array<{ userId: string; reason: UnbanFailReasons }> = [];
@ -60,7 +61,7 @@ export const MassunbanCmd = modActionsCmd({
}
try {
await pluginData.guild.unbanMember(userId, unbanReason != null ? encodeURIComponent(unbanReason) : undefined);
await pluginData.guild.bans.remove(userId, unbanReason != null ? encodeURIComponent(unbanReason) : undefined);
await casesPlugin.createCase({
userId,

View file

@ -8,6 +8,7 @@ import { waitForReply } from "knub/dist/helpers";
import { LogType } from "../../../data/LogType";
import { logger } from "../../../logger";
import { MutesPlugin } from "../../../plugins/Mutes/MutesPlugin";
import { TextChannel } from "discord.js";
export const MassmuteCmd = modActionsCmd({
trigger: "massmute",
@ -28,7 +29,7 @@ export const MassmuteCmd = modActionsCmd({
}
// Ask for mute reason
msg.channel.createMessage("Mute reason? `cancel` to cancel");
msg.channel.send("Mute reason? `cancel` to cancel");
const muteReasonReceived = await waitForReply(pluginData.client, msg.channel as TextChannel, msg.author.id);
if (
!muteReasonReceived ||
@ -39,7 +40,7 @@ export const MassmuteCmd = modActionsCmd({
return;
}
const muteReason = formatReasonWithAttachments(muteReasonReceived.content, msg.attachments);
const muteReason = formatReasonWithAttachments(muteReasonReceived.content, msg.attachments.array());
// Verify we can act upon all users
for (const userId of args.userIds) {
@ -58,7 +59,7 @@ export const MassmuteCmd = modActionsCmd({
});
// Show loading indicator
const loadingMsg = await msg.channel.createMessage("Muting...");
const loadingMsg = await msg.channel.send("Muting...");
// Mute everyone and count fails
const modId = msg.author.id;

View file

@ -1,16 +1,8 @@
import { modActionsCmd } from "../types";
import { commandTypeHelpers as ct } from "../../../commandTypes";
import { Case } from "../../../data/entities/Case";
import { canActOn, hasPermission, sendErrorMessage, sendSuccessMessage } from "../../../pluginUtils";
import { formatReasonWithAttachments } from "../functions/formatReasonWithAttachments";
import { CasesPlugin } from "../../Cases/CasesPlugin";
import { LogType } from "../../../data/LogType";
import { CaseTypes } from "../../../data/CaseTypes";
import { errorMessage, noop, resolveMember, resolveUser, stripObjectToScalars } from "../../../utils";
import { canActOn, sendErrorMessage } from "../../../pluginUtils";
import { noop, resolveMember, resolveUser } from "../../../utils";
import { isBanned } from "../functions/isBanned";
import { waitForReaction } from "knub/dist/helpers";
import { readContactMethodsFromArgs } from "../functions/readContactMethodsFromArgs";
import { warnMember } from "../functions/warnMember";
import { actualMuteUserCmd } from "../functions/actualMuteUserCmd";
@ -62,11 +54,11 @@ export const MuteCmd = modActionsCmd({
return;
} else {
// Ask the mod if we should upgrade to a forcemute as the user is not on the server
const notOnServerMsg = await msg.channel.createMessage("User not found on the server, forcemute instead?");
const reply = await waitForReaction(pluginData.client, notOnServerMsg, ["✅", "❌"], msg.author.id);
const notOnServerMsg = await msg.channel.send("User not found on the server, forcemute instead?");
const reply = false; // await waitForReaction(pluginData.client, notOnServerMsg, ["✅", "❌"], msg.author.id); FIXME waiting on waitForButton
notOnServerMsg.delete().catch(noop);
if (!reply || reply.name === "❌") {
if (!reply /*|| reply.name === "❌"*/) {
sendErrorMessage(pluginData, msg.channel, "User not on server, mute cancelled by moderator");
return;
}

View file

@ -25,13 +25,13 @@ export const NoteCmd = modActionsCmd({
return;
}
if (!args.note && msg.attachments.length === 0) {
if (!args.note && msg.attachments.size === 0) {
sendErrorMessage(pluginData, msg.channel, "Text or attachment required");
return;
}
const userName = `${user.username}#${user.discriminator}`;
const reason = formatReasonWithAttachments(args.note, msg.attachments);
const reason = formatReasonWithAttachments(args.note, msg.attachments.array());
const casesPlugin = pluginData.getPlugin(CasesPlugin);
const createdCase = await casesPlugin.createCase({

View file

@ -28,7 +28,7 @@ export const SoftbanCmd = modActionsCmd({
async run({ pluginData, message: msg, args }) {
await actualKickMemberCmd(pluginData, msg, { clean: true, ...args });
await msg.channel.createMessage(
await msg.channel.send(
"Softban will be removed in the future - please use the kick command with the `-clean` argument instead!",
);
},

View file

@ -45,11 +45,11 @@ export const UnbanCmd = modActionsCmd({
}
pluginData.state.serverLogs.ignoreLog(LogType.MEMBER_UNBAN, user.id);
const reason = formatReasonWithAttachments(args.reason, msg.attachments);
const reason = formatReasonWithAttachments(args.reason, msg.attachments.array());
try {
ignoreEvent(pluginData, IgnoredEventType.Unban, user.id);
await pluginData.guild.unbanMember(user.id, reason != null ? encodeURIComponent(reason) : undefined);
await pluginData.guild.bans.remove(user.id, reason != null ? encodeURIComponent(reason) : undefined);
} catch {
sendErrorMessage(pluginData, msg.channel, "Failed to unban member; are you sure they're banned?");
return;

View file

@ -5,7 +5,6 @@ import { resolveUser, resolveMember, noop } from "../../../utils";
import { MutesPlugin } from "../../../plugins/Mutes/MutesPlugin";
import { actualUnmuteCmd } from "../functions/actualUnmuteUserCmd";
import { isBanned } from "../functions/isBanned";
import { waitForReaction } from "knub/dist/helpers";
const opts = {
mod: ct.member({ option: true }),
@ -61,11 +60,11 @@ export const UnmuteCmd = modActionsCmd({
return;
} else {
// Ask the mod if we should upgrade to a forceunmute as the user is not on the server
const notOnServerMsg = await msg.channel.createMessage("User not found on the server, forceunmute instead?");
const reply = await waitForReaction(pluginData.client, notOnServerMsg, ["✅", "❌"], msg.author.id);
const notOnServerMsg = await msg.channel.send("User not found on the server, forceunmute instead?");
const reply = false; //await waitForReaction(pluginData.client, notOnServerMsg, ["✅", "❌"], msg.author.id); FIXME waiting on waitForButton
notOnServerMsg.delete().catch(noop);
if (!reply || reply.name === "❌") {
if (!reply /*|| reply.name === "❌"*/) {
sendErrorMessage(pluginData, msg.channel, "User not on server, unmute cancelled by moderator");
return;
}

View file

@ -8,9 +8,9 @@ import { LogType } from "../../../data/LogType";
import { CaseTypes } from "../../../data/CaseTypes";
import { errorMessage, resolveMember, resolveUser, stripObjectToScalars } from "../../../utils";
import { isBanned } from "../functions/isBanned";
import { waitForReaction } from "knub/dist/helpers";
import { readContactMethodsFromArgs } from "../functions/readContactMethodsFromArgs";
import { warnMember } from "../functions/warnMember";
import { TextChannel } from "discord.js";
export const WarnCmd = modActionsCmd({
trigger: "warn",
@ -56,7 +56,7 @@ export const WarnCmd = modActionsCmd({
let mod = msg.member;
if (args.mod) {
if (!(await hasPermission(pluginData, "can_act_as_other", { message: msg }))) {
msg.channel.createMessage(errorMessage("You don't have permission to use -mod"));
msg.channel.send(errorMessage("You don't have permission to use -mod"));
return;
}
@ -64,19 +64,19 @@ export const WarnCmd = modActionsCmd({
}
const config = pluginData.config.get();
const reason = formatReasonWithAttachments(args.reason, msg.attachments);
const reason = formatReasonWithAttachments(args.reason, msg.attachments.array());
const casesPlugin = pluginData.getPlugin(CasesPlugin);
const priorWarnAmount = await casesPlugin.getCaseTypeAmountForUserId(memberToWarn.id, CaseTypes.Warn);
if (config.warn_notify_enabled && priorWarnAmount >= config.warn_notify_threshold) {
const tooManyWarningsMsg = await msg.channel.createMessage(
const tooManyWarningsMsg = await msg.channel.send(
config.warn_notify_message.replace("{priorWarnings}", `${priorWarnAmount}`),
);
const reply = await waitForReaction(pluginData.client, tooManyWarningsMsg, ["✅", "❌"], msg.author.id);
const reply = false; //await waitForReaction(pluginData.client, tooManyWarningsMsg, ["✅", "❌"], msg.author.id); FIXME waiting on waitForButton
tooManyWarningsMsg.delete();
if (!reply || reply.name === "❌") {
msg.channel.createMessage(errorMessage("Warn cancelled by moderator"));
if (!reply /*|| reply.name === "❌"*/) {
msg.channel.send(errorMessage("Warn cancelled by moderator"));
return;
}
}

View file

@ -8,6 +8,7 @@ import { safeFindRelevantAuditLogEntry } from "../../../utils/safeFindRelevantAu
import { LogType } from "../../../data/LogType";
import { stripObjectToScalars, resolveUser, UnknownUser } from "../../../utils";
import { Case } from "../../../data/entities/Case";
import { GuildAuditLogs, User } from "discord.js";
/**
* Create a BAN case automatically when a user is banned manually.
@ -15,7 +16,8 @@ import { Case } from "../../../data/entities/Case";
*/
export const CreateBanCaseOnManualBanEvt = modActionsEvt({
event: "guildBanAdd",
async listener({ pluginData, args: { guild, user } }) {
async listener({ pluginData, args: { ban } }) {
const user = ban.user;
if (isEventIgnored(pluginData, IgnoredEventType.Ban, user.id)) {
clearIgnoredEvents(pluginData, IgnoredEventType.Ban, user.id);
return;
@ -23,7 +25,7 @@ export const CreateBanCaseOnManualBanEvt = modActionsEvt({
const relevantAuditLogEntry = await safeFindRelevantAuditLogEntry(
pluginData,
ErisConstants.AuditLogActions.MEMBER_BAN_ADD,
GuildAuditLogs.Actions.MEMBER_BAN_ADD as number,
user.id,
);
@ -34,7 +36,7 @@ export const CreateBanCaseOnManualBanEvt = modActionsEvt({
let reason = "";
if (relevantAuditLogEntry) {
const modId = relevantAuditLogEntry.user.id;
const modId = relevantAuditLogEntry.executor!.id;
const auditLogId = relevantAuditLogEntry.id;
mod = await resolveUser(pluginData.client, modId);

View file

@ -9,6 +9,7 @@ import { LogType } from "../../../data/LogType";
import { resolveUser, stripObjectToScalars, UnknownUser } from "../../../utils";
import { safeFindRelevantAuditLogEntry } from "../../../utils/safeFindRelevantAuditLogEntry";
import { Case } from "../../../data/entities/Case";
import { GuildAuditLogs, User } from "discord.js";
/**
* Create a KICK case automatically when a user is kicked manually.
@ -24,7 +25,7 @@ export const CreateKickCaseOnManualKickEvt = modActionsEvt({
const kickAuditLogEntry = await safeFindRelevantAuditLogEntry(
pluginData,
ErisConstants.AuditLogActions.MEMBER_KICK,
GuildAuditLogs.Actions.MEMBER_KICK as number,
member.id,
);
@ -40,7 +41,7 @@ export const CreateKickCaseOnManualKickEvt = modActionsEvt({
`Tried to create duplicate case for audit log entry ${kickAuditLogEntry.id}, existing case id ${createdCase.id}`,
);
} else {
mod = await resolveUser(pluginData.client, kickAuditLogEntry.user.id);
mod = await resolveUser(pluginData.client, kickAuditLogEntry.executor!.id);
const config = mod instanceof UnknownUser ? pluginData.config.get() : await pluginData.config.getForUser(mod);
@ -48,7 +49,7 @@ export const CreateKickCaseOnManualKickEvt = modActionsEvt({
const casesPlugin = pluginData.getPlugin(CasesPlugin);
createdCase = await casesPlugin.createCase({
userId: member.id,
modId: kickAuditLogEntry.user.id,
modId: mod.id,
type: CaseTypes.Kick,
auditLogId: kickAuditLogEntry.id,
reason: kickAuditLogEntry.reason || undefined,

View file

@ -8,6 +8,7 @@ import { safeFindRelevantAuditLogEntry } from "../../../utils/safeFindRelevantAu
import { stripObjectToScalars, resolveUser, UnknownUser } from "../../../utils";
import { LogType } from "../../../data/LogType";
import { Case } from "../../../data/entities/Case";
import { GuildAuditLogs, User } from "discord.js";
/**
* Create an UNBAN case automatically when a user is unbanned manually.
@ -15,7 +16,8 @@ import { Case } from "../../../data/entities/Case";
*/
export const CreateUnbanCaseOnManualUnbanEvt = modActionsEvt({
event: "guildBanRemove",
async listener({ pluginData, args: { guild, user } }) {
async listener({ pluginData, args: { ban } }) {
const user = ban.user;
if (isEventIgnored(pluginData, IgnoredEventType.Unban, user.id)) {
clearIgnoredEvents(pluginData, IgnoredEventType.Unban, user.id);
return;
@ -23,7 +25,7 @@ export const CreateUnbanCaseOnManualUnbanEvt = modActionsEvt({
const relevantAuditLogEntry = await safeFindRelevantAuditLogEntry(
pluginData,
ErisConstants.AuditLogActions.MEMBER_BAN_REMOVE,
GuildAuditLogs.Actions.MEMBER_BAN_REMOVE as number,
user.id,
);
@ -33,7 +35,7 @@ export const CreateUnbanCaseOnManualUnbanEvt = modActionsEvt({
let mod: User | UnknownUser | null = null;
if (relevantAuditLogEntry) {
const modId = relevantAuditLogEntry.user.id;
const modId = relevantAuditLogEntry.executor!.id;
const auditLogId = relevantAuditLogEntry.id;
mod = await resolveUser(pluginData.client, modId);

View file

@ -4,13 +4,14 @@ import { LogType } from "../../../data/LogType";
import { resolveMember } from "../../../utils";
import { hasDiscordPermissions } from "../../../utils/hasDiscordPermissions";
import { TextChannel, Constants, Permissions } from "discord.js";
/**
* Show an alert if a member with prior notes joins the server
*/
export const PostAlertOnMemberJoinEvt = modActionsEvt({
event: "guildMemberAdd",
async listener({ pluginData, args: { guild, member } }) {
async listener({ pluginData, args: { member } }) {
const config = pluginData.config.get();
if (!config.alert_on_rejoin) return;
@ -38,15 +39,15 @@ export const PostAlertOnMemberJoinEvt = modActionsEvt({
}
const botMember = await resolveMember(pluginData.client, pluginData.guild, pluginData.client.user!.id);
const botPerms = alertChannel.permissionsOf(botMember ?? pluginData.client.user!.id);
if (!hasDiscordPermissions(botPerms, Constants.Permissions.sendMessages)) {
const botPerms = alertChannel.permissionsFor(botMember ?? pluginData.client.user!.id);
if (!hasDiscordPermissions(botPerms, Permissions.FLAGS.SEND_MESSAGES)) {
logs.log(LogType.BOT_ALERT, {
body: `Missing "Send Messages" permissions for the \`alert_channel\` configured in \`mod_actions\`: \`${alertChannelId}\``,
});
return;
}
await alertChannel.createMessage(
await alertChannel.send(
`<@!${member.id}> (${member.user.username}#${member.user.discriminator} \`${member.id}\`) joined with ${actions.length} prior record(s)`,
);
}

View file

@ -9,6 +9,7 @@ import { formatReasonWithAttachments } from "./formatReasonWithAttachments";
import { kickMember } from "./kickMember";
import { ignoreEvent } from "./ignoreEvent";
import { isBanned } from "./isBanned";
import { GuildMember, TextChannel } from "discord.js";
export async function actualKickMemberCmd(
pluginData: GuildPluginData<ModActionsPluginType>,
@ -16,7 +17,7 @@ export async function actualKickMemberCmd(
args: {
user: string;
reason: string;
mod: Member;
mod: GuildMember;
notify?: string;
"notify-channel"?: TextChannel;
clean?: boolean;
@ -81,7 +82,7 @@ export async function actualKickMemberCmd(
ignoreEvent(pluginData, IgnoredEventType.Ban, memberToKick.id);
try {
await memberToKick.ban(1, encodeURIComponent("kick -clean"));
await memberToKick.ban({ days: 1, reason: encodeURIComponent("kick -clean") });
} catch {
sendErrorMessage(pluginData, msg.channel, "Failed to ban the user to clean messages (-clean)");
}
@ -90,14 +91,14 @@ export async function actualKickMemberCmd(
ignoreEvent(pluginData, IgnoredEventType.Unban, memberToKick.id);
try {
await pluginData.guild.unbanMember(memberToKick.id, encodeURIComponent("kick -clean"));
await pluginData.guild.bans.remove(memberToKick.id, encodeURIComponent("kick -clean"));
} catch {
sendErrorMessage(pluginData, msg.channel, "Failed to unban the user after banning them (-clean)");
}
}
if (kickResult.status === "failed") {
msg.channel.createMessage(errorMessage(`Failed to kick user`));
msg.channel.send(errorMessage(`Failed to kick user`));
return;
}

View file

@ -9,6 +9,7 @@ import { MutesPlugin } from "../../Mutes/MutesPlugin";
import { readContactMethodsFromArgs } from "./readContactMethodsFromArgs";
import { ERRORS, RecoverablePluginError } from "../../../RecoverablePluginError";
import { logger } from "../../../logger";
import { User, Message, TextChannel, GuildMember } from "discord.js";
/**
* The actual function run by both !mute and !forcemute.
@ -17,16 +18,16 @@ import { logger } from "../../../logger";
export async function actualMuteUserCmd(
pluginData: GuildPluginData<ModActionsPluginType>,
user: User | UnknownUser,
msg: Message<GuildTextableChannel>,
args: { time?: number; reason?: string; mod: Member; notify?: string; "notify-channel"?: TextChannel },
msg: Message,
args: { time?: number; reason?: string; mod: GuildMember; notify?: string; "notify-channel"?: TextChannel },
) {
// The moderator who did the action is the message author or, if used, the specified -mod
let mod: Member = msg.member;
let mod: GuildMember = msg.member!;
let pp: User | null = null;
if (args.mod) {
if (!(await hasPermission(pluginData, "can_act_as_other", { message: msg }))) {
sendErrorMessage(pluginData, msg.channel, "You don't have permission to use -mod");
sendErrorMessage(pluginData, msg.channel as TextChannel, "You don't have permission to use -mod");
return;
}
@ -35,7 +36,7 @@ export async function actualMuteUserCmd(
}
const timeUntilUnmute = args.time && humanizeDuration(args.time);
const reason = args.reason ? formatReasonWithAttachments(args.reason, msg.attachments) : undefined;
const reason = args.reason ? formatReasonWithAttachments(args.reason, msg.attachments.array()) : undefined;
let muteResult: MuteResult;
const mutesPlugin = pluginData.getPlugin(MutesPlugin);
@ -44,7 +45,7 @@ export async function actualMuteUserCmd(
try {
contactMethods = readContactMethodsFromArgs(args);
} catch (e) {
sendErrorMessage(pluginData, msg.channel, e.message);
sendErrorMessage(pluginData, msg.channel as TextChannel, e.message);
return;
}
@ -58,16 +59,16 @@ export async function actualMuteUserCmd(
});
} catch (e) {
if (e instanceof RecoverablePluginError && e.code === ERRORS.NO_MUTE_ROLE_IN_CONFIG) {
sendErrorMessage(pluginData, msg.channel, "Could not mute the user: no mute role set in config");
sendErrorMessage(pluginData, msg.channel as TextChannel, "Could not mute the user: no mute role set in config");
} else if (isDiscordRESTError(e) && e.code === 10007) {
sendErrorMessage(pluginData, msg.channel, "Could not mute the user: unknown member");
sendErrorMessage(pluginData, msg.channel as TextChannel, "Could not mute the user: unknown member");
} else {
logger.error(`Failed to mute user ${user.id}: ${e.stack}`);
if (user.id == null) {
// tslint-disable-next-line:no-console
console.trace("[DEBUG] Null user.id for mute");
}
sendErrorMessage(pluginData, msg.channel, "Could not mute the user");
sendErrorMessage(pluginData, msg.channel as TextChannel, "Could not mute the user");
}
return;
@ -102,5 +103,5 @@ export async function actualMuteUserCmd(
}
if (muteResult.notifyResult.text) response += ` (${muteResult.notifyResult.text})`;
sendSuccessMessage(pluginData, msg.channel, response);
sendSuccessMessage(pluginData, msg.channel as TextChannel, response);
}

View file

@ -6,12 +6,13 @@ import { sendErrorMessage, sendSuccessMessage, hasPermission } from "../../../pl
import { formatReasonWithAttachments } from "./formatReasonWithAttachments";
import { MutesPlugin } from "../../../plugins/Mutes/MutesPlugin";
import humanizeDuration from "humanize-duration";
import { User, Message, GuildMember, TextChannel } from "discord.js";
export async function actualUnmuteCmd(
pluginData: GuildPluginData<ModActionsPluginType>,
user: User | UnknownUser,
msg: Message,
args: { time?: number; reason?: string; mod?: Member },
args: { time?: number; reason?: string; mod?: GuildMember },
) {
// The moderator who did the action is the message author or, if used, the specified -mod
let mod = msg.author;
@ -19,7 +20,7 @@ export async function actualUnmuteCmd(
if (args.mod) {
if (!(await hasPermission(pluginData, "can_act_as_other", { message: msg, channelId: msg.channel.id }))) {
sendErrorMessage(pluginData, msg.channel, "You don't have permission to use -mod");
sendErrorMessage(pluginData, msg.channel as TextChannel, "You don't have permission to use -mod");
return;
}
@ -27,7 +28,7 @@ export async function actualUnmuteCmd(
pp = msg.author;
}
const reason = args.reason ? formatReasonWithAttachments(args.reason, msg.attachments) : undefined;
const reason = args.reason ? formatReasonWithAttachments(args.reason, msg.attachments.array()) : undefined;
const mutesPlugin = pluginData.getPlugin(MutesPlugin);
const result = await mutesPlugin.unmuteUser(user.id, args.time, {
@ -37,7 +38,7 @@ export async function actualUnmuteCmd(
});
if (!result) {
sendErrorMessage(pluginData, msg.channel, "User is not muted!");
sendErrorMessage(pluginData, msg.channel as TextChannel, "User is not muted!");
return;
}
@ -46,7 +47,7 @@ export async function actualUnmuteCmd(
const timeUntilUnmute = args.time && humanizeDuration(args.time);
sendSuccessMessage(
pluginData,
msg.channel,
msg.channel as TextChannel,
asSingleLine(`
Unmuting **${user.username}#${user.discriminator}**
in ${timeUntilUnmute} (Case #${result.case.case_number})
@ -55,7 +56,7 @@ export async function actualUnmuteCmd(
} else {
sendSuccessMessage(
pluginData,
msg.channel,
msg.channel as TextChannel,
asSingleLine(`
Unmuted **${user.username}#${user.discriminator}**
(Case #${result.case.case_number})

View file

@ -17,6 +17,7 @@ import { CasesPlugin } from "../../Cases/CasesPlugin";
import { CaseTypes } from "../../../data/CaseTypes";
import { logger } from "../../../logger";
import humanizeDuration from "humanize-duration";
import { DiscordAPIError, User } from "discord.js";
/**
* Ban the specified user id, whether or not they're actually on the server at the time. Generates a case.
@ -77,14 +78,13 @@ export async function banUserId(
ignoreEvent(pluginData, IgnoredEventType.Ban, userId);
try {
const deleteMessageDays = Math.min(30, Math.max(0, banOptions.deleteMessageDays ?? 1));
await pluginData.guild.banMember(
userId,
deleteMessageDays,
reason != null ? encodeURIComponent(reason) : undefined,
);
await pluginData.guild.bans.create(userId, {
days: deleteMessageDays,
reason: reason != null ? encodeURIComponent(reason) : undefined,
});
} catch (e) {
let errorMessage;
if (e instanceof DiscordRESTError) {
if (e instanceof DiscordAPIError) {
errorMessage = `API error ${e.code}: ${e.message}`;
} else {
logger.warn(`Error applying ban to ${userId}: ${e}`);

View file

@ -1,4 +1,6 @@
export function formatReasonWithAttachments(reason: string, attachments: Attachment[]) {
import { MessageAttachment } from "discord.js";
export function formatReasonWithAttachments(reason: string, attachments: MessageAttachment[]) {
const attachmentUrls = attachments.map(a => a.url);
return ((reason || "") + " " + attachmentUrls.join(" ")).trim();
}

View file

@ -1,6 +1,7 @@
import { GuildPluginData } from "knub";
import { ModActionsPluginType } from "../types";
import { UserNotificationMethod } from "../../../utils";
import { TextChannel } from "discord.js";
export function getDefaultContactMethods(
pluginData: GuildPluginData<ModActionsPluginType>,

View file

@ -4,6 +4,7 @@ import { isDiscordHTTPError, isDiscordRESTError, SECONDS, sleep } from "../../..
import { LogsPlugin } from "../../Logs/LogsPlugin";
import { LogType } from "../../../data/LogType";
import { hasDiscordPermissions } from "../../../utils/hasDiscordPermissions";
import { Permissions } from "discord.js";
export async function isBanned(
pluginData: GuildPluginData<ModActionsPluginType>,
@ -11,7 +12,7 @@ export async function isBanned(
timeout: number = 5 * SECONDS,
): Promise<boolean> {
const botMember = pluginData.guild.members.cache.get(pluginData.client.user!.id);
if (botMember && !hasDiscordPermissions(botMember.permissions, Constants.Permissions.banMembers)) {
if (botMember && !hasDiscordPermissions(botMember.permissions, Permissions.FLAGS.BAN_MEMBERS)) {
pluginData.getPlugin(LogsPlugin).log(LogType.BOT_ALERT, {
body: `Missing "Ban Members" permission to check for existing bans`,
});
@ -19,7 +20,7 @@ export async function isBanned(
}
try {
const potentialBan = await Promise.race([pluginData.guild.getBan(userId), sleep(timeout)]);
const potentialBan = await Promise.race([pluginData.guild.bans.fetch({ user: userId }), sleep(timeout)]);
return potentialBan != null;
} catch (e) {
if (isDiscordRESTError(e) && e.code === 10026) {

View file

@ -15,13 +15,14 @@ import { LogType } from "../../../data/LogType";
import { ignoreEvent } from "./ignoreEvent";
import { CaseTypes } from "../../../data/CaseTypes";
import { CasesPlugin } from "../../Cases/CasesPlugin";
import { GuildMember } from "discord.js";
/**
* Kick the specified server member. Generates a case.
*/
export async function kickMember(
pluginData: GuildPluginData<ModActionsPluginType>,
member: Member,
member: GuildMember,
reason?: string,
kickOptions: KickOptions = {},
): Promise<KickResult> {

View file

@ -30,7 +30,7 @@ export async function outdatedTempbansLoop(pluginData: GuildPluginData<ModAction
);
try {
ignoreEvent(pluginData, IgnoredEventType.Unban, tempban.user_id);
await pluginData.guild.unbanMember(tempban.user_id, reason != null ? encodeURIComponent(reason) : undefined);
await pluginData.guild.bans.remove(tempban.user_id, reason != null ? encodeURIComponent(reason) : undefined);
} catch (e) {
pluginData.state.serverLogs.log(LogType.BOT_ALERT, {
body: `Encountered an error trying to automatically unban ${tempban.user_id} after tempban timeout`,

View file

@ -1,3 +1,4 @@
import { TextChannel } from "discord.js";
import { disableUserNotificationStrings, UserNotificationMethod } from "../../../utils";
export function readContactMethodsFromArgs(args: {

View file

@ -1,3 +1,4 @@
import { Message, TextChannel } from "discord.js";
import { CaseTypes } from "../../../data/CaseTypes";
import { Case } from "../../../data/entities/Case";
import { LogType } from "../../../data/LogType";
@ -14,16 +15,16 @@ export async function updateCase(pluginData, msg: Message, args) {
}
if (!theCase) {
sendErrorMessage(pluginData, msg.channel, "Case not found");
sendErrorMessage(pluginData, msg.channel as TextChannel, "Case not found");
return;
}
if (!args.note && msg.attachments.length === 0) {
sendErrorMessage(pluginData, msg.channel, "Text or attachment required");
if (!args.note && msg.attachments.size === 0) {
sendErrorMessage(pluginData, msg.channel as TextChannel, "Text or attachment required");
return;
}
const note = formatReasonWithAttachments(args.note, msg.attachments);
const note = formatReasonWithAttachments(args.note, msg.attachments.array());
const casesPlugin = pluginData.getPlugin(CasesPlugin);
await casesPlugin.createCaseNote({
@ -39,5 +40,5 @@ export async function updateCase(pluginData, msg: Message, args) {
note,
});
sendSuccessMessage(pluginData, msg.channel, `Case \`#${theCase.case_number}\` updated`);
sendSuccessMessage(pluginData, msg.channel as TextChannel, `Case \`#${theCase.case_number}\` updated`);
}

View file

@ -10,15 +10,15 @@ import {
ucfirst,
UserNotificationResult,
} from "../../../utils";
import { waitForReaction } from "knub/dist/helpers";
import { CasesPlugin } from "../../Cases/CasesPlugin";
import { CaseTypes } from "../../../data/CaseTypes";
import { LogType } from "../../../data/LogType";
import { renderTemplate } from "../../../templateFormatter";
import { GuildMember } from "discord.js";
export async function warnMember(
pluginData: GuildPluginData<ModActionsPluginType>,
member: Member,
member: GuildMember,
reason: string,
warnOptions: WarnOptions = {},
): Promise<WarnResult> {
@ -42,13 +42,13 @@ export async function warnMember(
}
if (!notifyResult.success) {
if (warnOptions.retryPromptChannel && pluginData.guild.channels.has(warnOptions.retryPromptChannel.id)) {
const failedMsg = await warnOptions.retryPromptChannel.createMessage(
if (warnOptions.retryPromptChannel && pluginData.guild.channels.resolve(warnOptions.retryPromptChannel.id)) {
const failedMsg = await warnOptions.retryPromptChannel.send(
"Failed to message the user. Log the warning anyway?",
);
const reply = await waitForReaction(pluginData.client, failedMsg, ["✅", "❌"]);
const reply = false; //await waitForReaction(pluginData.client, failedMsg, ["✅", "❌"]); FIXME waiting on waitForButton
failedMsg.delete();
if (!reply || reply.name === "❌") {
if (!reply /*|| reply.name === "❌"*/) {
return {
status: "failed",
error: "Failed to message user",

View file

@ -11,6 +11,7 @@ import { GuildTempbans } from "../../data/GuildTempbans";
import Timeout = NodeJS.Timeout;
import { EventEmitter } from "events";
import { Queue } from "../../Queue";
import { TextChannel } from "discord.js";
export const ConfigSchema = t.type({
dm_on_warn: t.boolean,

View file

@ -20,6 +20,7 @@ import { mapToPublicFn } from "../../pluginUtils";
import { EventEmitter } from "events";
import { onMutesEvent } from "./functions/onMutesEvent";
import { offMutesEvent } from "./functions/offMutesEvent";
import { GuildMember } from "discord.js";
const defaultOptions = {
config: {
@ -92,9 +93,9 @@ export const MutesPlugin = zeppelinGuildPlugin<MutesPluginType>()({
muteUser: mapToPublicFn(muteUser),
unmuteUser: mapToPublicFn(unmuteUser),
hasMutedRole(pluginData) {
return (member: Member) => {
return (member: GuildMember) => {
const muteRole = pluginData.config.get().mute_role;
return muteRole ? member.roles.includes(muteRole) : false;
return muteRole ? member.roles.cache.has(muteRole) : false;
};
},

View file

@ -1,6 +1,7 @@
import { mutesCmd } from "../types";
import { sendSuccessMessage } from "../../../pluginUtils";
import { User } from "discord.js";
export const ClearBannedMutesCmd = mutesCmd({
trigger: "clear_banned_mutes",
@ -8,17 +9,14 @@ export const ClearBannedMutesCmd = mutesCmd({
description: "Clear dangling mutes for members who have been banned",
async run({ pluginData, message: msg }) {
await msg.channel.createMessage("Clearing mutes from banned users...");
await msg.channel.send("Clearing mutes from banned users...");
const activeMutes = await pluginData.state.mutes.getActiveMutes();
// Mismatch in Eris docs and actual result here, based on Eris's code comments anyway
const bans: Array<{ reason: string; user: User }> = (await pluginData.guild.getBans()) as any;
const bans: Array<{ reason: string; user: User }> = (await pluginData.guild.bans.fetch({ cache: true })) as any;
const bannedIds = bans.map(b => b.user.id);
await msg.channel.createMessage(
`Found ${activeMutes.length} mutes and ${bannedIds.length} bans, cross-referencing...`,
);
await msg.channel.send(`Found ${activeMutes.length} mutes and ${bannedIds.length} bans, cross-referencing...`);
let cleared = 0;
for (const mute of activeMutes) {

View file

@ -12,14 +12,14 @@ export const ClearMutesWithoutRoleCmd = mutesCmd({
const muteRole = pluginData.config.get().mute_role;
if (!muteRole) return;
await msg.channel.createMessage("Clearing mutes from members that don't have the mute role...");
await msg.channel.send("Clearing mutes from members that don't have the mute role...");
let cleared = 0;
for (const mute of activeMutes) {
const member = await resolveMember(pluginData.client, pluginData.guild, mute.user_id);
if (!member) continue;
if (!member.roles.includes(muteRole)) {
if (!member.roles.cache.has(muteRole)) {
await pluginData.state.mutes.clear(mute.user_id);
cleared++;
}

View file

@ -4,6 +4,7 @@ import { DBDateFormat, isFullMessage, MINUTES, noop, resolveMember } from "../..
import moment from "moment-timezone";
import { humanizeDurationShort } from "../../../humanizeDurationShort";
import { getBaseUrl } from "../../../pluginUtils";
import { GuildMember } from "discord.js";
export const MutesCmd = mutesCmd({
trigger: "mutes",
@ -21,7 +22,7 @@ export const MutesCmd = mutesCmd({
},
async run({ pluginData, message: msg, args }) {
const listMessagePromise = msg.channel.createMessage("Loading mutes...");
const listMessagePromise = msg.channel.send("Loading mutes...");
const mutesPerPage = 10;
let totalMutes = 0;
let hasFilters = false;
@ -47,13 +48,13 @@ export const MutesCmd = mutesCmd({
if (args.manual) {
// Show only manual mutes (i.e. "Muted" role added without a logged mute)
const muteUserIds = new Set(activeMutes.map(m => m.user_id));
const manuallyMutedMembers: Member[] = [];
const manuallyMutedMembers: GuildMember[] = [];
const muteRole = pluginData.config.get().mute_role;
if (muteRole) {
pluginData.guild.members.forEach(member => {
pluginData.guild.members.cache.forEach(member => {
if (muteUserIds.has(member.id)) return;
if (member.roles.includes(muteRole)) manuallyMutedMembers.push(member);
if (member.roles.cache.has(muteRole)) manuallyMutedMembers.push(member);
});
}
@ -85,7 +86,7 @@ export const MutesCmd = mutesCmd({
if (!member) {
if (!bannedIds) {
const bans = await pluginData.guild.getBans();
const bans = await pluginData.guild.bans.fetch({ cache: true });
bannedIds = bans.map(u => u.user.id);
}
@ -111,7 +112,7 @@ export const MutesCmd = mutesCmd({
const muteCasesById = muteCases.reduce((map, c) => map.set(c.id, c), new Map());
lines = filteredMutes.map(mute => {
const user = pluginData.client.user!.get(mute.user_id);
const user = pluginData.client.users.resolve(mute.user_id);
const username = user ? `${user.username}#${user.discriminator}` : "Unknown#0000";
const theCase = muteCasesById.get(mute.case_id);
const caseName = theCase ? `Case #${theCase.case_number}` : "No case";
@ -194,29 +195,31 @@ export const MutesCmd = mutesCmd({
if (totalPages > 1) {
hasReactions = true;
listMessage.addReaction("⬅");
listMessage.addReaction("➡");
listMessage.react("⬅");
listMessage.react("➡");
const paginationReactionListener = pluginData.events.on(
"messageReactionAdd",
({ args: { message: rMsg, emoji, member } }) => {
async ({ args: { reaction, user } }) => {
const rMsg = reaction.message;
const member = await pluginData.guild.members.fetch(user.id);
if (!isFullMessage(rMsg)) return;
if (rMsg.id !== listMessage.id) return;
if (member.id !== msg.author.id) return;
if (!["⬅", "➡"].includes(emoji.name)) return;
if (!["⬅", "➡"].includes(reaction.emoji.name!)) return;
if (emoji.name === "⬅" && currentPage > 1) {
if (reaction.emoji.name === "⬅" && currentPage > 1) {
drawListPage(currentPage - 1);
} else if (emoji.name === "➡" && currentPage < totalPages) {
} else if (reaction.emoji.name === "➡" && currentPage < totalPages) {
drawListPage(currentPage + 1);
}
rMsg.removeReaction(emoji.name, member.id).catch(noop);
reaction.remove().catch(noop);
},
);
clearReactionsFn = () => {
listMessage.removeReactions().catch(noop);
listMessage.reactions.removeAll().catch(noop);
pluginData.events.off("messageReactionAdd", paginationReactionListener);
};
bumpClearReactionsTimeout();

View file

@ -5,10 +5,10 @@ import { mutesEvt } from "../types";
*/
export const ClearActiveMuteOnMemberBanEvt = mutesEvt({
event: "guildBanAdd",
async listener({ pluginData, args: { user } }) {
const mute = await pluginData.state.mutes.findExistingMuteForUserId(user.id);
async listener({ pluginData, args: { ban } }) {
const mute = await pluginData.state.mutes.findExistingMuteForUserId(ban.user.id);
if (mute) {
pluginData.state.mutes.clear(user.id);
pluginData.state.mutes.clear(ban.user.id);
}
},
});

View file

@ -6,7 +6,7 @@ import { memberHasMutedRole } from "../functions/memberHasMutedRole";
*/
export const ClearActiveMuteOnRoleRemovalEvt = mutesEvt({
event: "guildMemberUpdate",
async listener({ pluginData, args: { member } }) {
async listener({ pluginData, args: { oldMember, newMember: member } }) {
const muteRole = pluginData.config.get().mute_role;
if (!muteRole) return;

View file

@ -15,7 +15,7 @@ export const ReapplyActiveMuteOnJoinEvt = mutesEvt({
if (muteRole) {
const memberRoleLock = await pluginData.locks.acquire(memberRolesLock(member));
await member.addRole(muteRole);
await member.roles.add(muteRole);
memberRoleLock.unlock();
}

View file

@ -16,17 +16,17 @@ export async function clearExpiredMutes(pluginData: GuildPluginData<MutesPluginT
const muteRole = pluginData.config.get().mute_role;
if (muteRole) {
await member.removeRole(muteRole);
member.roles = member.roles.filter(r => r !== muteRole);
await member.roles.remove(muteRole);
}
if (mute.roles_to_restore) {
const memberOptions: MemberOptions = {};
const guildRoles = pluginData.guild.roles;
memberOptions.roles = Array.from(
new Set([...mute.roles_to_restore, ...member.roles.filter(x => x !== muteRole && guildRoles.has(x))]),
);
await member.edit(memberOptions);
member.roles = memberOptions.roles;
const guildRoles = pluginData.guild.roles.cache;
let newRoles: string[] = member.roles.cache.keyArray();
newRoles =
muteRole && newRoles.includes(muteRole) ? newRoles.splice(newRoles.indexOf(muteRole), 1) : newRoles;
for (const toRestore of mute.roles_to_restore) {
if (guildRoles.has(toRestore) && toRestore !== muteRole) newRoles.push(toRestore);
}
await member.roles.set(newRoles);
}
lock.unlock();

View file

@ -1,7 +1,8 @@
import { GuildMember } from "discord.js";
import { GuildPluginData } from "knub";
import { MutesPluginType } from "../types";
export function memberHasMutedRole(pluginData: GuildPluginData<MutesPluginType>, member: Member): boolean {
export function memberHasMutedRole(pluginData: GuildPluginData<MutesPluginType>, member: GuildMember): boolean {
const muteRole = pluginData.config.get().mute_role;
return muteRole ? member.roles.includes(muteRole) : false;
return muteRole ? member.roles.cache.has(muteRole) : false;
}

View file

@ -19,6 +19,7 @@ import { LogType } from "../../../data/LogType";
import { Case } from "../../../data/entities/Case";
import { LogsPlugin } from "../../../plugins/Logs/LogsPlugin";
import { muteLock } from "../../../utils/lockNameHelpers";
import { TextChannel, User } from "discord.js";
export async function muteUser(
pluginData: GuildPluginData<MutesPluginType>,
@ -58,8 +59,8 @@ export async function muteUser(
if (member) {
const logs = pluginData.getPlugin(LogsPlugin);
// remove and store any roles to be removed/restored
const currentUserRoles = member.roles;
const memberOptions: MemberOptions = {};
const currentUserRoles = member.roles.cache.keyArray();
let newRoles: string[] = currentUserRoles;
const removeRoles = removeRolesOnMuteOverride ?? config.remove_roles_on_mute;
const restoreRoles = restoreRolesOnMuteOverride ?? config.restore_roles_on_mute;
@ -67,13 +68,13 @@ export async function muteUser(
if (!Array.isArray(removeRoles)) {
if (removeRoles) {
// exclude managed roles from being removed
const managedRoles = pluginData.guild.roles.filter(x => x.managed).map(y => y.id);
memberOptions.roles = managedRoles.filter(x => member.roles.includes(x));
await member.edit(memberOptions);
const managedRoles = pluginData.guild.roles.cache.filter(x => x.managed).map(y => y.id);
newRoles = currentUserRoles.filter(r => !managedRoles.includes(r));
await member.roles.set(newRoles);
}
} else {
memberOptions.roles = currentUserRoles.filter(x => !(<string[]>removeRoles).includes(x));
await member.edit(memberOptions);
newRoles = currentUserRoles.filter(x => !(<string[]>removeRoles).includes(x));
await member.roles.set(newRoles);
}
// set roles to be restored
@ -86,11 +87,11 @@ export async function muteUser(
}
// Apply mute role if it's missing
if (!member.roles.includes(muteRole)) {
if (!currentUserRoles.includes(muteRole)) {
try {
await member.addRole(muteRole);
await member.roles.add(muteRole);
} catch (e) {
const actualMuteRole = pluginData.guild.roles.find(x => x.id === muteRole);
const actualMuteRole = pluginData.guild.roles.cache.find(x => x.id === muteRole);
if (!actualMuteRole) {
lock.unlock();
logs.log(LogType.BOT_ALERT, {
@ -100,9 +101,9 @@ export async function muteUser(
}
const zep = await resolveMember(pluginData.client, pluginData.guild, pluginData.client.user!.id);
const zepRoles = pluginData.guild.roles.filter(x => zep!.roles.includes(x.id));
const zepRoles = pluginData.guild.roles.cache.filter(x => zep!.roles.cache.has(x.id));
// If we have roles and one of them is above the muted role, throw generic error
if (zepRoles.length >= 0 && zepRoles.some(zepRole => zepRole.position > actualMuteRole.position)) {
if (zepRoles.size >= 0 && zepRoles.some(zepRole => zepRole.position > actualMuteRole.position)) {
lock.unlock();
logs.log(LogType.BOT_ALERT, {
body: `Cannot mute user ${member.id}: ${e}`,
@ -125,7 +126,7 @@ export async function muteUser(
if (moveToVoiceChannel || cfg.kick_from_voice_channel) {
// TODO: Add back the voiceState check once we figure out how to get voice state for guild members that are loaded on-demand
try {
await member.edit({ channelID: moveToVoiceChannel });
await member.edit({ channel: moveToVoiceChannel });
} catch {} // tslint:disable-line
}
}

View file

@ -36,18 +36,17 @@ export async function unmuteUser(
const lock = await pluginData.locks.acquire(memberRolesLock(member));
const muteRole = pluginData.config.get().mute_role;
if (muteRole && member.roles.includes(muteRole)) {
await member.removeRole(muteRole);
member.roles = member.roles.filter(r => r !== muteRole);
if (muteRole && member.roles.cache.has(muteRole)) {
await member.roles.remove(muteRole);
}
if (existingMute?.roles_to_restore) {
const memberOptions: MemberOptions = {};
const guildRoles = pluginData.guild.roles;
memberOptions.roles = Array.from(
new Set([...existingMute.roles_to_restore, ...member.roles.filter(x => x !== muteRole && guildRoles.has(x))]),
);
await member.edit(memberOptions);
member.roles = memberOptions.roles;
const guildRoles = pluginData.guild.roles.cache;
let newRoles: string[] = member.roles.cache.keyArray();
newRoles = muteRole && newRoles.includes(muteRole) ? newRoles.splice(newRoles.indexOf(muteRole), 1) : newRoles;
for (const toRestore of existingMute.roles_to_restore) {
if (guildRoles.has(toRestore) && toRestore !== muteRole) newRoles.push(toRestore);
}
await member.roles.set(newRoles);
}
lock.unlock();
@ -85,7 +84,7 @@ export async function unmuteUser(
});
// Log the action
const mod = pluginData.client.user!.get(modId);
const mod = pluginData.client.users.fetch(modId);
if (unmuteTime) {
pluginData.state.serverLogs.log(LogType.MEMBER_TIMED_UNMUTE, {
mod: stripObjectToScalars(mod),

View file

@ -11,6 +11,7 @@ import { GuildMutes } from "../../data/GuildMutes";
import { CaseArgs } from "../Cases/types";
import Timeout = NodeJS.Timeout;
import { EventEmitter } from "events";
import { GuildMember } from "discord.js";
export const ConfigSchema = t.type({
mute_role: tNullable(t.string),
@ -58,7 +59,7 @@ export interface MutesPluginType extends BasePluginType {
}
export interface IMuteWithDetails extends Mute {
member?: Member;
member?: GuildMember;
banned?: boolean;
}

View file

@ -29,7 +29,7 @@ export const NamesCmd = nameHistoryCmd({
);
const usernameRows = usernames.map(r => `\`[${r.timestamp}]\` **${disableCodeBlocks(r.username)}**`);
const user = pluginData.client.user!.get(args.userId);
const user = await pluginData.client.users.fetch(args.userId);
const currentUsername = user ? `${user.username}#${user.discriminator}` : args.userId;
const nicknameDays = Math.round(NICKNAME_RETENTION_PERIOD / DAYS);

View file

@ -2,10 +2,15 @@ import { nameHistoryEvt } from "../types";
import { updateNickname } from "../updateNickname";
export const ChannelJoinEvt = nameHistoryEvt({
event: "voiceChannelJoin",
event: "voiceStateUpdate",
async listener(meta) {
meta.pluginData.state.updateQueue.add(() => updateNickname(meta.pluginData, meta.args.member));
meta.pluginData.state.updateQueue.add(() =>
updateNickname(
meta.pluginData,
meta.args.newState.member ? meta.args.newState.member : meta.args.oldState.member!,
),
);
},
});

View file

@ -1,11 +1,12 @@
import { GuildMember } from "discord.js";
import { GuildPluginData } from "knub";
import { NameHistoryPluginType } from "./types";
export async function updateNickname(pluginData: GuildPluginData<NameHistoryPluginType>, member: Member) {
export async function updateNickname(pluginData: GuildPluginData<NameHistoryPluginType>, member: GuildMember) {
if (!member) return;
const latestEntry = await pluginData.state.nicknameHistory.getLastEntry(member.id);
if (!latestEntry || latestEntry.nickname !== member.nick) {
if (!latestEntry && member.nick == null) return; // No need to save "no nickname" if there's no previous data
await pluginData.state.nicknameHistory.addEntry(member.id, member.nick);
if (!latestEntry || latestEntry.nickname !== member.nickname) {
if (!latestEntry && member.nickname == null) return; // No need to save "no nickname" if there's no previous data
await pluginData.state.nicknameHistory.addEntry(member.id, member.nickname);
}
}

View file

@ -8,8 +8,9 @@ import { LogsPlugin } from "../../Logs/LogsPlugin";
import { missingPermissionError } from "../../../utils/missingPermissionError";
import { canAssignRole } from "../../../utils/canAssignRole";
import { memberRolesLock } from "../../../utils/lockNameHelpers";
import { GuildMemberEditData, Permissions } from "discord.js";
const p = Constants.Permissions;
const p = Permissions.FLAGS;
export const LoadDataEvt = persistEvt({
event: "guildMemberAdd",
@ -26,16 +27,16 @@ export const LoadDataEvt = persistEvt({
return;
}
const toRestore: MemberOptions = {};
let toRestore: GuildMemberEditData = {};
const config = await pluginData.config.getForMember(member);
const restoredData: string[] = [];
// Check permissions
const me = pluginData.guild.members.cache.get(pluginData.client.user!.id)!;
let requiredPermissions = 0n;
if (config.persist_nicknames) requiredPermissions |= p.manageNicknames;
if (config.persisted_roles) requiredPermissions |= p.manageRoles;
const missingPermissions = getMissingPermissions(me.permission, requiredPermissions);
if (config.persist_nicknames) requiredPermissions |= p.MANAGE_NICKNAMES;
if (config.persisted_roles) requiredPermissions |= p.MANAGE_ROLES;
const missingPermissions = getMissingPermissions(me.permissions, requiredPermissions);
if (missingPermissions) {
pluginData.getPlugin(LogsPlugin).log(LogType.BOT_ALERT, {
body: `Missing permissions for persist plugin: ${missingPermissionError(missingPermissions)}`,
@ -61,7 +62,7 @@ export const LoadDataEvt = persistEvt({
if (rolesToRestore.length) {
restoredData.push("roles");
toRestore.roles = Array.from(new Set([...rolesToRestore, ...member.roles]));
toRestore.roles = Array.from(new Set([...rolesToRestore, ...member.roles.cache]));
}
}

View file

@ -2,12 +2,13 @@ import { persistEvt } from "../types";
import { IPartialPersistData } from "../../../data/GuildPersistedData";
import intersection from "lodash.intersection";
import { GuildMember } from "discord.js";
export const StoreDataEvt = persistEvt({
event: "guildMemberRemove",
async listener(meta) {
const member = meta.args.member as Member;
const member = meta.args.member as GuildMember;
const pluginData = meta.pluginData;
let persist = false;
@ -23,9 +24,9 @@ export const StoreDataEvt = persistEvt({
}
}
if (config.persist_nicknames && member.nick) {
if (config.persist_nicknames && member.nickname) {
persist = true;
persistData.nickname = member.nick;
persistData.nickname = member.nickname;
}
if (persist) {

View file

@ -2,6 +2,7 @@ import { postCmd } from "../types";
import { commandTypeHelpers as ct } from "../../../commandTypes";
import { sendErrorMessage, sendSuccessMessage } from "../../../pluginUtils";
import { formatContent } from "../util/formatContent";
import { TextChannel } from "discord.js";
export const EditCmd = postCmd({
trigger: "edit",
@ -24,7 +25,9 @@ export const EditCmd = postCmd({
return;
}
await pluginData.client.editMessage(savedMessage.channel_id, savedMessage.id, formatContent(args.content));
(pluginData.guild.channels.cache.get(savedMessage.channel_id) as TextChannel).messages.edit(savedMessage.id, {
content: formatContent(args.content),
});
sendSuccessMessage(pluginData, msg.channel, "Message edited");
},
});

View file

@ -6,6 +6,7 @@ import { trimLines } from "../../../utils";
import { formatContent } from "../util/formatContent";
import { parseColor } from "../../../utils/parseColor";
import { rgbToInt } from "../../../utils/rgbToInt";
import { MessageEmbed, TextChannel } from "discord.js";
const COLOR_MATCH_REGEX = /^#?([0-9a-f]{6})$/;
@ -42,17 +43,19 @@ export const EditEmbedCmd = postCmd({
}
}
const embed: Embed = savedMessage.data.embeds![0] as Embed;
const embed: MessageEmbed = savedMessage.data.embeds![0] as MessageEmbed;
if (args.title) embed.title = args.title;
if (content) embed.description = formatContent(content);
if (color) embed.color = color;
await pluginData.client.editMessage(savedMessage.channel_id, savedMessage.id, { embed });
(pluginData.guild.channels.cache.get(savedMessage.channel_id) as TextChannel).messages.edit(savedMessage.id, {
embed,
});
await sendSuccessMessage(pluginData, msg.channel, "Embed edited");
if (args.content) {
const prefix = pluginData.fullConfig.prefix || "!";
msg.channel.createMessage(
msg.channel.send(
trimLines(`
<@!${msg.author.id}> You can now specify an embed's content directly at the end of the command:
\`${prefix}edit_embed -title "Some title" content goes here\`

View file

@ -7,6 +7,7 @@ import { isValidEmbed, trimLines } from "../../../utils";
import { formatContent } from "../util/formatContent";
import { parseColor } from "../../../utils/parseColor";
import { rgbToInt } from "../../../utils/rgbToInt";
import { MessageEmbed, MessageEmbedOptions } from "discord.js";
export const PostEmbedCmd = postCmd({
trigger: "post_embed",
@ -46,7 +47,7 @@ export const PostEmbedCmd = postCmd({
}
}
let embed: Embed = { type: "rich" };
let embed: MessageEmbedOptions = {};
if (args.title) embed.title = args.title;
if (color) embed.color = color;
@ -73,7 +74,7 @@ export const PostEmbedCmd = postCmd({
if (args.content) {
const prefix = pluginData.fullConfig.prefix || "!";
msg.channel.createMessage(
msg.channel.send(
trimLines(`
<@!${msg.author.id}> You can now specify an embed's content directly at the end of the command:
\`${prefix}edit_embed -title "Some title" content goes here\`

View file

@ -20,7 +20,7 @@ export const ScheduledPostsListCmd = postCmd({
async run({ message: msg, pluginData }) {
const scheduledPosts = await pluginData.state.scheduledPosts.all();
if (scheduledPosts.length === 0) {
msg.channel.createMessage("No scheduled posts");
msg.channel.send("No scheduled posts");
return;
}

View file

@ -3,6 +3,7 @@ import { sorter } from "../../../utils";
import { sendErrorMessage } from "../../../pluginUtils";
import { commandTypeHelpers as ct } from "../../../commandTypes";
import { postMessage } from "../util/postMessage";
import { TextChannel } from "discord.js";
export const ScheduledPostsShowCmd = postCmd({
trigger: ["scheduled_posts", "scheduled_posts show"],

View file

@ -8,6 +8,7 @@ import { PostPluginType } from "../types";
import { parseScheduleTime } from "./parseScheduleTime";
import { postMessage } from "./postMessage";
import { TimeAndDatePlugin } from "../../TimeAndDate/TimeAndDatePlugin";
import { Message, Channel, TextChannel } from "discord.js";
const MIN_REPEAT_TIME = 5 * MINUTES;
const MAX_REPEAT_TIME = Math.pow(2, 32);
@ -27,22 +28,30 @@ export async function actualPostCmd(
} = {},
) {
if (!(targetChannel instanceof TextChannel)) {
msg.channel.createMessage(errorMessage("Channel is not a text channel"));
msg.channel.send(errorMessage("Channel is not a text channel"));
return;
}
if (content == null && msg.attachments.length === 0) {
msg.channel.createMessage(errorMessage("Message content or attachment required"));
if (content == null && msg.attachments.size === 0) {
msg.channel.send(errorMessage("Message content or attachment required"));
return;
}
if (opts.repeat) {
if (opts.repeat < MIN_REPEAT_TIME) {
sendErrorMessage(pluginData, msg.channel, `Minimum time for -repeat is ${humanizeDuration(MIN_REPEAT_TIME)}`);
sendErrorMessage(
pluginData,
msg.channel as TextChannel,
`Minimum time for -repeat is ${humanizeDuration(MIN_REPEAT_TIME)}`,
);
return;
}
if (opts.repeat > MAX_REPEAT_TIME) {
sendErrorMessage(pluginData, msg.channel, `Max time for -repeat is ${humanizeDuration(MAX_REPEAT_TIME)}`);
sendErrorMessage(
pluginData,
msg.channel as TextChannel,
`Max time for -repeat is ${humanizeDuration(MAX_REPEAT_TIME)}`,
);
return;
}
}
@ -53,7 +62,7 @@ export async function actualPostCmd(
// Schedule the post to be posted later
postAt = await parseScheduleTime(pluginData, msg.author.id, opts.schedule);
if (!postAt) {
sendErrorMessage(pluginData, msg.channel, "Invalid schedule time");
sendErrorMessage(pluginData, msg.channel as TextChannel, "Invalid schedule time");
return;
}
} else if (opts.repeat) {
@ -70,17 +79,17 @@ export async function actualPostCmd(
// Invalid time
if (!repeatUntil) {
sendErrorMessage(pluginData, msg.channel, "Invalid time specified for -repeat-until");
sendErrorMessage(pluginData, msg.channel as TextChannel, "Invalid time specified for -repeat-until");
return;
}
if (repeatUntil.isBefore(moment.utc())) {
sendErrorMessage(pluginData, msg.channel, "You can't set -repeat-until in the past");
sendErrorMessage(pluginData, msg.channel as TextChannel, "You can't set -repeat-until in the past");
return;
}
if (repeatUntil.isAfter(MAX_REPEAT_UNTIL)) {
sendErrorMessage(
pluginData,
msg.channel,
msg.channel as TextChannel,
"Unfortunately, -repeat-until can only be at most 100 years into the future. Maybe 99 years would be enough?",
);
return;
@ -88,18 +97,26 @@ export async function actualPostCmd(
} else if (opts["repeat-times"]) {
repeatTimes = opts["repeat-times"];
if (repeatTimes <= 0) {
sendErrorMessage(pluginData, msg.channel, "-repeat-times must be 1 or more");
sendErrorMessage(pluginData, msg.channel as TextChannel, "-repeat-times must be 1 or more");
return;
}
}
if (repeatUntil && repeatTimes) {
sendErrorMessage(pluginData, msg.channel, "You can only use one of -repeat-until or -repeat-times at once");
sendErrorMessage(
pluginData,
msg.channel as TextChannel,
"You can only use one of -repeat-until or -repeat-times at once",
);
return;
}
if (opts.repeat && !repeatUntil && !repeatTimes) {
sendErrorMessage(pluginData, msg.channel, "You must specify -repeat-until or -repeat-times for repeated messages");
sendErrorMessage(
pluginData,
msg.channel as TextChannel,
"You must specify -repeat-until or -repeat-times for repeated messages",
);
return;
}
@ -114,7 +131,7 @@ export async function actualPostCmd(
// Save schedule/repeat information in DB
if (postAt) {
if (postAt < moment.utc()) {
sendErrorMessage(pluginData, msg.channel, "Post can't be scheduled to be posted in the past");
sendErrorMessage(pluginData, msg.channel as TextChannel, "Post can't be scheduled to be posted in the past");
return;
}
@ -123,7 +140,7 @@ export async function actualPostCmd(
author_name: `${msg.author.username}#${msg.author.discriminator}`,
channel_id: targetChannel.id,
content,
attachments: msg.attachments,
attachments: msg.attachments.array(),
post_at: postAt
.clone()
.tz("Etc/UTC")
@ -162,7 +179,7 @@ export async function actualPostCmd(
// When the message isn't scheduled for later, post it immediately
if (!opts.schedule) {
await postMessage(pluginData, targetChannel, content, msg.attachments, opts["enable-mentions"]);
await postMessage(pluginData, targetChannel, content, msg.attachments.array(), opts["enable-mentions"]);
}
if (opts.repeat) {
@ -197,6 +214,6 @@ export async function actualPostCmd(
}
if (targetChannel.id !== msg.channel.id || opts.schedule || opts.repeat) {
sendSuccessMessage(pluginData, msg.channel, successMessage);
sendSuccessMessage(pluginData, msg.channel as TextChannel, successMessage);
}
}

View file

@ -4,14 +4,15 @@ import { PostPluginType } from "../types";
import { downloadFile } from "../../../utils";
import fs from "fs";
import { formatContent } from "./formatContent";
import { TextChannel, Message, MessageOptions, MessageAttachment } from "discord.js";
const fsp = fs.promises;
export async function postMessage(
pluginData: GuildPluginData<PostPluginType>,
channel: TextChannel,
content: MessageContent,
attachments: Attachment[] = [],
content: MessageOptions,
attachments: MessageAttachment[] = [],
enableMentions: boolean = false,
): Promise<Message> {
if (typeof content === "string") {
@ -27,20 +28,18 @@ export async function postMessage(
if (attachments.length) {
downloadedAttachment = await downloadFile(attachments[0].url);
file = {
name: attachments[0].filename,
name: attachments[0].name,
file: await fsp.readFile(downloadedAttachment.path),
};
}
if (enableMentions) {
content.allowedMentions = {
everyone: true,
users: true,
roles: true,
parse: ["everyone", "roles", "users"],
};
}
const createdMsg = await channel.createMessage(content, file);
const createdMsg = await channel.send(content, file);
pluginData.state.savedMessages.setPermanent(createdMsg.id);
if (downloadedAttachment) {

View file

@ -6,6 +6,7 @@ import { LogType } from "../../../data/LogType";
import moment from "moment-timezone";
import { postMessage } from "./postMessage";
import { TextChannel, User } from "discord.js";
const SCHEDULED_POST_CHECK_INTERVAL = 5 * SECONDS;
@ -15,7 +16,7 @@ export async function scheduledPostLoop(pluginData: GuildPluginData<PostPluginTy
const channel = pluginData.guild.channels.cache.get(post.channel_id);
if (channel instanceof TextChannel) {
const [username, discriminator] = post.author_name.split("#");
const author: Partial<User> = pluginData.client.user!.get(post.author_id) || {
const author: User = (await pluginData.client.users.fetch(post.author_id)) || {
id: post.author_id,
username,
discriminator,

View file

@ -3,6 +3,7 @@ import { commandTypeHelpers as ct } from "../../../commandTypes";
import { sendErrorMessage, sendSuccessMessage } from "../../../pluginUtils";
import { isDiscordRESTError } from "../../../utils";
import { Message } from "discord.js";
export const ClearReactionRolesCmd = reactionRolesCmd({
trigger: "reaction_roles clear",
@ -21,9 +22,9 @@ export const ClearReactionRolesCmd = reactionRolesCmd({
pluginData.state.reactionRoles.removeFromMessage(args.message.messageId);
let targetMessage: Message<TextChannel>;
let targetMessage: Message;
try {
targetMessage = await args.message.channel.getMessage(args.message.messageId);
targetMessage = await args.message.channel.messages.fetch(args.message.messageId);
} catch (err) {
if (isDiscordRESTError(err) && err.code === 50001) {
sendErrorMessage(pluginData, msg.channel, "Missing access to the specified message");
@ -33,7 +34,7 @@ export const ClearReactionRolesCmd = reactionRolesCmd({
throw err;
}
await targetMessage.removeReactions();
await targetMessage.reactions.removeAll();
sendSuccessMessage(pluginData, msg.channel, "Reaction roles cleared");
},

View file

@ -1,8 +1,6 @@
import { reactionRolesCmd, TReactionRolePair } from "../types";
import { commandTypeHelpers as ct } from "../../../commandTypes";
import { sendErrorMessage, sendSuccessMessage } from "../../../pluginUtils";
import { RecoverablePluginError, ERRORS } from "../../../RecoverablePluginError";
import { canUseEmoji, isDiscordRESTError, isValidEmoji, noop, trimPluginDescription } from "../../../utils";
import { applyReactionRoleReactionsToMessage } from "../util/applyReactionRoleReactionsToMessage";
import { canReadChannel } from "../../../utils/canReadChannel";
@ -41,7 +39,7 @@ export const InitReactionRolesCmd = reactionRolesCmd({
let targetMessage;
try {
targetMessage = await args.message.channel.getMessage(args.message.messageId).catch(noop);
targetMessage = await args.message.channel.messages.fetch(args.message.messageId).catch(noop);
} catch (e) {
if (isDiscordRESTError(e)) {
sendErrorMessage(pluginData, msg.channel, `Error ${e.code} while getting message: ${e.message}`);
@ -96,13 +94,13 @@ export const InitReactionRolesCmd = reactionRolesCmd({
return;
}
if (!pluginData.guild.roles.has(pair[1])) {
if (!pluginData.guild.roles.cache.has(pair[1])) {
sendErrorMessage(pluginData, msg.channel, `Unknown role ${pair[1]}`);
return;
}
}
const progressMessage = msg.channel.createMessage("Adding reaction roles...");
const progressMessage = msg.channel.send("Adding reaction roles...");
// Save the new reaction roles to the database
for (const pair of emojiRolePairs) {

View file

@ -4,6 +4,7 @@ import { addMemberPendingRoleChange } from "../util/addMemberPendingRoleChange";
import { LogsPlugin } from "../../Logs/LogsPlugin";
import { LogType } from "../../../data/LogType";
import { Message } from "discord.js";
const CLEAR_ROLES_EMOJI = "❌";
@ -12,9 +13,9 @@ export const AddReactionRoleEvt = reactionRolesEvt({
async listener(meta) {
const pluginData = meta.pluginData;
const msg = meta.args.message as Message;
const emoji = meta.args.emoji;
const userId = meta.args.member.id;
const msg = meta.args.reaction.message as Message;
const emoji = meta.args.reaction.emoji;
const userId = meta.args.user.id;
if (userId === pluginData.client.user!.id) {
// Don't act on own reactions
@ -39,7 +40,7 @@ export const AddReactionRoleEvt = reactionRolesEvt({
// User reacted with a reaction role emoji -> add the role
const matchingReactionRole = await pluginData.state.reactionRoles.getByMessageAndEmoji(
msg.id,
emoji.id || emoji.name,
emoji.id || emoji.name!,
);
if (!matchingReactionRole) return;
@ -59,9 +60,8 @@ export const AddReactionRoleEvt = reactionRolesEvt({
if (config.remove_user_reactions) {
setTimeout(() => {
pluginData.state.reactionRemoveQueue.add(async () => {
const reaction = emoji.id ? `${emoji.name}:${emoji.id}` : emoji.name;
const wait = sleep(1500);
await msg.channel.removeMessageReaction(msg.id, reaction, userId).catch(noop);
await meta.args.reaction.remove().catch(noop);
await wait;
});
}, 1500);

View file

@ -23,7 +23,7 @@ export async function addMemberPendingRoleChange(
const member = await resolveMember(pluginData.client, pluginData.guild, memberId);
if (member) {
const newRoleIds = new Set(member.roles);
const newRoleIds = new Set(member.roles.cache.keyArray());
for (const change of newPendingRoleChangeObj.changes) {
if (change.mode === "+") newRoleIds.add(change.roleId);
else newRoleIds.delete(change.roleId);
@ -38,7 +38,7 @@ export async function addMemberPendingRoleChange(
);
} catch (e) {
logger.warn(
`Failed to apply role changes to ${member.username}#${member.discriminator} (${member.id}): ${e.message}`,
`Failed to apply role changes to ${member.user.username}#${member.user.discriminator} (${member.id}): ${e.message}`,
);
}
}

View file

@ -6,6 +6,7 @@ import { isDiscordRESTError, sleep, isSnowflake } from "../../../utils";
import { logger } from "../../../logger";
import { LogsPlugin } from "../../Logs/LogsPlugin";
import { LogType } from "../../../data/LogType";
import { TextChannel } from "discord.js";
const CLEAR_ROLES_EMOJI = "❌";
@ -26,7 +27,7 @@ export async function applyReactionRoleReactionsToMessage(
let targetMessage;
try {
targetMessage = await channel.getMessage(messageId);
targetMessage = await channel.messages.fetch(messageId);
} catch (e) {
if (isDiscordRESTError(e)) {
if (e.code === 10008) {

View file

@ -4,6 +4,7 @@ import moment from "moment-timezone";
import humanizeDuration from "humanize-duration";
import { disableLinkPreviews } from "knub/dist/helpers";
import { SECONDS } from "../../../utils";
import { TextChannel } from "discord.js";
const REMINDER_LOOP_TIME = 10 * SECONDS;
const MAX_TRIES = 3;
@ -19,7 +20,7 @@ export async function postDueRemindersLoop(pluginData: GuildPluginData<Reminders
const target = moment.utc();
const diff = target.diff(moment.utc(reminder.created_at, "YYYY-MM-DD HH:mm:ss"));
const result = humanizeDuration(diff, { largest: 2, round: true });
await channel.createMessage({
await channel.send({
content: disableLinkPreviews(
`Reminder for <@!${reminder.user_id}>: ${reminder.body} \n\`Set at ${reminder.created_at} (${result} ago)\``,
),
@ -28,7 +29,7 @@ export async function postDueRemindersLoop(pluginData: GuildPluginData<Reminders
},
});
} else {
await channel.createMessage({
await channel.send({
content: disableLinkPreviews(`Reminder for <@!${reminder.user_id}>: ${reminder.body}`),
allowedMentions: {
users: [reminder.user_id],

View file

@ -3,6 +3,7 @@ import { sendErrorMessage, sendSuccessMessage, canActOn } from "../../../pluginU
import { rolesCmd } from "../types";
import { resolveRoleId, stripObjectToScalars, verboseUserMention } from "../../../utils";
import { LogType } from "../../../data/LogType";
import { GuildChannel } from "discord.js";
export const AddRoleCmd = rolesCmd({
trigger: "addrole",
@ -33,7 +34,7 @@ export const AddRoleCmd = rolesCmd({
}
// Sanity check: make sure the role is configured properly
const role = (msg.channel as GuildChannel).guild.roles.get(roleId);
const role = (msg.channel as GuildChannel).guild.roles.cache.get(roleId);
if (!role) {
pluginData.state.logs.log(LogType.BOT_ALERT, {
body: `Unknown role configured for 'roles' plugin: ${roleId}`,
@ -42,14 +43,14 @@ export const AddRoleCmd = rolesCmd({
return;
}
if (args.member.roles.includes(roleId)) {
if (args.member.roles.cache.has(roleId)) {
sendErrorMessage(pluginData, msg.channel, "Member already has that role");
return;
}
pluginData.state.logs.ignoreLog(LogType.MEMBER_ROLE_ADD, args.member.id);
await args.member.addRole(roleId);
await args.member.roles.add(roleId);
pluginData.state.logs.log(LogType.MEMBER_ROLE_ADD, {
member: stripObjectToScalars(args.member, ["user", "roles"]),

View file

@ -4,6 +4,7 @@ import { rolesCmd } from "../types";
import { resolveMember, resolveRoleId, stripObjectToScalars, successMessage } from "../../../utils";
import { LogType } from "../../../data/LogType";
import { logger } from "../../../logger";
import { GuildMember } from "discord.js";
export const MassAddRoleCmd = rolesCmd({
trigger: "massaddrole",
@ -15,9 +16,9 @@ export const MassAddRoleCmd = rolesCmd({
},
async run({ message: msg, args, pluginData }) {
msg.channel.createMessage(`Resolving members...`);
msg.channel.send(`Resolving members...`);
const members: Member[] = [];
const members: GuildMember[] = [];
const unknownMembers: string[] = [];
for (const memberId of args.members) {
const member = await resolveMember(pluginData.client, pluginData.guild, memberId);
@ -57,12 +58,12 @@ export const MassAddRoleCmd = rolesCmd({
return;
}
const membersWithoutTheRole = members.filter(m => !m.roles.includes(roleId));
const membersWithoutTheRole = members.filter(m => !m.roles.cache.has(roleId));
let assigned = 0;
const failed: string[] = [];
const alreadyHadRole = members.length - membersWithoutTheRole.length;
msg.channel.createMessage(
msg.channel.send(
`Adding role **${role.name}** to ${membersWithoutTheRole.length} ${
membersWithoutTheRole.length === 1 ? "member" : "members"
}...`,
@ -71,7 +72,7 @@ export const MassAddRoleCmd = rolesCmd({
for (const member of membersWithoutTheRole) {
try {
pluginData.state.logs.ignoreLog(LogType.MEMBER_ROLE_ADD, member.id);
await member.addRole(roleId);
await member.roles.add(roleId);
pluginData.state.logs.log(LogType.MEMBER_ROLE_ADD, {
member: stripObjectToScalars(member, ["user", "roles"]),
roles: role.name,
@ -97,6 +98,6 @@ export const MassAddRoleCmd = rolesCmd({
resultMessage += `\nUnknown members: ${unknownMembers.join(", ")}`;
}
msg.channel.createMessage(successMessage(resultMessage));
msg.channel.send(successMessage(resultMessage));
},
});

Some files were not shown because too many files have changed in this diff Show more