Google search with discord bot - javascript

I am working on a bot who searches to google with given arguments.
So i just want it to send the link of the top result found on google kinda like this
so here is the code till now
const Discord = require(`discord.js`);
const bot = new Discord.Client();
const config = require('./botconfig.json');
const prefix = '!g'
bot.on('ready', () => {
console.log('Google-Bot is ready!');
})
bot.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const searchTopic = args.join(' ')
//here it searches on google and provides the link
message.channel.send(`Here is the result! \n ${result}`)
})
bot.login(config.token)
thank you for reading!

You can simply add a link to the requested argument by using https://google.com/search?q=${args.join('+')}, then send it.
Example:
message.channel.send(`https://google.com/search?q=${args.join('+')}`)
You also need to join with a + because google encodes any spaces with a plus symbol.
I also have a suggestion that could lead to a potential problem.
First, make sure you're using the slice attribute after your args.join('+') to exclude the prefix from the argument. So you could use args.join('+').slice(1).
Here is your improved code:
const Discord = require(`discord.js`);
const bot = new Discord.Client();
const config = require('./botconfig.json');
const prefix = '!g'
bot.on('ready', () => {
console.log('Google-Bot is ready!');
})
bot.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const searchTopic = args.join('+').slice(1)
let googleResult = `https://google.com/search?q=${searchTopic}`
let searchEmbed = new Discord.MessageEmbed()
.setColor("#00ff00")
.setDescription(`Here's what Google came up with for ${searchTopic}!\n${googleResult}`)
message.channel.send(searchEmbed)
})
bot.login(config.token)

Related

handledPromiseRejectionWarning: TypeError: Cannot read property 'add' of undefined (Discord Bot)

I have been dealing with an issue with my discord bot captcha. The captcha works really well but when it comes to adding a role if they verified it slaps me with
handledPromiseRejectionWarning: TypeError: Cannot read property 'add' of undefined
This is my code:
const Discord = require('discord.js-12');
const client = new Discord.Client();
const prefix = 'ri-';
const Captcha = require("#haileybot/captcha-generator");
client.once('ready', () => {
console.log('Ready!');
});
let captcha = new Captcha();
console.log(captcha.value);
const path = require("path"),
fs = require("fs")
client.on('message', async message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
if (command === 'verification') {
let captcha = new Captcha();
message.channel.send(
"**Enter the text shown in the image below:**",
new Discord.MessageAttachment(captcha.JPEGStream, "captcha.jpeg")
);
let collector = message.channel.createMessageCollector(m => m.author.id === message.author.id);
collector.on("collect", m => {
if (m.content.toUpperCase() === captcha.value){ message.channel.send("Verified Successfully!");
let role = message.guild.roles.cache.find(r => r.id === "Verified");
message.author.roles.add(role);
}else{ message.channel.send("Failed Verification!");}
collector.stop();
});
}
});
client.login('you don't need this.');
Any help is appreciated! ^^
Error:
I see two problems in your code.
message.author refers to an user, which does not hold roles. Use message.member instead
Replace r.id with r.name, id is not a string.
Have a great day :)

Long discord.js arguments

I'm starting with discord.js and I have a question. Is it possible to make an infinite argument currently I have to use message.channel.send(${args}) and for example when I type $test 1 2 only 1 will be sent and 2 will not please help I wanted to make a reason for the command $kick but only one argument the first is often seen only the first sentence instead of the whole reason please help!
I don't think you know what I mean, I mean that the argument should not be a single word, for example command:$embed hello word :) I want the bot to send: hello word :) but it sends: hello without word and :) it doesn't have to be hello word :) it has to be the words given by the user I hope I wrote it clearly for any help thank you!
const Discord = require('discord.js');
const client = new Discord.Client();
const config = require('./config.json');
const fs = require('fs');
const prefix = "$";
const RED = "#EC0F0F";
const BLUE = "#1725E7";
const GREEN = "#17E729";
const FIOLET = "#880FEC";
client.once('ready', () => {
console.log('Ready!');
});
client.on('message', async message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(' ');
const command = args.shift().toLowerCase();
console.log(message.content);
if (message.content === `$embed`) {
const embesmess = new Discord.MessageEmbed()
.setTitle(`${args[0]}`)
.setColor(`${GREEN}`)
.setdescription(`HERE I WANT THIS ARGUMENT`)
message.channel.send(embesmess);
}
});
client.login(config.token);
Use something like
if (message.content.startsWith(`$embed`)) {
const embesmess = new Discord.MessageEmbed()
.setTitle(`${args.slice(1).join(" ")}`) //join all arguments besides the first
.setColor(`${GREEN}`)
.setdescription(`HERE I WANT THIS ARGUMENT`)
message.channel.send(embesmess);
}
This will combine all of your arguments excluding the first.

How can you get user responses from a dm? (Discord Node js bot)

