y21

Untitled

y21
Nov 12th, 2020
1,765
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const messagesKv = new pylon.KVNamespace('messages');
  2.  
  3. const MAX_VALUE_LENGTH = 1024 * 8;
  4. const MAX_ENTRIES_PER_KEY = 22;
  5.  
  6. type Maybe<T> = T | undefined;
  7. type TransactCallback = (arr: Maybe<string[]>) => string[];
  8. type HandlerCallback<T> = (arr: string[], id: T) => string[];
  9.  
  10. namespace handlers {
  11.   export function wrap<T>(fn: HandlerCallback<T>, id: T): TransactCallback {
  12.     return (arr) => {
  13.       if (!arr) return [];
  14.  
  15.       return fn(arr, id);
  16.     };
  17.   }
  18.  
  19.   export function add(arr: string[], id: string): string[] {
  20.     return arr.slice(-(MAX_VALUE_LENGTH / MAX_ENTRIES_PER_KEY)).concat(id);
  21.   }
  22.  
  23.   export function remove(arr: string[], id: string): string[] {
  24.     return arr.filter((x) => x !== id);
  25.   }
  26.  
  27.   export function removeAll(arr: string[], ids: string[]): string[] {
  28.     return arr.filter((x) => !ids.includes(x));
  29.   }
  30. }
  31.  
  32. discord.on(discord.Event.MESSAGE_CREATE, async (message) => {
  33.   await messagesKv.transact<string[]>(message.channelId, handlers.wrap(handlers.add, message.id));
  34. });
  35.  
  36. discord.on(discord.Event.MESSAGE_DELETE, async (message) => {
  37.   await messagesKv.transact<string[]>(message.channelId, handlers.wrap(handlers.remove, message.id));
  38. });
  39.  
  40. commands.on(
  41.   {
  42.     name: 'purge',
  43.     filters: discord.command.filters.canManageMessages()
  44.   },
  45.   (args) => ({
  46.     channel: args.guildTextChannel(),
  47.     count: args.number()
  48.   }),
  49.   async (message, { channel, count }) => {
  50.     const messages = await messagesKv
  51.       .get<string[]>(channel.id)
  52.       .then((x) => x?.slice(-count));
  53.  
  54.     if (!messages) return message.reply('no messages found');
  55.  
  56.     if (messages.length < 2 || messages.length > 100)
  57.       return message.reply(
  58.         `invalid count (expected >= 2 and <= 100; got=${messages.length})`
  59.       );
  60.  
  61.     await channel.bulkDeleteMessages(messages);
  62.     await messagesKv.transact<string[]>(channel.id, handlers.wrap(handlers.removeAll, messages));
  63.  
  64.     await message.reply(`ok, purged ${messages.length} messages..`);
  65.   }
  66. );
  67.  
RAW Paste Data