summary refs log tree commit diff homepage
path: root/src/Discord.ts
blob: caf89964cd0e0fe85596cd53b227249f6e4bd2df (plain) (blame)
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
import { Client, Intents, Message, TextChannel, User } from 'discord.js'

import emojiStrip from 'emoji-strip'

import type { Config } from './Config'

import Rcon from './Rcon'
import DiscordWebhooks from './DiscordWebhooks'
import { escapeUnicode } from './lib/util'

class Discord {
  config: Config
  client: Client
  webhookClient: DiscordWebhooks | null

  channel: TextChannel | null

  mentionCache: Map<string, User>

  constructor (config: Config, onReady?: () => void) {
    this.config = config

    this.client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] })
    if (onReady) this.client.once('ready', () => onReady())
    this.client.on('messageCreate', (message: Message) => this.onMessage(message))

    this.webhookClient = null

    this.channel = null

    this.mentionCache = new Map()
  }

  public async init () {
    try {
      await this.client.login(this.config.DISCORD_TOKEN)
    } catch (e) {
      console.log('[ERROR] Could not authenticate with Discord: ' + e)
      if (this.config.DEBUG) console.error(e)
      process.exit(1)
    }

    if (this.config.USE_WEBHOOKS) {
      this.webhookClient = new DiscordWebhooks(this.config)
      this.webhookClient.init()
    }

    if (this.config.DISCORD_CHANNEL_ID) {
      const channel = await this.client.channels.fetch(this.config.DISCORD_CHANNEL_ID) as TextChannel
      if (!channel) {
        console.log(`[INFO] Could not find channel with ID ${this.config.DISCORD_CHANNEL_ID}. Please check that the ID is correct and that the bot has access to it.`)
        process.exit(1)
      }
      this.channel = channel
    }

    if (this.channel) {
      console.log(`[INFO] Using channel #${this.channel.name} (id: ${this.channel.id}) in the server "${this.channel.guild.name}"`)
    }
  }

  private async onMessage (message: Message) {
    // no channel, done
    if (!this.channel) return
    // don't want to check other channels
    if (message.channel.id !== this.channel.id || message.channel.type !== 'GUILD_TEXT') return
    // if using webhooks, ignore this!
    if (message.webhookId) {
      // backwards compatability with older config
      if (this.config.USE_WEBHOOKS && this.config.IGNORE_WEBHOOKS === undefined) return

      // if ignoring all webhooks, ignore
      if (this.config.IGNORE_WEBHOOKS) {
        return
      } else if (this.config.USE_WEBHOOKS) {
        // otherwise, ignore all webhooks that are not the same as this one
        if (this.webhookClient!.id === message.webhookId) {
          if (this.config.DEBUG) console.log('[DEBUG] Ignoring webhook from self')
          return
        }
      }
    }
    // ensure that the message has a sender
    if (!message.author) return
    // ensure that the message is a text message
    if (message.type !== 'DEFAULT') return
    // if the same user as the bot, ignore
    if (message.author.id === this.client.user?.id) return
    // ignore any attachments
    if (message.attachments.size) return
    
    const command = this.buildMinecraftCommand(message)
    
    if (command) {
      if (this.config.DEBUG) console.log(`[DEBUG] Sending command "${command}" to the server`)

      const rcon = new Rcon(this.config.MINECRAFT_SERVER_RCON_IP, this.config.MINECRAFT_SERVER_RCON_PORT, this.config.DEBUG)
      try {
        await rcon.auth(this.config.MINECRAFT_SERVER_RCON_PASSWORD)
      } catch (e) {
        console.log('[ERROR] Could not auth with the server!')
        if (this.config.DEBUG) console.error(e)
      }

      let response: string | undefined;
      try {
        response = await rcon.command(command)
      } catch (e) {
        console.log('[ERROR] Could not send command!')
        if (this.config.DEBUG) console.error(e)
      }

      if (response?.startsWith('Unknown command') || response?.startsWith('Unknown or incomplete command')) {
        console.log('[ERROR] Could not send command! (Unknown command)')
        if (command.startsWith('tellraw')) {
          console.log('[INFO] Your Minecraft version may not support tellraw, please check MINECRAFT_TELLRAW_DOESNT_EXIST in the README')
        }
      }

      rcon.close()
    }
  }

  private buildMinecraftCommand (message: Message) {
    if (this.config.ALLOW_SLASH_COMMANDS && this.config.SLASH_COMMAND_ROLES_IDS && message.cleanContent.startsWith('/') && message.member) {
      const hasSlashCommandRole = this.config.SLASH_COMMAND_ROLES_IDS.some(id => message.member?.roles.cache.get(id))
      if (hasSlashCommandRole) {
        // send the raw command, can be dangerous...
        return message.cleanContent
      } else {
        const { username, discriminator } = message.author
        console.log(`[INFO] User ${username}#${discriminator} attempted to send a slash command without a role`)
        return
      }
    }

    const username = emojiStrip(message.author.username)

    let messageContent = message.cleanContent
    messageContent = messageContent.replace('@\u200b', '@')
    messageContent = emojiStrip(messageContent)

    const variables: {[index: string]: string} = {
      username,
      nickname: !!message.member?.nickname ? emojiStrip(message.member.nickname) : username,
      discriminator: message.author.discriminator,
      text: messageContent,
    }

    if (this.config.MINECRAFT_TELLRAW_DOESNT_EXIST) {
      const sayMessage = this.config.MINECRAFT_TELLRAW_DOESNT_EXIST_SAY_TEMPLATE
        .replace(/%username%/g, variables.username)
        .replace(/%nickname%/g, variables.nickname)
        .replace(/%discriminator%/g, variables.discriminator)
        .replace(/%message%/g, variables.text)
      return `say ${sayMessage}`
    }

    for (const [k, v] of Object.entries(variables)) {
      // use JSON to encode the strings for tellraw
      const stringified = JSON.stringify(v).slice(1, -1)
      // encode unicode characters for all fields
      variables[k] = escapeUnicode(stringified)
    }

    const tellrawComponent = this.config.MINECRAFT_TELLRAW_TEMPLATE
      .replace(/%username%/g, variables.username)
      .replace(/%nickname%/g, variables.nickname)
      .replace(/%discriminator%/g, variables.discriminator)
      .replace(/%message%/g, variables.text)
    return `tellraw @a ${tellrawComponent}`
  }

  private async replaceDiscordMentions(message: string): Promise<string> {
    const possibleMentions = message.match(/@[^#\s]*[#]?[0-9]{4}/gim)
    if (possibleMentions) {
      for (let mention of possibleMentions) {
        const mentionParts = mention.split('#')
        let username = mentionParts[0].replace('@', '')
        if (mentionParts.length > 1) {
          if (this.config.ALLOW_USER_MENTIONS) {
            let user = this.mentionCache.get(mention)
            if (!user) {
              // try fetching members by username to update cache
              await this.channel!.guild.members.fetch({ query: username })
              user = this.client.users.cache.find(user => user.username === username && user.discriminator === mentionParts[1])
            }

            if (user) {
              message = message.replace(mention, '<@' + user.id + '>')
              if (!this.mentionCache.has(mention)) this.mentionCache.set(mention, user)
            } else {
              console.log(`[ERROR] Could not find user by mention: "${mention}"`)
            }
          }
        }
      }
    }

    if (!this.config.ALLOW_HERE_EVERYONE_MENTIONS) {
      message = message
        .replace('@everyone', '@ everyone')
        .replace('@here', '@ here')
    }

    return message
  }

  private makeDiscordMessage(username: string, message: string) {
    return this.config.DISCORD_MESSAGE_TEMPLATE
      .replace('%username%', username)
      .replace('%message%', message)
  }

  public async sendMessage (username: string, message: string) {
    message = await this.replaceDiscordMentions(message)

    if (this.config.USE_WEBHOOKS) {
      const sentMessage = await this.webhookClient!.sendMessage(username, message)
      if (sentMessage) return
    }

    const messageContent = this.makeDiscordMessage(username, message)

    try {
      await this.channel!.send(messageContent)
    } catch (e) {
      console.log('[ERROR] Could not send Discord message through bot!')
      process.exit(1)
    }
  }
}

export default Discord