discordjs version 11.4.2
I type !a hello in channel but bot don't sent message
if(command === "!a hello"){
const msg = await message.channel.send("Checking Command...")
msg.edit("hello");
}
First of all, you need to define 'command', but in your case you can change out command with msg.content === '!a hello'. You also don't have to define 'msg', although I suppose you could do that still.
You can do this:
bot.on("message", msg => {
if (msg.content === "!a hello") {
msg.channel.send("Checking Command...").then(msg => {
msg.edit(`hello`);
});
}
});
Tell me if you need anything or need to remove something or add something. Hope this helps :)
My guess is that you have defined "command" to something like this somewhere in your code
const args = message.content.split(/ +/g);
const command = args.shift().toLowerCase();
What's causing you this problem would be this part of it: ".split(/ +/g);"
This splits everything with a space in between into substrings. So how can you fix it now? Either use the command "!a-hello" or don't use "command"
if (message.content === "!a hello") {
const msg = await message.channel.send("Checking Command...")
msg.edit("hello");
};
Related
I've coded a "say command" that's supposed to execute a message every time I type in -say.
It's working fine, I just want the prefix to be set to "?" instead of "-" only for that one command, the other ones are supposed to be set to the main one ("-"). On top of that I want it to delete the command after typing it in, so all that remains is the message [(e.g ?say hello --> (delete "?say hello" --> send message "hello" to text channel)]. I also want to specify the text channel in my command, instead of just setting it to send the messages only to one specific channel [e.g -say (message) (text channel)] It would also be pretty cool if it said something like "Done." and deleting that confirmation after ~5 sec.
So here is the code:
client.on('message', function(message) {
if(message.author.bot) return;
else if(isValidCommand(message, "say")) {
let sendMessage = message.content.substring(4);
let sendChannel = client.channels.cache.get('767374258492932106');
sendChannel.send(sendMessage)
}
});
In the following I will show you my not working code, trying to set the prefix to "?" but it didnt execute, only saying "declaration or statement expecting and missing or wrong punctuation..
client.on('message', function(message) {
if (['?'].every((prefix) => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
else if(isValidCommand(message, "say")) {
let sendMessage = message.content.substring(4);
let sendChannel = client.channels.cache.get('767374258492932106');
sendChannel.send(sendMessage)
}
});
It'd be really grateful if someone helped me with this. Thank you!
I am not sure what you trying to achieve with
if (['?'].every((prefix) => {
but this is what I would do
using args, substring and switch to identify the command.
The usage of the
client.on('message', async message =>{
if (message.author.bot) return;
if (message.content.startsWith(prefix)) {
let args = message.content.substring(prefix.length).split(" ");
switch (args[0].toLowerCase()){
case 'say': {
let sendMessage = message.content.substring(prefix.length +args[0].length+ args[1].length + 2); //2 is accounting for the 2 space between prefix and # and prefix and the main content
setTimeout(()=>{message.delete()},5000)
let sendChannel = client.channels.cache.get(args[1]);
sendChannel.send(sendMessage)
break;
}
}
}
if (message.content.startsWith(otherPrefix)) {
let args = message.content.substring(otherPrefix.length).split(" ");
switch (args[0].toLowerCase()){
case 'say': {
// Do something else
break;
}
}
}
});
Edit: The usage of the commend would be like
!say #generalTextChannel abc
where #generalTextChannel is tagging the channel
or
!say 767374258492932106 abc
where 767374258492932106 is the channel Id
I don't quite understand what are you trying to do with the prefixes.
When trying to detect a prefix in front of a command, you can just use the other line you used without ['?'].every
Use just this: if (!message.content.startsWith(prefix) || message.author.bot) return;.
Then check for each command individually under this. if (command == 'say')
A very simple way of getting arguments:
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
The say command would look something like this:
if(command == 'say'){
//then you could find the channel
//https://discord.js.org/#/docs/main/stable/class/ChannelManager?scrollTo=fetch
client.channels.fetch('222109930545610754')
.then(channel => {
channel.send(args.join(" ")) //sending the arguments joined with a space in the fetched channel
.then(msg => {setTimeout(function(){msg.delete()},5000)}) //delete after 5 seconds, please check if delete is a function (I didn't)
})
.catch(console.error);
}
['?'].every got me thinking you could use if(!['?', '-'].some(prefix => content.startsWith(prefix))) return to use more prefixes instead of the if statement.
I don't know what your saying. But here is how I would do it.
const Discord = require("discord.js");
const client = new Discord.Client();
const prefix = '!';
client.on('message', message => {
const args = message.content.slice(prefix.length).trim().split(/+ /);
const command = args.shift().toLowerCase();
if (command === 'say') {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const user = message.author;
if (!args[0]) {
user.send("Provide a word to say in the say command\nExample: !say Hello")
}
const say = args.join(" ");
message.channel.send(say)
message.delete()
}
})
client.login("PUT YOUR TOKEN HERE")
For the other prefix, you could do this:
client.on('message', async message => {
if(message.content === '?say') {
//the code (I don't know what is the code, I'm giving the way for the prefix)
} else {}
if(!message.content.startsWith(prefix) || message.author.bot) return
const args = message.content.slice(prefix.length).trim().split(/+ /);
const command = args.shift().toLowerCase();
//bla bla bla (the rest of the commands, etc.)
}
I use discord.js and I am making a bot that sends back the text that a user types but whatever I try I run into problems.
This is what I tried:
let s4 = (message.channel, message.content);
client.on('message', (message) => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if (command) {
messege.channel.send(s1 + s4);
}
});
It looks like your issue is in
const command = args.shift().toLowerCase();
if (command) {
messege.channel.send(s1 + s4);
}
you are putting an array into in if statement with nothing to turn it into a Boolean. Another issue you might have is that the command is a constant. I suggest replacing it with
let command = args.shift().toLowerCase();
messege.channel.send(s1 + s4);
Also, reading the comments, it looks like you referenced the message object before it was defined
In the future, please add the errors you are receiving to your question
I want to create a verify Command with discord.js v12 which gives you a verified Role which is defined in a Configfile.
Configfile:
{
"token": "my-token",
"status": "a game",
"statusurl": "",
"statustype": 0,
"botmanager": ["285470267549941761", "743136148293025864"],
"prefix": "m!",
"server": {
"343308714423484416": {
"active": true,
"hasBeta": true,
"adminroles": ["533646738813353984"],
"modroles": ["744589796361502774"],
"premiumtoken": "",
"welcomechannel": "653290718248435732",
"welcomemessage": "Hey Hey %user% at %server%",
"welcomemsgenabled": true,
"leavechannel": "653290718248435732",
"leavemessage": "Bye %user% at %server%",
"leavemsgenabled": true,
"verifiedrole": "533646700712296448",
"ruleschannel": "382197929605201920"
}
}
}
My Code:
const Discord = require('discord.js')
const client = new Discord.Client()
const config = require('./config.json')
client.on('ready', () => {
client.user.setStatus('online')
client.user.setActivity("m!help")
console.log(`Bot started successfully in ${client.guilds.cache.size} Guilds with ${client.users.cache.size} Users and ${client.channels.cache.size} Channels`)
})
client.on("message", async message => {
if(message.author.bot) return;
if(!message.content.startsWith(config.prefix)) return;
const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
if(command === "verify") {
if(args.length == 0) {
let member = message.mentions.members.first();
if(message.member.roles.cache.some(r=>[config.server[(message.guild.id)].modroles].includes(r.id))) {
if(!member) {
return message.channel.send(new Discord.MessageEmbed().setColor(0xd35400).setTitle("Invalid User").setDescription("Please use the following Syntax:\n `m!verify <Nutzer>`"))
} else {
var role = message.guild.roles.find(role => role.id === config.server[(message.guild.id)].verifiedrole);
member.roles.cache.add(config.guild[(message.guild.id)].verifiedrole)
}
} else {
message.channel.send(new Discord.MessageEmbed().setTitle("Missing Perms!").setDescription("You're missing the permission to execute this command!").setColor(0xe74c3c))
}
}
}
console.log("Command used: " + command + " " + args + " | User: " + message.author.id + " | Guild: " + message.guild.id)
}
}
})
client.login(config.token)
I removed the most Code so only this command is left. Important is, that this Bot have to be able to use at multiple Servers at the time.
What is wrong here?
OK, so lets make this a multi part answer. First "What is wrong here?" Well, for the most part your current code does not work because you don't use the brackets correctly. You are trying to close brackets that you don't open anywhere. You also use a few too many "if" statements in places where you don't need them.
Next is your concern about multiple servers. This is really not a problem if you write the code to be dynamic. The execution of the command is quick enough that you don't need to worry about two people trying to use the command and the roles getting mixed up.
What I would really advise you to do is take a look at this https://discordjs.guide/ and this https://discord.js.org/#/docs/main/stable/general/welcome
Now to the topic of this question, this is how you could do such a "verify" command. I also added a few notations into the code to explain what we're doing 🙂
client.on("message", message => { // You don't need the async here
// This is all working correctly
if (message.author.bot) return;
if (!message.content.startsWith(config.prefix)) return;
const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
if (command === "verify") {
// We define the server constant as the part of the JSON that deals with the server the message came from
// This makes accessing those values easier
const server = config.server[message.guild.id];
// Your code here was also working
let member = message.mentions.members.first();
// Here we first define the moderator role
// Technicaly this is not needed but it makes the whole code a little easier to understand
// We need modrole[0] here because the modrole entry in your JSON is an array
let modrole = message.guild.roles.cache.find(r => r.id === server.modroles[0]);
// Here we check if the member who calls this command has the needed role
// We need to use the ID of the role to check
if (!message.member.roles.cache.has(modrole.id)) {
// If the user does not have the required role we return here
// That way you don't need to use the 'else' statement
// Creating the embed object in multiple lines improves readability
return message.channel.send(new Discord.MessageEmbed()
.setTitle("Missing Perms!")
.setDescription("You're missing the permission to execute this command!")
.setColor(0xe74c3c)
);
}
if (!member) {
// Here we check if a member was tagged in the command and if that user exists
// Same reasons as above
return message.channel.send(new Discord.MessageEmbed()
.setColor(0xd35400)
.setTitle("Invalid User")
.setDescription(`Please use the following Syntax:\n '${config.prefix}verify <Nutzer>'`)
);
}
// Now we define the role that we want the bot to give
// Here we also don't need to do this but it improves readability and makes working with the role a little easier
var role = message.guild.roles.cache.find(role => role.id === server.verifiedrole);
// Here we add the role to the specified member
// We don't need to use the .cache here
member.roles.add(role.id);
// We can use something called "template strings" here so we don't need to combine multiple strings
// They allow us to put predefined values into the string
console.log(`Command used: ${command} ${args} | User: ${message.author.id} | Guild: ${message.guild.id}`)
}
})
If you want, that the command can be executed at multiple servers at the time you need to write the code in async/await. If you want to learn more about async you can get very good help especially for discord.js v12 here: Understanding async/await
you can get a command for a specifiq channel and give a role for acces to the server
basically all i need are simple commands that lets me type
<ban [user here]
or
<kick [user here]
and have have it kick/ban the refrenced user, i know this is probably the simplest thing in the world but i suck and im really new to discord bot coding and js in general so help me random people :D also this is probobly the stupidest thing in the world but i found another thing on this and it didnt work heres the code they tried:
if (msg.member.hasPermission("KICK_MEMBERS") {
if (msg.members.mentions.first()) {
try {
msg.members.mentions.first().kick();
} catch {
msg.reply("I do not have permissions to kick " + msg.members.mentions.first());
}else {
msg.reply("You do not have permissions to kick " + msg.members.mentions.first());
}
here is my code so far:
const Discord = require('discord.js');
const client = new Discord.Client();
const prefix = '<';
client.once('ready', () => {
console.log('Bot Online')
client.channels.cache.get('707840645192220714').send('Bot Online');
})
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if (command === 'ping>') {
message.channel.send('pong!');
}
else if (command === 'test>') {
message.channel.send('Test Working');
}
else if (command === 'help>') {
message.channel.send('<Ping> <Test> <Help> <Youtube>')
}
else if (command === 'youtube>'){
message.channel.send('https://www.youtube.com/channel/UCFK-ry9dVqsPsjr638g1ygw')
}
else if (command === 'kick>'){
}
else (message.channel.send('That Command Isnt Reconised Use <Help> To View
A List Of Commands'))
})
client.login('Token Here');
also im not going to require it but if you want you could help me get the suffix system working without having to just shove it at the end of my commands
For the code you tried, it doesn't work as there is no members property on the Message object. I think what you want to try is msg.mentions.members.first() - this gives you the first valid mention as a GuildMember object. From here, you can use the kick() and ban() methods as you please.
I'm actually making a discord bot with discord.js, and I was wondering how to do a command to delete a specific channel with a name
ex : !delete #general
I already tried to do the following:
if (command == "delete") {
channel.delete(args.join(" "))
}
but it doesn't work so I'm kinda stuck
thank you
You have to use the .delete method to delete a guild textchannel.
I added a new variable fetchedChannel which tries to fetch the channel by its name from args.
Try to use the following code:
const fetchedChannel = message.guild.channels.find(r => r.name === args.join(' '));
if (command === 'delete') {
fetchedChannel.delete();
}
That code now is old if you are going to up-date(with discord.js v12) it try with:
const fetchedChannel = message.guild.channels.cache.get(channel_id);
fetchedChannel.delete();
If you want to delete a specific channel with eval command then use this code
t!eval
const fetchedChannel = message.guild.channels.cache.get("CHANNEL_ID");
fetchedChannel.delete();
use:
message.channel.delete();
you can put it in client.on like this
client.on("message", message => {
message.channel.delete()
})