Emoji List Command Discord.js v12 - javascript

I created an emoji list command here is my code of the command:
const { MessageEmbed } = require('discord.js');
module.exports = {
name: "emojis",
description: "Gets a guild\'s emojis",
async run (client, message, args) {
const emojis = [];
message.guild.emojis.cache.forEach(e => emojis.push(`${e} **-** \`:${e.name}:\``));
const embed = new MessageEmbed()
.setTitle(`Emoji List`)
.setDescription(emojis.join('\n'))
message.channel.send(embed)
}
};
However I get this error in case the characters in the embed exceeds 2048 letters:
(node:211) UnhandledPromiseRejectionWarning: DiscordAPIError: Invalid Form Body
embed.description: Must be 2048 or fewer in length.
at RequestHandler.execute (/home/runner/Utki-the-bot/node_modules/discord.js/src/rest/RequestHandler.js:170:25)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:211) 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:211) [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.
Is there any way the bot can still show the emojis and there names. By using discord-menu or like that. I was unable to understand how to do that. Can you help me out? Thanks in Advance

As you can probably tell by the error message, your embed description is too long. You can split your message into several parts by using string.split() and send each shortened string as a separate message. Here's a rudimentary example.
const charactersPerMessage = 2000;
// we're going to go with 2000 instead of 2048 for breathing room
const emojis = message.guild.emojis.cache.map(e=> { return `${e} **-** \`:${e.name}:\`` }); // does virtually the same thing as forEach()
const numberOfMessages = Math.ceil(emojis.length/charactersPerMessage); // calculate how many messages we need
const embed = new MessageEmbed()
.setTitle(`Emoji List`);
for(i=0;i<numberOfMessages;i++) {
message.channel.send(
embed.setDescription(emojis.slice(i*charactersPerMessage, (i+1)*charactersPerMessage))
);
}
Do take note that emojis is now a string rather than an Array.

Related

Discord.js message.react is not a function

I have a discord bot set up that does reaction roles. I use IDs to cache the messages that need to have reactions. I make the bot first react with the according emojis before it handles them. This is what caching the messages looks like:
const guild = await client.guilds.fetch(info.GUILD_ID)
const channel1 = guild.channels.cache.get(info.MAINROLES_CHANNEL_ID)
const message1 = await channel1.messages.fetch(info.MAINROLES_MESSAGE_ID)
const channel2 = guild.channels.cache.get(info.HELPERROLES_CHANNEL_ID)
const message2 = await channel2.messages.fetch(info.HELPERROLES_MESSAGE_ID)
const channel3 = guild.channels.cache.get(info.VERIFICATION_CHANNEL_ID)
const message3 = await channel3.messages.fetch(info.VERIFICATION_MESSAGE_ID)
The problem I have is with message 2. When doing message1.react("🇱") everything works fine. However, when I do message2.react("🇱") I get an error. I see no reason for the error to be thrown as I get both messages the exact same way. Does this have to do with discord bot permissions? Or is it something else that I'm doing wrong?
This is the error:
(node:4102) UnhandledPromiseRejectionWarning: TypeError: message2.react is not a function
at Client.<anonymous> (/Users/denesgarda/Documents/GitHub/cmd/bot/index.js:47:12)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:4102) 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:4102) [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.
I can't comment yet but I will try to help you. So I think that the message1 and message2 are stuck because they are entered in the same time.
I am not sure but you can try to make it like this
const guild = await client.guilds.fetch(info.GUILD_ID)
const channel1 = guild.channels.cache.get(info.MAINROLES_CHANNEL_ID)
const message1 = await channel1.messages.fetch(info.MAINROLES_MESSAGE_ID)
message1.react(emoji);
const channel2 = guild.channels.cache.get(info.HELPERROLES_CHANNEL_ID)
const message2 = await channel2.messages.fetch(info.HELPERROLES_MESSAGE_ID)
message2.react(emoji);
const channel3 = guild.channels.cache.get(info.VERIFICATION_CHANNEL_ID)
const message3 = await channel3.messages.fetch(info.VERIFICATION_MESSAGE_ID)
message3.react(emoji);
If that doesn't work maybe try to get the id using const channel = bot.channels.cache.find(ch => ch.id === 'channelid'); this function

Why am I receiving an Invalid Form Body error with Discord API?

I'm making a discord bot but when I create a ping command it says the following:
(node:37584) UnhandledPromiseRejectionWarning: DiscordAPIError: Invalid Form Body
embed.footer.icon_url: Scheme "flashybot" is not supported. Scheme must be one of ('http', 'https').
embeds[0].footer.icon_url: Scheme "flashybot" is not supported. Scheme must be one of ('http', 'https').
at RequestHandler.execute (C:\Users\niels\Documents\VsCode Projects\Discord Bots\FlashyBot\node_modules\discord.js\src\rest\RequestHandler.js:154:13)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at async RequestHandler.push (C:\Users\niels\Documents\VsCode Projects\Discord Bots\FlashyBot\node_modules\discord.js\src\rest\RequestHandler.js:39:14)
at async callback (C:\Users\niels\Documents\VsCode Projects\Discord Bots\FlashyBot\commands\misc\ping.js:15:21)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:37584) 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:37584) [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.
My code for ping.js is:
const { MessageEmbed } = require("discord.js")
module.exports = {
commands: ["ping", 'pong'],
expectedArgs: "",
permissionError: '',
minArgs: 0,
maxArgs: null,
callback: async(message, args, text, client) => {
let pinging = new MessageEmbed()
.setTitle('Pinging....')
.setColor("RED")
.setFooter(client.user.avatarURL(), client.user.username)
const msg = await message.channel.send(pinging)
let embed = new MessageEmbed()
.setTitle('Pong! 🏓')
.addField("Api Latency", `${Math.floor(message.createdTimestamp - message.createdTimestamp)}ms`)
.addField("Latency", `${Math.floor(client.ws.ping)}ms`)
.setColor("LIGHT_GREEN")
.setFooter(client.user.avatarURL(), client.user.username)
.setTimestamp()
msg.edit(embed)
}
}
Can someone help me with this? I tried doing message.client.user.avatarURL() and also the displayAvatarURL() function but it keeps giving this error
Your logs say
embed.footer.icon_url: Scheme "flashybot" is not supported. Scheme must be one of ('http', 'https'). embeds[0].footer.icon_url: Scheme "flashybot" is not supported. Scheme must be one of ('http', 'https').
Which seems to indicate the url provided for your icon is incorrect (and does not start with http or https which is required).
I assume this is client.user.avatarURL() which is incorrect, try to replace it with a hard coded picture link and see if it helps. You may have an incorrect value in avatarURL...

How do I get the most recent message in discord.js?

Every time a message is sent in a specific channel, I want to print it to the console (with console.log). I am also going to color it with npm install colors. I go everywhere, even on Stack Overflow, but I cannot seem to find any information. I am coding a Scholastic Bowl-helping bot. Below is the code I have tried (I found this on Stack Overflow.)
message.fetch({ limit: 1 }).then(messages => {
let lastMessage = message.first();
if (message.channel.lastMessage = 'channel-id'){
console.log(lastMessage.red);
}
})
(Note that when I say 'channel-id' I mean the actual ID of the channel.)
The error I am getting is that message.first is not a thing.
How do I fix this error, and how can I get the most recent message in discord.js?
Edit: The exact error I got is this:
(node:12352) UnhandledPromiseRejectionWarning: TypeError: messages.first is not a function
at C:\Users\[user redacted]\Desktop\SchoBot\index.js:57:32
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:12352) 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:12352) [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.
Below is the edit for the 3rd comment on this question (sorted by oldest):
message.channel.fetch({ limit: 1 }).then(messages => {
let lastMessage = message.channel.first();
if (message.channel.lastMessage = 'channel-id'){
console.log(lastMessage.red);
}
})
Use message.channel.messages.fetch() instead of message.channel.fetch().
I didn't find the message.first function in the discord.js documentation, so I am not sure if it works. But you don't really need that function to fetch a message. The fetch function already did that for you.
In your case, the option limit: 1 will only return the most recent message, which is the command you use to trigger the fetch. If you want to fetch the most recent message but not your command, you should use limit: 2 instead and remove your command in the object later.
The fetch function will return an object containing message id and the content.
I assume that message.fetch needs to be message.channel.fetch

Play random sound

I'm making a discord bot and if I type $join into chat, I want the bot to join the voice channel that I'm in, and play a random sound.
case"join":
message.delete( {timeout: 5000})
const voiceChannel = message.member.voice.channel
if(voiceChannel) {
const connection = await voiceChannel.join()
const soundFile = fs.readFileSync("./sounds/")
const randFiles = soundFile[Math.floor(Math.random() * randFiles.length)]
const dispatcher = connection.play(randFiles)
} else {
message.reply("you need to be in a voice channel!").then(message => message.delete( {timeout: 5000}))
}
break;
I'm getting this error:
(node:13932) UnhandledPromiseRejectionWarning: Error: EISDIR: illegal operation on a directory, read
at Object.readSync (fs.js:524:3)
at tryReadSync (fs.js:349:20)
at Object.readFileSync (fs.js:386:19)
at Client.<anonymous> (C:\Users\PC\Desktop\doge_bot\doge-bot.js:124:38)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:13932) 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:13932) [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.
Have you read the documentation for readFileSync()? The only OS that readFileSync() successfully returns data on a directory path is on FreeBSD.
Instead, what it appears you're trying to do is grab a list of the files at a directory path; for this you could use fs.readdirSync():
const soundFile = fs.readdirSync("./sounds/")
fs.readFileSync("./sounds/") is for reading the contents of a file.
You're probably looking for fs.readdirSync("./sounds/") which gives you an array of files in a directory.

client.channels.get(id).send() not working

So a discord bot I'm creating has a twitch notifications, and it uses snekfetch to create a looping request function. On the return of the function I have client.channels.get(id).send(embed) however it doesn't message the channel id which I've given it.
const api = `https://api.twitch.tv/helix/streams?user_login=${streamer}`;
snekfetch.get(api).set('Client-ID', "XXXXXXXXXXXXXX").then(r => {
if (r.body.stream === null) {
setInterval(() => {
snekfetch.get(api).then(console.log(r.body))
}, 30000);
} else {
const embed = new discord.RichEmbed()
.setAuthor(
`${r.body.data.user_name} is live on Twitch`,
)
.setThumbnail(`http://static-cdn.jtvnw.net/ttv-boxart/live_user_${streamer}-500x500.jpg`)
.addField('Views', `${r.body.data.viewer_count}`, true)
return bot.channels.get(XXXXXXXXXXXX).send("TEST");
}
});
I have named my client bot so instead of client.channels it's bot.channels
It should in theory send the TEST message to whatever channel id I give it, however instead I get an error.
(node:62565) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'send' of undefined
at /Users/XXXXXXX/Desktop/HelperBot/main.js:61:50
at processTicksAndRejections (internal/process/task_queues.js:89:5)
(node:62565) 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(). (rejection id: 1)
(node:62565) [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.
your error has to do with that not all channels are text channels. Before you can send a message it has to be sure it can. so you could check if that's the case with the function .isText() when you have checked that it is the type should change to text channels which are dm text and news at this moment. those have the .send function
The error said it can't find the .send("Test") function of something that is not defined.
So the error come from bot.channels.get(XXXX)
bot.channels return a collection. If you search a specific item of this collection. You need to use .find and not .get
More info about .find here : https://discord.js.org/#/docs/main/stable/class/Collection?scrollTo=find

Categories

Resources