Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
This is the code
JavaScript
  1  const ms = require('ms')
  2  const fetch = require('node-fetch')
  3  const Discord = require('discord.js')
  4  const client = new Discord.Client()
  5  
  6  const config = require('./config.json')
  7  
  8  /**
  9   * This function is used to update statistics channel
 10   */
 11  const updateChannel = async () => {
 12  
 13      // Fetch statistics from mcapi.us
 14      const res = await fetch(`https://mcapi.us/server/status?ip=${config.ipAddress}${config.port ? `&port=${config.port}` : ''}`)
 15      if (!res) {
 16          const statusChannelName = `【🛡】Status: Offline`
 17          client.channels.cache.get(config.statusChannel).setName(statusChannelName)
 18          return false
 19      }
 20      // Parse the mcapi.us response
 21      const body = await res.json()
 22  
 23      // Get the current player count, or set it to 0
 24      const players = body.players.now
 25  
 26      // Get the server status
 27      const status = (body.online ? "Online" : "Offline")
 28  
 29      // Generate channel names
 30      const playersChannelName = `【👥】Players: ${players}`
 31      const statusChannelName = `【🛡】Status: ${status}`
 32  
 33      // Update channel names
 34      client.channels.cache.get(config.playersChannel).setName(playersChannelName)
 35      client.channels.cache.get(config.statusChannel).setName(statusChannelName)
 36  
 37      return true
 38  }
 39  
 40  client.on('ready', () => {
 41      console.log(`Ready. Logged as ${client.user.tag}.`)
 42      setInterval(() => {
 43          updateChannel()
 44      }, ms(config.updateInterval))
 45  })
 46  
 47  client.on('message', async (message) => {
 48  
 49      if(message.content === `${config.prefix}force-update`){
 50          if (!message.member.hasPermission('MANAGE_MESSAGES')) {
 51              return message.channel.send('Only server moderators can run this command!')
 52          }
 53          const sentMessage = await message.channel.send("Updating the channels, please wait...")
 54          await updateChannel()
 55          sentMessage.edit("Channels were updated successfully!")
 56      }
 57  
 58      if(message.content === `${config.prefix}stats`){
 59          const sentMessage = await message.channel.send("Fetching statistics, please wait...")
 60  
 61          // Fetch statistics from mcapi.us
 62          const res = await fetch(`https://mcapi.us/server/status?ip=${config.ipAddress}${config.port ? `&port=${config.port}` : ''}`)
 63          if (!res) return message.channel.send(`Looks like your server is not reachable... Please verify it's online and it isn't blocking access!`)
 64          // Parse the mcapi.us response
 65          const body = await res.json()
 66  
 67          const attachment = new Discord.MessageAttachment(Buffer.from(body.favicon.substr('data:image/png;base64'.length), 'base64'), "icon.png")
 68          const embed = new Discord.MessageEmbed()
 69              .setAuthor(config.ipAddress)
 70              .attachFiles(attachment)
 71              .setThumbnail("attachment://icon.png")
 72              .addField("Version", body.server.name)
 73              .addField("Connected", `${body.players.now} players`)
 74              .addField("Maximum", `${body.players.max} players`)
 75              .addField("Status", (body.online ? "Online" : "Offline"))
 76              .setColor("#FF0000")
 77              .setFooter("Open Source Minecraft Discord Bot")
 78          
 79          sentMessage.edit(`:chart_with_upwards_trend: Here are the stats for **${config.ipAddress}**:`, { embed })
 80      }
 81  
 82  })
 83  client.login(config.token)


What I have tried:

Console

(node:7548) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'substr' of null at Client. (C:\Users\RCIIND_4\Desktop\Vs Code\index.js:67:83) at processTicksAndRejections (internal/process/task_queues.js:95:5) (Use node --trace-warnings ... to show where the warning was created) (node:7548) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1) (node:7548) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Posted
Updated 28-Jul-21 6:44am
v2

1 solution

The error is thrown from line 67:
JavaScript
const attachment = new Discord.MessageAttachment(Buffer.from(body.favicon.substr('data:image/png;base64'.length), 'base64'), "icon.png")
Your request to mcapi.us did not return a JSON payload with a favicon property. You need to debug your code to examine the response, and handle the error accordingly.
 
Share this answer
 
Comments
Ishan varshney 29-Jul-21 0:14am    
This is the console error i am getting after the debug
UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'substr' of null
    at Client.<anonymous> (C:\Users\RCIIND_4\Desktop\Vs Code\index.js:67:83)
    at processTicksAndRejections (internal/process/task_queues.js:95:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:5796) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:5796) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Richard Deeming 29-Jul-21 3:21am    
Same error, same answer. Read my answer again.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900