How to fix Discord API: Unknown Message error? - javascript

I'm trying to make a meme command but whenever I try to use it I get this error "DiscordAPIError: Unknown Message".
This was working earlier but when I came back to my PC it started glitching out.
Here's my code
const { RichEmbed } = require("discord.js");
const randomPuppy = require("random-puppy");
const usedCommandRecently = new Set();
module.exports = {
name: "meme",
aliases: ["memes", "reddit"],
category: "fun",
description: "Sends a random meme",
run: async (client, message, args) => {
if (message.deletable) message.delete();
var Channel = message.channel.name
//Check it's in the right channel
if(Channel != "memes") {
const channelembed = new RichEmbed()
.setColor("BLUE")
.setTitle(`Use me in #memes`)
.setDescription(`Sorry ${message.author.username} this command is only usable in #memes !`)
return message.channel.send(channelembed);
}
//Check cooldown
if(usedCommandRecently.has(message.author.id)){
const cooldownembed = new RichEmbed()
.setColor("GREEN")
.setTitle("Slow it down, pal")
.setDescription(`Sorry ${message.author.username} this command has a 30 second cooldown per member, sorry for any inconvenice this may cause`)
message.channel.send(cooldownembed)
} else{
//Post meme
const subReddits = ["dankmeme", "meme", "me_irl"];
const random = subReddits[Math.floor(Math.random() * subReddits.length)];
const img = await randomPuppy(random);
const embed = new RichEmbed()
.setColor("RANDOM")
.setImage(img)
.setTitle(`From /r/${random}`)
.setURL(`https://reddit.com/r/${random}`);
message.channel.send(embed);
}
}
}

Im not sure, but maybe problem in your require block.
const { RichEmbed } = require("discord.js");
the right way its:
const Discord = require("discord.js");
let cooldownembed = new Discord.RichEmbed();
and why you use return here
return message.channel.send(channelembed);

Related

embed adding the same line multiple times

I'm currently working on a command show a user's profile using and embed but every time the command gets used the text gets added again. so if you use the command twice you see the text twice and so on. I've tried to find a solution for about an hour but I can't find anything. I've also tried to rewrite the code multiple times and I currently have this
const { discord, MessageEmbed } = require('discord.js');
const embed = new MessageEmbed();
const users = require('../users.json');
const stand = require('../standsInfo.json');
module.exports = {
name: 'profile',
description: 'show the users profile',
execute(message, args) {
var user = message.author;
var xpNeeded = (users[user.id].level+(users[user.id].level+1))*45;
embed.setTitle(`${user.username}'s profile`);
embed.setThumbnail(user.displayAvatarURL());
embed.addField('level', `${users[user.id].level}`);
embed.addField('experience', `${users[user.id].xp}/${xpNeeded}`);
message.channel.send({embeds: [embed] });
}
}
edit: so. I just realized what was wrong I used addField instead of setField
Move const embed = new MessageEmbed(); to inside the execute scope. Otherwise you will keep editing the same embed and sending again, with added fields
const { discord, MessageEmbed } = require('discord.js');
const users = require('../users.json');
const stand = require('../standsInfo.json');
module.exports = {
name: 'profile',
description: 'show the users profile',
execute(message, args) {
var user = message.author;
var xpNeeded = (users[user.id].level+(users[user.id].level+1))*45;
const embed = new MessageEmbed();
embed.setTitle(`${user.username}'s profile`);
embed.setThumbnail(user.displayAvatarURL());
embed.addField('level', `${users[user.id].level}`);
embed.addField('experience', `${users[user.id].xp}/${xpNeeded}`);
message.channel.send({embeds: [embed] });
}
}

Discord.js Cannot Read property 'run' of undefined

