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

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

Related

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

Emoji List Command Discord.js v12

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.

add roles to discord member

it was not giving an error a few days ago, now it is giving an error strangely.
when i add code to add or remove a role, I get this error.
My code:
let member = message.mentions.members.first();
let role = message.guild.roles.get("707628035498836069");
let role1 = message.guild.roles.get("769919065551929385");
member.addRole(role);
member.removeRole(role1);
Error code:
(node:16668) UnhandledPromiseRejectionWarning: TypeError: Supplied parameter was neither a Role nor a Snowflake.
at GuildMember.removeRole (C:\Users\user\Desktop\discordjssss\node_modules\discord.js\src\structures\GuildMember.js:516:38)
at Object.module.exports.baslat (C:\Users\user\Desktop\discordjssss\komutlar\genel\jaildenm.js:22:10)
at AdvancedClient.<anonymous> (C:\Users\user\Desktop\discordjssss\node_modules\discordjs-advanced\src\client.js:549:5)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:16668) 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:16668) [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.
In discord.js v.12 you need to use a slighty different syntax for finding and adding roles.
You find the roles by accessing the new cache object.
message.guild.roles.cache.get('your ID here');
You now add or remove the roles within the GuildMemberRoleManager.
member.roles.add(role here);
member.roles.remove(role here);
It needs to be said that you don't need to get the role object first. You can simply use the ID. But if you get the role first you can check if it actually exists. But that is neither here nor there.
Note: Your original problem was that your role wasn't found. Either because the role doesn't exist or the ID was wrong.

How can I get a Minecraft player's UUID from their username in NodeJS?

I know there are lots of other posts asking this same questions, but none of the others had the solution to my problem. I am using NodeJS and DiscordJS to create a discord bot, and I need to get the UUID of a Minecraft player from just their username, which will be provided as an argument in the command.
This is the function I have created to do this, however it doesn't seem to be working.
function getId(playername) {
const { data } = fetch(`https://api.mojang.com/users/profiles/minecraft/${args[2]}`)
.then(data => data.json())
.then(({ player }) => {
return player.id;
});
}
args[2] is the third argument of the command, which is formatted like this: <prefix> id <playername>. fetch is part of the 'node-fetch' npm module, which I have installed. I call the function when the command is sent, and it fetches the data from Mojang's API, but it can't get the UUID. This is the error:
(node:39416) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'id' of undefined
at C:\Users\archi\OneDrive\Documents\Programming\Discord Bots\Hypixel Discord Bot\index.js:161:21
at processTicksAndRejections (internal/process/task_queues.js:94:5)
(node:39416) 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:39416) [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.
It is saying it cannot read the property of 'id', which if you use the Mojang API, is the key for the UUID of a player. Any ideas?
Try using the playername instead of args[2] in the request URL, and making it return a promise. There's also no need to use { player }, as the object the API returns doesn't have a player propriety. Just use player as the argument for the arrow function.
function getId(playername) {
return fetch(`https://api.mojang.com/users/profiles/minecraft/${playername}`)
.then(data => data.json())
.then(player => player.id);
}
Then call it like so in your code:
// Using .then (anywhere)
getId(args[2]).then(id => {
console.log(`ID is ${id}`)
})
// Using await (inside of an async function)
const id = await getId(args[2])
console.log(`ID is ${id}`)

How do I scrape down a asynchrous JSON variable?

I am trying to make a Node.js bot, so I found a module, installed it and tried out its example code.
Now, I have an async function that loads some text from an API. This is the code:
(async () => {
// Display user's balance
balance = kraken.api('Balance');
console.log(await balance);
})();
When I run the code above, this is what I get in commandprompt:
{
error: [],
result: { A: '2.0', BC: '0.005', BCA: '111' }
}
How would I be able to make it only log a specific part of this, which looks like an array?
I've tried doing stuff like (to get it to return 2.0):
console.log(await balance.result.A)
But that does not seem to work as it returns this:
(node:6604) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'A' of undefined
(node:6604) [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.
Out of ideas and need help.. Thanks!
You habe to put your await statement in parentheses, like this:
console.log((await balance).result.A);
This will fetch the balance asynchronously, then log the result property.

Categories

Resources