How can I re-send an attachment from a message? - discord.js

So, what I want to do is something like this:
User: sends a command like this: mybot!announce #mention (message) (Attachs image)
Bot: gets the mention, message & attachment from the message, and deletes it. Then resends the message in an embed (see picture).
I managed to do everything else but I can't get the attachment & re-send it in the embed. Please, help :p
Here is the code I actually have, in case you need it:
if (command === 'announce')
{
var mention = args[0];
if (!args[0]) return message.channel.send('You need to mention someone!');
var actualMention = null;
if (mention === '#everyone')
{
actualMention = message.mentions.members.every();
}
else
{
actualMention = message.mentions.members.first();
}
var messageAnnouncement = args.slice(1).join(" ");
if (msgAnnouncement === null) return message.channel.send('You need to put the announcement itself!');
var imageAttachments = message.attachments;
const anunouncementEmbed = new Discord.MessageEmbed()
.setAuthor('YPBot - Announcement')
.setTitle(message.author.tag + ' made an announcement')
.setDescription('Mentioning: ' + mention + '\n\n' +
msgAnnouncement)
.setThumbnail(imageAttachments[0]);
message.channel.send(anunouncementEmbed);
}
Hope I explained myself well. In case I didn't, feel free to ask anything.

Message#attachments actually returns a Collection, so if you want the first element you need Collection#first(). From there you can access the MessageAttachment#url property.
.setThumbnail(imageAttachments.first().url);

Related

How do I compare the ID of the new members with the ones in the database?

I am trying to make a jail command when the members who has this role leave the server and rejoin again the role stay with them ,i want when new members enter the server to compare their ID with the one in the database, if is it true it gives a role again. my code:
client.on("guildMemberAdd",async (member)=>{
let injail = await db.fetch(`ja_${member.guild.id}`)
let role = msg.guild.roles.cache.find(n => n.name === 'Jail');
if(member.guild.id = injail){
member.roles.remove(user.roles.cache)
member.roles.add(role)
}
});
client.on('message', msg => {
if(msg.content.startsWith(prefix + 'jail')){
if(!owners.includes(msg.author.id)) return msg.channel.send("**You Dont Have Perms 📛**")
if(!msg.channel.guild) return;
var logChannel = msg.guild.channels.cache.find(channel => channel.id === logID)//LOG
let jailRole = msg.guild.roles.cache.find(n => n.name === 'Jail');
let user = msg.mentions.members.first() //You can change this to an ID
let args = msg.content.split(" ").slice(1).join(" ")
if(!args[0]) return msg.channel.send('**:x: Please Mention A User**')
if(user.hasPermission("ADMINISTRATOR")) return msg.channel.send("**Im NOT Allowed To Do This 📛**")
let there = db.get(`jl_${msg.guild.id}_${user}`, user.id)
if (there) return msg.channel.send('**This User AlREADY In Jail â›”**')
msg.channel.send(`**ADDED ${user} to the Jail! ✅**`)
db.set(`jl_${msg.guild.id}_${user}`, user.id)
user.roles.remove(user.roles.cache)
user.roles.add(jailRole)
let embed = new Discord.MessageEmbed()
.setTitle('Jail System')
.setAuthor(msg.author.tag,msg.author.avatarURL({dynamic:true}))
.addField("Status",`JOINED THE JAIL 🔴`)
.addField("User",`<#${user.id}> (ID: ${user.id})`)
.addField("By",`<#${msg.author.id}> (ID: ${msg.author.id})`)
.setTimestamp()
logChannel.send(embed)
}
});
Whenever people gets "jail" role, save "yes" to database.
and check condition as you did above.
here I'll give sample code:
// when people gets jail role, add following code:
db.set(`ja_${msg.guild.id}_${user}`, "yes") // or you can simply use boolean operator
// when guildMemberAdd event triggers check condition:
let condition = db.fech(`ja_${member.guild.id}_${member.user.id}`)
if(condition === "yes"){
// write code to add "jail" role to the member
}
else{
// your other code
}
Also don't forget to set "no" in the database whenever you remove jail role from member.

Discord.Js - making a bot that creates custom roles

