TypeError [ColorConvert]: Unable to convert color to a number - discord

client.on('messageCreate', (message) => {
// Check if the message content starts with '!commandname'.
if (message.content.startsWith('!dadada')) {
const Discord = require('discord.js');
const convert = require('color-convert');
const [color, ...messageArgs] = message.content.split(' ');
const messageContent = messageArgs.join(' ');
// Check if the color variable is a valid HSL color value.
if (!color || color.split(',').length !== 3) {
return message.channel.send("Invalid color value. Please provide a valid HSL color in the format 'hue,saturation,lightness'.");
}
// Convert the hue value from degrees to a percentage.
const [hue, saturation, lightness] = color.split(',').map((string, i) => {
if (i === 0) {
return parseInt(string, 10) / 360;
}
return string;
});
const rgbColor = convert.hsl.rgb([hue, saturation, lightness]);
// Create an embed with the specified color and message.
const embed = new Discord.EmbedBuilder()
.setColor(rgbColor)
.setDescription(messageContent);
// Send the embed to the channel.
message.channel.send({ embeds: [embed] });
}
});
I've been struggling for 5 hours and I can't make it :(
I didn't find any solution, do you have any idea?
Command format
!dadada 50,100%,50% text

Related

How do give only person that write i an specific discord channel xp

Here is the Code. I only want to give members xp when they write in a specific discord channel. How can i do that?
client.on('messageCreate', async message => {
if (!message.guild) return;
if (message.author.bot) return;
const prefix = '?'
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
const user = await Levels.fetch(message.author.id, message.guild.id);
if (!message.guild) return;
if (message.author.bot) return;
const randomAmountOfXp = Math.floor(Math.random() * 29) + 1; // Min 1, Max 30
const hasLeveledUp = await Levels.appendXp(message.author.id, message.guild.id, randomAmountOfXp);
if (hasLeveledUp) {
const user = await Levels.fetch(message.author.id, message.guild.id);
message.channel.send({ content: `${message.author}, congratulations! You have leveled up to **${user.level}**. :tada:` });
}
if (user.level === 5) {
message.member.roles.add("1022876270754791445");
} else if (user.level === 10) {
message.member.roles.add("1022876505132499054");
}else if (user.level === 10) {
message.member.roles.remove("1022876270754791445");
}
});
You can check message's channel id when event triggered.
if (message.channel.id !== "CHANNEL_ID") return;

Interaction has already been acknowledged when using a different button

I am getting the interaction has already been acknowledged error. Basically when the command is called the first time, the button and the modal work just fine. The second time, the button appears but then shows the modal and throws the "DiscordAPIError: Interaction has already been acknowledged." error. I am in a real slump.
} else if (order == "edit") {
let shelfNameSpaces = "";
for (let i = 1; i < args.length; i++) {
shelfNameSpaces += args[i] + " ";
}
let shelfName = shelfNameSpaces.trim();
let shelfObj = await Shelves.findOne({name: shelfName})
if (shelfObj) {
const embed = new MessageEmbed()
.setColor("#0099ff")
.setThumbnail(profileImage)
.setTitle(`${shelfObj["name"]}`)
.setDescription("Displaying shelf info")
.addField("Owner", `<#${shelfObj["owner"]}>`)
if (shelfObj["info"].length <= 0) {
embed.addField("Info", "No information added")
} else {
embed.addField("Info", shelfObj["info"])
}
let m = await message.channel.send({ embeds: [embed] })
const row = new MessageActionRow();
row.addComponents(
new MessageButton()
.setCustomId(`edit-shelf`)
.setLabel('Edit Shelf')
.setStyle("PRIMARY")
)
var buttons = await message.channel.send({ components: [row] })
setTimeout(() => {
if (buttons.deletable)
buttons.delete()
}, 60000);
// client.on("interactionCreate", async (interaction) => {
// module.exports = {
// name: 'interactionCreate',
// async execute (interaction) {
// }
// }
var editInfo, modal, editRow;
client.on("interactionCreate", async (interaction) => {
if (!interaction.isButton() || interaction.isModalSubmit()) return;
if (interaction.customId == "edit-shelf") {
// interaction.reply("Editing")
if (buttons.deletable)
buttons.delete()
modal = new Modal()
.setCustomId(`editModal`)
.setTitle('Edit Info')
editInfo = new TextInputComponent()
.setCustomId(`editInput`)
.setLabel("Input your edit")
.setValue(shelfObj["info"])
.setStyle("PARAGRAPH")
editRow = new MessageActionRow().addComponents(editInfo)
modal.addComponents(editRow)
await interaction.showModal(modal)
modalCheck++;
}
})
client.on("interactionCreate", async (inter) => {
if (!inter.isModalSubmit()) return;
inter.deferUpdate()
const editval = inter.fields.getTextInputValue('editInput')
// console.log(editval);
shelfObj["info"] = editval
const updatedShelf = new Shelves(shelfObj);
await updatedShelf.save()
const embed2 = new MessageEmbed()
.setColor("#0099ff")
.setThumbnail(profileImage)
.setTitle(`${shelfObj["name"]}`)
.setDescription("Displaying shelf info")
.addField("Owner", `<#${shelfObj["owner"]}>`)
if (shelfObj["info"].length <= 0) {
embed2.addField("Info", "No information added")
} else {
embed2.addField("Info", shelfObj["info"])
}
m.edit({ embeds: [embed2] })
// inter.reply("Shelf edited successfully")
// await inter.deleteReply()
// if (buttons.deletable)
// buttons.delete()
})
} else {
const embed = new MessageEmbed()
.setColor("#ff0000")
.setTitle("Shelves")
.setDescription("Unknown Shelf")
.addField("Error", "Shelf not found");
message.channel.send({ embeds: [embed] });
}
I've experienced this error multiple times, and I finally found out how to fix this error.
To start off, you need to install a package called nanoid (npm i nanoid in terminal).
At the top of your file, include const { nanoid } = require("nanoid");. This package is used for creating unique IDs for anything you'd like.
now, make a variable, and make it the following:
let id = `button-${nanoid()}`;
Make your .setCustomId() equal .setCustomId(id).
Lastly, make your if (interaction.customId == "edit-shelf") equal if (interaction.customId == id).
Note: If you have another error, try changing your nanoid package in your package.json to version ^3.3.4, and uninstall and install it again.

Eval command doesn't work at all, but it doesn't error

I'm trying to make an eval command for my bot. It doesn't error, but it doesn't send a message to the console or the discord channel. Heres my eval code:
const clean = async (client, text) => {
if (text && text.constructor.name == "Promise")
text = await text;
if (typeof text !== "string")
text = require("util").inspect(text, { depth: 1 });
text = text
.replace(/`/g, "`" + String.fromCharCode(8203))
.replace(/#/g, "#" + String.fromCharCode(8203));
text = text.replaceAll(client.token, "[REDACTED]");
return text;
}
client.on("messageCreate", async (message) => {
const args = message.content.split(" ").slice(1);
if (message.content.startsWith(`${p}eval`)) {
if (message.author.id !== 821682594830614578) {
return;
}
try {
const evaled = eval(args.join(" "));
const cleaned = await clean(client, evaled);
message.channel.send(`\`\`\`js\n${cleaned}\n\`\`\``);
} catch (err) {
message.channel.send(`\`ERROR\` \`\`\`xl\n${cleaned}\n\`\`\``);
}
}
});
Let me know if I have to give you more code.
It seems like you put a number as your ID... Discord.js IDs are in strings so you should put your ID into a string.
if (message.author.id !== "821682594830614578") {
return;
}
Probably your Discord ID is wrong. Tell me your discord username, I will add you as friend and will solve it in DMs.
This is my Discord Username Nishant1500#9735

How do I stop playing bot music? (Discord.js)

This code is for playing music, and I want to have a stop command on my bot. Could you help me?
const Discord = require("discord.js");
const client = new Discord.Client();
const config = require("./config.json")
const ytdl = require("ytdl-core")
const streamOptions = {seek:0, volume:1}
client.on("message", async message => {
if(message.author.bot) return
if(message.channel.type === "dm") return
if(!message.content.startsWith(config.prefix)) return
const args = message.content.slice(config.prefix.length).trim().split(/ +/g)
const comando = args.shift().toLocaleLowerCase()
if(comando === "play") {
var voiceChannel = message.guild.channels.cache.get("733122593019789314")
let file = args[0]
if(voiceChannel == null) {
console.log("Canal não encontrado.")
}
if(voiceChannel != null) {
console.log("Canal encontrado.")
await voiceChannel.join().then(connection => {
const stream = ytdl(file, {filter:"audioonly", quality:"highestaudio"})
const DJ = connection.play(stream, streamOptions)
DJ.on("end", end => {
voiceChannel.leave()
})
}).catch(console.error)
}
}/* I was trying to do the command this way:
else if(comando === "stop") {
voiceChannel.leave()
}*/
}
client.login(config.token);
Everything works, I just want to stop the music.
(I'm Brazilian, some words or sentences may be wrong.)
Thank you for your help! 😁
You can use StreamDispatcher.pause() and StreamDispatcher.resume().
Your StreamDispatcher is defined as DJ, so you can use:
DJ.pause(); // Pauses the stream.
DJ.resume(); // Resumes the stream.
DJ.destroy(); // Ends the stream.

Random Meme Command (discord.js v12)

I'm trying to make a 'random meme' command for my Discord Bot. I'm new to working with APIs, but I've tried my best.
The problem is, when I type the command, nothing happens. There are no errors, but the bot doesn't send anything in discord.
This is my code:
if (command === "meme")
async (client, message, args) => {
const subReddits = ["dankmeme", "meme", "me_irl"];
const random = subReddits[Math.floor(Math.random() * subReddits.length)];
const img = await randomPuppy(random);
const embed = new Discord.MessageEmbed()
.setColor(16776960)
.setFooter("test")
.setImage(img)
.setTitle(`Random Meme requested by <#${message.author.tag}>`)
.setURL(`https://reddit.com/r/${random}`)
message.channel.send(embed);
}
Here Is One That Will Show Info About The Meme
if(command === "meme") {
const subReddits = ["dankmeme", "meme", "me_irl"];
const random = subReddits[Math.floor(Math.random() * subReddits.length)];
try {
const { body } = await snekfetch
.get('https://www.reddit.com/r/${random}.json?sort=top&t=week')
.query({ limit: 800 });
const allowed = message.channel.nsfw ? body.data.children : body.data.children.filter(post => !post.data.over_18);
if (!allowed.length) return message.channel.send('It seems we are out of memes');
const randomnumber = Math.floor(Math.random() * allowed.length)
const embed = new Discord.RichEmbed()
.setColor(0x00A2E8)
.setTitle(allowed[randomnumber].data.title)
.setDescription("Posted by: " + allowed[randomnumber].data.author)
.setImage(allowed[randomnumber].data.url)
.addField("Other info:", "Up votes: " + allowed[randomnumber].data.ups + " / Comments: " + allowed[randomnumber].data.num_comments)
.setFooter("r/" + random)
message.channel.send(embed)
} catch (err) {
return console.log(err);
}
}
Let Me Know If It Don't Work, But I Should
client.on('message', 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 === "meme") {
async (client, message, args) =>
const subReddits = ["dankmeme", "meme", "me_irl"];
const random = subReddits[Math.floor(Math.random() * subReddits.length)];
const img = await randomPuppy(random);
const embed = new Discord.MessageEmbed()
.setColor(16776960)
.setFooter("test")
.setImage(img)
.setTitle(`Random Meme requested by <#${message.author.tag}>`)
.setURL(`https://reddit.com/r/${random}`)
message.channel.send(embed);
}
});
This should work, not quite sure, haven't tested it. (You can put in a command handler your self)
if (command === "meme")
async (client, message, args) => {
const fetch = require('node-fetch');
let userAvatar = message.author.avatarURL({ format: "png", dynamic: true, size: 2048 }); // this is just the users icon, u can remove it if you want.
fetch(`https://meme-api.herokuapp.com/gimme`)
.then(res => res.json())
.then(async json => {
const embed = new MessageEmbed()
.setAuthor(`${json.title}`, `${userAvatar + "?size=2048"}`, `${json.postLink}`)
.setImage(`${json.url}`)
.setFooter(`👍${json.ups} | ${json.subreddit}`)
.setColor("RANDOM")
message.channel.send(embed).catch((error) => {
console.log("An error has occured on the \"meme\" command\n", error)
})
}
Here you go! I've tested this on my own command handler.

Resources