DiscordJS Argument Slice - discord.js

I want to make a image embed via arguments, but I can't set the Title of the embed.
But when I try to run the comand, it errors out and the embed won't appear
if(message.content.startsWith(prefix + "foto-annuncio"))
{
if(!message.member.hasPermission(["MANAGE_MESSAGES"]))
{
/* error message pops out */
}
let argsresult;
let mChannel = message.mentions.channels.first()
message.delete()
argsresult = args.slice(1).join(" ")
let url = args.slice(1).join(" ");
let title = args.slice(2);
message.delete();
const embed = new Discord.RichEmbed ()
.setImage(url)
.setColor('#008000')
.setAuthor('Delta Logistics', 'https://cdn.discordapp.com/attachments/604963851561336832/665504827044003860/zoom_delta_6_discord.png')
.setTitle(title)
mChannel.send(embed).catch(err => console.log(err));
message.channel.send("Done!");
}

As Giuuliopime said you can't set an array as a title, you prob meant to join the arguments:
const title = args.slice(2).join(" ");

Related

When using a variable inside an embed I get [object Object] returned not the value (discord.js)

I am attempting to create a kick command for a bot and its working fine however when the bot logs the embed it doesn't display the data in the variable but [object Object]
The Embed Output
My code is as following
exports.run = async (client, message, args) => {
const username = message.mentions.members.first().user.username; //gets the first mentioned users username
let member = message.mentions.members.first();
if(!member) return message.reply("Please mention a valid member of this server");
if(!member.kickable) return message.reply("I cannot kick this member!");
const reason = args.slice(1).join(' ');
const kickedmessage = new MessageEmbed() //embed to send to a logs channel
.setColor('#1773BA')
.setTitle('User Kicked')
.setDescription({username} + "had been kicked for " + {reason})
;
client.channels.cache.get("771835493305286688").send(kickedmessage)//output the embed
member.kick(reason);
I am using discord.js v12
exports.run = async (client, message, args) => {
const username = message.mentions.members.first().user.username; //gets the first mentioned users username
let member = message.mentions.members.first();
if (!member) return message.reply("Please mention a valid member of this server");
if (!member.kickable) return message.reply("I cannot kick this member!");
const reason = args.slice(1).join(" ");
const kickedmessage = new MessageEmbed() //embed to send to a logs channel
.setColor("#1773BA")
.setTitle("User Kicked")
.setDescription(username + "had been kicked for " + reason);
client.channels.cache.get("771835493305286688").send(kickedmessage); //output the embed
member.kick(reason);
};

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 would I add a hug reaction command

I have no idea what I’m doing. I don’t code but my friend helped me out up to this part
const Discord = require('discord.js');
const client = new Discord.Client();
client.once('ready', () => {
console.log('This Bot is online!');
client.user.setActivity('Prefix +k')
});
client.on('message', msg=>{
if(msg.content === "+k Hello"){
msg.reply('Welcome!');
}
})
client.on('message', msg=>{
if(msg.content === "+k Credits"){
msg.reply('Pokemon DB for Info, MrTechGuy for code help!');
}
})
client.on('message', msg=>{
if(msg.content === "+k Credits"){
msg.reply('Pokemon DB for Info, MrTechGuy for code help!');
}
})
client.on('message', msg=>{
if(msg.content === "+k DAList"){
msg.reply('1 - Butterfree <:V:750540886680666282> <:grass:750540661396340826>, 2 = Butterfree <:VMAX:750540886701637743> <:grass:750540661396340826>,');
}
})
client.login('[REDACTED]');
Again, how would I add a hug command that targets the user, e.g. +k hug #user 1, my friend is out for the month and I do not know how to do it
response: #user 2 hugged #user 1 ! (gif here)
For this to work you will need to create a folder named "hug" and with images which are "gif".
if(message.content.startsWith('+k hug')) {
let user = msg.mentions.users.first(); // refers to the user you wish to mention
if (!user) {
let maxImageNumber1 = 7; // represents the number of images in the folder
let hug = Math.floor(Math.random() * (maxImageNumber1 - 1 + 1)) + 1;
let imageName1 = `${hug}.gif` // if the images you put are png/jpg just remove the ".gif" with either ".png" or ".jpg"
let imagePath1 = `/hug/${imageName1}` // folder name
let file1 = new Discord.MessageAttachment(imagePath1);
let embed1 = new Discord.MessageEmbed();
embed1.setImage(`attachment://${imageName1}`)
embed1.setDescription(`**${msg.author.username}** hugged their clone`)
embed1.setColor('RANDOM')
msg.channel.send({ files: [file1], embed: embed1 });
}
if (user) {
let maxImageNumber1 = 7; // represents the number of images in the folder
let hug = Math.floor(Math.random() * (maxImageNumber1 - 1 + 1)) + 1;
let imageName1 = `${hug}.gif` // if the images you put are png/jpg just remove the ".gif" with either ".png" or ".jpg"
let imagePath1 = `/hug/${imageName1}` // folder name
let file1 = new Discord.MessageAttachment(imagePath1);
let embed1 = new Discord.MessageEmbed();
embed1.setImage(`attachment://${imageName1}`)
embed1.setDescription(`**${msg.author.username}** hugged **${user.username}**`)
embed1.setColor('RANDOM')
msg.channel.send({ files: [file1], embed: embed1 });
}
}
Im assuming you are using discord.js v12
TIP:
I'd recommend you define your prefix with something like const prefix = '+k'; and when you want to make a command do this: if(message.content.startsWith(prefix + 'hug')){}

How to make this bot listen to argument after prefix and answer?

so i'm trying this 8ball bot, and everything is working fine, but i can't get how can i leave in the condition that only when the bot get "!verda arg1 arg2" it answers one of the replies in the array.
meanwhile my condition is if the user type the prefix "!verda" only, it replies , i want to include the argument too in the condition
const Discord = require("discord.js");
const client = new Discord.Client();
const cfg = require("./config.json");
const prefix = cfg.prefix;
client.on("message", msg => {
if (!msg.content.startsWith(prefix) || msg.author.bot) return;
const args = msg.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase;
if (msg.content === prefix){
let replies = [
"Yes.",
"No.",
"I don't know.",
"Maybe."
];
let result = Math.floor((Math.random() * replies.length));
msg.channel.send(replies[result]);
}
else if (msg.content === "!help"){
msg.channel.send("I have only 1 command [!verda]");
}
})
client.login(cfg.token);
const command = args.shift().toLowerCase;
toLowerCase is a function and therefore should be
const command = args.shift().toLowerCase();
By doing msg.content === prefix, you are checking if the whole content of the message is equal to that of cfg.prefix
if(msg.content.startsWith(`${prefix}8ball`) {
}
The answer was simple as i figured it out, i simply had to join the spaces
if (msg.content === `${prefix} ${args.join(" ")}`)

How do I make a command call a different command along with itself?

I don't know how to do this and I have been looking for answer but am unable to find it.
if message.content.startswith('^trivia autostart'):
await client.send_message(message.channel, "Game is starting!\n" +
str(player1) + "\n" + str(player2) + "\n" + str(player3) + "\n" +
str(player4) + "\n" + str(player5) + "\n" + str(player6) )
--
I have this code and i'm trying to make it so it when that code gets run that it calls my ^trivia play command without typing it in chat.
Is this possible?
The solution to that would be defining functions for each command you need to be called globally by your bot. Take the following example:
const Discord = require('discord.js');
const bot = new Discord.Client();
bot.on('error' => console.log);
bot.on('message', message => {
let prefix = '!';
let sender = message.author;
let msg = message.content;
let cont = msg.split(' ');
let args = cont.slice(1);
let cmd = msg.startsWith(prefix) ? cont[0].slice(prefix.length).toUpperCase() : undefined;
// Ping function
// can be: function pingCommand () {...}
let pingCommand = () => {
message.channel.send(`Pong!\nTime: ${bot.ping} ms`);
}
// Main command
if (cmd === 'PING') {
pingCommand();
}
// Calling command in another command
if (cmd === 'TEST') {
message.channel.send('Running a ping test on the bot');
pingCommand();
}
});
bot.login(token);
Hope you understand how it would work

Resources