I'm someone who just got into coding recently.
I'm trying to create a Discord bot that can do custom roles that can allow a user of that custom role to edit its hex or name.
There's also the creation of a role creator that also assigns the mentioned user the role.
My problem is that I've encountered an issue with the role creation + assignment and the commands that allow the user to edit their role.
Here are the problems:
(node:6288) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'get' of undefined for the role creator command
When I try to use the commands that allow the user to customize their roles, the commands don't work, or to be more specific, they don't activate.
I do believe that the codes I'm using could be outdated, therefore if that is the case, please give me the exact location and the right code.
Here are some pictures of the codes. I've pasted the codes below, but I'm a bit new to this forum, so please pay attention to the separating pieces like "Role Customization Code:" to distinguish which one's which. For some reason, the module.exports aren't going in there. Please describe and let me know a solution to these problems in a specific way since I am a newbie at this topic.
Role creation command + assignment error.
Role creation command + assignment code part 1.
Role creation command + assignment code part 2.
Role customization code part 1.
Role customization code part 2.
Role customization code part 3.
Role creation + assignment code:
const Discord = module.require("discord.js");
const guild = require("./config.json");
module.exports.run = async (bot, message, args) => {
const query = bot.db;
function embedFail(text) {
let embed = new Discord.RichEmbed().setColor("#ff0000").setDescription(text);
return embed;
}
function embedSuccess(text) {
let embed = new Discord.RichEmbed().setColor("#7CFC00").setDescription(text);
return embed;
}
if (!args[0]) return message.channel.send("Please specify a user to add!");
let toAdd = message.guild.members.get(args[0]) || message.guild.members.get(message.mentions.users.first().id);
let rolejoin = args.slice(1).join(" ");
let myRole = message.guild.roles.cache.get((val) => val.name.toLowerCase() === rolejoin.toLowerCase());
if (!toAdd) return message.channel.send("User not found!");
if (!rolejoin) return message.channel.send("Please specify a role to add!");
let botRole = message.guild.members.get(bot.user.id).highestRole;
let isPosition = botRole.comparePositionTo(myRole);
if (isPosition <= 0) return message.channel.send(embedFail("This role is higher than me, I cannot add this role!"));
let res = await query(`SELECT * FROM user_roles WHERE role_id='${myRole.id}'`);
if (res[0]) {
await query(`DELETE FROM user_roles where role_id='${myRole.id}'`);
toAdd.removeRole(myRole);
message.channel.send(embedSuccess(`Removed role ${myRole.name} from ${toAdd.user.username}`));
} else if (!res[0]) {
await query(`INSERT INTO user_roles (guild_id, user_id, role_id) VALUES ('${message.guild.id}',${toAdd.id},'${myRole.id}')`);
toAdd.addRole(myRole);
message.channel.send(embedSuccess(`Adding role ${myRole.name} to ${toAdd.user.username}`));
}
};
Role Customization Code:
const Discord = module.require("discord.js");
const guild = require("./config.json");
module.exports.run = async (bot, message, args, db) => {
const query = bot.db;
function embedFail(text) {
let embed = new Discord.RichEmbed().setColor("#ff0000").setDescription(text);
return embed;
}
function embedSuccess(text) {
let embed = new Discord.RichEmbed().setColor("#7CFC00").setDescription(text);
return embed;
}
let res = await query(`SELECT * FROM user_roles WHERE guild_id = '${message.guild.id}' AND user_id = '${message.author.id}'`);
if (!args[0]) {
if (!res[0]) return message.channel.send(embedFail("You do not have a role!"));
let myRole = message.guild.roles.cache.find(res[0].role_id);
let assignNames = "";
let embed = new Discord.RichEmbed()
.setAuthor(`Current role assigned to ${message.author.username}`, message.guild.iconURL)
.setColor(myRole.hexColor)
.addField(`Name`, `${myRole.name}`, true)
.addField(`Colour`, `${myRole.hexColor}`, true);
message.channel.send(embed);
} else {
if (!res[0]) return message.channel.send(embedFail("You do not have a role!"));
let myRole = message.guild.roles.cache.find(res[0].role_id);
if (!myRole) {
await query(`DELETE FROM user_roles where guild_id = '${message.guild.id}' AND role_id = '${res[i].role_id}' and user_id = '${res[i].user_id}'`);
return message.channel.send(embedFail("You do not have a role!"));
}
switch (args[0]) {
case "name":
let name = args.slice(1).join(" "),
oldName = myRole.name;
await myRole.setName(name);
await message.channel.send(embedSuccess(`You have changed ${oldName}'s name to ${name}!`));
break;
case "color":
case "color":
let hexCode = args[1],
oldHex = myRole.hexColor;
await myRole.setColor(hexCode);
await message.channel.send(embedSuccess(`You have changed ${myRole.name}'s color from ${oldHex} to #${hexCode}!`));
break;
}
}
};

How to know if a user already has a role in an addrole command

