javascript - TypeError:无法读取 guildCreate 事件中未定义的属性“id”
问题描述
我对 的定义有疑问guild.id
。我正在尝试创建一个事件,该事件将在机器人进入服务器时为服务器创建配置。
event.handler.js
:
const { readdirSync } = require("fs")
const ascii = require("ascii-table")
const chalk = require("chalk")
const {Constants: {Events}} = require("discord.js")
const serverEvents = Object.values(Events)
module.exports = (client) => {
const events = readdirSync(__dirname + "/../events").filter((file) =>
file.endsWith(".event.js"),
)
for (const file of events) {
const event = require(__dirname + `/../events/${file}`)
if(!event.run) {
console.log(chalk.redBright.bold(`event o nazwie '${file}' nie wykrywa funkcji run()! sprawdz dany plik!`));
process.exit(1)
}else if(typeof event.run !== 'function'){
console.log(chalk.redBright.bold(`event o nazwie '${file}' nie wykrywa funkcji run()! sprawdz dany plik!`));
process.exit(1)
}
if (serverEvents.includes(event.name)){
client.on(event.name, event.run)
}else {
console.log(chalk.redBright.bold(`event o nazwie '${file}' ma nie poprawną nazwe eventu!`));
process.exit(1)
}
}
}
onJoinBotGuild.event.js
:
module.exports = {
name: "guildCreate",
async run(msg) {
const { guild, client } = msg
const { settings } = client
// Save channel id to config
if (!settings.get(guild.id)) {
settings.set(guild.id, { clocks:[], prefix:[] })
}
client.saveConfig(guild.id)
}
}
index.js
:
const { Client } = require("discord.js")
const chalk = require("chalk")
const { token } = require("./config/config.js")
const client = new Client()
const commandHandler = require("./handlers/command.handler")
const settingsHandler = require("./handlers/settings.handler")
const eventHandler = require("./handlers/event.handler.js")
const log = console.log
const {guild} = client
// Initialize Comamnd Manager
commandHandler(client)
// Initialize Settings Manager
settingsHandler(client)
eventHandler(client)
client.on("ready", () => {
log(chalk.green(`Zalogowałeś się jako... -> `+chalk.red.bold( ` ${client.user.tag}!`)));
client.user.setPresence({ activity: { name: '*Jeśli potrzebujesz pomoocy użyj ?help*',type:'WATCHING' }, status: 'dnd' })
// Initialize interval for each guild
client.settings.forEach((config, guildId) => {
const { guilds } = client
// Check if guild exist
if (guilds.cache.has(guildId)) {
const guild = guilds.cache.get(guildId)
// Check if available
if (guild.available) {
// console.log("available")
// Set Interval for each channel
const clockChannels = config.clocks
setInterval(() => {
const time = new Date().toLocaleTimeString().slice(0, 5)
const channelName = ` ${time}`
clockChannels.forEach((channelId, index) => {
// Check if channel exists
if (guild.channels.cache.has(channelId)) {
// log("channel exist")
const channelToUpdate = guild.channels.cache.get(channelId)
channelToUpdate.setName(channelName)
} else {
// log("not exist")
// Remove Id from config
// that does not exist?
clockChannels.splice(index, 1)
client.saveConfig(guildId)
}
})
}, 1000)
}
}
client.saveConfig(guildId)
})
})
// Connect with Discord
client.login(token)
// Error handler - omit crashed
client.on("debug", () => {})
client.on("warn", () => {})
client.on("error", () => {})
settings.handler.js
:
const { Collection } = require("discord.js")
const { readdirSync, readFileSync, writeFileSync } = require("fs")
const yaml = require("js-yaml")
// Load server settings
const serverConfigPath = "/config/servers"
module.exports = (client) => {
// Settings Collection
client.settings = new Collection()
const settingsFiles = readdirSync(
__dirname + `/..${serverConfigPath}`,
).filter((file) => file.endsWith(".yaml"))
try {
for (const file of settingsFiles) {
const settingsFile = readFileSync(
__dirname + `/..${serverConfigPath}/${file}`,
"utf8",
)
const data = yaml.load(settingsFile)
const guildId = file.split(".")[0]
// Set server settings
client.settings.set(guildId, data)
}
} catch (e) {
console.log(e)
}
client.saveConfig = (guildId) => {
if (client.settings.has(guildId)) {
const config = client.settings.get(guildId)
try {
const yamlStr = yaml.dump(config)
writeFileSync(
__dirname + `/..${serverConfigPath}/${guildId}.yaml`,
yamlStr,
"utf8",
)
} catch (e) {
console.log(e)
}
}
}
}
发生的错误如下所示:
UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'id' of undefined
at Client.run (E:\Mega\GalusSecurtity\GalusSecurity\src\events\onJoinBotGuild.event.js:7:35)
at Client.emit (events.js:315:20)
at Object.module.exports [as GUILD_CREATE] (E:\Mega\GalusSecurtity\GalusSecurity\node_modules\discord.js\src\client\websocket\handlers\GUILD_CREATE.js:33:14)
at WebSocketManager.handlePacket (E:\Mega\GalusSecurtity\GalusSecurity\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:31)
at WebSocketShard.onPacket (E:\Mega\GalusSecurtity\GalusSecurity\node_modules\discord.js\src\client\websocket\WebSocketShard.js:444:22)
at WebSocketShard.onMessage (E:\Mega\GalusSecurtity\GalusSecurity\node_modules\discord.js\src\client\websocket\WebSocketShard.js:301:10)
at WebSocket.onMessage (E:\Mega\GalusSecurtity\GalusSecurity\node_modules\ws\lib\event-target.js:132:16)
at WebSocket.emit (events.js:315:20)
at Receiver.receiverOnMessage (E:\Mega\GalusSecurtity\GalusSecurity\node_modules\ws\lib\websocket.js:825:20)
at Receiver.emit (events.js:315:20)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:15832) 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:15832) [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.
解决方案
似乎您尝试获取有关guildCreate
机器人加入行会时发出的事件的消息。接受一个参数,guildCreate
公会创建。这guild
有一个client
属性,因此您可以在处理程序中使用它。
所以错误是当你解构时const { guild, client } = msg
,guild
将是未定义的,因为没有guild
属性guild
,只有client
。:)
尝试onJoinBotGuild.event.js
像这样更新您的文件:
module.exports = {
name: 'guildCreate',
async run(guild) {
const { client } = guild;
const { settings } = client;
// Save channel id to config
if (!settings.get(guild.id)) {
settings.set(guild.id, { clocks: [], prefix: [] });
}
client.saveConfig(guild.id);
},
};