Im created a bot for discord using Discord.js, and every time I try to run my Bal command through my command handler it rejects it with the error Cannot read property 'run' of undefined
here is my code for Index.js
const Discord = require('discord.js');
const db = require("#replit/database")
const client = new Discord.Client();
const token = process.env.TOKEN;
const keep_alive = require('./keep_alive.js')
const PREFIX = "orb ";
const fs = require('fs');
const activities_list = [
"orb help.",
`${client.guilds.cache.size} servers!`,
"n 3^o7 !"
];
client.commands = new Discord.Collection();
const ecocommandFiles = fs.readdirSync('./ecocommands/').filter(file => file.endsWith('.js'));
for(const file of ecocommandFiles){
const command = require(`./ecocommands/${file}`);
client.commands.set(command.name, command);
}
client.on('ready', () => {
console.log("Orbitus online");
setInterval(() => {
const index = Math.floor(Math.random() * (activities_list.length - 1) + 1);
client.user.setActivity(activities_list[index], { type: 'WATCHING' });
}, 30000);
});
//Command Handler\\
client.on('message', message =>{
if(!message.content.startsWith(PREFIX) || message.author.bot) return;
const args = message.content.slice(PREFIX.length).split(/ +/);
const command = args.shift().toLowerCase();
if(command === 'bal'){
client.commands.get('bal').run(message, args, Discord);
}
});
client.login(token);
And here is my code for Bal.js
module.exports.run = async (message, args, Discord) => {
if(!message.content.startsWith(PREFIX))return;
let user = message.mentions.members.first() || message.author;
let bal = db.fetch(`money_${message.guild.id}_${user.id}`)
if (bal === null) bal = 0;
let bank = await db.fetch(`bank_${message.guild.id}_${user.id}`)
if (bank === null) bank = 0;
let moneyEmbed = new Discord.RichEmbed()
.setColor("#FFFFFF")
.setDescription(`**${user}'s Balance**\n\nPocket: ${bal}\nBank: ${bank}`);
message.channel.send(moneyEmbed)
};
I really need help because I want to continue development on my bot.
Thanks for your time
so uuh , i think you should follow the official guide:
https://discordjs.guide/command-handling/
your's seems bit similar but maybe got from yt (etc)
anyway the issue is
you dont export name from Bal.js only run (function)
module.exports.run = .....
and as name is undefined
your here setting undefined as the key with your run function to client.commands (collection)
for(const file of ecocommandFiles){
const command = require(`./ecocommands/${file}`);
client.commands.set(command.name, command);
^^^^^^^^
}
now only key in the client.commands collection is undefined
client.commands.get('bal') this will come undefined as there is not command called bal in your collection (only undefined)
what you could do is add
module.exports.name = 'bal' into bal.js
every command from now on should have this (if you decide to use this way)
Again I would suggest you read the discord.js official guide as it very beginner friendly and has a command handler and dynamic command handling tutorials with additional features, I will leave the links down below if you need them :)
Links
Official-docs: Click-here
official guide (this is the official guide for beginners with d.js): Click-here
Command-Handling (guide): Click-here
Dynamic-Command-Handling(guide) : Click-here
Additional-Features) (guide): Click-here
Other guides:
Event handling (from the same official guide): Click-here
An-idiots-Guide (use jointly with the official guide): Click-here

Discord avatar display code is not running

I wanted to use the command "-ava #(user)" to display the avatar of the specified user. I created this code but I'm not sure why when I type the command in discord where the bot is, nothing is returned. This is the following code for my discord bot:
const BaseCommand = require('../../utils/structures/BaseCommand');
const Discord = require('discord.js');
module.exports = {
name: 'ava',
description: 'Provide user with certain avatar as requested.',
execute(message, args) {
if (args[0]) {
const user = message.mentions.users.first();
if (!user) return message.reply('Please mention a user to access their avatar');
const otherIconEmbed = new Discord.RichEmbed()
.setTitle(`${user.username}'s Avatar`)
.setImage(user.displayAvatarURL);
message.channel.send(otherIconEmbed).catch(err => console.log(err));
}
const myIconEmbed = new Discord.RichEmbed()
.setTitle(`${message.author.username}'s avatar!`)
.setImage(message.author.displayAvatarURL);
message.channel.send(myIconEmbed).catch(err => console.log(err));
}
}
Simply you have to put () after displayAvatarURL so it gives displayAvatarURL () and if you want to make it animated you must put displayAvatarURL ({dynamic: true}) 🙂

