I started to program a Discord-Bot, he hasn't that much functions at the moment. So at the moment im working on the command "!gif", so I type that command with an word (here it is "spider"), as a reponse I get a gif with a Spider-Tag.
So here is my Discord-Code:
if(command == "gif"){
message.channel.send(modSearchGif.searchForGif("spider"));
}
modSearchGif is a module which is implemented in this .js script.
The Module looks like this:
var GphApiClient = require('giphy-js-sdk-core')
const client = GphApiClient(process.env.GIPHYTOKEN)
const searchForGif = (gifName) => {
client.search('gifs', {"q": gifName, "limit": 1})
.then((response) => {
var gif = response.data[0].url;
return gif;
})
.catch((err) => {
return err;
})
}
module.exports.searchForGif = searchForGif;
So its really easy, if the command "gif" is writen in the Discord-Channel, the Bot is calling the module and give it the parameter "spider". Then the client search for this parameter in the giphy database and returns a json script. This is a Promise, if the Promise is fullfilled the gif is returned to the mainscript and will be send to the Discord-Channel.
Here is the Problem, the Promise call is async, so the Discord Command "message.channel.send" is executed before the promise is fullfilled, so the message is undefined and i get an error "Cannot send empty message".
I want the message.channel.send executed when the gif is returned, not earlier.
I really have no clue about this. Have you guys some ideas?
Thank you in advance!