Hi I Coded A Bot But I Want To limit Bot's One Exact Event in One Channel This is Code
No Errors Just Need To Lock This Event in one channel
module.exports = async (client, message) => {
if (message.author.bot) return
if (message.channel.type === "dm") {
const guild = client.guilds.cache.get("736112465678565437")
const channel = guild.channels.cache.find(c => c.name === "modmail-messages")
const embed = new Discord.MessageEmbed()
.setAuthor(`${message.author.tag} | ${message.author.id}`, message.author.displayAvatarURL())
.addField("Message", message.content)
.setFooter("Sent")
.setTimestamp()
.setColor("PURPLE")
await message.author.send("Sending To Staff...")
await channel.send(embed)
}
if (message.channel.type !== "dm" && message.guild.channels.cache.find(c => c.name === "modmail-messages")) {
const user = message.mentions.members.first()
const args = message.content.slice(process.env.PREFIX.length).trim().split(/ +/g)
let response = args.slice(1).join(' ')
if (!response)
return message.reply("please provide a response to the user!")
if (!user)
return message.reply("please specify a user!")
await user.send(`**(•Hyper Staff)** ${message.member.displayName}: ${response}`)
}
if (message.content.indexOf(process.env.PREFIX) !== 0) return
const args = message.content.slice(process.env.PREFIX.length).trim().split(/ +/g)
const command = args.shift().toLowerCase()
const cmd = client.commands.get(command)
if (!cmd) return
cmd.run(client, message, args)
}```
What do you mean by "locking the event in one channel"? You want the bot to send a message in a specific channel?
Related
I am trying to make a system that makes a user enter a code(like a verification code sent to the dms) before doing the action. I am trying to understand how my code can wait for the code to be entered, and I came across the awaitMessages tag. I am trying to understand how I can use it properly in my code. Here is my code.
const Discord = require("discord.js");
const config = require("./config.json");
const { MessageAttachment, MessageEmbed } = require('discord.js');
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES", "DIRECT_MESSAGES", "DIRECT_MESSAGE_REACTIONS", "DIRECT_MESSAGE_TYPING"], partials: ['CHANNEL',] })
const RichEmbed = require("discord.js");
const prefix = "!";
client.on("messageCreate", function(message) {
if (message.author.bot) return;
if (!message.content.startsWith(prefix)) return;
const commandBody = message.content.slice(prefix.length);
const args = commandBody.split(' ');
const command = args.shift().toLowerCase();
if (command === "news") {
if (message.channel.type == "DM") {
message.author.send(" ");
}
}
if (command === "help") {
message.author.send("The help desk is avaliable at this website: https://example.com/");
}
});
client.on("messageCreate", function(message) {
if (message.author.bot) return;
if (!message.content.startsWith(prefix)) return;
const commandBody = message.content.slice(prefix.length);
const args = commandBody.split(' ');
const command = args.shift().toLowerCase();
if (command === "ping") {
const timeTaken = Date.now() - message.createdTimestamp;
message.channel.send(`Pong! This message had a latency of ${timeTaken}ms.`);
}
if (command === "delete all messages") {
const timeTaken = Date.now() - message.createdTimestamp;
const code = Math.random(1,1000)
message.channel.send(`Executing command. Verification Required.`);
message.author.send(`Your code is the number ${code}.`)
message.channel.send(`Please confirm your code. The code has been sent to your dms. Confirm it in here.`)
message.channel.awaitMessage(code) {
message.channel.send('confirmed. Doing the action.')
}
}
});
client.login(config.BOT_TOKEN)
To wait for a response from the user, you can use a collector.
You can create a filter to see if the user sending the code is the same as the one who executed the command and if the code sent is correct
const filter = (msg) => msg.author.id === message.author.id && msg.content === code;
const collector = message.channel.createMessageCollector({
filter,
time: 60000,
});
collector.on('collect', (collectedMessage) => {
collector.stop('success');
message.channel.send('confirmed. Doing the action.')
});
collector.on('end', (collected, reason) => {
if (reason === 'success') return;
else message.channel.send('Timeout or error');
});
How assign role to user in discord by slash command?
This is my discord code by node.js using discord.js module.
After finish this code, I want add role on ready event.
Please fixt:
This small code doesn't working.
else if (command === "red") {
// Create a new text channel
let role = guild.roles.find((r) => r.id === "948192740632588329");
// Or add it to yourself
message.member.roles.add(role);
}
in below.
const Discord = require("discord.js");
const config = require("./config.json");
const {
Client,
Intents,
MessageEmbed,
MessageAttachment,
} = require("discord.js");
const { MessageActionRow, MessageButton } = require("discord.js");
const client = new Client({
intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES],
});
client.on("messageCreate", function (message) {
let guild = message.guild;
if (message.author.bot) return;
if (!message.content.startsWith(prefix)) return;
const commandBody = message.content.slice(prefix.length);
const args = commandBody.split(" ");
const command = args.shift().toLowerCase();
if (command === "ping") {
const timeTaken = Date.now() - message.createdTimestamp;
message.reply(`Pong! This message had a latency of ${timeTaken}ms.`);
} else if (command === "sum") {
const numArgs = args.map((x) => parseFloat(x));
const sum = numArgs.reduce((counter, x) => (counter += x));
message.reply(`The sum of all the arguments you provided is ${sum}!`);
} else if (command === "channel") {
// Create a new text channel
guild.channels
.create("nft-checking", { reason: "Needed a cool new channel" })
.then(console.log)
.catch(console.error);
} else if (command === "red") {
// Create a new text channel
let role = guild.roles.find((r) => r.id === "948192740632588329");
// Or add it to yourself
message.member.roles.add(role);
}
});
if (command === "ping") {
const timeTaken = Date.now() - message.createdTimestamp;
message.reply(ping! This message had a latency of ${timeTaken}ms.);
Replace these line with this
Or
Just correct the spelling of from pong to ping.
I am currently making a music Discord Bot. My problem is at the fist lines of the command : even when the user is in a voice channel, voiceChannel is marked as undefined and the bot return "You have to be in a voice channel to use this command"
client.on("message", async message => {
if(message.author.bot) return;
const serverQueue = queue.get(message.guild.id);
if(message.content.indexOf(PREFIX) !== 0) return;
const args = message.content.slice(PREFIX.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
if (command === "play" || command === "p") {
const args = message.content.split(" ");
const searchString = args.slice(1).join(" ");
const url = args[1] ? args[1].replace(/<(.+)>/g, "$1") : "";
const serverQueue = queue.get(message.guild.id);
const voiceChannel = message.member.voiceChannel;
if (!voiceChannel) return message.channel.send("You have to be in a voice channel to use this command");
}
});
have a look here
message.member.voiceChannel;
doesn't exist in discord.js version 12 and up
you need to use
message.member.voice.channel.
I tried to many things the thing. But I m not able to change the config file by using the command. I want to add channel id in that config
const fs = require('fs');
const config = require('../config.json')
const Discord = require('discord.js');
const client = new Discord.Client();
module.exports.run = async (client, message, args) => {
let owner = process.env.OWNER.split(',')
if(!owner.includes(message.author.id)) {
return message.reply("This command is not made for everyone")
}
if (message.channel.type === "dm" || message.author.bot || message.author === client.user) return; // Checks if we're on DMs, or the Author is a Bot, or the Author is our Bot, stop.
fs.writeFile('./config.json', args[0], (err) => {
if (err) console.log(err)
})
message.channel.send("Done")
}
exports.help = {
name: "wtp",
category: "General",
description: "Add this channel into WTP",
usage: "wtp <channel_id>"
};```
Also you can do it like this, add/change variable of config and then save it.
const fs = require('fs');
const config = require('../config.json')
const Discord = require('discord.js');
const client = new Discord.Client();
module.exports.run = async (client, message, args) => {
let owner = process.env.OWNER.split(',')
if(!owner.includes(message.author.id)) return message.reply("This command is not made for everyone")
if (message.channel.type === "dm" || message.author.bot || message.author === client.user) return; // Checks if we're on DMs, or the Author is a Bot, or the Author is our Bot, stop.
if (args.length === 0) return message.reply('Pls mention a channell')
let targetChannel = message.mentions.channels.first() || message.guild.channels.get(args[0])
if (!targetChannel) return message.reply('Cant fin`d channel')
config.channed_id = targetChannel.id
fs.writeFile('./config.json',JSON.stringify(config) , (err) => {
if (err) console.log(err);
message.channel.send("Done")
})
}
exports.help = {
name: "wtp",
category: "General",
description: "Add this channel into WTP",
usage: "wtp <channel_id>"
};
I would like to break up my following code into multiple files for management instead of having everything run on the main file. The whole code is located as one Node.js modal know as index.js I would like to break the code up into multiple files management.js and interantion.js and they communicate with node.js
const Discord = require("discord.js");
const client = new Discord.Client();
const config = require("./config.json");
const ms = require("ms");
client.on("ready", () => {
console.log(`Bot has started, with ${client.users.size} users, in ${client.channels.size} channels of ${client.guilds.size} guilds.`);
client.user.setGame(config.game);
});
client.on("guildCreate", guild => {
console.log(`New guild joined: ${guild.name} (id: ${guild.id}). This guild has ${guild.memberCount} members!`);
client.user.setGame(`on ${client.guilds.size} servers`);
});
client.on("guildDelete", guild => {
console.log(`I have been removed from: ${guild.name} (id: ${guild.id})`);
});
client.on("guildMemberAdd", function(member) {
//Welcomes a user
member.guild.channels.find("name", "general").send("Please welcome " + member.toString() + " to the server! " + member.toString() + " Make sure to read the rules and enjoy your stay :heart:." + " https://imgur.com/a/pCcSm");
});
//managment
client.on("message", async message => {
if (message.author.bot) return;
if (message.content.indexOf(config.prefix) !== 0) return;
const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
var mutedrole = message.guild.roles.find("name", "muted");
//Managment
if (command === "say") {
if (!message.member.roles.some(r => ["Management"].includes(r.name))) return message.reply("Sorry, you don't have permissions to use this!");
const sayMessage = args.join(" ");
message.delete().catch(O_o => {});
message.channel.send(sayMessage);
}
if (command === "kick") {
if (!message.member.roles.some(r => ["Management"].includes(r.name))) return message.reply("Sorry, you don't have permissions to use this!");
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 user! Do they have a higher role? Do I have kick permissions?");
let reason = args.slice(1).join(' ');
if (!reason) return message.reply("Please indicate a reason for the kick!");
await member.kick(reason).catch(error => message.reply(`Sorry ${message.author} I couldn't kick because of : ${error}`));
message.reply(`${member.user.tag} has been kicked by ${message.author.tag} because: ${reason}`);
}
if (command === "ban") {
if (!message.member.roles.some(r => ["Management"].includes(r.name))) return message.reply("Sorry, you don't have permissions to use this!");
let member = message.mentions.members.first();
if (!member) return message.reply("Please mention a valid member of this server");
if (!member.bannable) return message.reply("I cannot ban this user! Do they have a higher role? Do I have ban permissions?");
let reason = args.slice(1).join(' ');
if (!reason) return message.reply("Please indicate a reason for the ban!");
await member.ban(reason).catch(error => message.reply(`Sorry ${message.author} I couldn't ban because of : ${error}`));
message.reply(`${member.user.tag} has been banned by ${message.author.tag} because: ${reason}`);
}
if (command === "purge") {
if (!message.member.roles.some(r => ["Management"].includes(r.name))) return message.reply("Sorry, you don't have permissions to use this!");
const deleteCount = parseInt(args[0], 10);
if (!deleteCount || deleteCount < 2 || deleteCount > 100) return message.reply("Please provide a number between 2 and 100 for the number of messages to delete");
const fetched = await message.channel.fetchMessages({
count: deleteCount
});
message.channel.bulkDelete(fetched).catch(error => message.reply(`Couldn't delete messages because of: ${error}`));
}
if (command == "mute") {
let member = message.mentions.members.first();
if (!member) return message.reply("Please mention a member");
let muteRole = message.guild.roles.find("name", "Muted");
if (!muteRole) return message.reply("Role: Muted not found.");
let params = message.content.split(" ").slice(1);
let time = args[1];
if (!time) return message.reply("Please specify how long the user should be muted.");
member.addRole(muteRole.id);
message.channel.send(`You've been muted for ${ms(ms(time), {long: true})}, ${member.user.tag}`);
setTimeout(function() {
member.removeRole(muteRole.id);
message.channel.send(`${member.user.tag} You were unmuted! The mute lasted: ${ms(ms(time), {long: true})}`)
}, ms(time));
}
//interaction
if (command === "ping") {
const m = await message.channel.send("Pong");
m.edit(`Fine here you go >.<! Latency is ${m.createdTimestamp - message.createdTimestamp}ms. API Latency is ${Math.round(client.ping)}ms`);
}
if (command == "drops") {
message.channel.send("https://docs.google.com/spreadsheets/d/1_SlTjrVRTgHgfS7sRqx4CeJMqlz687HdSlYqiW-JvQA/htmlview?sle=true#gid=0");
}
});
client.login(config.token);
The result look something like this:
index.js
const Discord = require("discord.js");
const client = new Discord.Client();
const config = require("./config.json");
const ms = require("ms");
client.on("ready", () => {
console.log(`Bot has started, with ${client.users.size} users, in ${client.channels.size} channels of ${client.guilds.size} guilds.`);
client.user.setGame(config.game);
});
client.on("guildCreate", guild => {
console.log(`New guild joined: ${guild.name} (id: ${guild.id}). This guild has ${guild.memberCount} members!`);
client.user.setGame(`on ${client.guilds.size} servers`);
});
client.on("guildDelete", guild => {
console.log(`I have been removed from: ${guild.name} (id: ${guild.id})`);
});
client.on("guildMemberAdd", function(member) {
//Welcomes a user
member.guild.channels.find("name", "general").send("Please welcome " + member.toString() + " to the server! " + member.toString() + " Make sure to read the rules and enjoy your stay :heart:." + " https://imgur.com/a/pCcSm");
});
//managment
client.on("message", async message => {
if (message.author.bot) return;
if (message.content.indexOf(config.prefix) !== 0) return;
const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
});
client.login(config.token);
managment.js
//Managment
if (command === "say") {
if (!message.member.roles.some(r => ["Management"].includes(r.name))) return message.reply("Sorry, you don't have permissions to use this!");
const sayMessage = args.join(" ");
message.delete().catch(O_o => {});
message.channel.send(sayMessage);
}
if (command === "kick") {
if (!message.member.roles.some(r => ["Management"].includes(r.name))) return message.reply("Sorry, you don't have permissions to use this!");
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 user! Do they have a higher role? Do I have kick permissions?");
let reason = args.slice(1).join(' ');
if (!reason) return message.reply("Please indicate a reason for the kick!");
await member.kick(reason).catch(error => message.reply(`Sorry ${message.author} I couldn't kick because of : ${error}`));
message.reply(`${member.user.tag} has been kicked by ${message.author.tag} because: ${reason}`);
}
if (command === "ban") {
if (!message.member.roles.some(r => ["Management"].includes(r.name))) return message.reply("Sorry, you don't have permissions to use this!");
let member = message.mentions.members.first();
if (!member) return message.reply("Please mention a valid member of this server");
if (!member.bannable) return message.reply("I cannot ban this user! Do they have a higher role? Do I have ban permissions?");
let reason = args.slice(1).join(' ');
if (!reason) return message.reply("Please indicate a reason for the ban!");
await member.ban(reason).catch(error => message.reply(`Sorry ${message.author} I couldn't ban because of : ${error}`));
message.reply(`${member.user.tag} has been banned by ${message.author.tag} because: ${reason}`);
}
if (command === "purge") {
if (!message.member.roles.some(r => ["Management"].includes(r.name))) return message.reply("Sorry, you don't have permissions to use this!");
const deleteCount = parseInt(args[0], 10);
if (!deleteCount || deleteCount < 2 || deleteCount > 100) return message.reply("Please provide a number between 2 and 100 for the number of messages to delete");
const fetched = await message.channel.fetchMessages({
count: deleteCount
});
message.channel.bulkDelete(fetched).catch(error => message.reply(`Couldn't delete messages because of: ${error}`));
}
if (command == "mute") {
let member = message.mentions.members.first();
if (!member) return message.reply("Please mention a member");
let muteRole = message.guild.roles.find("name", "Muted");
if (!muteRole) return message.reply("Role: Muted not found.");
let params = message.content.split(" ").slice(1);
let time = args[1];
if (!time) return message.reply("Please specify how long the user should be muted.");
member.addRole(muteRole.id);
message.channel.send(`You've been muted for ${ms(ms(time), {long: true})}, ${member.user.tag}`);
setTimeout(function() {
member.removeRole(muteRole.id);
message.channel.send(`${member.user.tag} You were unmuted! The mute lasted: ${ms(ms(time), {long: true})}`)
}, ms(time));
}
interaction.js
//interaction
if (command === "ping") {
const m = await message.channel.send("Pong");
m.edit(`Fine here you go >.<! Latency is ${m.createdTimestamp - message.createdTimestamp}ms. API Latency is ${Math.round(client.ping)}ms`);
}
if (command == "drops") {
message.channel.send("https://docs.google.com/spreadsheets/d/1_SlTjrVRTgHgfS7sRqx4CeJMqlz687HdSlYqiW-JvQA/htmlview?sle=true#gid=0");
}
I have tried using a required method, but it gives me file not found error.
I'm not entirely sure how you could do this, possibly by using fs or something similar. You could, however, use commando.js rather than discord.js.
Commando.js has one index file for logging in and so on, and then each command is set up into different categories under folders and each command has its own file. It's certainly something to look into.