I have a probleme, I don't know why but when I use the command "!button", I have an error, there is my code for check it:
const discord = require('discord.js');
const client = new discord.Client();
const disbut = require('discord-buttons')(client);
client.on("message", async (message) => {
if (message.content == "!button") { // Use this command only once and only on one channel.
let buttons = new disbut.MessageButton()
.setStyle('green') // Button Color
.setLabel('Test') // Button Name
.setID('Button') // Button ID
message.channel.send('Message Text.', { buttons: [buttons] });
}
if (message.content == "!urlbutton") { // Use this command only once and only on one channel.
let buttons2 = new disbut.MessageButton()
.setStyle('url') // Button Url
.setLabel('Discord') // Button Name
.setURL('https://discord.com') // URL for forwarding
.setDisabled()
message.channel.send('Message Text.', { buttons: [buttons2] });
}
});
the error:
let buttons = new disbut.MessageButton()
^
TypeError: Cannot read property 'MessageButton' of undefined
at Client.<anonymous> (C:\Users\Sans\Desktop\discord-button-main\index.js:8:30)
at Client.emit (node:events:394:28)
at MessageCreateAction.handle (C:\Users\Sans\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (C:\Users\Sans\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
what's the probleme ? I don't really know ^^" (there is not all my code)
I would take a look at this guide to learn more about buttons and interactions.
This uses discord.js v13
To fix the immediate problem, it will require recoding, as follows:
const { Client, MessageActionRow, MessageButton } = require('discord.js');
const client = new Client();
client.on('messageCreate', async message => {
if (message.content === '!button') {
let buttons = new MessageActionRow()
.addComponents(
new MessageButton()
.setStyle('SUCCESS') //Choices are PRIMARY, a blurple button, SECONDARY, a grey button, SUCCESS, a green button, DANGER, a red button, LINK, a button that navigates to a URL.
.setLabel('Test')
.setCustomId('button')
message.channel.send({
content: 'Message Text',
components: [buttons]
})
} else if (message.content === '!urlbutton') {
let buttons2 = new MessageActionRow()
.addComponents(
new MessageButton()
.setStyle('LINK')
.setLabel('Test')
.setURL('https://discord.com')
message.channel.send({
content: 'Message Text',
components: [buttons2]
})
}
})
How the buttons are interacted with would be under a different listener:
client.on('interactionCreate', async interaction => {
if (interaction.isButton()) {
const buttonID = interaction.customId
if (buttonID === 'button') {
// do something
return interaction.reply({
content: 'Say something',
ephemeral: true //set false or remove if you want everyone to see the response
}
}
}
Related
I am coding a bot with the below command and it throws an error, but i don't know where is the error
i tried my best
const Discord = require("discord.js");
const client = new Discord.Client({
allowedMentions: {
parse: ["roles", "users", "everyone"],
},
intents: [
Discord.Intents.FLAGS.GUILDS,
Discord.Intents.FLAGS.GUILD_MESSAGES,
Discord.Intents.FLAGS.DIRECT_MESSAGES
]
});
const config = require("../config.json");
module.exports = {
name: "quar",
run: async (client, message, args) => {
if (!message.member.permissions.has("ADMINISTRATOR")) return;
let role = message.guild.roles.cache.find(role => role.name === "Quarantined" || role.name === "Quarantine")
let member = message.mentions.members.first() || message.guild.members.cache.get(args[0])
let reason = message.content.split(" ").slice(2).join(" ")
if(!reason) reason = "No reason given."
if(!role) return message.channel.send("❌ This server doesn't have a quarantine role!")
if(!member) return message.channel.send("❌ You didn't mention a member!")
if(member.roles.cache.has(role.id)) return message.channel.send(`❌ That user already quarantined!`)
member.roles.add(role)
.then (() => {
const embed = new Discord.MessageEmbed()
.setTitle(`✅ ${member.user.tag} was quarantined!`)
.setColor("RANDOM")
.setTimestamp()
embed.setFooter(`Requested by ${message.author.username}`)
message.channel.send(embed)
member.send(`You were quarantined in \`${message.guild.name}\`. Reason: ${reason} `).catch(error => {
message.channel.send(`❌ Can't send DM to ${member.user.tag}!`);
});
})
}
}
If I have made a mistake, please help me out
Sorry I don't speak English well
Try the below code out, I made notes along the way to explain as well as improved a small bit of code. I assume this is a collection of 2 separate files which is why they are separated. If they aren't 2 separate files, you do not need the top section, just the bottom.
const {
Client,
Intents,
MessageEmbed
} = require("discord.js");
const client = new Client({
allowedMentions: {
parse: ["roles", "users", "everyone"],
},
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.DIRECT_MESSAGES
]
});
const config = require("../config.json");
const {
MessageEmbed,
Permissions
} = require("discord.js");
module.exports = {
name: "quar",
run: async (client, message, args) => {
if (!message.member.permissions.has(Permissions.FLAGS.ADMINISTRATOR)) return;
let role = message.guild.roles.cache.find(role => role.name === "Quarantined" || role.name === "Quarantine")
let member = message.mentions.members.first() || message.guild.members.cache.get(args[0])
let reason = message.content.split(" ").slice(2).join(" ")
if (!reason) reason = "No reason given."
if (!role) return message.channel.send("❌ This server doesn't have a quarantine role!")
if (!member) return message.channel.send("❌ You didn't mention a member!")
if (member.roles.cache.has(role.id)) return message.channel.send(`❌ That user already quarantined!`)
member.roles.add(role)
.then(() => {
const embed = new MessageEmbed()
.setTitle(`✅ ${member.user.tag} was quarantined!`)
.setColor("RANDOM")
.setTimestamp()
.setFooter({
text: `Requested by ${message.author.username}`
})
// author and footer are now structured like this
// .setAuthor({
// name: 'Some name',
// icon_url: 'https://i.imgur.com/AfFp7pu.png',
// url: 'https://discord.js.org',
// })
// .setFooter({
// text: 'Some footer text here',
// icon_url: 'https://i.imgur.com/AfFp7pu.png',
// })
message.channel.send({
embeds: [embed]
}) //embeds must be sent as an object and this was the actual line that was causing the error.
member.send(`You were quarantined in \`${message.guild.name}\`. Reason: ${reason} `).catch(() => { // if error is not used, it is not required to be stated
message.channel.send(`❌ Can't send DM to ${member.user.tag}!`);
});
})
}
}
So I'm making a command that starts with a slash command, then you need to press a button, the bot send a emebed when you press the button, and then it waits for a message, and when the user sends a message the bot responds.
So here is how it goes:
slahs command
emebed with a button
chek if button is pressed and then send another embed
wait for users message check it and then sends something
Here is the code for the button message:
`client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
if (interaction.commandName === 'reactor') {
const row = new MessageActionRow()
.addComponents(
new MessageButton()
.setCustomId('Start')
.setLabel('Start')
.setStyle('PRIMARY'),
);
const exampleEmbed = new MessageEmbed()
.setTitle('Now you will the to grab the materials')
.setDescription("Type out the words that will be given bt don't be too slow")
await interaction.reply({ embeds: [exampleEmbed], components: [row] });
}
});`
Here is the code that cheks if the button is pressed sends a message and then waits for a spesific users message:
`client.on("message", message => {
if (!message.isButton()) return; // cheking if is button
if (message.customId == "Start") { //if button clicked is start do this
const exampleEmbed = new MessageEmbed() //creating a message
.setDescription('Type out the words that will be given')
.setThumbnail('https://cdn.discordapp.com/attachments/844145839898492929/953741341186228354/Hk86.png')
await interaction.reply({embeds: [exampleEmbed]}); //print out the embed
message.channel.awaitMessages(m => m.author.id == message.author.id, //cheking the next message
{ max: 1, time: 30000 }).then(collected => { //sets timer and then collect info
if (collected.first().content.toLowerCase() == 'Hk86') { //chek if message is yes
message.reply('it works!');
}
});
}
});`
And here are the imports:
const { Client, Collection, Intents, MessageActionRow, MessageButton, MessageEmbed} = require('discord.js');
const { token } = require('./config.json');
const client = new Client({ intents: \[Intents.FLAGS.GUILDS\] });
client.commands = new Collection();
I think the reason the bot doesn't send a message is because you didn't include the GUILD_MESSAGES intent.
const client = new Discord.Client({
intents: ["GUILDS", "GUILD_MESSAGES", "GUILD_WEBHOOKS", "DIRECT_MESSAGES", "GUILD_BANS", "GUILD_MEMBERS", "GUILD_VOICE_STATES"], //must use intents
allowedMentions: ["users"] //stops people from using +say #everyone
});
That's my code for my client.
i am trying to make it so as soon as you type: mememe it will react with: your nickname is now:
my current code is
const Discord = require("discord.js");
const client = new discord.client();
client.login(process.env.SECRET);
const embed = new Discord.MessageEmbed()
.setTitle("This is Embed Title")
.setDiscription("this is embed discription")
.setColor("RANDOM")
.SetFooter("This is Embed Footer");
const nicknames = ["dumbass", "idiot", "op", "man", "power", "docter"];
client.on("ready", () => {
client.user.setPresence({ activity: { name: "brave" }, status: "invisible" });
});
client.on("message", (message) => {
if (message.content === "ding") {
message.channel.send === "dong";
}
if (message.content === "embed") {
message.channel.send(embed);
}
});
if (message.content("mememe")) {
const index = Math.floor(Math.random() * nicknames.length);
message.channel.send(nicknames[index]);
}
but i dont know why it does not work it says as a error: Parsing error: Unexpected token
that is all and idk how to fix that
Edit : you guys were useless
I first want to say: Please fix your indents (I did it for you below here.
const Discord = require("discord.js")
const client = new Discord.Client()
client.login(process.env.SECRET)
// const embed = new Discord.MessageEmbed()
// .setTitle("This is Embed Title")
// .setDiscription("this is embed discription")
// .setColor("RANDOM")
// .SetFooter("This is Embed Footer");
const nicknames = ["dumbass", "idiot" , "op" , "man" , "power" , "docter"]
client.on("ready" , () => {
client.user.setPresence({ activity: { name: "brave"}, status: "invisible"})
})
client.on("message" , message => {
if(message.content === ("ding")) {
message.channel.send === ("dong")
}
if(message.content === ("embed")) {
message.channel.send(embed)
}
if(message.content === ("mememe")) {
const index = Math.floor(Math.random() * nicknames.length);
message.channel.send(nicknames[index])
}
})
The issue was you were calling the mememe command wrong. Above you used messega.content === "..."
In the mememe command you used message.content("mememe"). This does not work. Changes it (or copying the code above should fix the issue. Maybe an idea for you. You could add a feature where it changes the Users Nickname instead of sending a random one.
I am trying to do a discord bot that creates channels among others, but I can't achieve it because my code it's supposed to create a channel but... I tried a lot of things, these are the two that haven't given me error: (I substituted the bot's token with DONOTLOOK, I won't have problems...)
OPTION 1:
const Discord = require('discord.js');
const bot = new Discord.Client();
bot.login('DONOTLOOK');
bot.on('ready', () => {
console.log('Logged in as ${bot.user.tag}!');
});
bot.on('message', msg => {
if (msg.content === 'ping') {
msg.reply('Pong!');
var server = msg.guild;
bot.channels.add("anewchannel", {type: 0});
}
});
OPTION 2:
const Discord = require('discord.js');
const bot = new Discord.Client();
bot.login('DONOTLOOK');
bot.on('ready', () => {
console.log(`Logged in as ${bot.user.tag}!`);
});
bot.on('message', msg => {
if (msg.content === 'ping') {
msg.reply('Pong!');
var server = msg.guild;
const channel = bot.channels.add("newchannel", {type: 0});
}
});
That don't gave me any node.js error on console, the bot answered me but haven't created the channel. I also looked two references(https://discord.com/developers/docs/resources/guild#create-guild-channel, https://discord.js.org/#/docs/main/stable/class/GuildChannelManager?scrollTo=create), no one's solutions worked, the discord.com one gave me node.js error too. The two options above are taken from the discord.js file, they gave no node.js errors but doesn't create the channel. If someone can help me please.
discord.js v13 has changed some stuff.
Updated version:
bot.on("messageCreate", message => { // instead of 'message', it's now 'messageCreate'
if (message.content === "channel") {
message.guild.channels.create("channel name", {
type: "GUILD_TEXT", // syntax has changed a bit
permissionOverwrites: [{ // same as before
id: message.guild.id,
allow: ["VIEW_CHANNEL"],
}]
});
message.channel.send("Channel Created!");
})
I would also recommend using bot.guilds.cache.get(message.guildId). This removes the need to use the API to fetch the user.
The code below explains how to create a text channel from a command.
bot.on('message', msg => { //Message event listener
if (msg.content === 'channel') { //If the message contained the command
message.guild.channels.create('Text', { //Create a channel
type: 'text', //Make sure the channel is a text channel
permissionOverwrites: [{ //Set permission overwrites
id: message.guild.id,
allow: ['VIEW_CHANNEL'],
}]
});
message.channel.send("Channel Created!); //Let the user know that the channel was created
}
});
If you don't want to use messages to create you can use..
var bot = client.guilds.cache.get("<GUILD-ID>");
server.channels.create("<CHANNEL-TEXT>", "<CHANNEL-TYPE>").then(channel => {
var cat = server.channels.cache.find(c => c.name == "BUSINESSES" && c.type == "category");
if (!cat) { console.log("category does not exist"); return; }
channel.setParent(cat.id);
})
This is something with the const or var. I think that it won't work unless I recode it. Here is my problem:
bot.on('ready', () => {
^
ReferenceError: bot is not defined
at C:\Users\Dylan\Desktop\discord bot\app.js:7:1
at ContextifyScript.Script.runInThisContext (vm.js:50:33)
at Object.runInThisContext (vm.js:139:38)
at Module._compile (module.js:607:28)
at Object.Module._extensions..js (module.js:654:10)
at Module.load (module.js:556:32)
at tryModuleLoad (module.js:499:12)
at Function.Module._load (module.js:491:3)
at Function.Module.runMain (module.js:684:10)
at startup (bootstrap_node.js:187:16)
Here is my code:
const Discord = require('discord');
const bot = new Discord.Bot();
const fs = require('fs')
const commandsList = fs.readFileSync('Storage/commands.txt','utf8');
});
bot.on('ready', () => {
// This event will run if the bot starts, and logs in, successfully.
console.log(`Bot has started, with ${client.users.size} users, in ${client.channels.size} channels.`);
});
bot.on('message', message => {
if (message.content === '!ping') {
message.channel.send('pong');
}
});
bot.on('message', message => {
if (message.content === '!apply') {
message.channel.send('GOGLE STUFF');
}
});
bot.on('message', message => {
if (message.content === '!server') {
message.channel.send('LA');
}
});
bot.on('message', message => {
if (message.content === '!do you know dae wae') {
message.channel.send('Yes I know dae wae brother');
}
});
bot.on('message', message => {
if (message.content === 'do you have a bot?') {
message.channel.send('no');
}
});
bot.on('message', message => {
if (message.content === 'who is the owner') {
message.channel.send('FantasmicNerd, duh');
}
});
bot.on('message', message => {
if (message.content === 'can i be staff' || message.content === 'can I be staff?' || message.content === 'can i be staff?') {
message.channel.send('Application - lalalalalala');
}
});
bot.on('message', message => {
if (message.content === 'somebody touch my spaghet') {
message.channel.send('SOMEBODY TOUCH YOUR SPAGHET!');
}
});
bot.on('message', message => {
if (message.content === 'so how about that airline food') {
message.channel.send('HAAHAHAHHAHAHAHHAHAHAHAHAHHAHAHHAHAHAHAHHAHAHAAHAHAHHAHAHAHHAHAHAHAHAHHAHAHHAHAHAHAHHAHA');
}
});
bot.on('ready',() => {
console.log('Bot Launched...')
bot.user.setStatus('Online')
bot.user.setActivity('on The Magical')
});
bot.on('message', message => {
if (message.content === '?help' || message.content === '?Help') {
message.channel.send('I have messaged you the commands and prefix.');
}
});
bot.on('message', message => {
if (message.content === '?help' || message.content === '?Help') {
message.author.sendMessage(commandsList);
}
});
bot.on('ready', function() {
bot.user.setUsername("The Magical");
// THIS MUST BE THIS WAY
bot.login('NDA0NjYzNzIwNDQzMzc5NzEy.DUapFw.zjDvPkG4QxZJ1rdxDYaPZEaVpiM');
I have looked all over for answers but nothing seems to work. I end up with this in cmd prompt when I try to run it
Where you're requiring the library you need to change it to discord.js to get access to the library.
Also the library does not expose a class called "Bot" so you need change that to "Client".
I'm guessing the )}; on line 5 is supposed to be closing the ready event on line 88.
But I suggest you just stick with one ready event, so put the status and activity methods in the first ready event and remove the other ones. Also, if you've set your bot username to what you want I would remove that method, or put a check to see if the username is already set to what you want, and if it is then don't change it.
Same with all the message events as the ready ones, stick to one message event and just chain all the if statements in that one. Example:
bot.on('message', message => {
if (message.content === '!ping') {
message.channel.send('pong');
}
else if (message.content === '!apply') {
message.channel.send('GOGLE STUFF');
}
...
});
Also you need to remember what you define your variables as. In the first ready event you use client.users instead of what you have defined, which is bot.
According to discord.js API document, there is no Bot class.
Maybe what you need is
const client = new Discord.Client();
I suggest you check the document and example for your application.