summary refs log tree commit diff homepage
path: root/src/Discord.ts
blob: ffdd05bf7d9a4527c66af76bf931643bffcc19c2 (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
import {Client, Message, Snowflake, TextChannel} from 'discord.js'

import emojiStrip from 'emoji-strip'
import axios from 'axios'

import { Config } from './Config'

import Rcon from './Rcon'

class Discord {
  config: Config
  client: Client

  channel: Snowflake

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

    this.client = new Client()
    if (onReady) this.client.once('ready', () => onReady())
    this.client.on('message', (message: Message) => this.onMessage(message))

    this.channel = config.DISCORD_CHANNEL_ID || ''
  }

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

  private getChannelIdFromName (name: string) {
    // remove the # if there is one
    if (name.startsWith('#')) name = name.substring(1, name.length)
    // @ts-ignore
    const channel: TextChannel = this.client.channels.find((c: TextChannel) => c.type === 'text' && c.name === name && !c.deleted)
    if (channel) {
      this.channel = channel.id
      console.log(`[INFO] Found channel #${channel.name} (id: ${channel.id}) in the server "${channel.guild.name}"`)
    } else {
      console.log(`[INFO] Could not find channel ${name}! Check that the name is correct or use the ID of the channel instead (DISCORD_CHANNEL_ID)!`)
      process.exit(1)
    }
  }

  private parseDiscordWebhook (url: string) {
    const re = /discordapp.com\/api\/webhooks\/([^\/]+)\/([^\/]+)/

    // the is of the webhook
    let id = null
    let token = null

    if (!re.test(url)) {
      // In case the url changes at some point, I will warn if it still works
      console.log('[WARN] The Webhook URL may not be valid!')
    } else {
      const match = url.match(re)
      if (match) {
        id = match[1]
        token = match[2]
      }
    }

    return { id, token }
  }

  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 || message.channel.type !== '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
        const { id } = this.parseDiscordWebhook(this.config.WEBHOOK_URL)
        if (id === message.webhookID) {
          if (this.config.DEBUG) console.log('[INFO] Ignoring webhook from self')
          return
        }
      }
    }
    // if the same user as the bot, ignore
    if (message.author.id === this.client.user.id) return
    // ignore any attachments
    if (message.attachments.array().length) return

    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 command = ''
    if (this.config.ALLOW_SLASH_COMMANDS && this.config.SLASH_COMMAND_ROLES && message.cleanContent.startsWith('/')) {
      const author = message.member
      if (author.roles.find(r => this.config.SLASH_COMMAND_ROLES.includes(r.name))) {
        // send the raw command, can be dangerous...
        command = message.cleanContent
      } else {
        console.log('[INFO] User attempted a slash command without a role')
      }
    } else {
      command = `/tellraw @a ${this.makeMinecraftTellraw(message)}`
    }

    if (this.config.DEBUG) console.log(`[DEBUG] Sending command "${command}" to the server`)

    if (command) {
      await rcon.command(command).catch((e) => {
        console.log('[ERROR] Could not send command!')
        if (this.config.DEBUG) console.error(e)
      })
    }
    rcon.close()
  }

  private makeMinecraftTellraw(message: Message): string {
    const variables: {[index: string]: string} = {
      username: emojiStrip(message.author.username),
      discriminator: message.author.discriminator,
      text: emojiStrip(message.cleanContent)
    }
    // hastily use JSON to encode the strings
    for (const v of Object.keys(variables)) {
      variables[v] = JSON.stringify(variables[v]).slice(1,-1)
    }

    return this.config.MINECRAFT_TELLRAW_TEMPLATE
      .replace(/%username%/g, variables.username)
      .replace(/%discriminator%/g, variables.discriminator)
      .replace(/%message%/g, variables.text)
  }

  private replaceDiscordMentions(message: string): string {
    const possibleMentions = message.match(/@*.*#[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) {
            const user = this.client.users.find(user => user.username === username && user.discriminator === mentionParts[1])
            if (user) {
              message = message.replace(mention, '<@' + user.id + '>')
            }
          }
        }

        if (['here', 'everyone'].includes(username)) {
          // remove these large pings
          if (!this.config.ALLOW_HERE_EVERYONE_MENTIONS) {
            message = message
              .replace('@everyone', '@ everyone')
              .replace('@here', '@ here')
          }
        }
      }
    }
    return message
  }

  private makeDiscordWebhook (username: string, message: string) {
    message = this.replaceDiscordMentions(message)

    let avatarURL
    if (username === this.config.SERVER_NAME + ' - Server') { // use avatar for the server
      avatarURL = this.config.SERVER_IMAGE || 'https://minotar.net/helm/Steve/256.png'
    } else { // use avatar for player
      avatarURL = `https://minotar.net/helm/${username}/256.png`
    }

    return {
      username: username,
      content: message,
      'avatar_url': avatarURL,
    }
  }

  private makeDiscordMessage(username: string, message: string) {
    message = this.replaceDiscordMentions(message)

    return this.config.DISCORD_MESSAGE_TEMPLATE
      .replace('%username%', username)
      .replace('%message%', message)
  }

  public async sendMessage (username: string, message: string) {
    if (this.config.USE_WEBHOOKS) {
      const webhook = this.makeDiscordWebhook(username, message)
      try {
        await axios.post(this.config.WEBHOOK_URL, webhook, { headers: { 'Content-Type': 'application/json' } })
      } catch (e) {
        console.log('[ERROR] Could not send Discord message through WebHook!')
        if (this.config.DEBUG) console.log(e)
      }
    } else {
      // find the channel
      const channel = this.client.channels.find((ch) => ch.id === this.config.DISCORD_CHANNEL_ID && ch.type === 'text') as TextChannel
      if (channel) {
        await channel.send(this.makeDiscordMessage(username, message))
      } else {
        console.log(`[ERROR] Could not find channel with ID ${this.config.DISCORD_CHANNEL_ID}!`)
      }
    }
  }
}

export default Discord