Add spam plugin. Add clean commands. Update Knub to 9.6.0.
This commit is contained in:
parent
ad6afdfac1
commit
7ded84b924
11 changed files with 539 additions and 85 deletions
|
@ -1,51 +1,9 @@
|
|||
import { Plugin, decorators as d } from "knub";
|
||||
import { decorators as d, Plugin } from "knub";
|
||||
import { Invite, Message } from "eris";
|
||||
import url from "url";
|
||||
import tlds from "tlds";
|
||||
import escapeStringRegexp from "escape-string-regexp";
|
||||
import { GuildLogs } from "../data/GuildLogs";
|
||||
import { LogType } from "../data/LogType";
|
||||
import { stripObjectToScalars } from "../utils";
|
||||
|
||||
const urlRegex = /(\S+\.\S+)/g;
|
||||
const protocolRegex = /^[a-z]+:\/\//;
|
||||
|
||||
const getInviteCodesInString = (str: string): string[] => {
|
||||
const inviteCodeRegex = /(?:discord.gg|discordapp.com\/invite)\/([a-z0-9]+)/gi;
|
||||
const inviteCodes = [];
|
||||
let match;
|
||||
|
||||
// tslint:disable-next-line
|
||||
while ((match = inviteCodeRegex.exec(str)) !== null) {
|
||||
inviteCodes.push(match[1]);
|
||||
}
|
||||
|
||||
return inviteCodes;
|
||||
};
|
||||
|
||||
const getUrlsInString = (str: string): url.URL[] => {
|
||||
const matches = str.match(urlRegex) || [];
|
||||
return matches.reduce((urls, match) => {
|
||||
if (!protocolRegex.test(match)) {
|
||||
match = `https://${match}`;
|
||||
}
|
||||
|
||||
let matchUrl: url.URL;
|
||||
try {
|
||||
matchUrl = new url.URL(match);
|
||||
} catch (e) {
|
||||
return urls;
|
||||
}
|
||||
|
||||
const hostnameParts = matchUrl.hostname.split(".");
|
||||
const tld = hostnameParts[hostnameParts.length - 1];
|
||||
if (tlds.includes(tld)) {
|
||||
urls.push(matchUrl);
|
||||
}
|
||||
|
||||
return urls;
|
||||
}, []);
|
||||
};
|
||||
import { getInviteCodesInString, getUrlsInString, stripObjectToScalars } from "../utils";
|
||||
|
||||
export class CensorPlugin extends Plugin {
|
||||
protected serverLogs: GuildLogs;
|
||||
|
|
|
@ -158,17 +158,25 @@ export class LogsPlugin extends Plugin {
|
|||
const mod = relevantAuditLogEntry ? relevantAuditLogEntry.user : unknownUser;
|
||||
|
||||
if (addedRoles.length) {
|
||||
this.serverLogs.log(LogType.MEMBER_ROLE_ADD, {
|
||||
member,
|
||||
role: this.guild.roles.get(addedRoles[0]),
|
||||
mod: stripObjectToScalars(mod)
|
||||
});
|
||||
this.serverLogs.log(
|
||||
LogType.MEMBER_ROLE_ADD,
|
||||
{
|
||||
member,
|
||||
role: this.guild.roles.get(addedRoles[0]),
|
||||
mod: stripObjectToScalars(mod)
|
||||
},
|
||||
member.id
|
||||
);
|
||||
} else if (removedRoles.length) {
|
||||
this.serverLogs.log(LogType.MEMBER_ROLE_REMOVE, {
|
||||
member,
|
||||
role: this.guild.roles.get(removedRoles[0]),
|
||||
mod: stripObjectToScalars(mod)
|
||||
});
|
||||
this.serverLogs.log(
|
||||
LogType.MEMBER_ROLE_REMOVE,
|
||||
{
|
||||
member,
|
||||
role: this.guild.roles.get(removedRoles[0]),
|
||||
mod: stripObjectToScalars(mod)
|
||||
},
|
||||
member.id
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -230,7 +238,7 @@ export class LogsPlugin extends Plugin {
|
|||
|
||||
@d.event("messageDelete")
|
||||
onMessageDelete(msg: Message) {
|
||||
if (msg.type !== 0) return;
|
||||
if (msg.type != null && msg.type !== 0) return;
|
||||
|
||||
if (msg.member) {
|
||||
this.serverLogs.log(
|
||||
|
@ -256,10 +264,14 @@ export class LogsPlugin extends Plugin {
|
|||
|
||||
@d.event("messageDeleteBulk")
|
||||
onMessageDeleteBulk(messages: Message[]) {
|
||||
this.serverLogs.log(LogType.MESSAGE_DELETE_BULK, {
|
||||
count: messages.length,
|
||||
channel: messages[0] ? messages[0].channel : null
|
||||
});
|
||||
this.serverLogs.log(
|
||||
LogType.MESSAGE_DELETE_BULK,
|
||||
{
|
||||
count: messages.length,
|
||||
channel: messages[0] ? messages[0].channel : null
|
||||
},
|
||||
messages[0] && messages[0].id
|
||||
);
|
||||
}
|
||||
|
||||
@d.event("voiceChannelJoin")
|
||||
|
|
|
@ -258,6 +258,11 @@ export class ModActionsPlugin extends Plugin {
|
|||
});
|
||||
}
|
||||
|
||||
public async muteMember(member: Member, muteTime: number = null, reason: string = null) {
|
||||
await member.addRole(this.configValue("mute_role"), reason);
|
||||
await this.mutes.addOrUpdateMute(member.id, muteTime);
|
||||
}
|
||||
|
||||
@d.command("mute", "<member:Member> [time:string] [reason:string$]")
|
||||
@d.permission("mute")
|
||||
async muteCmd(msg: Message, args: any) {
|
||||
|
@ -283,8 +288,7 @@ export class ModActionsPlugin extends Plugin {
|
|||
|
||||
// Apply "muted" role
|
||||
this.serverLogs.ignoreLog(LogType.MEMBER_ROLE_ADD, args.member.id);
|
||||
await args.member.addRole(this.configValue("mute_role"), args.reason);
|
||||
await this.mutes.addOrUpdateMute(args.member.id, muteTime);
|
||||
this.muteMember(args.member, muteTime, args.reason);
|
||||
|
||||
// Create a case
|
||||
await this.createCase(args.member.id, msg.author.id, CaseType.Mute, null, args.reason);
|
||||
|
@ -713,7 +717,7 @@ export class ModActionsPlugin extends Plugin {
|
|||
return this.displayCase(caseOrCaseId, caseLogChannelId);
|
||||
}
|
||||
|
||||
protected async createCase(
|
||||
public async createCase(
|
||||
userId: string,
|
||||
modId: string,
|
||||
caseType: CaseType,
|
||||
|
@ -770,6 +774,7 @@ export class ModActionsPlugin extends Plugin {
|
|||
if (!member) continue;
|
||||
|
||||
try {
|
||||
this.serverLogs.ignoreLog(LogType.MEMBER_ROLE_REMOVE, member.id);
|
||||
await member.removeRole(this.configValue("mute_role"));
|
||||
} catch (e) {} // tslint:disable-line
|
||||
|
||||
|
|
226
src/plugins/Spam.ts
Normal file
226
src/plugins/Spam.ts
Normal file
|
@ -0,0 +1,226 @@
|
|||
import { decorators as d, Plugin } from "knub";
|
||||
import { Message, TextChannel } from "eris";
|
||||
import {
|
||||
cleanMessagesInChannel,
|
||||
getEmojiInString,
|
||||
getUrlsInString,
|
||||
stripObjectToScalars
|
||||
} from "../utils";
|
||||
import { LogType } from "../data/LogType";
|
||||
import { GuildLogs } from "../data/GuildLogs";
|
||||
import { ModActionsPlugin } from "./ModActions";
|
||||
import { CaseType } from "../data/CaseType";
|
||||
|
||||
enum RecentActionType {
|
||||
Message = 1,
|
||||
Mention,
|
||||
Link,
|
||||
Attachment,
|
||||
Emoji,
|
||||
Newline
|
||||
}
|
||||
|
||||
interface IRecentAction {
|
||||
type: RecentActionType;
|
||||
userId: string;
|
||||
channelId: string;
|
||||
timestamp: number;
|
||||
count: number;
|
||||
}
|
||||
|
||||
export class SpamPlugin extends Plugin {
|
||||
protected logs: GuildLogs;
|
||||
|
||||
protected recentActions: IRecentAction[];
|
||||
|
||||
private expiryInterval;
|
||||
|
||||
getDefaultOptions() {
|
||||
return {
|
||||
config: {
|
||||
max_messages: null,
|
||||
max_mentions: null,
|
||||
max_links: null,
|
||||
max_attachments: null,
|
||||
max_emojis: null,
|
||||
max_newlines: null,
|
||||
max_duplicates: null
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
onLoad() {
|
||||
this.logs = new GuildLogs(this.guildId);
|
||||
this.expiryInterval = setInterval(() => this.clearOldRecentActions(), 1000 * 60);
|
||||
this.recentActions = [];
|
||||
}
|
||||
|
||||
onUnload() {
|
||||
clearInterval(this.expiryInterval);
|
||||
}
|
||||
|
||||
addRecentAction(
|
||||
type: RecentActionType,
|
||||
userId: string,
|
||||
channelId: string,
|
||||
timestamp: number,
|
||||
count = 1
|
||||
) {
|
||||
this.recentActions.push({
|
||||
type,
|
||||
userId,
|
||||
channelId,
|
||||
timestamp,
|
||||
count
|
||||
});
|
||||
}
|
||||
|
||||
getRecentActionCount(type: RecentActionType, userId: string, channelId: string, since: number) {
|
||||
return this.recentActions.reduce((count, action) => {
|
||||
if (action.timestamp < since) return count;
|
||||
if (action.type !== type) return count;
|
||||
if (action.channelId !== channelId) return count;
|
||||
return count + action.count;
|
||||
}, 0);
|
||||
}
|
||||
|
||||
clearRecentUserActions(type: RecentActionType, userId: string, channelId: string) {
|
||||
this.recentActions = this.recentActions.filter(action => {
|
||||
return action.type !== type || action.userId !== userId || action.channelId !== channelId;
|
||||
});
|
||||
}
|
||||
|
||||
clearOldRecentActions() {
|
||||
// TODO: Figure out expiry time from longest interval in the config?
|
||||
const expiryTimestamp = Date.now() - 1000 * 60 * 5;
|
||||
this.recentActions = this.recentActions.filter(action => action.timestamp >= expiryTimestamp);
|
||||
}
|
||||
|
||||
async detectSpam(
|
||||
msg: Message,
|
||||
type: RecentActionType,
|
||||
spamConfig: any,
|
||||
actionCount: number,
|
||||
description: string
|
||||
) {
|
||||
if (actionCount === 0) return;
|
||||
|
||||
this.addRecentAction(type, msg.author.id, msg.channel.id, msg.timestamp, actionCount);
|
||||
const recentMessagesCount = this.getRecentActionCount(
|
||||
type,
|
||||
msg.author.id,
|
||||
msg.channel.id,
|
||||
msg.timestamp - 1000 * spamConfig.interval
|
||||
);
|
||||
|
||||
if (recentMessagesCount > spamConfig.count) {
|
||||
if (spamConfig.clean !== false) {
|
||||
const cleanCount =
|
||||
type === RecentActionType.Message ? spamConfig.count : spamConfig.cleanCount || 20;
|
||||
|
||||
await cleanMessagesInChannel(
|
||||
this.bot,
|
||||
msg.channel as TextChannel,
|
||||
cleanCount,
|
||||
msg.author.id,
|
||||
"Spam detected"
|
||||
);
|
||||
this.logs.log(LogType.SPAM_DELETE, {
|
||||
member: stripObjectToScalars(msg.member, ["user"]),
|
||||
channel: stripObjectToScalars(msg.channel),
|
||||
description,
|
||||
limit: spamConfig.count,
|
||||
interval: spamConfig.interval
|
||||
});
|
||||
}
|
||||
|
||||
if (spamConfig.mute) {
|
||||
const guildData = this.knub.getGuildData(this.guildId);
|
||||
const modActionsPlugin = guildData.loadedPlugins.get("mod_actions") as ModActionsPlugin;
|
||||
if (!modActionsPlugin) return;
|
||||
|
||||
this.logs.ignoreLog(LogType.MEMBER_ROLE_ADD, msg.member.id);
|
||||
await modActionsPlugin.muteMember(
|
||||
msg.member,
|
||||
spamConfig.muteTime ? spamConfig.muteTime * 1000 : 120 * 1000,
|
||||
"Automatic spam detection"
|
||||
);
|
||||
await modActionsPlugin.createCase(
|
||||
msg.member.id,
|
||||
this.bot.user.id,
|
||||
CaseType.Mute,
|
||||
null,
|
||||
"Automatic spam detection",
|
||||
true
|
||||
);
|
||||
this.logs.log(LogType.MEMBER_MUTE_SPAM, {
|
||||
member: stripObjectToScalars(msg.member, ["user"]),
|
||||
channel: stripObjectToScalars(msg.channel),
|
||||
description,
|
||||
limit: spamConfig.count,
|
||||
interval: spamConfig.interval
|
||||
});
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
@d.event("messageCreate")
|
||||
onMessageCreate(msg: Message) {
|
||||
if (msg.author.bot) return;
|
||||
|
||||
const maxMessages = this.configValueForMsg(msg, "max_messages");
|
||||
if (maxMessages) {
|
||||
this.detectSpam(msg, RecentActionType.Message, maxMessages, 1, "too many messages");
|
||||
}
|
||||
|
||||
const maxMentions = this.configValueForMsg(msg, "max_mentions");
|
||||
if (maxMentions && (msg.mentions.length || msg.roleMentions.length)) {
|
||||
this.detectSpam(
|
||||
msg,
|
||||
RecentActionType.Mention,
|
||||
maxMentions,
|
||||
msg.mentions.length + msg.roleMentions.length,
|
||||
"too many mentions"
|
||||
);
|
||||
}
|
||||
|
||||
const maxLinks = this.configValueForMsg(msg, "max_links");
|
||||
if (maxLinks && msg.content) {
|
||||
const links = getUrlsInString(msg.content);
|
||||
this.detectSpam(msg, RecentActionType.Link, maxLinks, links.length, "too many links");
|
||||
}
|
||||
|
||||
const maxAttachments = this.configValueForMsg(msg, "max_attachments");
|
||||
if (maxAttachments && msg.attachments.length) {
|
||||
this.detectSpam(
|
||||
msg,
|
||||
RecentActionType.Attachment,
|
||||
maxAttachments,
|
||||
msg.attachments.length,
|
||||
"too many attachments"
|
||||
);
|
||||
}
|
||||
|
||||
const maxEmoji = this.configValueForMsg(msg, "max_emoji");
|
||||
if (maxEmoji && msg.content) {
|
||||
const emojiCount = getEmojiInString(msg.content).length;
|
||||
this.detectSpam(msg, RecentActionType.Emoji, maxEmoji, emojiCount, "too many emoji");
|
||||
}
|
||||
|
||||
const maxNewlines = this.configValueForMsg(msg, "max_newlines");
|
||||
if (maxNewlines && msg.content) {
|
||||
const newlineCount = (msg.content.match(/\n/g) || []).length;
|
||||
this.detectSpam(
|
||||
msg,
|
||||
RecentActionType.Newline,
|
||||
maxNewlines,
|
||||
newlineCount,
|
||||
"too many newlines"
|
||||
);
|
||||
}
|
||||
|
||||
// TODO: Max duplicates
|
||||
}
|
||||
}
|
|
@ -1,31 +1,43 @@
|
|||
import { Plugin, decorators as d } from "knub";
|
||||
import { Message, TextChannel } from "eris";
|
||||
import { errorMessage } from "../utils";
|
||||
import { Plugin, decorators as d, reply } from "knub";
|
||||
import { Channel, Message, TextChannel, User } from "eris";
|
||||
import { errorMessage, getMessages, stripObjectToScalars, successMessage } from "../utils";
|
||||
import { GuildLogs } from "../data/GuildLogs";
|
||||
import { LogType } from "../data/LogType";
|
||||
|
||||
const MAX_SEARCH_RESULTS = 15;
|
||||
const MAX_CLEAN_COUNT = 50;
|
||||
|
||||
export class UtilityPlugin extends Plugin {
|
||||
protected logs: GuildLogs;
|
||||
|
||||
getDefaultOptions() {
|
||||
return {
|
||||
permissions: {
|
||||
roles: false,
|
||||
level: false
|
||||
level: false,
|
||||
search: false,
|
||||
clean: false,
|
||||
info: false
|
||||
},
|
||||
overrides: [
|
||||
{
|
||||
level: ">0",
|
||||
permissions: {
|
||||
level: true
|
||||
}
|
||||
},
|
||||
{
|
||||
level: ">=50",
|
||||
permissions: {
|
||||
roles: true
|
||||
roles: true,
|
||||
level: true,
|
||||
search: true,
|
||||
clean: true,
|
||||
info: true
|
||||
}
|
||||
}
|
||||
]
|
||||
};
|
||||
}
|
||||
|
||||
onLoad() {
|
||||
this.logs = new GuildLogs(this.guildId);
|
||||
}
|
||||
|
||||
@d.command("roles")
|
||||
@d.permission("roles")
|
||||
async rolesCmd(msg: Message) {
|
||||
|
@ -48,4 +60,125 @@ export class UtilityPlugin extends Plugin {
|
|||
`The permission level of ${member.username}#${member.discriminator} is **${level}**`
|
||||
);
|
||||
}
|
||||
|
||||
@d.command("search", "<query:string$>")
|
||||
@d.permission("search")
|
||||
async searchCmd(msg: Message, args: { query: string }) {
|
||||
const query = args.query.toLowerCase();
|
||||
const matchingMembers = this.guild.members.filter(member => {
|
||||
const fullUsername = `${member.user.username}#${member.user.discriminator}`;
|
||||
if (member.nick && member.nick.toLowerCase().indexOf(query) !== -1) return true;
|
||||
if (fullUsername.toLowerCase().indexOf(query) !== -1) return true;
|
||||
return false;
|
||||
});
|
||||
|
||||
if (matchingMembers.length > 0) {
|
||||
let header;
|
||||
const resultText = matchingMembers.length === 1 ? "result" : "results";
|
||||
|
||||
if (matchingMembers.length > MAX_SEARCH_RESULTS) {
|
||||
header = `Found ${matchingMembers.length} ${resultText} (showing ${MAX_SEARCH_RESULTS})`;
|
||||
} else {
|
||||
header = `Found ${matchingMembers.length} ${resultText}`;
|
||||
}
|
||||
|
||||
const lines = matchingMembers.slice(0, MAX_SEARCH_RESULTS).map(member => {
|
||||
return `${member.user.username}#${member.user.discriminator} (${member.id})`;
|
||||
});
|
||||
lines.sort((a, b) => {
|
||||
return a.toLowerCase() < b.toLowerCase() ? -1 : 1;
|
||||
});
|
||||
|
||||
msg.channel.createMessage(`${header}\n\`\`\`${lines.join("\n")}\`\`\``);
|
||||
} else {
|
||||
msg.channel.createMessage(errorMessage("No results found"));
|
||||
}
|
||||
}
|
||||
|
||||
async cleanMessages(channel: Channel, messageIds: string[], mod: User) {
|
||||
this.logs.ignoreLog(LogType.MESSAGE_DELETE, messageIds[0]);
|
||||
this.logs.ignoreLog(LogType.MESSAGE_DELETE_BULK, messageIds[0]);
|
||||
await this.bot.deleteMessages(channel.id, messageIds);
|
||||
this.logs.log(LogType.CLEAN, {
|
||||
mod: stripObjectToScalars(mod),
|
||||
channel: stripObjectToScalars(channel),
|
||||
count: messageIds.length
|
||||
});
|
||||
}
|
||||
|
||||
@d.command("clean", "<count:number>")
|
||||
@d.command("clean all", "<count:number>")
|
||||
@d.permission("clean")
|
||||
async cleanAllCmd(msg: Message, args: { count: number }) {
|
||||
if (args.count > MAX_CLEAN_COUNT || args.count <= 0) {
|
||||
msg.channel.createMessage(
|
||||
errorMessage(`Clean count must be between 1 and ${MAX_CLEAN_COUNT}`)
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const messagesToClean = await getMessages(
|
||||
msg.channel as TextChannel,
|
||||
m => m.id !== msg.id,
|
||||
args.count
|
||||
);
|
||||
if (messagesToClean.length > 0)
|
||||
await this.cleanMessages(msg.channel, messagesToClean.map(m => m.id), msg.author);
|
||||
|
||||
msg.channel.createMessage(
|
||||
successMessage(
|
||||
`Cleaned ${messagesToClean.length} ${messagesToClean.length === 1 ? "message" : "messages"}`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@d.command("clean user", "<userId:string> <count:number>")
|
||||
@d.permission("clean")
|
||||
async cleanUserCmd(msg: Message, args: { userId: string; count: number }) {
|
||||
if (args.count > MAX_CLEAN_COUNT || args.count <= 0) {
|
||||
msg.channel.createMessage(
|
||||
errorMessage(`Clean count must be between 1 and ${MAX_CLEAN_COUNT}`)
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const messagesToClean = await getMessages(
|
||||
msg.channel as TextChannel,
|
||||
m => m.id !== msg.id && m.author.id === args.userId,
|
||||
args.count
|
||||
);
|
||||
if (messagesToClean.length > 0)
|
||||
await this.cleanMessages(msg.channel, messagesToClean.map(m => m.id), msg.author);
|
||||
|
||||
msg.channel.createMessage(
|
||||
successMessage(
|
||||
`Cleaned ${messagesToClean.length} ${messagesToClean.length === 1 ? "message" : "messages"}`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@d.command("clean bot", "<count:number>")
|
||||
@d.permission("clean")
|
||||
async cleanBotCmd(msg: Message, args: { count: number }) {
|
||||
if (args.count > MAX_CLEAN_COUNT || args.count <= 0) {
|
||||
msg.channel.createMessage(
|
||||
errorMessage(`Clean count must be between 1 and ${MAX_CLEAN_COUNT}`)
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const messagesToClean = await getMessages(
|
||||
msg.channel as TextChannel,
|
||||
m => m.id !== msg.id && m.author.bot,
|
||||
args.count
|
||||
);
|
||||
if (messagesToClean.length > 0)
|
||||
await this.cleanMessages(msg.channel, messagesToClean.map(m => m.id), msg.author);
|
||||
|
||||
msg.channel.createMessage(
|
||||
successMessage(
|
||||
`Cleaned ${messagesToClean.length} ${messagesToClean.length === 1 ? "message" : "messages"}`
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue