violation.ts 19 KB

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