How do I send a random Image from a google search? - javascript

I'm VERY new to JavaScript (Started last week), and I couldn't find a working answer.
How does one exactly send a random image with a keyword from Google Images to a Discord Channel?
Here's my code so far:
const GoogleImages = require('google-images');
const Discord = require('discord.js');
const client = new Discord.Client();
const client2 = new GoogleImages('', '');
client.on('ready', () => {
console.log('I am ready!');
});
client2.search('Riolu Pokemon')
.then(images => {});
client.on('message', message => {
if (message.content === 'more riolu') {
return message.channel.send(images);
}
});
client.login('');

Solved with:
const GoogleImages = require("google-images");
const { Client, Attachment } = require("discord.js");
const client = new Client;
const googleImages = new GoogleImages("", "");
async function onMessage(message) {
if (message.content !== "more riolu") return;
try {
const results = await googleImages.search("Riolu Pokemon");
const reply = !results.length ?
"No results" :
new Attachment(results[Math.floor(Math.random() * results.length)].url);
message.channel.send(reply);
}
catch (e) {
console.error(e);
message.channel.send("Error happened, see the console");
}
}
client
.on("ready", () => console.log("I am ready!"))
.on("message", onMessage)
.login("");

Related

discord.js deleting only user messages and bot

I want to make my bot to delete only user's messages in a certain channel and not the bot's. I tried doing it using the code below but it kept on deleting the both the bot's messages and mine.
const Discord = require("discord.js");
const client = new Discord.Client();
const { MessageEmbed } = require("discord.js");
const avalibleFormats = ['png', 'gif', 'jpeg', 'jpg']
client.on("ready", () => {
console.log("I am ready!");
});
client.on("message", message => {
if (message.channel.id == '829616433985486848') {
message.delete();
}
if (message.channel.id !== '829616433985486848') {
return;
}
let image = getImage(message)
if (!image) {
return;
}
let embed = new MessageEmbed();
embed.setImage(image.url)
embed.setColor(`#2f3136`)
message.channel.send(embed)
});
const getImage = (message) => message.attachments.find(attachment => checkFormat(attachment.url))
const checkFormat = (url) => avalibleFormats.some(format => url.endsWith(format))
client.login(token);
Well, you only say that if the channel id is 829616433985486848, delete the message. you should also check if the author is a bot using the message.author.bot property:
const avalibleFormats = ['png', 'gif', 'jpeg', 'jpg'];
const checkFormat = (url) => avalibleFormats.some((format) => url.endsWith(format));
const getImage = (message) => message.attachments.find((attachment) => checkFormat(attachment.url));
client.on('message', (message) => {
const certainChannelId = '829616433985486848';
// if the channel is not 829616433985486848, return to exit
if (message.channel.id !== certainChannelId)
return;
// the rest of the code only runs if the channel is 829616433985486848
const image = getImage(message);
// if author is not a bot, delete the message
if (!message.author.bot)
message.delete();
if (!image)
return;
const embed = new MessageEmbed()
.setImage(image.url)
.setColor('#2f3136');
message.channel.send(embed);
});
Actually, if the message is posted by a bot, you don't even need to run anything in there so you can check that right at the beginning and exit early:
client.on('message', (message) => {
if (message.author.bot || message.channel.id !== '829616433985486848')
return;
const image = getImage(message);
if (image) {
const embed = new MessageEmbed()
.setImage(image.url)
.setColor('#2f3136');
message.channel.send(embed);
}
message.delete();
});
If you want it to work in multiple channels, you can create an array of channel IDs and use Array#includes() to check if the current channel ID is in that array:
client.on('message', (message) => {
const channelIDs = ['829616433985486848', '829616433985480120', '829616433985485571'];
if (message.author.bot || !channelIDs.includes(message.channel.id))
return;
const image = getImage(message);
if (image) {
const embed = new MessageEmbed()
.setImage(image.url)
.setColor('#2f3136');
message.channel.send(embed);
}
message.delete();
});

receive audio form a user with discord bot