Discord move bot

I'm trying to make a boot that, after entering the command >summon #nick, starts moving the user from one rooom to another, here's the problem:
CODE:
const Discord = require('discord.js');
const client = new Discord.Client();
const guild = new Discord.Guild(client, Object);
module.exports = {
name: 'summon',
description: "Vyvolá člověka",
execute(message, args) {
const times = 6;
let i = 0;
const member = message.mentions.members.first();
const channel1 = message.guild.members.cache.get("689511445519794177");
const channel2 = message.guild.members.cache.get("774780272738566194");
if(member == null){
message.channel.send("Nezadal jsi uživatele!");
console.log("Špatné použití příkazu.");
} else {
Discord.GuildMember.setVoiceChannel(channel1);
message.channel.send("debug1");
Discord.GuildMember.setVoiceChannel(channel2);
message.channel.send("debug2");
}}
};
ERROR IS:
PS C:\Users\-----\Desktop\------\----> node .
MilanCXL je online!
C:\Users\----\Desktop\-----\------\commands\summon.js:26
Discord.GuildMember.setVoiceChannel(channel1);
^
TypeError: Discord.GuildMember.setVoiceChannel is not a function
at Object.execute (C:\Users\----\Desktop\----\-----\commands\summon.js:26:33)
at Client.<anonymous> (C:\Users\---\Desktop\----\-----\main.js:39:39)
Thanks for respond,
ancle FIX
Presumably you want member.setVoiceChannel(channel1) and not Discord.GuildMember.setVoiceChannel(channel1);?

Discord js giveaway command

I am currently trying to make a Discord.js command where the first person who reacts wins the prize. There are 2 issues that I am encountering right now. First, the bot is picking up the last prize that was entered through with the command rather than the current one. Secondly, the giveaway sent before a bot restart won't work after the bot restarts.
Here is the code:
const DropModel = require('../modules/DropModel');
const { MessageEmbed, ReactionCollector } = require("discord.js")
const { COLOR, MONGO } = require("../util/BotUtil");
module.exports = {
name: "drop",
description: "First to react wins the giveaway!",
async execute(message, args) {
let prizes = args.slice(0).join(' ').toString()
if (!prizes) return message.channel.send("You didn't provide a prize.");
const newDrop = new DropModel({
guildId: message.guild.id,
prize: prizes,
channelId: message.channel.id,
createdBy: message.author,
timeCreated: new Date(),
});
newDrop.save();
let Drops = await DropModel.findOne({ guildId: message.guild.id, channelId: message.channel.id });
if (!Drops) return;
const { prize, createdBy } = Drops;
const DropEmbed = new MessageEmbed()
.setTitle(`${prize}`)
.setDescription(`First to React with 🎁 wins the giveaway
Hosted by: ${createdBy}`)
.setColor(COLOR)
.setTimestamp();
const dropMsg = await message.channel.send(`🎁 **giveaway** 🎁`, DropEmbed);
await Drops.remove();
await dropMsg.react('🎁');
const filter = (reaction, user) => !user.bot;
const reaction = new ReactionCollector(dropMsg, filter, { max: 1 });
reaction.on('collect', async (reaction, user) => {
const { embeds } = dropMsg;
const embed = embeds[0];
embed.setTitle(`Someone called giveaway!`);
embed.setDescription(`Winner: ${user.toString()}
Please contact ${createdBy} to claim your giveaway!`);
await dropMsg.edit(embed);
dropMsg.channel.send(`${user.toString()} won **${prize}**!`);
});
}
}
Any help regarding the issues mentioned above would be appreciated! Thanks!
You can save the giveaway end timestamp in JSON file or whatever database and then delete it when it's finished.

Categories

Resources