summary refs log tree commit diff homepage
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/Config.ts5
-rw-r--r--src/Discord.ts113
-rw-r--r--src/DiscordWebhooks.ts112
-rw-r--r--src/Shulker.ts30
4 files changed, 156 insertions, 104 deletions
diff --git a/src/Config.ts b/src/Config.ts
index 485d6ae..8b18aa7 100644
--- a/src/Config.ts
+++ b/src/Config.ts
@@ -7,7 +7,6 @@ export interface Config {
   IGNORE_WEBHOOKS: string
   DISCORD_TOKEN: string
   DISCORD_CHANNEL_ID: string
-  DISCORD_CHANNEL_NAME: string
   DISCORD_MESSAGE_TEMPLATE: string
 
   MINECRAFT_SERVER_RCON_IP: string
@@ -29,7 +28,7 @@ export interface Config {
   ALLOW_USER_MENTIONS: boolean
   ALLOW_HERE_EVERYONE_MENTIONS: boolean
   ALLOW_SLASH_COMMANDS: boolean
-  SLASH_COMMAND_ROLES: string[]
+  SLASH_COMMAND_ROLES_IDS: string[]
 
   WEBHOOK: string
   REGEX_SERVER_PREFIX: string
@@ -40,7 +39,9 @@ export interface Config {
   SERVER_NAME: string
   SERVER_IMAGE: string
   HEAD_IMAGE_URL: string
+  UUID_API_URL: string
   DEFAULT_PLAYER_HEAD: string
+
   SHOW_SERVER_STATUS: boolean
   SHOW_PLAYER_CONN_STAT: boolean
   SHOW_PLAYER_ADVANCEMENT: boolean
diff --git a/src/Discord.ts b/src/Discord.ts
index 8071d7e..087619b 100644
--- a/src/Discord.ts
+++ b/src/Discord.ts
@@ -1,20 +1,20 @@
 import { Client, Intents, Message, TextChannel, User } from 'discord.js'
 
 import emojiStrip from 'emoji-strip'
-import axios from 'axios'
 
 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
 
-  uuidCache: Map<string, string>
   mentionCache: Map<string, User>
 
   constructor (config: Config, onReady?: () => void) {
@@ -24,9 +24,10 @@ class Discord {
     if (onReady) this.client.once('ready', () => onReady())
     this.client.on('messageCreate', (message: Message) => this.onMessage(message))
 
+    this.webhookClient = null
+
     this.channel = null
 
-    this.uuidCache = new Map()
     this.mentionCache = new Map()
   }
 
@@ -39,9 +40,12 @@ class Discord {
       process.exit(1)
     }
 
-    if (this.config.DISCORD_CHANNEL_NAME && !this.config.DISCORD_CHANNEL_ID) {
-      await this.getChannelIdFromName(this.config.DISCORD_CHANNEL_NAME)
-    } else if (this.config.DISCORD_CHANNEL_ID) {
+    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.`)
@@ -55,45 +59,6 @@ class Discord {
     }
   }
 
-  private async getChannelIdFromName (name: string) {
-    // remove the # if there is one
-    if (name.startsWith('#')) name = name.substring(1, name.length)
-
-    // fetch all the channels in every server
-    for (const guild of this.client.guilds.cache.values()) {
-      await guild.channels.fetch()
-    }
-
-    const channel = this.client.channels.cache.find((c) => c.isText() && c.type === 'GUILD_TEXT' && c.name === name && !c.deleted)
-    if (channel) {
-      this.channel = channel as TextChannel
-    } 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 = /discord[app]?.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
@@ -109,8 +74,7 @@ class Discord {
         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.webhookClient!.id === message.webhookId) {
           if (this.config.DEBUG) console.log('[INFO] Ignoring webhook from self')
           return
         }
@@ -134,8 +98,8 @@ class Discord {
     }
 
     let command: string | undefined;
-    if (this.config.ALLOW_SLASH_COMMANDS && this.config.SLASH_COMMAND_ROLES && message.cleanContent.startsWith('/') && message.member) {
-      const hasSlashCommandRole = message.member.roles.cache.find(r => this.config.SLASH_COMMAND_ROLES.includes(r.name))
+    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...
         command = message.cleanContent
@@ -164,7 +128,7 @@ class Discord {
       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('Your Minecraft version may not support tellraw, please look into MINECRAFT_TELLRAW_DOESNT_EXIST!')
+          console.log('[INFO] Your Minecraft version may not support tellraw, please check MINECRAFT_TELLRAW_DOESNT_EXIST in the README')
         }
       }
     }
@@ -240,45 +204,6 @@ class Discord {
     return message
   }
 
-  private async getUUIDFromUsername (username: string): Promise<string | null> {
-    username = username.toLowerCase()
-    if (this.uuidCache.has(username)) return this.uuidCache.get(username)!
-    // otherwise fetch and store
-    try {
-      const response = await (await axios.get('https://api.mojang.com/users/profiles/minecraft/' + username)).data
-      const uuid = response.id
-      this.uuidCache.set(username, uuid)
-      if (this.config.DEBUG) console.log(`[DEBUG] Fetched UUID ${uuid} for username "${username}"`)
-      return uuid
-    } catch (e) {
-      console.log(`[ERROR] Could not fetch uuid for ${username}, falling back to Steve for the skin`)
-      return null
-    }
-  }
-
-  private getHeadUrl(uuid: string): string {
-    const url = this.config.HEAD_IMAGE_URL || 'https://mc-heads.net/avatar/%uuid%/256'
-    return url.replace(/%uuid%/, uuid)
-  }
-
-  private async makeDiscordWebhook (username: string, message: string) {
-    const defaultHead = this.getHeadUrl(this.config.DEFAULT_PLAYER_HEAD || 'c06f89064c8a49119c29ea1dbd1aab82') // MHF_Steve
-
-    let avatarURL
-    if (username === this.config.SERVER_NAME + ' - Server') { // use avatar for the server
-      avatarURL = this.config.SERVER_IMAGE || defaultHead
-    } else { // use avatar for player
-      const uuid = await this.getUUIDFromUsername(username)
-      avatarURL = !!uuid ? this.getHeadUrl(uuid) : defaultHead
-    }
-
-    return {
-      username,
-      content: message,
-      'avatar_url': avatarURL,
-    }
-  }
-
   private makeDiscordMessage(username: string, message: string) {
     return this.config.DISCORD_MESSAGE_TEMPLATE
       .replace('%username%', username)
@@ -289,14 +214,8 @@ class Discord {
     message = await this.replaceDiscordMentions(message)
 
     if (this.config.USE_WEBHOOKS) {
-      const webhook = await this.makeDiscordWebhook(username, message)
-      try {
-        await axios.post(this.config.WEBHOOK_URL, webhook, { headers: { 'Content-Type': 'application/json' } })
-        return
-      } catch (e) {
-        console.log('[ERROR] Could not send Discord message through WebHook! Falling back to sending through bot.')
-        if (this.config.DEBUG) console.log(e)
-      }
+      const sentMessage = await this.webhookClient!.sendMessage(username, message)
+      if (sentMessage) return
     }
 
     const messageContent = this.makeDiscordMessage(username, message)
diff --git a/src/DiscordWebhooks.ts b/src/DiscordWebhooks.ts
new file mode 100644
index 0000000..fcdf57f
--- /dev/null
+++ b/src/DiscordWebhooks.ts
@@ -0,0 +1,112 @@
+import { WebhookClient, WebhookMessageOptions } from 'discord.js'
+
+import axios from 'axios'
+
+import type { Config } from './Config'
+
+class DiscordWebhooks {
+  private config: Config
+
+  private webhookClient: WebhookClient
+
+  private uuidCache: Map<string, string>
+
+  public id: string | null
+  private token: string | null
+
+  constructor (config: Config) {
+    this.config = config
+
+    this.id = null
+    this.token = null
+
+    this.uuidCache = new Map()
+  }
+
+  public init () {
+    const { id, token } = this.parseDiscordWebhook(this.config.WEBHOOK_URL)
+
+    if (!id || !token) {
+      process.exit(1)
+    }
+
+    this.id = id
+    this.token = token
+
+    this.webhookClient = new WebhookClient({ id, token })
+  }
+
+  private parseDiscordWebhook (url: string) {
+    const re = /discord[app]?.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)
+      id = match?.[1]
+      token = match?.[2]
+    }
+
+    return { id, token }
+  }
+
+  private async getUUIDFromUsername (username: string): Promise<string | null> {
+    username = username.toLowerCase()
+    if (this.uuidCache.has(username)) return this.uuidCache.get(username)!
+    // otherwise fetch and store
+    try {
+      const response = await (
+        await axios.get((this.config.UUID_API_URL ?? 'https://api.mojang.com/users/profiles/minecraft/%username%').replace('%username%', username))
+      ).data
+      const uuid = response.id
+      this.uuidCache.set(username, uuid)
+      if (this.config.DEBUG) console.log(`[DEBUG] Fetched UUID ${uuid} for username "${username}"`)
+      return uuid
+    } catch (e) {
+      console.log(`[ERROR] Could not fetch uuid for ${username}, falling back to Steve for the skin`)
+      return null
+    }
+  }
+
+  private getHeadUrl(uuid: string): string {
+    const url = this.config.HEAD_IMAGE_URL || 'https://mc-heads.net/avatar/%uuid%/256'
+    return url.replace(/%uuid%/, uuid)
+  }
+
+  private async makeDiscordWebhook (username: string, message: string) {
+    const defaultHead = this.getHeadUrl(this.config.DEFAULT_PLAYER_HEAD || 'c06f89064c8a49119c29ea1dbd1aab82') // MHF_Steve
+
+    const messsageOptions: WebhookMessageOptions = {
+      username,
+      content: message,
+    }
+
+    if (username === this.config.SERVER_NAME + ' - Server') { // use avatar for the server
+      if (this.config.SERVER_IMAGE) messsageOptions.avatarURL = this.config.SERVER_IMAGE
+    } else { // use avatar for player
+      const uuid = await this.getUUIDFromUsername(username)
+      messsageOptions.avatarURL = !!uuid ? this.getHeadUrl(uuid) : defaultHead
+    }
+
+    return messsageOptions
+  }
+
+  public async sendMessage (username: string, message: string) {
+    const webhookContent = await this.makeDiscordWebhook(username, message)
+    try {
+      await this.webhookClient!.send(webhookContent)
+      return true
+    } catch (e) {
+      console.log('[ERROR] Could not send Discord message through WebHook! Falling back to sending through bot.')
+      if (this.config.DEBUG) console.log(e)
+      return false
+    }
+  }
+}
+
+export default DiscordWebhooks
diff --git a/src/Shulker.ts b/src/Shulker.ts
index 1846def..8f6a5bb 100644
--- a/src/Shulker.ts
+++ b/src/Shulker.ts
@@ -5,14 +5,22 @@ import Handler, { LogLine } from './MinecraftHandler'
 
 import type { Config } from './Config'
 
+interface OutdatedConfigMessages {
+  [key: string]: string
+}
+
 class Shulker {
   config: Config
   discordClient: DiscordClient
   handler: Handler
 
-  readonly deprecatedConfigs: string[] = ['DEATH_KEY_WORDS']
+  readonly deprecatedConfigs: OutdatedConfigMessages = {
+    'DEATH_KEY_WORDS': '`DEATH_KEY_WORDS` has been replaced with `REGEX_DEATH_MESSAGE`. Please update this from the latest example config.'
+  }
 
-  constructor() {
+  readonly removedConfigs: OutdatedConfigMessages = {
+    'DISCORD_CHANNEL_NAME': 'Please remove this config line. Use the channel ID with `DISCORD_CHANNEL_ID` rather than the channel name.',
+    'SLASH_COMMAND_ROLES': 'Please use the slash command role IDs with `SLASH_COMMAND_ROLES_IDS` instead.'
   }
 
   loadConfig () {
@@ -30,10 +38,22 @@ class Shulker {
       return false
     }
 
-    for (const option of this.deprecatedConfigs) {
-      if (this.config.hasOwnProperty(option)) {
-        console.log('[WARN] Using deprecated config option ' + option + '. Check README.md for current options.')
+    for (const configKey of Object.keys(this.deprecatedConfigs)) {
+      if (this.config.hasOwnProperty(configKey)) {
+        console.log('[WARN] Using deprecated config option ' + configKey + '. Check README.md for current options. These options will be removed in a future release.')
+        console.log('       ' + this.deprecatedConfigs[configKey])
+      }
+    }
+
+    const hasRemovedConfig = Object.keys(this.config).some(key => Object.keys(this.removedConfigs).includes(key))
+    if (hasRemovedConfig) {
+      for (const configKey of Object.keys(this.removedConfigs)) {
+        if (this.config.hasOwnProperty(configKey)) {
+          console.log('[ERROR] Using removed config option ' + configKey + '. Check README.md for current options.')
+          console.log('        ' + this.removedConfigs[configKey])
+        }
       }
+      process.exit(1)
     }
 
     if (this.config.USE_WEBHOOKS) {