I am trying to make a Discord bot for announcements. I want to create a command which will read the data from the message and convert it into Embedded message.
An example command: !announce Title, Description, Link, Image
const Discord = require('discord.js');
const bot = new Discord.Client();
//listener
bot.on('ready', () => {
bot.user.setGame('Hello!')
});
bot.on('message', (message) => {
if(message.content == 'text') {
const embed = new Discord.RichEmbed()
.setTitle("Title!")
.setDescription("Description")
.setImage("https://i.imgur.com/xxxxxxxx.png")
.setURL("https://google.com")
.addField("Text", true)
//Nope
.setThumbnail("https://i.imgur.com/Rmiwd1j.png")
.setColor(0x00AE86)
.setFooter("Footer", "https://i.imgur.com/xxxxxxxx.png")
.setTimestamp()
/*
* Blank field, useful to create some space.
*/
message.channel.send({embed});
}});
bot.login('token');
I want Embed to be changed based on the text.
How can I do this?
First, you'll need to detect the command: you can use String.startsWith() to detect !announce:
if (message.content.startsWith('!announce')) {...}
Then you'll have to get the other parts of the command by splitting the string: you can separate them with a comma, as you did (title, description, ...), or with whatever character you want (I'll use a comma in my example).
String.slice() will help you get rid of the !announce part, while String.split() will create an Array with the other parts.
This code will generate an embed like this from the command !announce Title, Description, http://example.com/, http://www.hardwarewhore.com/wp-content/uploads/2018/03/dcord.png
client.on("message", message => {
if (message.content.startsWith('!announce')) {
let rest_of_the_string = message.content.slice('!announce'.length); //removes the first part
let array_of_arguments = rest_of_the_string.split(','); //[title, description, link, image]
let embed = new Discord.RichEmbed()
.setTitle(array_of_arguments[0])
.setDescription(array_of_arguments[1])
.setImage(array_of_arguments[3])
.setURL(array_of_arguments[2])
.addField("Text", true)
.setThumbnail("https://i.imgur.com/Rmiwd1j.png")
.setColor(0x00AE86)
.setFooter("Footer", array_of_arguments[3])
.setTimestamp();
message.channel.send({ embed });
}
});
I suggest using the text instead of the description and remind that the second argument of the .addField() is the text, not the inline value
Related
I am very new to Discord.js so please forgive me for any basic errors.
I am trying to create a command that will ask for a name, and then store the users input into a variable, however this is proving itself quite difficult.
After the program sends the message "What would you like to name your event?", I type "TEST", and then it sends another message saying "createevent", the command word.
client.on('message', async message => {
if (message.author.bot) return;
if (message.content.startsWith('createevent')) {
const filter = m => m.author.id === message.author.id;
message.channel.startTyping()
await sleep(500);
message.channel.stopTyping()
message.lineReply('What would you like to name your event?')
message.channel.awaitMessages(filter, {max: 1, time: 50000}).then(collected => {
const eventname = message.content;
message.channel.send(eventname);
})
}
});
First of all, you should stop the collector and, as you said you want to know the content that the user replies, the content in your case would be collected.content not message.content.
I'm new to working with discord bot and decided to try it out, to start I just wanted to make the bot send an attachment (image, video, etc) when for example, "sendpicture" is written in chat.
I've changed the code several times yet I get the same error everytime, "Attachment is not a constructor" or "Discord.Attachment is not a constructor".
My current code looks like this:
const client = new Discord.Client();
client.once(`ready`, () => {
console.log("online");
});
const PREFIX = "!"
//replying with a text message
client.on('message', msg => {
if (msg.content === 'test1') {
msg.channel.send('working');
}
});
//replying with attachment
client.on("message", function(message){
let args = message.content.substring(PREFIX.lenght).split(" ");
switch(args[0]) {
case "test2":
message.channel.send(new Discord.Attachment(`.a/this/bestpic.png`, `bestpic.png`) )
.then(msg => {
//aaaaaaaa
})
.catch(console.error);
break;
}
})
tyia
Had you tried looking at the official documentation ?
I don't think you should use new Discord.Attachment(), try this instead :
switch(args[0]) {
case "test2":
message.channel.send({
files: [{
attachment: '.a/this/bestpic.png',
name: 'bestpic.png'
}]
}).then(msg => {
//aaaaaaaa
}).catch(console.error);
break;
}
Discord.Attachment() is not a thing, i believe the answer you are looking for is this :)
new Discord.MessageAttachment()
Try this code, short and simple to use.
if (message.content.toLowerCase() === 'word') { //only word, without prefix
message.channel.send({ files: ['./path_to_your_file'] })
}
You should try using MessageAttachment because Discord.Attachment is not a thing, then add the attachment into the files property
I would consider making the attachment a variable instead of putting it directly into the function, it is optional tho
const { MessageAttachment } = require("discord.js");
const attachment = new MessageAttachment("url", "fileName(optional)", data(optional));
message.channel.send({ files: [attachment] }).then(//code...)
Let me know if it works
I'm working on semi-gacha bot command where you can pull characters and so on. I want to display the characters image after the user pulls and here is where I get stuck, it just doesn't display anything and I found what looked like the answer on here, but it didn't help, as I would get the same result and I don't get any errors, so I don't know what exactly is wrong. I have tried printing out the result of MessageAttachment first:
const attachment = new Discord.MessageAttachment('./chars/1.Jakku.png', '1.Jakku.png');
console.log(attachment);
and I get: undefined, anybody has any ideas of what am I doing wrong? And yes, I have discord.js library imported.
Relevant part of the code:
collector.on('collect', reaction => {
//new embd
const newEmbd = new Discord.MessageEmbed();
// gacha logic
if (reaction.emoji.name === '✅') {
const values = Object.values(chars);
const randomChar = values[parseInt(Math.floor(Math.random()*values.length))];
const attachment = new Discord.MessageAttachment('./chars/1.Jakku.png', '1.Jakku.png');
const charData = randomChar.split('.');
newEmbd
.setTitle(`You pulled: ${charData[1]}!`)
.setColor('YELLOW')
.attachFiles(attachment)
.setImage(`attachment://1.Jakku.png`);
embdReact.edit(newEmbd);
pulled = true;
} else if (reaction.emoji.name === '❌') {
newEmbd
.setTitle('Time for gacha!')
.setColor('YELLOW')
.addFields(
{ name: 'Result:', value: 'You decided against pulling' }
);
embdReact.edit(newEmbd);
};
});
You need to use the correct syntax for attaching files as per this guide
const exampleEmbed = new Discord.MessageEmbed()
.setTitle('Some title')
.attachFiles(['./chars/1.Jakku.png'])
message.channel.send(exampleEmbed);
I created a discord bot with the goal to generate reactive embeds with emoji-buttons. My problem is all the embeds created with the bot are modified simultaneously once a 'button' is pressed.
Below a pseudo-code of my bot:
const raidEmbed = new Discord.MessageEmbed() //create the embed
//some code to fill the embed
message.channel.send(raidEmbed).then(embedMessage => {
embedMessage.react('❌')
.then(()=>embedMessage.react('⭕')
//more react to create all the 'buttons'
client.on('messageReactionAdd', (reaction, user) => {
//some code to do stuff when the right 'button' is pressed
//then reset the button with this code:
if (user.id !== client.user.id) {
reaction.users.remove(user.id);
}
const newEmbed = new Discord.MessageEmbed()
//code to create the new embed
embedMessage.edit(newEmbed);
}
})
I don't understand why all my embeds are linked together and how to fix this issue.
Your embeds are not all linked together. The issue here is that you are using a global event to check for reactions. This is the part of your code that is the issue:
client.on('messageReactionAdd', (reaction, user) => {
//some code to do stuff when the right 'button' is pressed
//then reset the button with this code:
if (user.id !== client.user.id) {
reaction.users.remove(user.id);
}
const newEmbed = new Discord.MessageEmbed()
//code to create the new embed
embedMessage.edit(newEmbed);
}
What this part of your code is doing is whenever a reaction is added to any message, all of your embeds are edited. This means that even adding a reaction to a message that is not an embed will cause all of your embeds to be modified. messageReactionAdd is a global event, meaning it applies to all messages, not just your embed messages.
The best solution is to use a reaction collector instead of a reaction event. Reaction collectors are created on specific messages, so only the embed you reacted on will be modified.
Here is an example with your code, it may not necessarily be a working example but it should give you a general idea of how to accomplish this:
const raidEmbed = new Discord.MessageEmbed() //create the embed
//some code to fill the embed
message.channel.send(raidEmbed).then(embedMessage => {
embedMessage.react('❌')
.then(()=>embedMessage.react('⭕')
//more react to create all the 'buttons'
const filter = (reaction, user) => (r.emoji.name == "❌" || r.emoji.name == "⭕") && user.id === message.author.id;
const collector = embedMessage.createReactionCollector(filter, { time: 15000 });
collector.on('collect', reaction => {
//some code to do stuff when the right 'button' is pressed
//then reset the button with this code:
reaction.users.remove(message.author.id);
const newEmbed = new Discord.MessageEmbed()
//code to create the new embed
embedMessage.edit(newEmbed);
}
})
You can also use the filter to narrow down which users' reactions should be collected as well as what specific reactions you want to collect.
This is my first time using js. I need to ban a certain word in a certain channel. I don't want the message to be deleted if it is not in the specific channel.
For Example:
I want to ban the word "goodbye" in the #greeting channel
BUT
I don't want to ban the word "goodbye" In the #farewell channel
How would I go about this?
Thanks.
By the way I wanted to use example code, but none of it made any sense.
I wrote a simple example for you on how to achieve this:
const Discord = require("discord.js");
const Client = new Discord.Client();
const ForbiddenWords = {
"ChannelID": ["goodbaye", "bye"] // Greeting channel
};
Client.on("ready", () => {
console.log(`${Client.user.tag} is ready!`);
});
Client.on("message", (message) => { // Fired when the bot detects a new message.
if (message.author.bot) {return false}; // Checking if the message author is a bot.
if (ForbiddenWords[message.channel.id]) { // Checking if the current channel has any forbidden words in the ForbiddenWords Object
if (ForbiddenWords[message.channel.id].some(word => message.content.toString().toLowerCase().includes(word))) { // Checking if the message contains any forbidden words
message.delete(); // Deleting the message.
};
};
});
Client.login(process.env.DISCORD_AUTH_TOKEN);