My code worked fine but I changed some things and now it doesn't...
When I type !ping in the any channel it doesn't work.
the bot is on the server and an admin.
I changed the token down there
here's the code: Does anyone see something??
const Discord = require(`discord.js`),
client = new Discord.Client(),
prefix = `!`,
NO = `801418578069815297`
YES = `801418578300764180`
client.login(`bruh`)
client.once(`ready`, () => {
console.log(`online.`)
client.user.setPresence({
status: `online`,
game: {
name: `You`,
type: `WATCHING`
}
})
})
client.on(`message`, message =>{
if(!message.content.startsWith(prefix) || message.author.client) return
const args = message.content.slice(prefix.length).trim().split(` `)
const arg = args.toString().split(sep)
const command = args.shift().toLowerCase()
if(command === `ping`){
message.channel.send(`pong!`)
}
}
)
EDIT:
I put some log outputs in:
const Discord = require("discord.js");
let client = new Discord.Client();
let prefix = "!";
console.log("discord, client, prefix defined.")
client.login("bruh");
console.log("logged in.")
client.once("ready", () => {
console.log("online.");
client.user.setPresence({
status: "online",
game: {
name: "You",
type: "WATCHING"
}
});
});
client.on("message", message =>{
console.log("message recieved")
if(!message.content.startsWith(prefix) || message.author.client) return;
console.log("it's a command.")
const args = message.content.slice(prefix.length).trim().split(" ");
console.log("splitted.")
const arg = args.toString().split(sep);
console.log("args defined.")
const command = args.shift().toLowerCase();
console.log("command defined.")
if(command === "ping") {
console.log("command identified:"+command)
message.channel.send("pong!");
console.log("message sent.")
}
});
The output is:
logged in.
online.
message recieved
I looked at that closely but still didn't find anything...
The problem is, you're using commas where you should be using semicolons, so JS will be interepreting this strangely which will give you undefined behaviour. You should also preferably prefix your variables with let, var or const otherwise this could also lead to undefined behaviour. It is recommended to use let over var.
Try the code below to fix your problem:
const Discord = require(`discord.js`);
let client = new Discord.Client();
let prefix = '!';
let NO = "801418578069815297";
let YES = "801418578300764180";
client.login(`bruh`);
client.once(`ready`, () => {
console.log(`online.`);
client.user.setPresence({
status: `online`,
game: {
name: `You`,
type: `WATCHING`
}
});
});
client.on(`message`, message =>{
if(!message.content.startsWith(prefix) || message.author.client) return;
const args = message.content.slice(prefix.length).trim().split(' ');
const command = args.shift().toLowerCase();
if(command === `ping`) {
message.channel.send(`pong!`);
}
});
I've had problems in the past with using wrong quotation marks, that might be the case for you here as well
Try to replace all your ` with ' or "
I found a way to make it work. contact me on discord Moderpo#0172 if you wanna know the answer I'll have to find out what I did because I forgot lol
Related
My Discord bot (Discord.js) isn't replying correctly to the command.
when it asks "How is your day", and a user responds, the output is only from the "good response". So like, when you say that you had a bad day it'll respond: "That's great to hear!".
here is the code for my discord bot:
module.exports= {
name: 'hello',
description: "Greet the Best Maid from Genshin!",
execute(message, args){
let filter = m => m.author.id === message.author.id;
message.channel.send("Hi! I am Noelle, maid of the Knights of Favonius. It's a pleasure to meet you, how was your day?"). then(() => {
message.channel.awaitMessages(filter, { max: 1, time: 15000, errors: ['time'] })
.then(message => {
message = message.first()
if (message.content == 'Good', 'Great', 'Ok', 'Fine') {
const replies = ["That's GREAT to hear!", "Ohhh, how exciting!", "I hope that your days will continue to be wonderful"]
message.replytext = Math.floor((Math.random()*replies.length) + 0);
message.channel.send(replies[message.replytext]);
} else if (message.content == 'Bad', 'Tired', 'Depressing') {
const replies = ["That's really unfortunate", "Oh my, it will get better", "I hope that your days will become fantastic onwards", "Would you like some tea to get rid off some stress?"]
message.replytext = Math.floor((Math.random()*replies.length) + 0);
message.channel.send(replies[message.replytext]);
} else {
message.channel.send("I don't seem to understand")
}
})
.catch(collected => {
message.channel.send("It seems like you don't want to talk about it. I am free anytime if you want to talk about it. ^-^");
});
})
}
}
here below is the "main.js"
const Discord = require('discord.js');
const client = new Discord.Client();
const prefix = '>'
const fs = require('fs');
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
for(const file of commandFiles){
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
client.once('ready', () => {
console.log('How may I be of assistance?');
});
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 === 'hello'){
client.commands.get('hello').execute(message, args);
} else if (command == ''){
client.commands.get('').execute(message, args);
} else if (command == ''){
client.commands.get('').execute(message, args);
} else if (command == ''){
client.commands.get('').execute(message, args);
} else if (command == ''){
client.commands.get('').execute(message, args);
}
});
client.login(Token)
Your issue is in your if statement.
if (message.content == 'Good', 'Great', 'Ok', 'Fine')
This will always return true, because the comma operator returns the value of the last operand which is the string 'fine'. Strings in Javascript are truthy so this will always return true.
For a quick fix you can use the or statement
if (message.content == 'Good' || message.content == 'Great' || message.content == 'Ok' || message.content == 'Fine')
Or if you want a more extendable option you can store all your good responses in a set, and then check that the set contains the option.
const goodResponses = new Set{['Good', 'Great', 'Ok', 'Fine']};
if(goodResponses.has(message.content){
... }
You will also have to do the same thing for the bad responses.
The , operator in js chains multiple expressions together and returns the value of the last one which in this case is the string 'Fine'. 'Fine' is truthy, so your first if is always true.
To see if the message is contained in a list of words, your can instead use includes with an array:
if (['Good', 'Great', 'Ok', 'Fine'].includes(message.content)) {
}
The above solution is still case sensitive, so you could optionally compare the lowercased message instead:
if (['good', 'great', 'ok', 'fine'].includes(message.content.toLowerCase())) {
}
But it will still only match if the message is "Good" with no other words or characters. You can also make it check each word in the message (removing any non-letter or whitespace characters) to see if any of them match:
// separated into a function so its reusable
const matchesAny = (str, words) => {
const cleanedStringParts = str.toLowerCase().replace(/[^\w\s]/g, '').split(/\s+/g)
return words.some(word => cleanedStringParts.includes(word))
}
const options = ['good', 'great', 'ok', 'fine']
console.log('Good', matchesAny('Good', options))
console.log('good', matchesAny('good', options))
console.log('Good!', matchesAny('Good!', options))
console.log('>>good', matchesAny('>>good', options))
console.log('im doing good!', matchesAny('im doing good!', options))
console.log('bad', matchesAny('bad', options))
console.log('>bad', matchesAny('>bad', options))
console.log('foo', matchesAny('foo', options))
It can be used as
const matchesAny = (str, words) => {
const cleanedStringParts = str.toLowerCase().replace(/[^\w\s]/g, '').split(/\s+/g)
return words.some(word => cleanedStringParts.includes(word))
}
module.exports = {
name: 'hello',
execute: (message, args) {
const filter = m => m.author.id === message.author.id;
message.channel.send("How was your day?").then(() => {
message.channel.awaitMessages(filter, { max: 1, time: 15000, errors: ['time'] })
.then(async messages => {
const response = messages.first()
if (matchesAny(response.content, ['good', 'great'])) {
// reply
} else if (matchesAny(response.content, ['bad', 'tired'])) {
// reply
} else {
await message.channel.send("I don't seem to understand")
}
})
.catch(async collected => {
await message.channel.send("It seems like you don't want to talk about it");
});
})
}
}
I'm having a problem with my anti ping system. It works alone, but with the other stuff (If (data) ... } else if (!data) {...) they overlap. If I add the if (comrade) on top of the if (data), other commands stop working but the anti ping works. Here is my code (also I get no errors):
const pinger = new Set();
const pinged = new Set();
client.on('message', async (message) => {
const data = await prefix.findOne({
GuildID: message.guild.id
});
let embed = new Discord.MessageEmbed();
const messageArray = message.content.split(" ");
const cmd = messageArray[0];
const args = messageArray.slice(1);
if (data) {
const prefix = data.Prefix;
if (!message.content.startsWith(prefix)) return;
const commandfile = client.commands.get(cmd.slice(prefix.length).toLowerCase() || client.commands.get(client.aliases.get(cmd.slice(prefix.length).toLowerCase())));
commandfile.run(client, message, args);
} else if (!data) {
const prefix = "!";
if (!message.content.startsWith(prefix)) return;
const commandfile = client.commands.get(cmd.slice(prefix.length).toLowerCase() || client.commands.get(client.aliases.get(cmd.slice(prefix.length).toLowerCase())));
commandfile.run(client, message, args);
}
let comrade = message.guild.member(message.mentions.users.first())
let mrole = message.guild.roles.cache.find(r => r.name === 'dont ping again');
let comradeid = message.guild.members.cache.get(comrade.user.id);
let authorid = message.guild.members.cache.get(message.author.id);
if (comrade) {
if (message.author.bot) return;
if (pinger.has(authorid), pinged.has(comradeid)) {
message.guild.channels.cache.forEach(f => {
f.overwritePermissions([{
id: mrole.id,
deny: ['SEND_MESSAGES']
}]);
})
authorid.roles.add(mrole)
setTimeout(() => {
authorid.roles.remove(mrole)
}, 30000)
embed.setTitle('BRUH')
embed.setDescription('YOU CANT MASS PING THAT PERSON')
embed.setColor('RED')
message.channel.send(embed)
} else {
if (!mrole) message.guild.roles.create({ data: { name: 'dont ping again' } });
if (comrade.roles.cache.find(role => role.name === 'dont ping me')) {
pinged.add(comradeid)
setTimeout(() => {
pinged.delete(comradeid)
}, 15000)
pinger.add(authorid)
setTimeout(() => {
pinger.delete(authorid)
}, 15000);
}
}
}
})
It uses a mongoDB (database) because I want my bot to have a change its prefix for other guilds command (which works perfectly). Here the commands work (the if (data) where it checks for a prefix), but the anti pinging system doesn't. I've tried a lot of stuff, but they end up not working. Thanks in advance.
so I'm trying to make a command that where you type $test and it gives you, for example, a "Test" role. This is my current code but I keep getting an error: "Cannot read property 'addRole' of undefined"
const Discord = require("discord.js");
const { send } = require("process");
const { clear } = require("console");
const client = new Discord.Client();
var prefix = "$";
client.login("token");
//TEST COMMAND
client.on("message", message => {
if (message.content.startsWith(prefix + "test")) {
message.channel.send("You have been given `Need to be tested` role! You will be tested shortly!")
client.channels.get("701547440310059059").send(` please test ${message.author}!`)
const member = message.mentions.members.first();
let testRole = message.guild.roles.find(role => role.id == "609021049375293460")
member.addRole(testRole)
}})
client.on('ready',()=>{
console.log(`[READY] Logged in as ${client.user.tag}! ID: ${client.user.id}`);
let statuses = [
" status "
]
setInterval(function(){
let status = statuses[Math.floor(Math.random() * statuses.length)];
client.user.setActivity(status, {type:"WATCHING"})
}, 3000) //Seconds to Random
});
Please let me know how I can do this easily or something.
In discord.js v12, GuildMember does not have a function .addRole, you need to use GuildMemberRoleManager's .add, also you need to add .cache when getting roles from server, like this:
const member = message.mentions.members.first();
let testRole = message.guild.roles.cache.find(role => role.id == "609021049375293460")
member.roles.add(testRole)
Okay, you are getting the error Cannot read property 'addRole' of undefined.
This means that the member variable is undefined, which could be caused by the fact that you didn't mention a member.
In this line, you put const member = message.mentions.members.first(); which means when you run the command, you have to mention someone to add the role to.
Hope this helps.
In newest version of discord.js you can try the following code:
// Where '799617378904178698' is your role id
message.guild.roles.fetch('799617378904178698')
.then(role => {
console.log(`The role color is: ${role.color}`);
console.log(`The role name is: ${role.name}`);
let member = message.mentions.members.first();
member.roles.add(role).catch(console.error);
})
.catch(console.error);
Works in case you're trying to add a certain role. You ought to call it like that:
(prefix)commandName #member
Found one more solution in case you want to give any role to any user (except bot)
main.js (or index.js whatever you have):
const Discord = require('discord.js');
const client = new Discord.Client();
const prefix = '+';
const fs = require("fs");
client.commands = new Discord.Collection()
const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
client.once('ready', () => {
console.log('Bot is online');
});
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
console.log(args);
const command = args.shift().toLowerCase();
if (command == 'giveany') {
const role = args[1].slice(3, args[1].length - 1);
client.commands.get('giveany').execute(message, args, role);
}
});
client.login('token');
giveany.js :
module.exports = {
name: 'giveany',
description: 'adds any role to a member',
execute(message, args, role) {
console.log(role);
message.guild.roles.fetch(role)
.then(r => {
console.log(`The role color is: ${r.color}`);
console.log(`The role name is: ${r.name}`);
let member = message.mentions.members.first();
if (member != undefined) {
console.log('member=' + member);
member.roles.add(r).catch(console.error);
} else {
message.channel.send('You cannot give a role to a user that is either bot or undefined');
}
}).catch( (error) => {
console.error(error);
message.channel.send('Could not find given role: ' + args[1]);
});
}
}
Calling: +giveany #Username #Role
making a discord bot in javascript with visual studio code but for some reason getting an error. I'll show you the code that is relevant first.
Overall trying to get a temporary mute function to work and I want to add it to the available commands which pops up when you hit !help. Table looks like this:
!help
classes I'm working with
Here is the index.js:
const { Client, Collection } = require("discord.js");
const { config } = require("dotenv");
const fs = require("fs");
const client = new Client({
disableEveryone: true
});
client.commands = new Collection();
client.aliases = new Collection();
client.categories = fs.readdirSync("./commands/");
config({
path: __dirname + "/.env"
});
["command"].forEach(handler => {
require(`./handlers/${handler}`)(client);
});
client.on("ready", () => {
console.log(`Hi, ${client.user.username} is now online!`);
client.user.setPresence({
status: "online",
game: {
name: "you get boosted❤️",
type: "Watching"
}
});
});
client.on("message", async message => {
const prefix = "!";
if (message.author.bot) return;
if (!message.guild) return;
if (!message.content.startsWith(prefix)) return;
if (!message.member) message.member = await message.guild.fetchMember(message);
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const cmd = args.shift().toLowerCase();
if (cmd.length === 0) return;
let command = client.commands.get(cmd);
if (!command) command = client.commands.get(client.aliases.get(cmd));
if (command)
command.run(client, message, args);
});
client.login(process.env.TOKEN);
Here is tempmute:
bot.on('message', message => {
let args = message.content.substring(PREFIX.length).split(" ");
switch (args[0]) {
case 'mute':
var person = message.guild.member(message.mentions.users.first() || message.guild.members.get(args[1]));
if(!person) return message.reply("I CANT FIND THE USER " + person)
let mainrole = message.guild.roles.find(role => role.name === "Newbie");
let role = message.guild.roles.find(role => role.name === "mute");
if(!role) return message.reply("Couldn't find the mute role.")
let time = args[2];
if(!time){
return message.reply("You didnt specify a time!");
}
person.removeRole(mainrole.id)
person.addRole(role.id);
message.channel.send(`#${person.user.tag} has now been muted for ${ms(ms(time))}`)
setTimeout(function(){
person.addRole(mainrole.id)
person.removeRole(role.id);
console.log(role.id)
message.channel.send(`#${person.user.tag} has been unmuted.`)
}, ms(time));
break;
}
});
Here is the help.js which lists all commands
const { RichEmbed } = require("discord.js");
const { stripIndents } = require("common-tags");
module.exports = {
name: "help",
aliases: ["h"],
category: "info",
description: "Returns all commands, or one specific command info",
usage: "[command | alias]",
run: async (client, message, args) => {
if (args[0]) {
return getCMD(client, message, args[0]);
} else {
return getAll(client, message);
}
}
}
function getAll(client, message) {
const embed = new RichEmbed()
.setColor("RANDOM")
const commands = (category) => {
return client.commands
.filter(cmd => cmd.category === category)
.map(cmd => `- \`${cmd.name}\``)
.join("\n");
}
const info = client.categories
.map(cat => stripIndents`**${cat[0].toUpperCase() + cat.slice(1)}** \n${commands(cat)}`)
.reduce((string, category) => string + "\n" + category);
return message.channel.send(embed.setDescription(info));
}
function getCMD(client, message, input) {
const embed = new RichEmbed()
const cmd = client.commands.get(input.toLowerCase()) || client.commands.get(client.aliases.get(input.toLowerCase()));
let info = `No information found for command **${input.toLowerCase()}**`;
if (!cmd) {
return message.channel.send(embed.setColor("RED").setDescription(info));
}
if (cmd.name) info = `**Command name**: ${cmd.name}`;
if (cmd.aliases) info += `\n**Aliases**: ${cmd.aliases.map(a => `\`${a}\``).join(", ")}`;
if (cmd.description) info += `\n**Description**: ${cmd.description}`;
if (cmd.usage) {
info += `\n**Usage**: ${cmd.usage}`;
embed.setFooter(`Syntax: <> = required, [] = optional`);
}
return message.channel.send(embed.setColor("GREEN").setDescription(info));
}
ERROR:
Error message, bot not defined.
Overall trying to get a temporary mute function to work and I want to add it to the available commands which pops up when you hit !help. Table looks like this:
!help
I think the tempmute simply doesn't work because you use bot.on() instead of client.on(), which was defined in the index.js. I can't help you for the rest but everything is maybe related to this.
I have been trying to work with a game's API: the app fetches data from the API and shows it in the console but, when I try to show it in the Discord chat, it seems to fail to execute the .find() function.
I have tried to remove the .find() function and directly displaying the body of the result.
const Discord = require('discord.js');
const bot = new Discord.Client();
const prefix = "!";
const token = "...";
const snekfetch = require("snekfetch");
bot.on('ready', () => {
console.log('This Bot Is online');
bot.user.setActivity("Rainbow Six Siege", {
type: "WATCHING"
});
});
bot.on('message', message => {
if (!message.content.startsWith(prefix)) return;
const args = message.content.slice(prefix.length).split(' ');
const command = args.shift().toLowerCase();
if (command === 'server') {
message.channel.send(`Server name: ${message.guild.name}\nTotal members: ${message.guild.memberCount}`);
} else if (command === 'detail') {
if (!args.length) {
return message.channel.send(`Correct Syntax : !details platform username`);
} else if (args[0] === message.content) {
}
let name = `${args[1]}`;
let plat = `${args[0]}`;
const api = `https://someweb/api/search.php?platform=${plat}&search=${name}`;
snekfetch.get(api).then(r => {
let body = r.body;
let entry = body.find(post => post.p_name === `${args[1]}`);
if (!entry) return message.channel.send("error");
});
}
});
bot.login(token);
My Console.log
{ results:
[ { p_id: 'f2d8bf92-472a-4381-8b53-41eb374b0ca6',
p_name: 'TR3STO',
p_level: 68,
p_platform: 'uplay',
p_user: 'f2d8bf92-472a-4381-8b53-41eb374b0ca6',
p_currentmmr: 374,
p_currentrank: 1,
verified: 0,
kd: 59 } ],
totalresults: 1 }
I think you are looking for searching in result instead. edit your code as following may help
let entry = body.results.find(post => post.p_name === `${args[1]}`);