Parsing error: Unexpected token Client Discord.js - node.js

Ok so i have this problem, i am new at node.js, please help, the error says: "Parsing error: Unexpected token Client" i've tried to do something for a while and i don't know what to do.
const {Client, Intents} = require('discord.js')
const client = new Client({intents: ["GUILD_MESSAGES"]})
client.login("TOKEN")
client.on('ready', function () {
}
Client.on("message", message => { try{
let server1 = "861068256844316683";
let server2 = "936852675352481842";
let channel1 = "861068256844316686";
let channel2 = "936852675352481845";
let emojis = [":joy:",":rofl:",":heart_eyes:",":smiling_face_with_3_hearts:",":sunglasses:",":nerd:",":face_with_monocle:",":kissing_heart:",":pensive:",":rage:",":face_with_symbols_over_mouth:",":hot_face:",":cold_face:",":thinking:",":flushed:",":scream:",":yawning_face:",":lying_face:",":heart_eyes_cat:",":joy_cat:",":scream_cat:"];
let msj = message.content;
if (msj.includes("#everyone")) return;
if (msj.includes("#here")) return;
if (msj.includes("<#&")) return;
if (msj.includes("http")) return;
if(message.channel.id === channel1){
let emoji = emojis[Math.floor(Math.random() * 21)];
if(message.member.id === "947818875137953863") return;
let chatGlobal = Client.guilds.cache.find(g => g.id === server2).channels.cache.find(c => c.id === channel2);
chatGlobal.send(`**${emoji} ${message.member.user.username}:**\n> ${msj.replace("\n","\n> ")}`);
}
if(message.channel.id === channel2){
let emoji = emojis[Math.floor(Math.random() * 21)];
if(message.member.id === "947818875137953863") return;
let chatGlobal = Client.guilds.cache.find(g => g.id === server1).channels.cache.find(c => c.id === channel1);
chatGlobal.send(`**${emoji} ${message.member.user.username}:**\n> ${msj.replace("\n","\n> ")}`);
}
} catch(error){
console.log(error)
}})

The error is coming because you missed a parentheses when you are calling client.on('ready'). Also, as #omar al-hamad told, you are confusing the client (with a small c) with Client which is completely different. Your fixed code might look something like this:
const { Client } = require("discord.js");
const client = new Client({ intents: ["GUILD_MESSAGES"] });
let server1 = "861068256844316683";
let server2 = "936852675352481842";
let channel1 = "861068256844316686";
let channel2 = "936852675352481845";
let emojis = [
":joy:",
":rofl:",
":heart_eyes:",
":smiling_face_with_3_hearts:",
":sunglasses:",
":nerd:",
":face_with_monocle:",
":kissing_heart:",
":pensive:",
":rage:",
":face_with_symbols_over_mouth:",
":hot_face:",
":cold_face:",
":thinking:",
":flushed:",
":scream:",
":yawning_face:",
":lying_face:",
":heart_eyes_cat:",
":joy_cat:",
":scream_cat:",
];
client.on("ready", function () {
console.log(`Logged in as ${client.user.tag}!`)
});
client.on("message", (message) => {
try {
if (message.author.bot) return
let msj = message.content;
if (msj.includes("#everyone")) return;
if (msj.includes("#here")) return;
if (msj.includes("<#&")) return;
if (msj.includes("http")) return;
if (message.channel.id === channel1) {
let emoji = emojis[Math.floor(Math.random() * 21)];
if (message.member.id === "947818875137953863") return;
let chatGlobal = Client.guilds.cache
.find((g) => g.id === server2)
.channels.cache.find((c) => c.id === channel2);
chatGlobal.send(
`**${emoji} ${message.member.user.username}:**\n> ${msj.replace(
"\n",
"\n> "
)}`
);
}
if (message.channel.id === channel2) {
let emoji = emojis[Math.floor(Math.random() * 21)];
if (message.member.id === "947818875137953863") return;
let chatGlobal = Client.guilds.cache
.find((g) => g.id === server1)
.channels.cache.find((c) => c.id === channel1);
chatGlobal.send(
`**${emoji} ${message.member.user.username}:**\n> ${msj.replace(
"\n",
"\n> "
)}`
);
}
} catch (error) {
console.log(error);
}
});
client.login("TOKEN");
(Note: I took the liberty to format the code and put some variables at the top so it can be accessed everywhere.)

you declared client with small letters like this:
const client = new Client({intents: ["GUILD_MESSAGES"]})
---------^
and then you are trying to call with with a capital C like this:
Client.on
instead do:
client.on

Related

tag a user using discord node js

I want to make a command that tags a user when there name got mentoined. But now the bot only tags the username and not a nickname the person has in the server
client.on("message", message => {
if(message.content === 'test'){
message.channel.send("works")
console.log("logged the message")
}
})
client.on("message", message => {
const list = message.guild;
list.members.cache.each(member => {
pinging = member.user.id
console.log(member.user.username)
if(message.content.includes(member.user.username)){
message.channel.send(`<#${pinging}>`)
}
})
})
can anyone help?
First thing, you only want to have one listener for the message event, so try this code:
client.on("message", message => {
if (message.content === 'test'){
message.channel.send("works")
console.log("logged the message")
}
// insert choices from below here
})
If you want it to listen for a member being tagged
const mentionedMember = message.mentions.members.first()
if (mentionedMember){
message.channel.send(`${mentionedMember}`)
}
Now if you want it to listen for username instead of #username
const args = message.content.slice().trim().split(' ')
const guild = message.guild
args.forEach(arg => {
const member = guild.members.cache.find(member => member.user.username.toLowerCase() === arg.toLowerCase())
if (member) {
message.channel.send(`${member}`)
} else {
return
}
})
To listen for displayName
const args = message.content.slice().trim().split(' ')
const guild = message.guild
args.forEach(arg => {
const member = guild.members.cache.find(member => member.displayName.toLowerCase() === arg.toLowerCase())
if (member) {
message.channel.send(`${member}`)
} else {
return
}
})

How assign role to user in discord by slash command?

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.

Having issues in Discord.js with Promise

i'm trying to make this work, but there's this issue : UnhandledPromiseRejectionWarning: DiscordAPIError: Cannot send an empty message
let regex = /<:\s([a-zA-Z])\w+:\s([0-9])\w+>|<a:\s([a-zA-Z])\w+:\s([0-9])\w+>|<:([a-zA-Z])\w+:([0-9])\w+>|<#!([0-9])\w+>|<#!\s([0-9])\w+>|<#\s([0-9])\w+>|<#([0-9])\w+>|<#([0-9])\w+>/g
async function traduire(msg, lang) {
translate(msg, {
to: lang
}).then(res => {
str = res.text
if (!msg.match(regex)) return str.toString()
MsgJoin = msg.split(" ").join("")
if (MsgJoin.match(regex)) {
MsgRegex = MsgJoin.match(regex)
}
let RegexStr = str.match(/<(.*?)\>/g)
let MidMsg = str
for (let i = 0; i < MsgRegex.length; i++) {
MidMsg = MidMsg.replace(RegexStr[i], MsgRegex[i])
FinalMsg = MidMsg
}
return FinalMsg.toString()
})
}
bot.on('message', msg => {
try {
let MessTrans = msg.content;
let reactionFilter = (reaction, user) => reaction.emoji.name === '🇫🇷' && msg.author.id !== "724682218454253588"
msg.awaitReactions(reactionFilter, {
max: 1
}).then(() => {
const traduction = await traduire(MessTrans, "fr")
msg.channel.send(traduction)
})
} catch (error) {
msg.channel.send('There\'s an error, try again !')
}
})
the issue is from the msg.channel.send(traduction) but i don't know how to fix it, all I know is that it's a Promise error, and I have to use async / await.

Cannot read the property 'inviter' of undefined

I am getting a Cannot read the property 'inviter' of undefined error, and I'm not quite sure why. Here is my code:
Client.on('guildMemberAdd', async (member) => {
const cachedInvites = GuildInvites.get(member.guild.id);
const nweInvites = await member.guild.fetchInvites();
GuildInvites.set(member.guild.id, nweInvites);
try {
const usedInvites = nweInvites.find(
(inv) => cachedInvites.get(inv.code) < inv.uses
);
const embed = new Discord.MessageEmbed()
.setDescription(
`${member.user.tag} is the ${member.guild.memberCount}th member. \nInvited by ${usedInvites.inviter.username} \nNumber of uses: ${usedInvites.uses}`
)
.setTimestamp()
.setColor('YELLOW');
const WelcomeChannel = member.guild.channels.cache.find(
(channel) => channel.id === '704908658068422698'
);
WelcomeChannel.send(embed).catch((err) => {
console.log(err);
});
} catch (err) {
console.log(err);
}
});
Client.login();
I'm trying to create an invite manager bot. Any help would be appreciated, thanks!
What you can do is manage that situation by protecting your code.
try {
const usedInvites = nweInvites.find(
(inv) => cachedInvites.get(inv.code) < inv.uses
);
if (!usedInvites) {
return;
}
const embed = new Discord.MessageEmbed()
.setDescription(
`${member.user.tag} is the ${member.guild.memberCount}th member. \nInvited by ${usedInvites.inviter.username} \nNumber of uses: ${usedInvites.uses}`
)
.setTimestamp()
.setColor('YELLOW');
const WelcomeChannel = member.guild.channels.cache.find(
(channel) => channel.id === '704908658068422698'
);
WelcomeChannel.send(embed).catch((err) => {
console.log(err);
});
}
I added: if (!usedInvites) return; but you can do whatever action you need.

Discord.js -- message is not defined

const client = new Discord.Client();
const ayarlar = require('./ayarlar.json');
var prefix = ayarlar.prefix;
client.on('ready', () => {
console.log(`Botun olan ${client.user.tag}sunucuya giriş yaptı ve artık aktif!`);
});
client.on('message', msg => {
if (msg.content.toLowerCase() === 'salak aziz') {
msg.channel.send('nerden bildin? helal olsun');
}
if (message.content === `${prefix}mal`) {
message.channel.send('Aziz Mert');
} else if (message.content === `${prefix}adam`) {
message.channel.send('Ata');
}
});
Im a beginner.
The error is 'ReferenceError: message is not defined' How can i fix it?
Thanks.
That is because you defined the parameter of the message event as msg not message
const client = new Discord.Client();
const ayarlar = require('./ayarlar.json');
var prefix = ayarlar.prefix;
client.on('ready', () => {
console.log(`Botun olan ${client.user.tag}sunucuya giriş yaptı ve artık aktif!`);
});
client.on('message', message => {
if (message.content.toLowerCase() === 'salak aziz') {
message.channel.send('nerden bildin? helal olsun');
}
if (message.content === `${prefix}mal`) {
message.channel.send('Aziz Mert');
} else if (message.content === `${prefix}adam`) {
message.channel.send('Ata');
}
});

Resources