discord.js - put code into embed - javascript

I have the following code:
("...............🚗......").then(sentMessage => sentMessage.edit("............🚗.........")).then(sentMessage => sentMessage.edit("........🚗............")).then(sentMessage => sentMessage.edit(".....🚗...............")).then(sentMessage => sentMessage.edit("..🚗..................")).then(sentMessage => sentMessage.edit("🚗....................")).then(sentMessage => sentMessage.edit("😮....🚗..............")).then(sentMessage => sentMessage.edit(".😧..🚗......................")).then(sentMessage => sentMessage.edit("..:tired_face:.:red_car:......................")).then(sentMessage => sentMessage.edit("...:ghost::red_car:......................")
How can I put this into a discord.js embed with the following code:
message.channel.send({
"embed": {
"title": "Car",
"description": - i want the above code to be here -,
"color": 16763981,
"footer": {
"text": "Have a fun ride!"
}
}
})
}
Is this possible in discord.js? If so, please help me out! Have no clue how to achieve this.
:) Will

I don't know what exactly you are trying to do. I guess what you made is an animation, if not, and you just want to print litterally this piece of code in your embed, just put this piece of code inside backticks
description: `("...............🚗......")
.then(sentMessage => sentMessage.edit("............🚗........."))
.then(sentMessage => sentMessage.edit("........🚗............"))
.then(sentMessage => sentMessage.edit(".....🚗..............."))
.then(sentMessage => sentMessage.edit("..🚗.................."))
.then(sentMessage => sentMessage.edit("🚗...................."))
.then(sentMessage => sentMessage.edit("😮....🚗.............."))
.then(sentMessage => sentMessage.edit(".😧..🚗......................"))
.then(sentMessage => sentMessage.edit("..:tired_face:.:red_car:......................"))
.then(sentMessage => sentMessage.edit("...:ghost::red_car:......................")`,
Then it looks like this :
If you want to make an animation, you're gonna have to use the bot to delete and rewrite the embed for each step of your animation (You can't just edit an embed if I'm not wrong)
Try to be more specific on what you really want to display

If I'm understanding you correctly, you want to send the first snippet of code into the description field and edit it, trying to make it be an animation?
I haven't tried editing an embedded message before but this is how I would go around it.
const sendCarAnimation = async (message) => {
// define the steps here
const animationSteps = [
"...............🚗......",
"............🚗.........",
"........🚗............",
".....🚗...............",
"..🚗..................",
"🚗....................",
"😮....🚗..............",
".😧..🚗......................",
"..:tired_face:.:red_car:......................",
"...:ghost::red_car:......................"
];
// generate an embed using the RichEmbed functionality
const embed = new Discord.RichEmbed()
.setTitle('Car')
.setDescription(animationSteps[0])
.setColor(16763981)
.setFooter('Have a fun ride!')
// initialize the message with the first embed
let messageState = await message.channel.send(embed);
// loop through and edit the message
let isFirst = true;
for(let currentStep of animationSteps) {
if(isFirst) {
isFirst = false;
continue;
}
embed.setDescription(currentStep);
messageState = await messageState.edit(embed);
}
}
NOTE: This will take a lot of requests to do and you will most likely get rate limited by discord for doing this. So I don't think this is a good idea. Here's their documentation on it. You can probably pull off some tricky code using the Discord.js's
client.on('rateLimit', (rateLimitInfo) => {});
event. Documentation link to this as well. Good luck!

Instead of deleting it and sending it again you can create a variable of the lastMessage (you might have to make a delay before selecting it) then do message.edit()

