(node:7548) UnhandledPromiseRejectionWarning: TypeError: 无法读取 null 的属性“substr”
在客户端。 (C:\Users\RCIIND_4\Desktop\Vs Code\index.js:67:83)
在 processTicksAndRejections (internal/process/task_queues.js:95:5)
(使用 node --trace-warnings ...
显示警告的创建位置)
(节点:7548)UnhandledPromiseRejectionWarning:未处理的承诺拒绝。这个错误要么是因为在没有 catch 块的情况下抛出了异步函数,要么是因为拒绝了一个没有用 .catch() 处理过的承诺。要在未处理的承诺拒绝时终止节点进程,请使用 CLI 标志 --unhandled-rejections=strict
(请参阅 https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode)。 (拒绝编号:1)
(节点:7548)[DEP0018] 弃用警告:不推荐使用未处理的承诺拒绝。将来,未处理的承诺拒绝将以非零退出代码终止 Node.js 进程。
这是代码
const ms = require('ms')
const fetch = require('node-fetch')
const Discord = require('discord.js')
const client = new Discord.Client()
const config = require('./config.json')
/**
* This function is used to update statistics channel
*/
const updateChannel = async () => {
// Fetch statistics from mcapi.us
const res = await fetch(`https://mcapi.us/server/status?ip=${config.ipAddress}${config.port ? `&port=${config.port}` : ''}`)
if (!res) {
const statusChannelName = `【?】Status: Offline`
client.channels.cache.get(config.statusChannel).setName(statusChannelName)
return false
}
// Parse the mcapi.us response
const body = await res.json()
// Get the current player count, or set it to 0
const players = body.players.now
// Get the server status
const status = (body.online ? "Online" : "Offline")
// Generate channel names
const playersChannelName = `【?】Players: ${players}`
const statusChannelName = `【?】Status: ${status}`
// Update channel names
client.channels.cache.get(config.playersChannel).setName(playersChannelName)
client.channels.cache.get(config.statusChannel).setName(statusChannelName)
return true
}
client.on('ready', () => {
console.log(`Ready. Logged as ${client.user.tag}.`)
setInterval(() => {
updateChannel()
}, ms(config.updateInterval))
})
client.on('message', async (message) => {
if(message.content === `${config.prefix}force-update`){
if (!message.member.hasPermission('MANAGE_MESSAGES')) {
return message.channel.send('Only server moderators can run this command!')
}
const sentMessage = await message.channel.send("Updating the channels, please wait...")
await updateChannel()
sentMessage.edit("Channels were updated successfully!")
}
if(message.content === `${config.prefix}stats`){
const sentMessage = await message.channel.send("Fetching statistics, please wait...")
// Fetch statistics from mcapi.us
const res = await fetch(`https://mcapi.us/server/status?ip=${config.ipAddress}${config.port ? `&port=${config.port}` : ''}`)
if (!res) return message.channel.send(`Looks like your server is not reachable... Please verify it's online and it isn't blocking access!`)
// Parse the mcapi.us response
const body = await res.json()
const attachment = new Discord.MessageAttachment(Buffer.from(body.favicon.substr('data:image/png;base64'.length), 'base64'), "icon.png")
const embed = new Discord.MessageEmbed()
.setAuthor(config.ipAddress)
.attachFiles(attachment)
.setThumbnail("attachment://icon.png")
.addField("Version", body.server.name)
.addField("Connected", `${body.players.now} players`)
.addField("Maximum", `${body.players.max} players`)
.addField("Status", (body.online ? "Online" : "Offline"))
.setColor("#FF0000")
.setFooter("Open Source Minecraft Discord Bot")
sentMessage.edit(`:chart_with_upwards_trend: Here are the stats for **${config.ipAddress}**:`, { embed })
}
})
client.login(config.token)
这是更新后的代码
const ms = require('ms')
const fetch = require('node-fetch')
const Discord = require('discord.js')
const client = new Discord.Client()
const config = require('./config.json')
/**
* This function is used to update statistics channel
*/
const updateChannel = async () => {
// Fetch statistics from mcapi.us
const res = await fetch(`https://mcapi.us/server/status?ip=${config.ipAddress}${config.port ? `&port=${config.port}` : ''}`)
if (!res) {
const statusChannelName = `【?】Status: Offline`
client.channels.cache.get(config.statusChannel).setName(statusChannelName)
return false
}
// Parse the mcapi.us response
const body = await res.json()
// Get the current player count, or set it to 0
const players = body.players.now
// Get the server status
const status = (body.online ? "Online" : "Offline")
// Generate channel names
const playersChannelName = `【?】Players: ${players}`
const statusChannelName = `【?】Status: ${status}`
// Update channel names
client.channels.cache.get(config.playersChannel).setName(playersChannelName)
client.channels.cache.get(config.statusChannel).setName(statusChannelName)
return true
}
client.on('ready', () => {
console.log(`Ready. Logged as ${client.user.tag}.`)
setInterval(() => {
updateChannel()
}, ms(config.updateInterval))
})
client.on('message', async (message) => {
if(message.content === `${config.prefix}force-update`){
if (!message.member.hasPermission('MANAGE_MESSAGES')) {
return message.channel.send('Only server moderators can run this command!')
}
const sentMessage = await message.channel.send("Updating the channels, please wait...")
await updateChannel()
sentMessage.edit("Channels were updated successfully!")
}
if(message.content === `${config.prefix}stats`){
const sentMessage = await message.channel.send("Fetching statistics, please wait...")
// Fetch statistics from mcapi.us
const res = await fetch(`https://mcapi.us/server/status?ip=${config.ipAddress}${config.port ? `&port=${config.port}` : ''}`)
if (!res) return message.channel.send(`Looks like your server is not reachable... Please verify it's online and it isn't blocking access!`)
// Parse the mcapi.us response
const body = await res.json()
let embed = new Discord.MessageEmbed()
.setAuthor(config.ipAddress);
if (attachment) { new Discord.MessageAttachment(Buffer.from(body.favicon.substr('data:image/png;base64,'.length), 'base64'), "icon.png")
embed = embed.attachFiles(attachment);
}
embed = embed.setThumbnail("attachment://icon.png")
.addField("Version", body.server.name)
.addField("Connected", `${body.players.now} players`)
.addField("Maximum", `${body.players.max} players`)
.addField("Status", (body.online ? "Online" : "Offline"))
.setColor("#FF0000")
.setFooter("Open Source Minecraft Discord Bot");
sentMessage.edit(`:chart_with_upwards_trend: Here are the stats for **${config.ipAddress}**:`, { embed })
}
})
client.login(config.token)
答案 0 :(得分:0)
body.favicon
是 null
,但您尝试在此处使用它:
body.favicon.substr(...)
如果这个值有可能是 null
(而且显然是),那么你不能假设它会有一个值。你必须先检查。从那里,您需要决定当此值为 null
时您希望代码做什么。例如,您可以像这样添加 null
检查:
const attachment = body.favicon ? new Discord.MessageAttachment(Buffer.from(body.favicon.substr('data:image/png;base64'.length), 'base64'), "icon.png") : null;
这使用 ?:
条件运算符来检查 body.favicon
是否有值。如果是,请按照当前代码进行操作。如果它没有值,请将 attachment
设置为 null
。
从那里您需要决定当 attachment
为 null
时要做什么。您可能无法像那样在 Discord API 中使用它。因此,您也可以在此处在条件检查中包装一些逻辑:
let embed = new Discord.MessageEmbed()
.setAuthor(config.ipAddress);
if (attachment) { // <--- here
embed = embed.attachFiles(attachment)
.setThumbnail("attachment://icon.png");
}
embed = embed.addField("Version", body.server.name)
.addField("Connected", `${body.players.now} players`)
.addField("Maximum", `${body.players.max} players`)
.addField("Status", (body.online ? "Online" : "Offline"))
.setColor("#FF0000")
.setFooter("Open Source Minecraft Discord Bot");
更新
在您更新的代码中,您已经完全删除了 attachment
的定义。那肯定会简化问题。如果这是您想要做的,那么您还需要删除任何使用 attachment
的代码。例如:
let embed = new Discord.MessageEmbed()
.setAuthor(config.ipAddress);
.addField("Version", body.server.name)
.addField("Connected", `${body.players.now} players`)
.addField("Maximum", `${body.players.max} players`)
.addField("Status", (body.online ? "Online" : "Offline"))
.setColor("#FF0000")
.setFooter("Open Source Minecraft Discord Bot");