aboutsummaryrefslogtreecommitdiff
path: root/src/utils/loading-message.ts
blob: 53a2aed9cb12fb107c4820565eb5e330f6763814 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import {TextChannel, Message, MessageReaction} from 'discord.js';
import delay from 'delay';

const INITAL_DELAY = 500;
const PERIOD = 500;

export default class {
  public isStopped = true;
  private readonly channel: TextChannel;
  private readonly text: string;
  private msg!: Message;

  constructor(channel: TextChannel, text = 'cows! count \'em') {
    this.channel = channel;
    this.text = text;
  }

  async start(): Promise<void> {
    this.msg = await this.channel.send(this.text);

    const icons = ['🐮', '🐴', '🐄'];

    const reactions: MessageReaction[] = [];

    let i = 0;
    let isRemoving = false;

    this.isStopped = false;

    (async () => {
      await delay(INITAL_DELAY);

      while (!this.isStopped) {
        if (reactions.length === icons.length) {
          isRemoving = true;
        }

        // eslint-disable-next-line no-await-in-loop
        await delay(PERIOD);

        if (isRemoving) {
          const reactionToRemove = reactions.shift();

          if (reactionToRemove) {
            // eslint-disable-next-line no-await-in-loop
            await reactionToRemove.users.remove(this.msg.client.user!.id);
          } else {
            isRemoving = false;
          }
        } else {
          if (!this.isStopped) {
            // eslint-disable-next-line no-await-in-loop
            reactions.push(await this.msg.react(icons[i % icons.length]));
          }

          i++;
        }
      }
    })();
  }

  async stop(str = 'u betcha'): Promise<Message> {
    const wasAlreadyStopped = this.isStopped;

    this.isStopped = true;

    const editPromise = str ? this.msg.edit(str) : null;
    const reactPromise = str && !wasAlreadyStopped ? (async () => {
      await this.msg.fetch();
      await Promise.all(this.msg.reactions.cache.map(async react => {
        if (react.me) {
          await react.users.remove(this.msg.client.user!.id);
        }
      }));
    })() : null;

    await Promise.all([editPromise, reactPromise]);

    return this.msg;
  }
}