Got it! What I did to solve it was on startup, to grab the right channel using channel = client.user.guilds.cache.get("Guild id here").channels.cache.get("channel id"), built an embed that just said old, and then sent the embed.
I did include an array of animation steps like Emil Choparinov, and a msgProgress variable. The bot detects when a message is sent, and checks if (msg.content === ''). if true, it will set the recievedEmbed constant to msg.embeds[0].
Then, a new const, embed, is set to a new Discord.MessageEmbed, using the old embed as a starting point, and setting the title to animationSteps[msgProgress]. It then calls msg.edit(embed), and changes the msgProgress variable by 1.
There is also a client.on('messageUpdate', msg => {}), and it has the same code, except at the start, it checks if msg progress > 9, and if so, it returns. Here is the code:
require('dotenv').config();
const Discord = require('discord.js');
const client = new Discord.Client();
var channel;
const genericEmbed = new Discord.MessageEmbed()
.setTitle("old");
const animationSteps = [
"...............:red_car:......",
"............:red_car:.........",
"........:red_car:............",
".....:red_car:...............",
"..:red_car:..................",
":red_car:....................",
":open_mouth:....:red_car:..............",
".:cold_sweat:..:red_car:......................",
"..:tired_face:.:red_car:......................",
"...:ghost::red_car:......................"
];
var msgProgress = 0;
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
channel = client.guilds.cache.get("753227876207165570").channels.cache.get("753227876207165573");
console.log(channel);
const firstEmbed = new Discord.MessageEmbed()
.setTitle("old");
channel.send(firstEmbed);
});
client.on('message', msg => {
if (msg.content === '') {
console.log("good");
channel = msg.channel;
const receivedEmbed = msg.embeds[0];
const embed = new Discord.MessageEmbed(receivedEmbed)
.setTitle(animationSteps[msgProgress]);
msg.edit(embed);
msgProgress++;
}
});
client.on('messageUpdate', msg => {
if (msgProgress > 9) {
return;
}
if (msg.content === '') {
console.log("good");
channel = msg.channel;
const receivedEmbed = msg.embeds[0];
const embed = new Discord.MessageEmbed(receivedEmbed)
.setTitle(animationSteps[msgProgress]);
msg.edit(embed);
msgProgress++;
}
});
client.login(process.env.DISCORD_TOKEN);
Hope this helped! 😃

Related

Optional Arguments in Commands