I want to send an error message saying that the user already has the role if they do in an addrole command.My current command is:
const { MessageEmbed } = require("discord.js");
module.exports = {
name: "addrole",
description: "adds a role to a member",
execute: async (message , args) => {
if (!message.member.hasPermission("MANAGE_ROLES")) return message.channel.send("Invalid Permissions")
let member = message.mentions.members.first();
let role = message.mentions.roles.first();
if (!member)
return message.reply("Please mention a valid member of this server");
if (!role) return message.reply("please mention a valid role of this server");
const highest = message.member.roles.highest;
if(highest.comparePositionTo(role) <= 0)
return message.channel.send(`You cannot add roles equal/higher to that member's highest role`)
let addroleembed = new MessageEmbed()
.setTitle(`:white_check_mark: ${role.name} has been added to ${member.user.tag}`)
.setFooter(`Action performed by ${message.author.tag}`)
.setColor('77B255')
addroleembed.setTimestamp();
member.roles.add(role);
message.channel.send(addroleembed)
}}
I have tried using
if(!message.member.roles.cache.some(r=>[`${role.name}`].includes(r.name)))
and
if (member.roles.has(role.id) {
But neither of these seem to work, Anyone know the reason behind this? If I can't use either of these methods, Can you suggest me a solution?
You are so close!
All you need is cache when using has()
member.roles.cache.has(<RoleID>);
Learn More Here
You need to combine your two tries.
if(message.member.roles.cache.has("role ID") {
//rest of your code
}

Discord.js problem searching in the roles of a user

I am trying to create a command, in this case it is activated with / attack, the mechanism I am looking for is that if the target user (mentioned) has the role (Lavander) which is a kind of shield, send an embed message saying defended and remove the role from you (break the shield) and if the target user (mentioned) does not have the shield role, just send a different message saying attacked. This is the code that I have been doing but it does not work for me even if it does not give errors, simply when using it, it ignores the role detection and sends both messages for some reason that I do not know, can someone help me?
if (message.content.startsWith('/attack')) {
let Lavander = message.guild.roles.cache.find(role => role.name == "Lavander");
let member = message.mentions.members.first();
if (message.member.roles.cache.has(Lavander)) return
member.roles.remove(Lavander);
message.channel.send(new Discord.MessageEmbed()
.setColor("GOLD")
.setTitle(message.author.username)
.setDescription("Defended"))
message.channel.send(new Discord.MessageEmbed()
.setColor("GOLD")
.setTitle(message.author.username)
.setDescription("Attacked"))
}
For me it seems like let Lavander = message.guild.roles.cache.find(role => role.name == "Lavander"); might be supposed to be let Lavander = message.guild.roles.cache.find(role => role.name === 'Lavander'); but without the info about the glitches and/or errors, I can't tell you anything else.
method collection.has require id as property. So you need somethink like this:
bot.on('message', (message) => {
if (message.content.startsWith('/attack')) {
let lavander = message.guild.roles.cache.find((role) => role.name === 'Lavander');
let member = message.mentions.members.first();
if (!member || !lavander) return message.reply('No role or member');
if (message.member.roles.cache.has(lavander.id)) {
member.roles.remove(lavander);
let embed = new Discord.MessageEmbed()
.setColor('GOLD')
.setTitle(message.author.username)
.setDescription('Defended');
} else {
let embed = new Discord.MessageEmbed()
.setColor('GOLD')
.setTitle(message.author.username)
.setDescription('Attacked');
message.channel.send(embed);
}
}
});

Discord.js how to use bot mention and a set prefix as prefixes

I want to make it so that if I do [prefix] [command] it will give the same effect as [mention bot] [command] but the way I create commands and args makes that difficult:
The prefix is stored as var prefix = '!3';
And this is how I create commands:
bot.on('message', msg => {
if (!msg.content.startsWith(prefix) || msg.author.bot)
return;
//the first message after '!13 '
//!
let args = msg.content.toLowerCase().substring(prefix.length).split(" ");
//^
//any capitalisation is allowed (ping,Ping,pIng etc.)
switch(args[1]) {
case 'ping': //if user inputs '!3 ping'
msg.channel.send('Pong!') //send a message to the channel 'Pong!'
}//switch (command) ends here
};//event listener ends here
You can have a list of predefined prefixes and loop over that to determine if the msg has a prefix from that list.
let prefixList = ['!31 ', '!asdf ', `<#${bot.user.id}> `, `<#!${bot.user.id}> `]
function hasPrefix(str) {
for(let pre of prefixList)
if(str.startsWith(pre))
return true;
return false;
}
<#${bot.user.id}> , <#!${bot.user.id}> will set up bot mention as a prefix.
Here's the shorter version of secretlyrice's answer:
const startsWithPrefix = (command) =>
['!prefix1 ', '!prefix2', <#botId>, <#!botId>].some(p => command.startsWith(p))
Nice code, but change it 1 to 0
switch(args[0]) {
case 'ping': //if user inputs '!3 ping'
msg.channel.send('Pong!') //send a message to the channel 'Pong!'
}
I assume you are running on an older version of Discord.js cause if you are using v13 message is depricated and should be messageCreate but this is what I used when I wasn't using slash commands.
const escapeRegex = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
const prefix = '!'
bot.on('message', async msg => {
const prefixRegex = new RegExp(`^(<#!?${bot.user.id}>|${escapeRegex(prefix)})\\s*`)
if (!prefixRegex.test(message.content)) return
// checks for bot mention or prefix
const [, matchedPrefix] = message.content.match(prefixRegex)
const args = message.content.slice(matchedPrefix.length).trim().split(/ +/)
// removes prefix or bot mention
const command = args.shift().toLowerCase()
// gets command from next arg
if (command === 'ping') {
msg.channel.send('Pong!')
}
})

Resources