violation.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. import { Plugin, ICommandData, Command, Event, BotEventData } from "src/model/plugin";
  2. import { parseArgs, tryDo, parseDuration, UNIT_MEASURES, Option } from "src/util";
  3. import { GuildMember, Guild, MessageEmbed, Message, TextChannel, PartialGuildMember } 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. })
  122. async muteUser({ message }: ICommandData): Promise<void> {
  123. const info = await this.parseCommand(message);
  124. if (!info.ok)
  125. return;
  126. const handler = this.getViolationHandler(Mute);
  127. if (!handler) {
  128. logger.error("Couldn't find handler for Mute");
  129. return;
  130. }
  131. await this.applyTimedViolation(Mute, info, "mute", handler.start, handler.stop);
  132. await this.sendViolationMessage(message, info, "User has been muted for server violation");
  133. }
  134. private getViolationHandler(type: ObjectType<TimedViolation>): TimedViolationStopHandler {
  135. for (const handler of this.timedViolationHandlers) {
  136. if (handler.type == type)
  137. return handler;
  138. }
  139. throw new Error("Couldn't find handler for violation type!");
  140. }
  141. private async applyTimedViolation<T extends TimedViolation>(type: ObjectType<T>, info: ViolationInfo, command = "violation", apply: StartViolationFunction, remove: StopViolationFunction) {
  142. if (info.dryRun)
  143. return;
  144. const violationRepo = getRepository(type);
  145. const existingViolation = await violationRepo.findOne({
  146. where: {
  147. userId: info.member.id,
  148. guildId: info.guild.id,
  149. valid: true
  150. }
  151. });
  152. if (existingViolation) {
  153. logger.warn("%s: trying to reapply on user %s#%s (%s)", command, info.member.user.username, info.member.user.discriminator, info.member.id);
  154. await violationRepo.update({ id: existingViolation.id } as unknown as FindConditions<T>, { endsAt: info.endDate } as unknown as QueryDeepPartialEntity<T>);
  155. const job = this.jobs[existingViolation.id];
  156. rescheduleJob(job, info.endDate);
  157. } else {
  158. const newViolation = await violationRepo.save({
  159. guildId: info.guild.id,
  160. userId: info.member.id,
  161. reason: info.reason,
  162. endsAt: info.endDate,
  163. valid: true,
  164. } as unknown as DeepPartial<T>);
  165. this.jobs[newViolation.id] = scheduleJob(info.endDate, this.scheduleRemoveViolation(type, info.guild.id, info.member.id, remove, command));
  166. }
  167. await apply(info.member, info.settings);
  168. }
  169. private scheduleRemoveViolation<T extends TimedViolation>(type: ObjectType<T>, guildId: string, userId: string, handle: StopViolationFunction, command = "violation") {
  170. return async () => {
  171. const settingsRepo = getRepository(GuildViolationSettings);
  172. const settings = await settingsRepo.findOne(guildId);
  173. if (!settings) {
  174. logger.warn("un-%s: no violation settings found for guild %s", command, guildId);
  175. return;
  176. }
  177. const repo = getRepository(type);
  178. const violation = await repo.findOne({
  179. where: {
  180. guildId: guildId,
  181. userId: userId,
  182. valid: true
  183. }
  184. });
  185. if (!violation) {
  186. logger.warn("un-%s: no violation found for user ID %s in guild %s", command, userId, guildId);
  187. return;
  188. }
  189. await repo.update({ id: violation.id } as unknown as FindConditions<T>, { valid: false } as unknown as QueryDeepPartialEntity<T>);
  190. delete this.jobs[violation.id];
  191. const guild = client.bot.guilds.resolve(guildId);
  192. if (!guild) {
  193. logger.warn("un-%s: couldn't find guild %s", command, guildId);
  194. return;
  195. }
  196. await handle(guild, userId, settings);
  197. };
  198. }
  199. private async resolveUser(guild: Guild, id: string): Promise<GuildMember | undefined> {
  200. const result = MENTION_PATTERN.exec(id);
  201. if (result) {
  202. const userId = result[1];
  203. const fetchResult = await tryDo(guild.members.fetch(userId));
  204. if (fetchResult.ok)
  205. return fetchResult.result;
  206. }
  207. const fetchResult = await tryDo(guild.members.fetch(id));
  208. if (!fetchResult.ok)
  209. return undefined;
  210. return fetchResult.result;
  211. }
  212. private async parseCommand(message: Message, command = "violation"): Promise<Option<ViolationInfo>> {
  213. if (!message.guild) {
  214. await message.reply("cannot do in DMs!");
  215. return { ok: false };
  216. }
  217. const violationSettingsRepo = getRepository(GuildViolationSettings);
  218. const settings = await violationSettingsRepo.findOne(message.guild.id);
  219. if (!settings) {
  220. await message.reply("sorry, this server doesn't have violation settings set up.");
  221. logger.error(
  222. "%s was called in guild %s (%s) on user %s which doesn't have config set up!",
  223. command,
  224. message.guild.name,
  225. message.guild.id,
  226. message.author.id);
  227. return { ok: false };
  228. }
  229. const [directive, userId, duration, ...rest] = parseArgs(message.content);
  230. const dryRun = directive.endsWith("?");
  231. const noAnnounce = directive.endsWith("!");
  232. if (!userId) {
  233. await message.reply("no user specified!");
  234. return { ok: false };
  235. }
  236. if (userId == message.author.id) {
  237. await message.reply(`cannot ${command} yourself!`);
  238. return { ok: false };
  239. }
  240. const member = await this.resolveUser(message.guild, userId);
  241. if (!member) {
  242. await message.reply("couldn't find the given user!");
  243. logger.error("Tried to %s user %s but couldn't find them by id!", command, userId);
  244. return { ok: false };
  245. }
  246. let durationMs = parseDuration(duration);
  247. let reasonArray = rest;
  248. if (!durationMs) {
  249. durationMs = UNIT_MEASURES.d as number;
  250. reasonArray = [duration, ...reasonArray];
  251. }
  252. const endDate = new Date(Date.now() + durationMs);
  253. let reason = reasonArray.join(" ");
  254. if (!reason)
  255. reason = "None given";
  256. return {
  257. ok: true,
  258. duration: durationMs,
  259. endDate: endDate,
  260. guild: message.guild,
  261. member: member,
  262. reason: reason,
  263. settings: settings,
  264. dryRun: dryRun,
  265. noAnnounce: noAnnounce
  266. };
  267. }
  268. private async sendViolationMessage(message: Message, info: ViolationInfo, title: string) {
  269. let announceChannel: TextChannel | null = null;
  270. if ((info.noAnnounce || info.dryRun) && message.channel.type == "text") {
  271. announceChannel = message.channel;
  272. }
  273. else if (info.settings.violationInfoChannelId) {
  274. const ch = info.guild.channels.resolve(info.settings.violationInfoChannelId);
  275. if (ch && ch.type == "text")
  276. announceChannel = ch as TextChannel;
  277. else if (message.channel.type == "text") {
  278. announceChannel = message.channel;
  279. }
  280. }
  281. await announceChannel?.send(new MessageEmbed({
  282. title: `${info.dryRun ? "[DRY RUN] " : ""}${title}`,
  283. color: 4944347,
  284. timestamp: new Date(),
  285. footer: {
  286. text: client.botUser.username
  287. },
  288. author: {
  289. name: client.botUser.username,
  290. iconURL: client.botUser.avatarURL() ?? undefined
  291. },
  292. fields: [
  293. {
  294. name: "Username",
  295. value: info.member.toString()
  296. },
  297. {
  298. name: "Duration",
  299. value: humanizeDuration(info.duration, { unitMeasures: UNIT_MEASURES })
  300. },
  301. {
  302. name: "Reason",
  303. value: info.reason
  304. }
  305. ]
  306. }));
  307. }
  308. }