I'm working on a discord project and in that project i need to record a user voice, i'm following this document.
so far this is what i wrote:
const fs = require('fs');
const Discord = require('discord.js');
const client = new Discord.Client();
client.once('ready', () => {
console.log('Ready!');
});
client.on('message', async message => {
if (message.content === 'a' && message.member.voice.channel) {
const connection = await message.member.voice.channel.join();
const audio = connection.receiver.createStream('user_id?', { mode: 'pcm' });
audio.pipe(fs.createWriteStream('user_audio'));
}
});
client.login('token');
but the problem is that always the user_audio file is empty!
This is a bug in discord.js, to solve this problem we need to play an audio...
const fs = require('fs');
const Discord = require('discord.js');
const client = new Discord.Client();
const { Readable } = require('stream');
const SILENCE_FRAME = Buffer.from([0xF8, 0xFF, 0xFE]);
class Silence extends Readable {
_read() {
this.push(SILENCE_FRAME);
this.destroy();
}
}
client.once('ready', () => {
console.log('Ready!');
});
client.on('message', async message => {
if (message.content === 's' && message.member.voice.channel) {
const connection = await message.member.voice.channel.join();
const audio = connection.receiver.createStream(message, { mode: 'pcm', end: 'manual' });
audio.pipe(fs.createWriteStream('user_audio'));
connection.play(new Silence(), { type: 'opus' });
console.log(message.member.user.id);
}
});
client.login('token');

Discord JS reaction err

could anyone explain to me why am I getting this error when I'm trying to get my role from a reaction: UnhandledPromiseRejectionWarning: TypeError: reaction.users.last is not a function? Thanks, I've attached the code too.
Code:
const Discord = require('discord.js');
const client = new Discord.Client();
const config = require('./config.json');
client.on('ready', () => {
console.log('Ready!');
});
client.on('message', async (message) => {
if (message.content === 'l!verify') {
const reactmessage = await message.channel.send(
'Am intrebat 100 de Romani, vrei rolul de GUEST?'
);
await reactmessage.react('👌');
const filter = (reaction, user) => reaction.emoji.name === '👌' && !user.bot;
const collector = reactmessage.createReactionCollector(filter, {
time: 15000,
});
collector.on('collect', async (reaction) => {
const user = reaction.users.last();
const guild = reaction.message.guild;
const member = guild.member(user) || (await guild.fetchMember(user));
member.addRole(config.roleid);
});
}
});
client.login(config.token);
MessageReaction.users returns a ReactionUserManager, not a Collection. Make sure to use the cache property.
const user = reaction.users.cache.last();

Post mentioned user's avatar embedded using Discord.js