I've started making a bot for my discord server since something happened to the last one.
I've been trying to get the bot to get the user's (it DMS) input, but can't figure out how to do this.
Down below is what I have done so far
const Discord = require('discord.js');
const client = new Discord.Client();
const prefix = 'a!';
const Commands = '!help !version !post';
const MarketplaceCommnads = "Looking for Devs For Hire Looking for Creations Sell Creations"
const Version = '1.0.0';
client.once('ready', () => {
console.log('Bot is online!');
});
const helpEmbed = new Discord.MessageEmbed()
.setTitle('Help')
.setColor('#ff0000')
.addField('Command List', Commands)
const postEmbed = new Discord.MessageEmbed()
.setTitle("Post")
.setColor("#ff0000")
.addField('The bot has dmed you')
const dmEmbed = new Discord.MessageEmbed()
.setTitle("New Post")
.setColor("#ff0000")
.addField("Create a new post", MarketplaceCommnads)
const lookingfordevsEmbed = new Discord.MessageEmbed()
.setTitle("Looking for Devs")
.setColor("#ff0000")
.addField("Post everything here (What you're looking for, payment, etc): ")
const versionEmbed = new Discord.MessageEmbed()
.setTitle('Version')
.setColor('#ff0000')
.addField('Version', Version)
.setColor('#ff0000')
client.on('message', message =>{
if(!message.content.startsWith(prefix) || message.author.bot ) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if (command === 'help'){
message.channel.send(helpEmbed);
}
if (command === 'version'){
message.channel.send(versionEmbed);
}
if (command === 'post'){
message.channel.send(postEmbed);
message.author.send(dmEmbed);
const Message = Response()
if (Message === 'Looking for Devs'){
message.author.send(lookingfordevsEmbed);
}
}
});
I've used Node JS before, but this is the first time I've created a bot, so I'm trying to learn how all of this works so this may seem like an obvious error. Solutions I have tried before making this question: Youtube and Googling
So you can first check if it is a DM by using Message#channel and seeing if it is a DMChannel and to get their User you can do Message#author which returns a User.
Here is the documentation for each things I have talked about
Message: https://discord.js.org/#/docs/main/stable/class/Message
DMChannel: https://discord.js.org/#/docs/main/stable/class/DMChannel
User: https://discord.js.org/#/docs/main/stable/class/User
Hope this helped!

Discord.jc / ReferenceError: MessageAttachment is not defined

I get this error and it seems that the bot cannot find an image.
How do I define the path of the image? It is located in: C:\Users\Yanzi\Desktop\LaisaBot\Emotes?
const Discord = require("discord.js");
const config = require("./config.json");
const client = new Discord.Client();
const prefix = "!";
client.on("message", function(message) {
if (message.author.bot) return;
if (!message.content.startsWith(prefix)) return;
const commandBody = message.content.slice(prefix.length);
const args = commandBody.split(' ');
const command = args.shift().toLowerCase();
if (command === "ping") {
const timeTaken = Date.now() - message.createdTimestamp;
message.reply(`Pong! This message had a latency of ${timeTaken}ms.`);
} else if (command === "sum") {
const numArgs = args.map(x => parseFloat(x));
const sum = numArgs.reduce((counter, x) => counter += x);
message.reply(`The sum of all the arguments you provided is ${sum}!`);
}
// If the message is '!rip'
else if (message.content === '!rip') {
// Create the attachment using MessageAttachment
const attachment = new MessageAttachment('./laisa2.png');
// Send the attachment in the message channel with a content
message.channel.send(`${message.author},`, attachment);
}
});
client.login(config.BOT_TOKEN);
You are calling MessageAttachment when you have not defined it.
It is part of the Discord libary you required at the top so you have two solutions:
Use new Discord.MessageAttachment instead of new MessageAttachment
Where you required Discord at the top replace this with { MessageAttachment }, please be aware that you will also need to add , client and others to that object as you are calling Discord.Client further up. This will result in const { MessageAttachment, Client } = require('discord.js');
I hope this helps, be sure to read the docs and checkout some tutorials.
You can take a look here for info on destructing:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
https://dmitripavlutin.com/javascript-object-destructuring/

How to make commands for discord bot non-case sensitive

const Discord = require("discord.js");
//ignore 1 up and 1 down
const client = new Discord.Client();
//prefix
const prefix = `+`;
//log for me
client.once(`ready`, () => {
console.log("IM POWERED UP")
});
//commands
client.on(`message`, message =>{
const args = message.content.slice(prefix.lengh).split(/ +/);
//Username..(embed)
if (message.content === `${prefix}Username`){
let messageArray = message.content.split(" ");
let args = message.content.split(` `);
let command = messageArray[1].toLowerCase();
const embed = new Discord.MessageEmbed()
.setTitle(`user information`)
.addField(`Your Username is`, message.author.username)
.addField(`Bugs`, `To report bugs please go to TxPsycho#1080 and you may earn a reward!`)
.setThumbnail(message.author.displayAvatarURL())
.setFooter(`Wanna get Valorant cheats? Join here`)
.setColor(`RANDOM`)
message.channel.send(embed);
}
//help command
if (message.content === `${prefix}Help`){
const embed = new Discord.MessageEmbed()
.setTitle(`Help`)
.addField(`A list of commands are below!`)
.setThumbnail(message.author.displayAvatarURL())
.setDescription(`AMOTHERFUCKINGTESTYOUMOTHERFUCKAYOUTHINKITSFUNNYCALLINGAT2AM`)
.setColor(`RANDOM`)
message.channel.send(embed);
}
});
//ignore this and leave it at bottom
client.login(`Nz`)
I am not sure how to make the commands caps insensitive, this is the error it’s been giving me. I have been searching but found no information. Down below is the link to an error that I have been receiving when I try to debug the code.
Click here to see the error picture
Like rogue said the issue is calling toLowerCase on undefined here:
let command = messageArray[1].toLowerCase();
The real command would be at 0, since arrays are 0 indexed
You might want to shift it instead so you can get the args easier:
Message: !help 12 24 36
const args = message.content.split(" ");
const command = args.shift().toLowerCase();
console.log(args);
// => [12, 24, 36]
console.log(args[0]);
// => 12
After that you just compare command instead of message.content:
if(command === "!help") {
}
You can sanitise messages with toLowerCase
console.log('ALPHABET'.toLowerCase()); // 'alphabet'
console.log('aLPhABeT'.toLowerCase()); // 'alphabet'
console.log('alphabet'.toLowerCase()); // 'alphabet'

Categories