#javascript #node.js #discord #discord.js
#javascript #node.js #Discord #discord.js
Вопрос:
Итак, я пытаюсь сделать Discord.js команда snipe в моем боте с обработчиками команд, и все работает нормально, событие on messageDelete тоже работает нормально, но когда я удаляю сообщение пользователя и запускаю !snipe , я получаю сообщение об ошибке: Cannot read property 'get' of undefined
. Вот мои файлы ботов:
Файл бота
const { Client, Message, Collection, Discord } = require('discord.js'); const mongoose = require('mongoose'); const config = require('./config.json'); const client = require('./dashboard/modules/auth-client');
const bot = new Client();
bot.snipes = new Collection();
bot.login(config.bot.token);
mongoose.connect(config.mongoURI, { useNewUrlParser: true, useUnifiedTopology: true }, (error) => error
? console.log('Failed to connect to database')
: console.log('Connected to database'));
module.exports = bot;
require('./handlers/event-handler'); require('./dashboard/server');
Событие удаления сообщения
const Event = require("./event");
const { MessageEmbed } = require('discord.js')
const { bot } = require("../../bot.js")
module.exports = class extends Event {
on = "messageDelete";
async invoke(msg) {
if (msg.author.bot) return;
const snipes = msg.client.snipes.get(msg.channel.id) || [];
snipes.unshift({
content: msg.content,
author: msg.author,
image: msg.attachments.first() ? msg.attachments.first().proxyURL : null,
date: new Date().toLocaleString("en-GB", {
dataStyle: "full",
timeStyle: "short",
}),
});
snipes.splice(10);
msg.client.snipes.set(msg.channel.id, snipes);
let embed = new MessageEmbed()
.setTitle(`New message deleted!`)
.setDescription(
`**The user ${msg.author.tag} has deleted a message in <#${msg.channel.id}>**`
)
.addField(`Content`, msg.content, true)
.setColor(`RED`);
let channel = msg.guild.channels.cache.find(
(ch) => ch.name === "bot-logs"
);
if (!channel) return;
channel.send(embed);
} catch(e) { }
};
Команда Snipe
const { MessageEmbed } = require('discord.js');
const bot = require('../bot.js');
module.exports = class {
name = 'snipe';
category = 'General';
async execute(bot, msg, args) {
const snipes = bot.snipes.get(msg.channel.id) || [];
const snipedmsg = snipes[args[0] - 1 || 0];
if (!snipedmsg) return msg.channel.send("Not a valid snipe!");
const Embed = new MessageEmbed()
.setAuthor(snipedmsg.author.tag, snipedmsg.author.displayAvatarURL({ dynamic: true, size: 256 }))
.setDescription(snipedmsg.content)
.setFooter(`Date: ${snipedmsg.date} | ${args[0] || 1}/${snipes.length}`)
if (snipedmsg.attachment) Embed.setImage(snipedmsg.attachment);
msg.channel.send(Embed);
}
}
Комментарии:
1. Вы установили
bot.snipes = new Collection();
, но затем прочитали его черезmsg.client.snipes
.
Ответ №1:
Вы можете использовать этот код, если хотите:
const Discord = require("discord.js")
const db = require("quick.db")
module.exports = {
name: "snipe",
aliases: ["ms", "messagesnipe"],
category: "info",
usage: "(prefix)snipe",
description: "Get last message which is deleted with message Author and Image(If any)",
run:async (client, message, args) => {
const msg = client.snipes.get(message.channel.id)
if(!msg) return message.channel.send("There's nothing to snipe!")
const embed = new Discord.MessageEmbed()
.setAuthor(msg.author)
.setDescription(msg.content)
if(msg.image)embed
.setImage(msg.image)
.setColor("00FFFF")
.setTimestamp();
message.channel.send(embed)
}
}
Ответ №2:
Упоминается ли в ошибке конкретная строка, в которой возникает ошибка?
Возможное использование отсутствует <db>.get
.
И еще одна вещь заключается в том, где вы используете message.client.snipes.get
событие удаления сообщения. Возможно, заменить на bot.snipes
.