Why does my discord bot ignore awaitMessages? - javascript

i tried using await message to store words in an array and then send them to discord. Here's the bot code:
const Discord = require('discord.js');
const {prefix, token} = require('./config.json');
const client = new Discord.Client();
client.once("ready", (message) => {
console.log("Bot is online!");
client.user.setActivity("Komnata", {type: "WATCHING"});
})
client.on("message", async message => {
if (message.content.startsWith(`${prefix}role`)) {
await message.delete();
const filter = m => {m.author.id === message.author.id};
message.reply("Choose embed title (message will expire after 10 seconds").then(r => r.delete(10000));
message.channel.awaitMessages(filter, {max: 1, time: 10000}).then(collected => {
var newArray = []
newArray.push(collected);
message.channel.send(newArray[0])
}).catch(err =>{
message.reply("Time has expired!").then(r => r.delete(3000));
})
}
})
client.login(token);
When i send a message to the channel(which contains one word), the bot completely ignores it and i get an error in the console:
Bot is online!
(node:3228) UnhandledPromiseRejectionWarning: DiscordAPIError: Cannot send an empty message
at item.request.gen.end (c:\Users\Adam\Desktop\botd\node_modules\discord.js\src\client\rest\RequestHandlers\Sequential.js:85:15)
at then (c:\Users\Adam\Desktop\botd\node_modules\snekfetch\src\index.js:215:21)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:3228) 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: 2)
(node:3228) [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.

Solved: i had to leave out the curly brackets on the filter

Related

I am getting a 400 bad request while using google custom search with discord.js! what am I doing wrong here?

I am building a discord bot which searches a query on google using the custom search api but i am getting this error! here's my code, what am i doing wrong?
const Discord = require("discord.js");
const request = require("node-superfetch");
var fs = require('fs');
module.exports = {
name: 'google',
description: "searches google ",
cooldown: 10,
permissions: [],
async execute(message, args, cmd, client, Discord) {
let googleKey = "XXXX";
let csx = "be4b47b9b3b849a71";
let query = args.join(" ");
let result;
if(!query) return message.reply("Please enter a Valid Query");
result = await search(query);
if (!result) return message.reply("Invalid Search");
const embed = new Discord.MessageEmbed()
.setTite(result.title)
.setDescription(result.snippet)
.setImage(result.pagemap ? result.pagemap.cse_thumbnail[0].src : null)
.setURL(result.link)
.setColor(0x7289DA)
.setFooter("Powered by Google")
return message.channel.send(embed);
async function search(query) {
const { body } = await request.get("https://customsearch.googleapis.com/customsearch/v1").query({
key: googleKey, cs: csx, safe: "off", q: query
});
if(!body.items) return null;
return body.items[0];
}
}
}
ERROR MESSAGE: (node:10944) UnhandledPromiseRejectionWarning: Error: 400 Bad Request
at Request._request (D:\Coding\FLASH\node_modules\node-superfetch\index.js:58:16)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at async search (D:\Coding\FLASH\commands\google.js:31:26)
at async Object.execute (D:\Coding\FLASH\commands\google.js:17:14)
(Use node --trace-warnings ... to show where the warning was created)
(node:10944) 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:10944) [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.

DiscordAPIErrorL: Missing Access

I can't seem to figure out the problem with my code. I don't see no errors but when it joins a server, it'll error out and possibly stop running. I would appreciate the help!
index.js
const Discord = require('discord.js');
const client = new Discord.Client();
const KeepAlive = require('./server');
client.on('message', function (msg) {
const Logged = new Discord.MessageEmbed()
.setTitle(msg.author.tag)
.setDescription(msg.content)
.setColor('0x00AAFF')
.setTimestamp();
if(msg.author.id === 'BOT-ID-GOES-HERE') {
console.log('')
} else if(msg.author.username) {
const channel = client.channels.cache.find(channel => channel.name === 'logs')
channel.send(Logged)
}
});
client.on('ready', ()=> {
console.log('Connected as '+client.user.tag)
});
KeepAlive()
client.login(process.env.token);
server.js
const express = require('express')
const server = express()
server.all('/', (req, res) => {
res.send('Bot is running!')
});
function KeepAlive() {
server.listen(671, () => {});
console.log('Server is ready!')
}
module.exports = KeepAlive
now the error is
(node:313) UnhandledPromiseRejectionWarning: DiscordAPIError: Missing Access
at RequestHandler.execute (/home/runner/Censored-Logging/node_modules/discord.js/src/rest/RequestHandler.js:154:13)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
at async RequestHandler.push (/home/runner/Censored-Logging/node_modules/discord.js/src/rest/RequestHandler.js:39:14)
(node:313) 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:313) [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'm still pretty new with errors, I can't read them properly.

How to fix Unhandled promise rejection in nodejs?

I get an error message I don't know how to fix:
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: 2)
My code:
const Discord = require('discord.js');
const client = new Discord.Client();
const fs = require('fs');
client.login('NzUzNzAwMzQ2MDI2Nzg2ODI2.X1qAJQ.K-2nBZOSxz8k0LAnGmNC_EGaKqQ');
(async () => {
client.on('message', async (message) => {
// Voice only works in guilds, if the message does not come from a guild,
// we ignore it
if (!message.guild)
return;
if (message.content === '/join') {
// Only try to join the sender's voice channel if they are in one themselves
if (message.member.voice.channel) {
const connection = await message.member.voice.channel.join();
} else {
message.reply('You need to join a voice channel first!');
}
const dispatcher = connection.playFile('C:/Users/vikto/Desktop/FFBot/Audio/gab.mp3');
}
});
throw();
})()
client.login('NzUzNzAwMzQ2MDI2Nzg2ODI2.X1qAJQ.K-2nBZOSxz8k0LAnGmNC_EGaKqQ');
you should encompass all that code inside a try catch as there several statements can also produce a rejected promise.

