violation.ts 17 KB

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