Declaration Or Statment expected Javascript/Discord.js - javascript

So Im coding in javascript a discord bot and then what happens is i get an Declaration Or Statment expected error even if its not needed
const client = new Discord.Client({ intents: 32767 });
client.on("ready", () => {
console.log("✔✔ online")
})
client.on("messageCreate", message => {
const prefix = ">"
if(!message.content.startsWith(prefix)) return;
const messageArray = message.content.split(" ");
const cmd = messageArray[0];
const args = messageArray.slice(1);
if (message.content === `${prefix}test`) {
message.reply("Working")
}
if (cmd == `${prefix}kick`) {
if(!args[0]) return message.reply("Please Mention Someone or Put That Persons ID or Put That Persons Username to Kick The User Out Of The Server!");
const member = (message.mentions.members.first() || message.guild.members.cache.get(args[0]) || message.guild.members.cache.find(x => x.user.username.toLowerCase() === args.slice.join(" ") || x.user.username === args[0]));
if(!message.member.permissions.has("KICK_MEMBERS")) return message.reply("Since When You Have a kick members perm" || "You need to have the kick permission perm to use this command");
});
client.login("not showing token ");```

You have a wrong synatax. Your code should be
const client = new Discord.Client({ intents: 32767 });
client.on("ready", () => {
console.log("✔✔ online")
})
client.on("messageCreate", message => {
const prefix = ">"
if(!message.content.startsWith(prefix)) return;
const messageArray = message.content.split(" ");
const cmd = messageArray[0];
const args = messageArray.slice(1);
if (message.content === `${prefix}test`) {
message.reply("Working")
}
if (cmd == `${prefix}kick`) {
if(!args[0]) return message.reply("Please Mention Someone or Put That Persons ID or Put That Persons Username to Kick The User Out Of The Server!");
const member = (message.mentions.members.first() || message.guild.members.cache.get(args[0]) || message.guild.members.cache.find(x => x.user.username.toLowerCase() === args.slice.join(" ") || x.user.username === args[0]));
if(!message.member.permissions.has("KICK_MEMBERS")) return message.reply("Since When You Have a kick members perm" || "You need to have the kick permission perm to use this command");
};
});
client.login("not showing token ");

Related

how do i unban user with discord.js

hey i need my code which i wrote fixed because it wont work here it is the terminal shows the args arent defined if there is some how a different way to do this its accepted too thanks in advance. <3
const Discord = require('discord.js');
const { Client, MessageEmbed } = require('discord.js');
const bot = new Client();
const token = 'tokengoeshere';
bot.on('message', message => {
if (!message.guild) return;
const ubWords = ["!unban", "?unban", ".unban","-unban","!ub","?ub",".ub","-ub"];
if (ubWords.some(word => message.content.toLowerCase().includes(word)) )
if(!message.member.hasPermission("BAN_MEMBERS")) {
return message.reply(`, You do not have perms to unban someone`)
}
if(!message.guild.me.hasPermission("BAN_MEMBERS")) {
return message.reply(`, I do not have perms to unban someone`)
}
let userID = args[0]
message.guild.fetchBans().then(bans=> {
if(bans.size == 0) return
let bUser = bans.find(b => b.user.id == userID)
if(!bUser) return
message.guild.members.unban(bUser.user)
})
});
bot.login(token);
let userID = args[0]
if (!userID) return message.reply("Please specify the user ID you wish to unban!")
try {
message.guild.fetchBans().then(bans => {
if(bans.size === 0) {
return message.reply("There is no users banned!")
} else {
message.guild.members.unban(userID)
}
})
} catch (err) {
console.log(err)
}
You can simply define args like this:
const args = message.content.slice('?'.length).trim().split(/ +/g)
Put it after the message.guild check

verify command in a specific channel, and a specific message without prefix

I'm basically trying to code something where you need to send a message to a specific channel, and a specific message to send to get a specific role, basically like verifying as such but without the prefix but an error keeps popping up and i cant get rid of it.
The script i am trying to fix:
bot.on("message", async message => {
if(message.channel.id === '753928667427635230'){
if(message.content == 'test'){
let role = message.guild.roles.cache.find('757964609222344744')
let member = message.author.id
member.roles.add(role)
message.channel.send('script works')
}
}
The error code below:
(node:14284) UnhandledPromiseRejectionWarning: TypeError: fn is not a function
at Map.find (C:\Users\haxor\Desktop\HardWareProject\node_modules\#discordjs\collection\dist\index.js:161:17)
at Client.<anonymous> (C:\Users\haxor\Desktop\HardWareProject\main.js:37:50)
at Client.emit (events.js:315:20)
at MessageCreateAction.handle (C:\Users\haxor\Desktop\HardWareProject\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (C:\Users\haxor\Desktop\HardWareProject\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
my entire script:
const Discord = require('discord.js')
const bot = new Discord.Client()
const botsettings = require('./botsettings.json')
const fs = require('fs')
bot.commands = new Discord.Collection();
bot.aliases = new Discord.Collection();
fs.readdir("./commands/", (err, files) => {
if(err) console.log(err);
let jsfile = files.filter(f => f.split('.').pop() === 'js');
if(jsfile.length <= 0){
console.log('Commands aren\'t found!');
return;
}
jsfile.forEach((f) => {
let props = require(`./commands/${f}`);
console.log(`${f} loaded!`)
bot.commands.set(props.help.name, props);
props.help.aliases.forEach(alias => {
bot.aliases.set(alias, props.help.name);
})
})
})
bot.on("ready", async () => {
console.log(`Logged in as ${bot.user.username}`);
bot.user.setActivity(`HardLies`, {type: 'WATCHING' });
})
// Where the current error is at
bot.on("message", async message => {
if(message.channel.id === '753928667427635230'){
if(message.content == 'test'){
let role = message.guild.roles.cache.find('757964609222344744')
let member = message.author.id
member.roles.add(role)
message.channel.send('script works')
}
}
if(message.channel.type === 'dm') return;
if(message.author.bot) return;
let prefix = botsettings.prefix;
if(!message.content.startsWith(prefix)) return;
let args = message.content.slice(prefix.length).trim().split(/ +/g);
let cmd;
cmd = args.shift().toLowerCase();
let command;
let commandFile = bot.commands.get(cmd.slice(prefix.length));
if(commandFile) commandFile.run(bot, message, args);
if(bot.commands.has(cmd)){
command = bot.commands.get(cmd);
} else if(bot.aliases.has(cmd)){
command = bot.commands.get(bot.aliases.get(cmd));
}
try {
command.run(bot, message, args);
} catch (e){
return;
}
});
bot.login(botsettings.token);
The error "fn is not a function" is when you used .find(value) but this is an incorrect use. Try .find(u => u.id ==== ID) (for members .find(m => m.user.id === ID) or a better way you can just use .get(ID)
Second, you are trying to add a role to a User object. Wich is not possible. You'll have to use a GuildMember object (the difference) So instead use :
const user = message.member
And last, to add a role you'l have to use cache before the add function
member.roles.cache.add(role)
Your code should look list :
bot.on("message", async message => {
if(message.channel.id === '753928667427635230'){
if(message.content == 'test'){
let role = message.guild.roles.cache.get('757964609222344744')
let member = message.author.id
member.roles.cache.add(role)
message.channel.send('script works')
}
}

When i enter my discord bot token in visualstudiocode and i run it in command prompt it doesent work

My token for my discord bot isn't working.
When I go into the command prompt and I type node ., it says:
Syntax Error: Invalid or unexpected token
I'm pretty sure nothing is wrong with my code.
Heres my code:
const Discord = require("discord.js");
const client = new Discord.Client();
const prefix = "?";
client.once("ready", () => {
console.log("KeyBot is 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!");
}
});
const args = message.content.split(" ").slice(1);
const user = message.mentions.users.first();
const banReason = args.slice(1).join(" ");
if (!user) {
try {
if (!message.guild.members.get(args.slice(0, 1).join(" ")))
throw new Error("Couldn't get a Discord user with this userID!");
user = message.guild.members.get(args.slice(0, 1).join(" "));
user = user.user;
} catch (error) {
return message.reply("Couldn' get a Discord user with this userID!");
}
}
if (user === message.author)
return message.channel.send("You can't ban yourself");
if (!reason) return message.reply("You forgot to enter a reason for this ban!");
if (!message.guild.member(user).bannable)
return message.reply(
"You can't ban this user because you the bot has not sufficient permissions!"
);
await message.guild.ban(user);
const Discord = require("discord.js");
const banConfirmationEmbed = new Discord.RichEmbed()
.setColor("RED")
.setDescription(`✅ ${user.tag} has been successfully banned!`);
message.channel.send({
embed: banConfirmationEmbed,
});
const modlogChannelID = "";
if (modlogChannelID.length !== 0) {
if (!client.channels.get(modlogChannelID)) return undefined;
const banConfirmationEmbedModlog = new Discord.RichEmbed()
.setAuthor(
`Banned by **${msg.author.username}#${msg.author.discriminator}**`,
msg.author.displayAvatarURL
)
.setThumbnail(user.displayAvatarURL)
.setColor("RED")
.setTimestamp().setDescription(`**Action**: Ban
**User**: ${user.username}#${user.discriminator} (${user.id})
**Reason**: ${reason}`);
client.channels.get(modlogChannelID).send({
embed: banConfirmationEmbedModlog,
});
}
const args = message.content.split(" ").slice(1);
const amount = args.join(" ");
if (!amount)
return msg.reply(
"You haven't given an amount of messages which should be deleted!"
);
if (isNaN(amount)) return msg.reply("The amount parameter isn`t a number!");
if (amount > 100)
return msg.reply("You can`t delete more than 100 messages at once!");
if (amount < 1) return msg.reply("You have to delete at least 1 message!");
await msg.channel.messages
.fetch({
limit: amount,
})
.then((messages) => {
msg.channel.bulkDelete(messages);
});
client.login("token");