I'm using Discord.js for a discord bot and I'm trying to make it so that when you do the command !avatar #user
It will reply back with an embedded image of the mentioned user's avatar. I keep getting:
(node:3168) UnhandledPromiseRejectionWarning: DiscordAPIError: Invalid Form Body embed.image.url: Not a well formed URL.
This is the code I have so far, however I'm unaware of how else to grab the user's avatar?
const Discord = require('discord.js');
const config = require('./config.json');
const client = new Discord.Client();
function getUserFromMention(mention) {
if (!mention) return;
if (mention.startsWith('<#') && mention.endsWith('>')) {
mention = mention.slice(2, -1);
if (mention.startsWith('!')) {
mention = mention.slice(1);
}
return client.users.get(mention);
}
}
function getUserFromMentionRegEx(mention) {
const matches = mention.match(/^<#!?(\d+)>$/);
const id = matches[1];
return client.users.get(id);
}
client.once('ready', () => {
console.log('Ready!');
});
const prefix = "!";
client.on('message', message => {
if (!message.content.startsWith(prefix)) return;
const withoutPrefix = message.content.slice(prefix.length);
const split = withoutPrefix.split(/ +/);
const command = split[0];
const args = split.slice(1);
if (command === 'avatar') {
if (args[0]) {
const user = getUserFromMention(args[0]);
const userAvatar = user.displayAvatarURL;
if (!user) {
return message.reply('Please use a proper mention if you want to see someone else\'s avatar.');
}
const avatarEmbed = new Discord.RichEmbed()
.setColor('#275BF0')
.setImage('userAvatar');
message.channel.send(avatarEmbed);
}
return message.channel.send(`${message.author.username}, your avatar: ${message.author.displayAvatarURL}`);
}
});
client.login(config.token);
you dont need parse mentions with another function, discord have method for this. You can use message.mentions.members.first()
And you try to set image a string, with text userAvatar so sure you got error.
You can get mention member avatar and send it with this code.
const Discord = require('discord.js');
const config = require('./config.json');
const client = new Discord.Client();
client.once('ready', () => {
console.log('Ready!');
});
const prefix = "!";
client.on('message', message => {
if (!message.content.startsWith(prefix)) return;
const withoutPrefix = message.content.slice(prefix.length);
const split = withoutPrefix.split(/ +/);
const command = split[0];
const args = split.slice(1);
if (command === 'avatar') {
let targetMember;
if(!message.mentions.members.first()) {
targetMember = message.guild.members.get(message.author.id);
} else {
targetMember = message.mentions.members.first()
}
let avatarEmbed = new Discord.RichEmbed()
.setImage(targetMember.user.displayAvatarURL)
.setColor(targetMember.displayHexColor);
message.channel.send(avatarEmbed);
}
});

Is there a way to delay sending a Discord message after something has successfully loaded?

So, I´ve tried to create a RichEmbed Message which should be executed, right after the User has left the Discord. In this RichEmbed should´ve been a random GIF from giphy, which I´ve created in the getGiphyPic() function using this node module: https://github.com/risan/giphy-random
When this event gets executed, the embed is beeing sent without the .setImage(). I´ve tried to do console.log and it seems like the message is beeing sent, before the URL is successfully created.
I´ve already tried to make the event function async and await the creation of the image var, I´ve also tried to create a promise after the giphyRandom function, but that doesn´t seems to solve my problem.
const Discord = require('discord.js');
const { token, giphyToken } = require('./config.json');
const client = new Discord.Client();
const giphyRandom = require("giphy-random");
function getGiphyPic() {
(async () => {
await giphyRandom(giphyToken, {
tag: "fail",
rating: "pg-13"
}).then(resp => {
let { data } = resp;
console.log('Created GiphyURL: ' + JSON.stringify(data.image_url))
return JSON.stringify(data.image_url);
});
})();
};
client.on('guildMemberRemove', async function (member) {
var logChannel = client.channels.get('60370230389694091');
if (!logChannel) return;
var image = await getGiphyPic();
var embed = new Discord.RichEmbed()
.setColor(0xc62828)
.setAuthor('Someone has left the Server!', member.user.avatarURL);
.setImage(image);
logChannel.send(embed).then(message => console.log("Sent message!"));
});
you could just use the promise supplied to you...
const Discord = require('discord.js');
const { token, giphyToken } = require('./config.json');
const client = new Discord.Client();
const giphyRandom = require("giphy-random");
function getGiphyPic() {
return giphyRandom(giphyToken, {
tag: "fail",
rating: "pg-13"
}).then(resp => {
let { data } = resp;
console.log('Created GiphyURL: ' + JSON.stringify(data.image_url))
return data.image_url; // give correct response
});
};
client.on('guildMemberRemove', function (member) {
var logChannel = client.channels.get('60370230389694091');
if (!logChannel) return;
getGiphyPic().then(image => {
var embed = new Discord.RichEmbed()
.setColor(0xc62828)
.setAuthor('Someone has left the Server!', member.user.avatarURL);
.setImage(image);
logChannel.send(embed).then(message => console.log("Sent message!"));
});
});
async / await can be useful for complex flow control but seems unneeded here, if you want to use it, you're way overcomplicating it:
function getGiphyPic() {
return giphyRandom(giphyToken, {
tag: "fail",
rating: "pg-13"
}).then(resp => {
let { data } = resp;
console.log('Created GiphyURL: ' + JSON.stringify(data.image_url))
return data.image_url;
});
};
just return the promise and async / await will handle the rest.

Categories