EDIT
I doubt if you can find a correct answer below since this question is too general. And the answer posted by me will most likely only work for that cmd handler and the version this was written for is v12
--Original Question--
how do I make the options like ?d and ? f optional and the order want matter but it will create the embed on the given options
'example: .embed ?d description: this will create an embed with only a description'
I have already tried but I messed up here is the code [Removed for private reasons]
but this outputs this : [removed]
What you need to do is : go in your main file(like index.js) and set in top of code this :
const Discord = require('discord.js');
Then where command 'embed' is you need to set this :
if(command === 'embed'){
client.commands.get('embed').execute(message, args, Discord);
Then in your command folder you will make a file named embed.js . In embed.js you need to set this code:
module.exports = {
name: 'embed',
description: 'Embed Test',
execute(message, args, Discord){
const newEmbed = new Discord.MessageEmbed()
.setTitle('Your Title')
.setColor('RANDOM')
.setFooter('Some Footer here', 'another footer here' )
.setDescription('> ?testa\n' + '> ?testb\n' + '> testc');
message.delete();
message.channel.send(newEmbed);
}
});
And you get only the description after command and message with command ([prefix]embed) will delete after you post it !
Okay i fixed it my self : )
i splited the args by (?) and went through each value to see if the args have the needed options
here is what I did for future reference :
let text = args.join(' ')
const Embed = new Discord.MessageEmbed()
let errrors = []
if(!text) return message.channel.send('Error')
let tex = text.split('?')
tex.forEach(async e => { .........
if(e.toLowerCase().startsWith('d')) {
let description = e.replace('d', '')
if(description.length == 0) {
return await errrors.push('Description option was given but no description was given!!')
} else {
await Embed.setDescription(description)
}
} else if(e.toLowerCase().startsWith('t')) ........
}
// then
if(errrors.length > 0) {
let errr = errrors
Embed.setTitle('Following errors occured while constructing your embed')
Embed.setDescription(errr)
return message.channel.send(Embed)
} else {
message.channel.send(Embed)
}

How do I make a user answer a question using reactions in Discord.js?

I want the user to answer a "yes or no" question using reactions. Here is my code below.
var emojiArray = ['🔥', '👍', '👎', '✅', '❌'];
client.on('message', (negotiate) => {
const listen = negotiate.content;
const userID = negotiate.author.id;
var prefix = '!';
var negotiating = false;
let mention = negotiate.mentions.user.first();
if(listen.toUpperCase().startsWith(prefix + 'negotiate with '.toUpperCase()) && (mention)) {
negotiate.channel.send(`<#${mention.id}>, do you want to negotiate with ` + `<#${userID}>`)
.then(r => r.react(emojiArray[3], emojiArray[4]));
negotiating = true;
}
if(negotiating == true && listen === 'y') {
negotiate.channel.send('Please type in the amount and then the item you are negotiating.');
} else return;
})
As you can see, the code above allows the user to tag someone and negotiate with them (the negotiating part doesn't matter). When the user tags someone else, it asks them if they want to negotiate with the user that tagged them. If the user says yes, they negotiate.
I want to do this in a cleaner way using reactions in discord. Is there any way to just add a yes or no reaction emoji and the user will have to click yes or no in order to confirm?
First of all, you kinda messed up while getting the user object of the mentioned user, so just so you know it's negotiate.mentions.users.first()!
While wanting to request user input through reactions, we'd usually want to use either one of the following:
awaitReactions()
createReactionCollector
Since I personally prefer awaitReactions(), here's a quick explanation on how to use it:
awaitReactions is a message object extension and creates a reaction collector over the message that we pick. In addition, this feature also comes with the option of adding a filter to it. Here's the filter I usually like to use:
const filter = (reaction, user) => {
return emojiArray.includes(reaction.emoji.name) && user.id === mention.id;
// The first thing we wanna do is make sure the reaction is one of our desired emojis!
// The second thing we wanna do is make sure the user who reacted is the mentioned user.
};
From there on, we could very simply implement our filter in our awaitReactions() function as so:
message.awaitReactions(filter, {
max: 1, // Accepts only one reaction
time: 30000, // Will not work after 30 seconds
errors: ['time'] // Will display an error if using .catch()
})
.then(collected => { // the reaction object the user reacted with
const reaction = collected.first();
// Your code here! You can now use the 'reaction' variable in order to check certain if statements such as:
if (reaction.emoji.name === '🔥') console.log(`${user.username} reacted with Fire emoji!`)
Finally, your code should look like this:
const filter = (reaction, user) => {
return emojiArray.includes(reaction.emoji.name) && user.id === mention.id;
};
message.awaitReactions(filter, {
max: 1,
time: 30000,
errors: ['time']
})
.then(collected => {
const reaction = collected.first();
if (reaction.emoji.name === '🔥') console.log(`${user.username} reacted with Fire emoji!`)
you should use a ReactionCollector:
var emojiArray = ['🔥', '👍', '👎', '✅', '❌'];
const yesEmoji = '✅';
const noEmoji = '❌';
client.on('message', (negotiate) => {
const listen = negotiate.content;
const userID = negotiate.author.id;
var prefix = '!';
var negotiating = false;
let mention = negotiate.mentions.user.first();
if(listen.toUpperCase().startsWith(prefix + 'negotiate with '.toUpperCase()) && (mention)) {
negotiate.channel.send(`<#${mention.id}>, do you want to negotiate with ` + `<#${userID}>`)
.then(async (m) => {
await m.react(yesEmoji);
await m.react(noEmoji);
// we want to get an answer from the mentioned user
const filter = (reaction, user) => user.id === mention.id;
const collector = negotiate.createReactionCollector(filter);
collector.on('collect', (reaction) => {
if (reaction.emoji.name === yesEmoji) {
negotiate.channel.send('The mentioned user is okay to negotiate with you!');
// add your negotiate code here
} else {
negotiate.channel.send('The mentioned user is not okay to negotiate with you...');
}
});
});
negotiating = true;
}
})
This allows you to listen for new reactions added to a message. Here is the documentation: https://discord.js.org/#/docs/main/stable/class/Message?scrollTo=createReactionCollector

Why is my script not letting my bot add reactions to the embed message it is sending? (discord.js)

I am a big novice with JavaScript coding so if you can make this a pre simple explanation that'd be MUCH appreciated.
So basically I have made this small script in order to send a poll to another channel using the arguments I have made the user put in and then format it and send it as an embedded message
The script is sending the whole thing formated however the final step of not adding the reactions is the issue.
(they are custom reactions which I have already defined you'll see below)
if (args.length >= 1) {
message.delete().then(() => {
const pollEmbed = new Discord.RichEmbed()
.setColor('#ABDFF2')
.setTitle("** " + pollArgs[0] + " **")
.setDescription(pollArgs[1])
.addField('*Click on the reactions below to cast your opinion on this poll!*', 'If you would like to start your own poll: !help in <#726235250136580106>')
.setTimestamp()
.setThumbnail(message.author.displayAvatarURL)
.setFooter(message.author.tag + " | Peace Keeper", message.author.displayAvatarURL)
let yes = message.guild.emojis.find('name', "yes")
let no = message.guild.emojis.find('name', "no")
suggestionschannel.send(pollEmbed).then(message.react(yes, no));
In case you need to see the full code here it is:
const Discord = require("discord.js");
const client = new Discord.Client();
module.exports.run = async (bot, message, args) => {
const suggestionschannel = message.guild.channels.find("name", "suggestions");
let pollArgs = args.slice(0).join(" ").split('|');
if (args.length >= 1) {
message.delete().then(() => {
const pollEmbed = new Discord.RichEmbed()
.setColor('#ABDFF2')
.setTitle("** " + pollArgs[0] + " **")
.setDescription(pollArgs[1])
.addField('*Click on the reactions below to cast your opinion on this poll!*', 'If you would like to start your own poll: !help in <#726235250136580106>')
.setTimestamp()
.setThumbnail(message.author.displayAvatarURL)
.setFooter(message.author.tag + " | Peace Keeper", message.author.displayAvatarURL)
let yes = message.guild.emojis.find('name', "yes")
let no = message.guild.emojis.find('name', "no")
suggestionschannel.send(pollEmbed).then(message.react(yes, no));
})
} else {
message.delete().catch();
const pollErrEmbed = new Discord.RichEmbed()
.setColor('FF6961')
.setTitle("**error!**")
.addField("use the correct format: !polls-start <title> | <message>", "If you need help do: `!polls-help`.")
.setTimestamp()
.setFooter(message.author.tag + " | Peace Keeper", message.author.displayAvatarURL)
message.reply(pollErrEmbed).then(msg => msg.delete(10000));
}
}
module.exports.help = {
name: "polls-start"
}
Your code seems good only one tiny edit!
Instead of
suggestionschannel.send(pollEmbed).then(message.react(yes, no));
You would need to use
suggestionschannel.send(pollEmbed).then(message => {
message.react(yes);
message.react(no);
});
Also remember about Updating Discord.js to v12, as soon v11 support is going to end!

Discord.js channel isn't defined welcome message

Im finding myself stuck with defining the "channel" and i keep getting channel not defind im definetly
new to JS but i thought i covered defining could someone help me out here ive tried to define it with a var channel = , and a let channel but cant seem to get any to work.
client.on("guildMemberAdd", (member) => {
const guild = member.guild;
newUsers.set(member.id, member.user);
if (newUsers.size > 1) {
const defaultChannel = guild.channels.find(channel => channel.permissionsFor(guild.me).has("SEND_MESSAGES"));
const userlist = newUsers.map(u => u.toString()).join(" ");
defaultChannel.send("Welcome to the server!\n" + userlist);
newUsers.clear();
}
});
That repo you are using is not updated. Try with this
const defaultChannel = guild.channels.cache.find(channel => channel.name === "NAME");

Why doesn't kicking people work using discord.js

const Discord = require("discord.js"),
bot = new Discord.Client();
let pre = "?"
bot.on("message", async msg => {
var msgArray = msg.content.split(" ");
var args = msgArray.slice(1);
var prisonerRole = msg.guild.roles.find("name", "Prisoner");
let command = msgArray[0];
if (command == `${pre}roll`) {
if (!msg.member.roles.has(prisonerRole.id)) {
roll = Math.floor(Math.random()*6)+1;
msg.reply(`You rolled a ${roll}`)
} else {
msg.reply(`HaHa NOOB, you're in prison you don't get priveleges!`)
}
}
if (command == `${pre}kick`) {
var leaderRole = msg.guild.roles.find("name", "LEADER");
var co_leaderRole = msg.guild.roles.find("name", "CO-LEADER");
if (msg.member.roles.has(leaderRole.id) ||
msg.member.roles.has(co_leaderRole.id)) {
var kickUser = msg.guild.member(msg.mentions.users.first());
var kickReason = args.join(" ").slice(22);
msg.guild.member(kickUser).kick();
msg.channel.send(`${msg.author} has kicked ${kickUser}\nReason: ${kickReason}`);
} else {
return msg.reply("Ya pleb, you can't kick people!");
}
}
})
bot.login("token").then(function() {
console.log('Good!')
}, function(err) {
console.log('Still good, as long as the process now exits.')
bot.destroy()
})
Everything works except actually kicking the person. The message sends nut it doesn't kick people. For example, when I type in ?kick #BobNuggets#4576 inactive, it says
#rishabhase has kicked #BobNuggets
Reason: inactive
But it doesn't actually kick the user, which is weird, can you help me?
Change
msg.guild.member(kickUser).kick();
to
kickUser.kick();
also, make sure the bot is elevated in hierarchy
Use kickUser.kick();
I recommend using a command handler to neaten up your code. You don't want all your commands in one .js file.
Try something like this for the Ban command itself. I use this for my Bot:
client.on("message", (message) => {
if (message.content.startsWith("!ban")) {
if(!message.member.roles.find("name", "Role that can use this bot"))
return;
// Easy way to get member object though mentions.
var member= message.mentions.members.first();
// ban
member.ban().then((member) => {
// Successmessage
message.channel.send(":wave: " + member.displayName + " has been successfully banned :point_right: ");
}).catch(() => {
// Failmessage
message.channel.send("Access Denied");
});
}
});
That should work, set the role you want to use it (cAsE sEnSiTiVe) and change !ban to whatever you feel like using. If you change all "ban"s in this to kick, it will have the same effect. If this helped you, mark this as the answer so others can find it, if not, keep looking :)

Categories