Working on a Discord bot with discord.js, tempmute won't work

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.

Discord.js/javascript issue with a error. ReferenceError: command not defined

const Discord = require("discord.js");
const bot = new Discord.Client();
let prefix="!"
bot.on("ready", () => {
bot.user.setStatus("idle");
console.log(`Demon Is Online`)
const update = () => {
bot.user.setActivity("!help | residing on " + bot.guilds.size + " Servers", { type: 'WATCHING' });
};
bot.on('ready', update);
bot.on('guildCreate', update);
bot.on('guildRemove', update);
bot.on("message", message => {
if(message.author.bot) return;
if(message.channel.type === "dm") return;
let messageArray = message.content.split(" ");
let command = messageArray[0];
let args = messageArray.slice(1);
if(!command.startsWith(prefix)) return;
});
if(command === `${prefix}userinfo`) {
let embed = new Discord.RichEmbed()
.setAuthor(message.author.username)
.setColor("#3498db")
.setThumbnail( `${message.author.avatarURL}`)
.addField("Name", `${message.author.username}#${message.author.discriminator}`)
.addField("ID", message.author.id)
message.reply("I've Sent Your User Info Through DM!");
message.channel.send({embed});
}});
if("command" === `${prefix}help`) {
let embed = new Discord.RichEmbed()
.addField("!help", "gives you this current information")
.setTitle("Help")
.setColor("#3498db")
.addField("!userinfo", "gives you info about a user(currently being worked on)")
.addField("!serverinfo","gives you info about a server(currently working on it)")
.addField("link to support server","https://discord.gg/NZ2Zvjm")
.addField("invite link for bot","https://discordapp.com/api/oauth2/authorize?client_id=449983742224760853&permissions=84993&scope=bot")
message.reply("here's a list of commands that i'm able to do")
message.channel.send({embed});
messageArray = message.content.split("");
let command = messageArray[0];
if(command === `${prefix}serverinfo`) {
let embed = new Discord.RichEmbed()
.setAuthor(message.author.username)
.setColor("#3498db")
.addField("Name", `${message.guild.name}`)
.addField("Owner", `${message.guild.owner.user}`)
.addField("Server ID" , message.guild.id)
.addField("User Count", `${message.guild.members.filter(m => m.presence.status !== 'offline').size} / ${message.guild.memberCount}`)
.addField("Roles", `${message.guild.roles.size}`);
message.channel.send({embed});
}
};
bot.login("token goes here")
I have this code that I need help with its stopping my discord bot from coming online. I use javascript and discord.js and node.js and could use help I tried searching youtube and also servers on discord and asking some friends but they all tell me to learn the language which I been trying. but anyways here's my error
output
command doesnt exist in the context that its being referenced.
you have
bot.on("message", message => {
if(message.author.bot) return;
if(message.channel.type === "dm") return;
let messageArray = message.content.split(" ");
let command = messageArray[0];
let args = messageArray.slice(1);
if(!command.startsWith(prefix)) return;
});
and then youre referencing command below here. which means it is out of scope, since it is defined int eh scope of bot.on('message' ...
paste the command snippet into the bot.on('message' code and, reset ur bot and try sending it a message, i think you'll see desired results.
full example will look like this:
bot.on('ready', update)
bot.on('guildCreate', update)
bot.on('guildRemove', update)
bot.on('message', message => {
if (message.author.bot) return
if (message.channel.type === 'dm') return
let messageArray = message.content.split(' ')
let command = messageArray[0]
let args = messageArray.slice(1)
if (!command.startsWith(prefix)) return
if (command === `${prefix}userinfo`) {
let embed = new Discord.RichEmbed()
.setAuthor(message.author.username)
.setColor('#3498db')
.setThumbnail(`${message.author.avatarURL}`)
.addField(
'Name',
`${message.author.username}#${message.author.discriminator}`
)
.addField('ID', message.author.id)
message.reply("I've Sent Your User Info Through DM!")
message.channel.send({ embed })
}
if (`${prefix}help` === 'command') {
let embed = new Discord.RichEmbed()
.addField('!help', 'gives you this current information')
.setTitle('Help')
.setColor('#3498db')
.addField(
'!userinfo',
'gives you info about a user(currently being worked on)'
)
.addField(
'!serverinfo',
'gives you info about a server(currently working on it)'
)
.addField('link to support server', 'https://discord.gg/NZ2Zvjm')
.addField(
'invite link for bot',
'https://discordapp.com/api/oauth2/authorize?client_id=449983742224760853&permissions=84993&scope=bot'
)
message.reply("here's a list of commands that i'm able to do")
message.channel.send({ embed })
messageArray = message.content.split('')
let command = messageArray[0]
if (command === `${prefix}serverinfo`) {
let embed = new Discord.RichEmbed()
.setAuthor(message.author.username)
.setColor('#3498db')
.addField('Name', `${message.guild.name}`)
.addField('Owner', `${message.guild.owner.user}`)
.addField('Server ID', message.guild.id)
.addField(
'User Count',
`${
message.guild.members.filter(m => m.presence.status !== 'offline')
.size
} / ${message.guild.memberCount}`
)
.addField('Roles', `${message.guild.roles.size}`)
message.channel.send({ embed })
}
}
})
bot.login('token goes here')
Note i didnt fix ALL your issues, there seems to be a few more stragglers left, i just tried to answer your specific question :)

Categories

Resources