Giphy not working on Discord bot (javascript) - javascript

I was following this tutorial on how to make a discord bot, everything was working fine until 33:32 where he added the giphy stuff i had already installed giphy sdk/api, created an application, but after he made the search statement he said you can console log it so i did it, and there were some gif results coming out, which returned undefined on my console(i dunno why), then he added some math stuff, which i also did, then at the point where he added the messaging part where he also added this code files:[responseFinal.images.fixed_height.url] which then returned this on my console
(node:3136) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'images' of undefined
at D:\Discord bots\Oboto v2.0\index.js:24:61
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:3136) 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:3136) [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.
and this confused the flip outta me, then i picked an alt approach, instead of doing giphy.search i did
giphy.random with the same arguments, removed the math stuff and console.log(response)the response and guess what it actually gave me a single gif!(in the console of course) then i implemented to my files:[]statement aaaaand it returned the same thing (cannot read property 'images' of undefined) im also kinda new to discord.js and javascript, also here is my entire code,
const Discord = require('discord.js');
const { prefix, token, giphyToken } = require('./config.json');
const client = new Discord.Client();
var GphApiClient = require('giphy-js-sdk-core')
giphy = GphApiClient(giphyToken)
client.once('ready', () => {
console.log('Ready!');
});
client.on('message', message => {
if (message.member.hasPermission(["KICK_MEMBERS", "BAN_MEMBERS"])){
if (message.content.startsWith(`${prefix}kick`)) {
let member = message.mentions.members.first();
member.kick().then((member) =>{
giphy.random('gifs', {'q':'fail'})
.then((response) => {
console.log(response);
message.channel.send(":wave:",{files:[response.images.fixed_height.url]});
})
})
}
}
})
client.login(token);

cannot read property 'images' of undefined, this means you are trying to access a null object. Same as null pointer exception in java. It means your response is null.
And you are also getting UnhandledPromiseRejectionWarning which means your promise is throwing error which you are not catching anywhere. You can catch your error like this
member.kick().then((member) =>{
giphy.random('gifs', {'q':'fail'})
.then((response) => {
console.log(response);
message.channel.send(":wave:",{files:[response.images.fixed_height.url]});
}).catch(e => { console.error(e}) }
}).catch(e => { console.error(e) }
Now you can see what error you are getting. You can also use try catch approach with async await.

THIS CODE IS FIXED BY ME :D
Discord Bot - Kick member with Giphy
IM NOT A PROFESSIONAL AT ALL.
You can also add this giphy to new member notice.
const Discord = require('discord.js');
const { prefix, token, giphyToken } = require('./config.json');
const bot = new Discord.Client();
var GphApiClient = require('giphy-js-sdk-core');
bot.giphy = GphApiClient(giphyToken);
bot.on('message', (message) => {
if (message.member.hasPermission(['KICK_MEMBER', 'BAN_MEMBERS'])) {
//console.log(message.content);
if (message.content.startsWith(`${prefix}kick`)) {
//message.channel.send("kick")
let member = message.mentions.members.first();
member.kick().then((member) => {
bot.giphy.search('gifs', { q: 'fail' }).then((response) => {
var totalResponses = response.data.length;
var responseIndex = Math.floor(Math.random() * 10 + 1) % totalResponses;
var responseFinal = response.data[responseIndex];
message.channel.send(':wave: ' + member.displayName + ' has been kicked!',{
files: [responseFinal.images.fixed_height.url]
}
)
})
})
}
}
});
bot.login(token);

Related

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.

Node UnhandledPromiseRejectionWarning when saving to MongoDb

New to node- I'm trying to save some of my tweets from Twitter API into mongo using Twit package.
I've connected to mongodb on port 27017 using mongoose, and this piece of code I've written seems to save the tweets to my db, however I seem to be getting this warning back everytime I save a document:
(node:9991) 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: 8)
Here is my code:
const Tweet = require('./app/models/tweet.model.js');
const dbConfig = require('./config/database.config.js');
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect(dbConfig.url, {
useNewUrlParser: true
}).then(() => {
console.log("Successfully connected to the database");
}).catch(err => {
console.log('Could not connect to the database. Exiting now...', err);
process.exit();
});
var Twit = require("twit");
var config = require("./config/twitter.config");
var T = new Twit(config);
var params = {
screen_name: "decade3uk",
count: 2
};
T.get("statuses/user_timeline", params, gotData);
function gotData(err, data, response) {
var tweets = data;
for(var i=0;i<tweets.length;i++){
const tweet = new Tweet({
created_at:tweets[i].created_at,
id_str:tweets[i].id_str,
text:tweets[i].text
});
tweet.save()
.then(entry => {
response.send(entry);
}).catch(err => {
response.status(500).send({
message: err.message || "Some error occurred while creating the Tweet."
});
});
}
}
What is best practice to get rid of this error?
Why don't you try to find where is that exception coming from and what exactly it is. You can find that by adding the following code to your server file, just to make sure you get what's causing the exception.
process.on('unhandledRejection', (reason, promise) => {
console.log("Reason: ",reason,"promise: ",promise);
})

(node:4677) UnhandledPromiseRejectionWarning: Unhandled promise rejection

im creating a discord bot in Glitch.com and i was creating a Warn command, when i finished i try to node him and it works but when I try to warn someone it not warn the user who i selected, so, i go to console log and i fund this error:
"(node:4677) 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: 4)"
I watch the async and for me it its good, but idk, can you please help me?
const Discord = require("discord.js");
const fs = require("fs");
const ms = require("ms");
let warns = JSON.parse(fs.readFileSync("./warnings.json", "utf8"));
module.exports.run = async (bot, message, args) => {
if(!message.member.hasPermission("MANAGE_MEMBERS")) return message.reply("I cant warn a staff member");
let wUser = message.guild.member(message.mentions.users.first()) || message.guild.members.get(args[0])
if(!wUser) return message.reply("Sir >:( listen plez mention someone no trollies >:(");
if(wUser.hasPermission("MANAGE_MESSAGES")) return message.reply("hey stahp u dont have permision >:(");
let reason = args.join(" ").slice(22);
if(!warns[wUser.id]) warns[wUser.i
] = {
warns: 0
};
warns[wUser.id].warns++;
fs.writeFile("./warnings.json", JSON.stringify(warns), (err) => {
if(err) console.log(err);
});
let warnEmbed = new Discord.RichEmbed()
.setDescription("Warns")
.setAuthor(message.author.name)
.setColor("#ff0000")
.addField("Warned User", wUser.tag)
.addField("Warned in", message.channel)
.addField("Number of Warnings", warns[wUser.id].warns)
.addField("Reason:", reason);
let warnchannel = message.guild.channels.fin('name', "incidents");
if(!warnchannel) return message.reply("Couldn't find channel, if you dont have one create one");
warnchannel.send(warnEmbed);
if(warns[wUser.id].warns == 2) {
let muterole = message.guild.roles.fin('name', "muted");
if(!muterole) return message.reply("You dont have a muterole!, that breaks my heart :(!");
let mutetime = "10m";
await(wUser.addRole(muterole.id));
message.channel.send('${wUser.tag} has been temporaly muted');
setTimeout(function(){
wUser.removeRole(muterole.id)
message.channel.reply('Carlos is da best')
})
}
if(warns[wUser.id].warns == 3) {
message.guild.member(wUser).ban(reason);
message.channel.send('${wUser.tag} has been banned.')
}
}
Well, whats happening is something inside your function is throwing an error. A promise is failing to resolve. To handle promises failing you either follow with .catch(callback) if you are using the .then(callback).catch(callback) style, or you surround with
try{
}
catch(err){
}
if you're using async and await. This should help you figure out what is failing exactly

Why does my discord bot ignore awaitMessages?

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

Express route hanging async await

I am converting my application to use async/await instead of callbacks for query request made on the backend. It's been going good so far, but I am on a bit of a snag. My page is hanging on getting a get route and not rendering the ejs page. The console from the server also displays,
(node:7036)
UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): ReferenceError: qryFindLocalID is not defined
(node:7036) .
[DEP0018] DeprecationWarning: Unhandled promise rejections are depreca
ted. In the future, promise rejections that are not handled will terminate the Nod
e.js process with a non-zero exit code.
Any help would be appreciated.
The code so far is,
router.get("/secure", async (req, res) => {
let user = req.session.passport.user;
try {
if (user.chkUserStatus) {
if (user.lWaterLabID == 0 || user.lWaterlabID == -9999) {
// in both cases sLabID is set to 0
// assign the correct value for sLabName
user.sLabName = user.lWaterLabID == 0 ? "Site Admin" : "Uber Admin";
} else {
let labName = await request.query(
"Some Query"
);
user.sLabName = labName[0].sLabName;
}
} else {
// Houston we've got a problem ...
// user.chkUserStatus is not truthy
req.flash("loginMessage", "User Status is invalid.");
res.redirect("/");
}
const qryFindLocalID = await request.query(
`Some Query`
);
if (user.lWaterLabID == 0) {
const listRecentReports = await request.query(Some Query);
} else {
const listRecentReports = await request.query(Some Query);
}
} catch (err) {
// ... error checks
}
res.render("secure/index", {
qryFindLocalID: qryFindLocalID,
user: user,
listRecentReports: listRecentReports
});
});
The error message talks about an unhandled promise, but that's just wrapping the actual error, which is: ReferenceError: qryFindLocalID is not defined.
So where are you using qryFindLocalID? Ah, right at the bottom in the res.render call.
res.render("secure/index", {
qryFindLocalID: qryFindLocalID,
user: user,
listRecentReports: listRecentReports
});
Now why is qryFindLocalID undefined here? You defined it above in the try-catch block. But there's your problem -- You used const, so qryFindLocalID only exists in the try-catch. Outside of that, it doesn't exist.
You can fix that by using var in the try-catch (var is scoped to the function), or define qryFindLocalID using let ABOVE the try-catch.

Categories