DiscordJS Making bot that can assign a role when a message is reacted to

Upon running the command, the bot should post an embed message with a reaction (which it does, but with an error). The error has to do with assigning the role I believe because no role is assigned when a reaction is added. If there is an easier way to do this using the role id instead of searching for the role name I could do that too.
read-me-first.js
module.exports = {
name: 'read-me-first',
cooldown: 5,
description: 'Server verification',
// eslint-disable-next-line no-unused-vars
execute(message, args) {
message.delete();
const Discord = require('discord.js');
const exampleEmbed = new Discord.MessageEmbed()
.setColor('#E33333')
.setTitle('VERIFICATION')
.setDescription('<a:loading:717623386247004270> By reacting to this message, you agree to the <#717624229713018910> and gain access to the rest of the discord server. <a:loading:717623386247004270>')
.attachFiles(['/home/shares/public/BytePvP/bytepvp.png'])
.setThumbnail('attachment://bytepvp.png')
// .setTimestamp()
.setFooter('BytePvP', 'attachment://bytepvp.png');
if (!message.member.hasPermission('MANAGE_MESSAGES')) {
return message.reply('You do not have permission to use this command!');
}
message.channel.send({ embed: exampleEmbed }).then(embedMessage => {
embedMessage.react('717623421068116008')
.catch(() => console.error('One of the emojis failed to react.'));
});
const filter = (reaction, user) => {
return ['717623421068116008'].includes(reaction.emoji.name) && user.id === message.author.id;
};
message.awaitReactions(filter, { max: 1, time: 60000, errors: ['time'] })
.then(collected => {
const reaction = collected.first();
const role = message.guild.roles.cache.find(role => role.name === 'Member');
const member = message.mentions.members.first();
member.roles.add(role);
});
},
};
Error:
(node:32547) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'roles' of undefined
at /home/shares/public/BytePvP/commands/read-me-first.js:35:12
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:32547) 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:32547) [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.
Edits made:
message.awaitReactions(filter, { max: 1, time: 60000, errors: ['time'] })
.then((collected, user) => {
const reaction = collected.first();
const role = message.guild.roles.cache.find(role => role.name === 'Member');
const member = message.guild.member(user);
member.roles.add(role);
});
New error:
(node:24026) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'roles' of null
at /home/shares/public/BytePvP/commands/read-me-first.js:35:12
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:24026) 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:24026) [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.```
Alternatively, you could use :
.then((collected, user) => {
and then convert the user into a member using :
const member = message.guild.member(user);

Running code with node.js gives an error, but without node it works perfectly

Im using Visual Studio Code. When i run my code normally(CTRL+ALT+N), it works perfectly. However, when i run it in Windows Powershell with node.js, it gives me an error.
This is my code:
if (message.content.startsWith(`${prefix}role`)) {
const filter = m => m.author.id === message.author.id;
message.delete(1);
message.reply("Choose title (message will expire after 10 seconds")
.then((r) => {
sleep(1)
botlastMSG = message.channel.lastMessageID
r.delete(10000)
})
message.channel.awaitMessages(filter, {max: 1, time: 10000, errors: ['time']}).then(collected => {
var response = collected.first().content
var respMsG = message.channel.lastMessageID
message.channel.fetchMessage(botlastMSG).then(msg => msg.delete(1));
if (response == "cancel") return message.channel.send("Cancelled!").then(r => r.delete(2000))
newArr.push(response)
show = 1
message.channel.fetchMessage(respMsG).then(msg => msg.delete(1))//deletes response
}).catch(err =>{message.reply("Time has expired!").then(r => r.delete(3000))})
while (show == 0) {
await sleep(1)
}
And this is the error i get when its run with node:
(node:23652) UnhandledPromiseRejectionWarning: DiscordAPIError: Cannot send an empty message
at item.request.gen.end (C:\Users\Adam\Desktop\botd\node_modules\discord.js\src\client\rest\RequestHandlers\Sequential.js:85:15)
at then (C:\Users\Adam\Desktop\botd\node_modules\snekfetch\src\index.js:215:21)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:23652) 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: 2)
(node:23652) [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.

Categories