violation.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. import { Plugin, ICommandData, Command, Event, BotEventData } from "src/model/plugin";
  2. import { parseArgs, parseDuration, UNIT_MEASURES, isAuthorisedAsync } from "src/util";
  3. import { GuildMember, Guild, MessageEmbed, Message, TextChannel, PartialGuildMember, User } from "discord.js";
  4. import { eventLogger, logger } from "src/logging";
  5. import { client } from "src/client";
  6. import humanizeDuration from "humanize-duration";
  7. import { getRepository, ObjectType, FindConditions, DeepPartial } from "typeorm";
  8. import { GuildViolationSettings } from "@shared/db/entity/GuildViolationSettings";
  9. import { Mute, Violation } from "@shared/db/entity/Violation";
  10. import { scheduleJob, Job, rescheduleJob } from "node-schedule";
  11. import { QueryDeepPartialEntity } from "typeorm/query-builder/QueryPartialEntity";
  12. import { tryDo, Option } from "@shared/common/async_utils";
  13. const MENTION_PATTERN = /<@!?(\d+)>/;
  14. interface ViolationInfo {
  15. member: GuildMember;
  16. endDate: Date;
  17. duration: number;
  18. guild: Guild;
  19. reason: string;
  20. settings: GuildViolationSettings;
  21. dryRun: boolean;
  22. noAnnounce: boolean;
  23. }
  24. type TimedViolation = Violation & { endsAt: Date };
  25. type ModifyViolationFunction = (member: GuildMember | PartialGuildMember, settings: GuildViolationSettings, violation: DeepPartial<TimedViolation>) => DeepPartial<TimedViolation>;
  26. type StartViolationFunction = (member: GuildMember | PartialGuildMember, settings: GuildViolationSettings, violation: TimedViolation) => Promise<void>;
  27. type StopViolationFunction = (guild: Guild, userId: string, settings: GuildViolationSettings, violation: TimedViolation) => Promise<void>;
  28. interface TimedViolationStopHandler {
  29. type: ObjectType<TimedViolation>;
  30. start: StartViolationFunction;
  31. stop: StopViolationFunction;
  32. modify?: ModifyViolationFunction;
  33. command: string;
  34. }
  35. @Plugin
  36. export class ViolationPlugin {
  37. jobs: Record<number, Job> = {};
  38. timedViolationHandlers: TimedViolationStopHandler[] = [
  39. {
  40. command: "mute",
  41. type: Mute,
  42. start: async (member: GuildMember | PartialGuildMember, settings: GuildViolationSettings, violation: TimedViolation): Promise<void> => {
  43. const muteRoleResolve = await tryDo(member.guild.roles.fetch(settings.muteRoleId));
  44. if (!muteRoleResolve.ok || !muteRoleResolve.result) {
  45. logger.error(
  46. "mute: Tried to mute user %s#%s (%s) but mute role ID %s is invalid!",
  47. member.user?.username,
  48. member.user?.discriminator,
  49. member.user?.id,
  50. settings.muteRoleId);
  51. return;
  52. }
  53. // First mute, then remove other roles
  54. await member.roles.add(muteRoleResolve.result);
  55. const mute = violation as Mute;
  56. if (mute.previousRoles) {
  57. const result = await tryDo(member.roles.remove(mute.previousRoles));
  58. if (!result.ok) {
  59. logger.error("mute: couldn't remove all roles from user %s#%s (%s)!" ,
  60. member.user?.username,
  61. member.user?.discriminator,
  62. member.user?.id);
  63. }
  64. }
  65. },
  66. stop: async (guild: Guild, userId: string, settings: GuildViolationSettings, violation: TimedViolation): Promise<void> => {
  67. const muteRoleResolve = await tryDo(guild.roles.fetch(settings.muteRoleId));
  68. if (!muteRoleResolve.ok || !muteRoleResolve.result) {
  69. logger.warn("mute: couldn't find mute role id %s (removed from server?)", settings.muteRoleId);
  70. return;
  71. }
  72. const muteRole = muteRoleResolve.result;
  73. const memberResolve = await tryDo(guild.members.fetch(userId));
  74. if (!memberResolve.ok) {
  75. logger.warn("mute: user %s is not on the server anymore", userId);
  76. return;
  77. }
  78. await memberResolve.result.roles.remove(muteRole);
  79. const mute = violation as Mute;
  80. if (mute.previousRoles) {
  81. const result = await tryDo(memberResolve.result.roles.add(mute.previousRoles));
  82. if (!result.ok) {
  83. logger.warn("mute: couldn't readd all roles for user %s (tried to restore role ids: %s)", memberResolve.result.id, mute.previousRoles.join(", "));
  84. }
  85. }
  86. },
  87. modify: (member: GuildMember | PartialGuildMember, settings: GuildViolationSettings, violation: DeepPartial<Mute>): DeepPartial<Mute> => {
  88. const originalRoles = member.roles.cache.keyArray().filter(r => r != settings.muteRoleId);
  89. violation.previousRoles = originalRoles;
  90. return violation;
  91. }
  92. }
  93. ];
  94. async start(): Promise<void> {
  95. for (const handler of this.timedViolationHandlers) {
  96. const repo = getRepository(handler.type);
  97. const validViolations = await repo.find({
  98. where: { valid: true }
  99. });
  100. for (const violation of validViolations) {
  101. const stopJob = this.scheduleRemoveViolation(handler.type, violation.guildId, violation.userId, handler.stop, handler.command);
  102. if (violation.endsAt <= new Date())
  103. await stopJob();
  104. else
  105. this.jobs[violation.id] = scheduleJob(violation.endsAt, stopJob);
  106. }
  107. }
  108. }
  109. @Event("guildMemberAdd")
  110. async onUserJoin(data: BotEventData, member: GuildMember | PartialGuildMember): Promise<void> {
  111. const settingsRepo = getRepository(GuildViolationSettings);
  112. const settings = await settingsRepo.findOne(member.guild.id);
  113. if (!settings)
  114. return;
  115. const hasActiveViolations = await getRepository(Violation).findOne({
  116. where: {
  117. guildId: member.guild.id,
  118. userId: member.id,
  119. valid: true
  120. }
  121. });
  122. if (!hasActiveViolations)
  123. return;
  124. for (const handler of this.timedViolationHandlers) {
  125. const repo = getRepository(handler.type);
  126. const activeViolations = await repo.find({
  127. where: {
  128. guildId: member.guild.id,
  129. userId: member.id,
  130. valid: true
  131. }
  132. });
  133. if (activeViolations.length == 0)
  134. continue;
  135. for (const violation of activeViolations) {
  136. if (violation.endsAt < new Date())
  137. await repo.update({ id: violation.id }, { valid: false });
  138. else
  139. await handler.start(member, settings, violation);
  140. }
  141. }
  142. }
  143. @Command({
  144. type: "prefix",
  145. pattern: "mute",
  146. auth: true,
  147. documentation: {
  148. example: "mute[?!] <user> [<duration>] [<reason>]",
  149. description: "Mutes for a given duration and reason. ? = dry run, ! = no announcement"
  150. }
  151. })
  152. async muteUser({ message }: ICommandData): Promise<void> {
  153. await tryDo(message.delete());
  154. const info = await this.parseCommand(message, "mute");
  155. if (!info.ok)
  156. return;
  157. const handler = this.getViolationHandler(Mute);
  158. if (!handler) {
  159. logger.error("Couldn't find handler for Mute");
  160. return;
  161. }
  162. if (!info.dryRun) {
  163. eventLogger.warn("User %s#%s muted user %s#%s for %s because: %s", message.author.username, message.author.discriminator, info.member.user.username, info.member.user.discriminator, info.duration, info.reason);
  164. }
  165. await this.applyTimedViolation(Mute, info, "mute", handler.start, handler.stop, handler.modify);
  166. await this.sendViolationMessage(message, info, "User has been muted for server violation");
  167. }
  168. @Command({
  169. type: "prefix",
  170. pattern: "unmute",
  171. auth: true,
  172. documentation: {
  173. example: "unmute <user>",
  174. description: "Unmutes user"
  175. }
  176. })
  177. async unmuteUser({ message }: ICommandData): Promise<void> {
  178. await tryDo(message.delete());
  179. await this.removeTimedViolation(Mute, message, "mute");
  180. }
  181. private getViolationHandler(type: ObjectType<TimedViolation>): TimedViolationStopHandler {
  182. for (const handler of this.timedViolationHandlers) {
  183. if (handler.type == type)
  184. return handler;
  185. }
  186. throw new Error("Couldn't find handler for violation type!");
  187. }
  188. private async removeTimedViolation<T extends TimedViolation>(type: ObjectType<T>, message: Message, command = "violation") {
  189. if (!message.guild) {
  190. await message.reply("cannot do in DMs!");
  191. return;
  192. }
  193. const settingsRepo = getRepository(GuildViolationSettings);
  194. const settings = await settingsRepo.findOne(message.guild.id);
  195. if (!settings) {
  196. message.reply("this guild doesn't have violation settings set up!");
  197. return;
  198. }
  199. const [, userId] = parseArgs(message.content);
  200. if (!userId) {
  201. await message.reply("no user specified!");
  202. return;
  203. }
  204. if (userId == message.author.id) {
  205. await message.reply(`cannot ${command} yourself!`);
  206. return;
  207. }
  208. const user = await this.resolveUser(userId);
  209. if (!user) {
  210. await message.reply("couldn't find the given user!");
  211. logger.error("Tried to un-%s user %s but couldn't find them by id!", command, userId);
  212. return;
  213. }
  214. const violationRepo = getRepository(type);
  215. const existingViolation = await violationRepo.findOne({
  216. where: {
  217. guildId: message.guild.id,
  218. userId: user.id,
  219. valid: true
  220. }
  221. });
  222. if (!existingViolation) {
  223. await message.reply(`user has no existing active ${command}s in the DB!`);
  224. return;
  225. }
  226. await violationRepo.update({ id: existingViolation.id } as unknown as FindConditions<T>, { valid: false } as unknown as QueryDeepPartialEntity<T>);
  227. delete this.jobs[existingViolation.id];
  228. const handler = this.getViolationHandler(type);
  229. await handler.stop(message.guild, user.id, settings, existingViolation);
  230. await message.reply(`removed ${command} on user!`);
  231. }
  232. private async applyTimedViolation<T extends TimedViolation>(type: ObjectType<T>, info: ViolationInfo, command = "violation", apply: StartViolationFunction, remove: StopViolationFunction, modify?: ModifyViolationFunction) {
  233. if (info.dryRun)
  234. return;
  235. const violationRepo = getRepository(type);
  236. const existingViolation = await violationRepo.findOne({
  237. where: {
  238. userId: info.member.id,
  239. guildId: info.guild.id,
  240. valid: true
  241. }
  242. });
  243. let appliedViolation: T;
  244. if (existingViolation) {
  245. logger.warn("%s: trying to reapply on user %s#%s (%s)", command, info.member.user.username, info.member.user.discriminator, info.member.id);
  246. await violationRepo.update({ id: existingViolation.id } as unknown as FindConditions<T>, { endsAt: info.endDate } as unknown as QueryDeepPartialEntity<T>);
  247. const job = this.jobs[existingViolation.id];
  248. rescheduleJob(job, info.endDate);
  249. appliedViolation = existingViolation;
  250. } else {
  251. let rawViolation: DeepPartial<TimedViolation> = {
  252. guildId: info.guild.id,
  253. userId: info.member.id,
  254. reason: info.reason,
  255. endsAt: info.endDate,
  256. valid: true,
  257. };
  258. if (modify) {
  259. rawViolation = modify(info.member, info.settings, rawViolation);
  260. }
  261. const newViolation = await violationRepo.save(rawViolation as unknown as DeepPartial<T>);
  262. this.jobs[newViolation.id] = scheduleJob(info.endDate, this.scheduleRemoveViolation(type, info.guild.id, info.member.id, remove, command));
  263. appliedViolation = newViolation;
  264. }
  265. await apply(info.member, info.settings, appliedViolation);
  266. }
  267. private scheduleRemoveViolation<T extends TimedViolation>(type: ObjectType<T>, guildId: string, userId: string, handle: StopViolationFunction, command = "violation") {
  268. return async () => {
  269. const settingsRepo = getRepository(GuildViolationSettings);
  270. const settings = await settingsRepo.findOne(guildId);
  271. if (!settings) {
  272. logger.warn("un-%s: no violation settings found for guild %s", command, guildId);
  273. return;
  274. }
  275. const repo = getRepository(type);
  276. const violation = await repo.findOne({
  277. where: {
  278. guildId: guildId,
  279. userId: userId,
  280. valid: true
  281. }
  282. });
  283. if (!violation) {
  284. logger.warn("un-%s: no violation found for user ID %s in guild %s", command, userId, guildId);
  285. return;
  286. }
  287. await repo.update({ id: violation.id } as unknown as FindConditions<T>, { valid: false } as unknown as QueryDeepPartialEntity<T>);
  288. delete this.jobs[violation.id];
  289. const guild = client.bot.guilds.resolve(guildId);
  290. if (!guild) {
  291. logger.warn("un-%s: couldn't find guild %s", command, guildId);
  292. return;
  293. }
  294. await handle(guild, userId, settings, violation);
  295. };
  296. }
  297. private async resolveUser(id: string): Promise<User | undefined> {
  298. const result = MENTION_PATTERN.exec(id);
  299. if (result) {
  300. const userId = result[1];
  301. const fetchResult = await tryDo(client.bot.users.fetch(userId));
  302. if (fetchResult.ok)
  303. return fetchResult.result;
  304. }
  305. const fetchResult = await tryDo(client.bot.users.fetch(id));
  306. if (!fetchResult.ok)
  307. return undefined;
  308. return fetchResult.result;
  309. }
  310. private async parseCommand(message: Message, command = "violation"): Promise<Option<ViolationInfo>> {
  311. if (!message.guild) {
  312. await message.reply("cannot do in DMs!");
  313. return { ok: false };
  314. }
  315. const violationSettingsRepo = getRepository(GuildViolationSettings);
  316. const settings = await violationSettingsRepo.findOne(message.guild.id);
  317. if (!settings) {
  318. await message.reply("sorry, this server doesn't have violation settings set up.");
  319. logger.error(
  320. "%s was called in guild %s (%s) on user %s which doesn't have config set up!",
  321. command,
  322. message.guild.name,
  323. message.guild.id,
  324. message.author.id);
  325. return { ok: false };
  326. }
  327. const [directive, userId, duration, ...rest] = parseArgs(message.content);
  328. const dryRun = directive.endsWith("?");
  329. const noAnnounce = directive.endsWith("!");
  330. if (!userId) {
  331. await message.reply("no user specified!");
  332. return { ok: false };
  333. }
  334. const user = await this.resolveUser(userId);
  335. if (!user) {
  336. await message.reply("couldn't find the given user!");
  337. logger.error("Tried to %s user %s but couldn't find them by id!", command, userId);
  338. return { ok: false };
  339. }
  340. if (user.id == message.author.id) {
  341. await message.reply(`cannot ${command} yourself!`);
  342. return { ok: false };
  343. }
  344. if (user.id == client.botUser.id) {
  345. await message.reply(`cannot apply ${command} on me!`);
  346. return { ok: false };
  347. }
  348. const memberResolve = await tryDo(message.guild.members.fetch(user));
  349. if (!memberResolve.ok) {
  350. await message.reply("user is not member of the server anymore!");
  351. logger.error("Tried to %s user %s but they are not on the server anymore!", command, userId);
  352. return { ok: false };
  353. }
  354. if (await isAuthorisedAsync(memberResolve.result)) {
  355. await message.reply(`cannot apply ${command} on another moderator!`);
  356. return { ok: false };
  357. }
  358. let durationMs = parseDuration(duration);
  359. let reasonArray = rest;
  360. if (!durationMs) {
  361. durationMs = UNIT_MEASURES.d as number;
  362. reasonArray = [duration, ...reasonArray];
  363. }
  364. const endDate = new Date(Date.now() + durationMs);
  365. let reason = reasonArray.join(" ");
  366. if (!reason)
  367. reason = "None given";
  368. return {
  369. ok: true,
  370. duration: durationMs,
  371. endDate: endDate,
  372. guild: message.guild,
  373. member: memberResolve.result,
  374. reason: reason,
  375. settings: settings,
  376. dryRun: dryRun,
  377. noAnnounce: noAnnounce
  378. };
  379. }
  380. private async sendViolationMessage(message: Message, info: ViolationInfo, title: string) {
  381. let announceChannel: TextChannel | null = null;
  382. if ((info.noAnnounce || info.dryRun) && message.channel.type == "text") {
  383. announceChannel = message.channel;
  384. }
  385. else if (info.settings.violationInfoChannelId) {
  386. const ch = info.guild.channels.resolve(info.settings.violationInfoChannelId);
  387. if (ch && ch.type == "text")
  388. announceChannel = ch as TextChannel;
  389. else if (message.channel.type == "text") {
  390. announceChannel = message.channel;
  391. }
  392. }
  393. await announceChannel?.send(new MessageEmbed({
  394. title: `${info.dryRun ? "[DRY RUN] " : ""}${title}`,
  395. color: 4944347,
  396. timestamp: new Date(),
  397. footer: {
  398. text: client.botUser.username
  399. },
  400. author: {
  401. name: client.botUser.username,
  402. iconURL: client.botUser.avatarURL() ?? undefined
  403. },
  404. fields: [
  405. {
  406. name: "Username",
  407. value: info.member.toString()
  408. },
  409. {
  410. name: "Duration",
  411. value: humanizeDuration(info.duration, { unitMeasures: UNIT_MEASURES })
  412. },
  413. {
  414. name: "Reason",
  415. value: info.reason
  416. }
  417. ]
  418. }));
  419. }
  420. }