client.on('message', message => {
if (message.content === `L!hug`) {
if (!message.mentions.users.size) {
return message.reply('you need to tag a user in order to hug them!!');
const taggeduser = message.mentions.users.first();
}
// message goes below!
message.channel.send(userID + ` you just got a hug https://tenor.com/view/anime-cuddle-cute-gif-12668750`);
}
});
I have tried a few ideas and I am very new to this library of language (discord.js)
You can use message.mentions.members.first()
client.on('message', message => {
if (message.content.startsWith('L!hug')) {
let targetMember = message.mentions.members.first();
if(!targetMember) return message.reply('you need to tag a user in order to hug them!!');
// message goes below!
message.channel.send(`<#${targetMember.user.id}> you just got a hug https://tenor.com/view/anime-cuddle-cute-gif-12668750`);
}
});
Discord.js uses many custom toString() and an User return his mention.
So if you want to mention an user in a message you can do
This :
`<#${user.id}>`
But a faster way is this :
`${user}`
And you can simply put user without any String it works also if the function runs a .toString() on your string.
like this :
message.channel.send(user + " has made something");
Will mention the user.
Note :
It won't work anymore in v13.
If you use a command handler like this one
this is how you would make it work
module.exports = {
name: "hug",
description: "# someone to hug them through the bot command.",
nsfw: false,
execute(message, args){
const targetmember = message.mentions.members.first()
if (!targetmember) return message.reply("you need to tag a user in order to hug them.");
var huggifs = [`${targetmember} Recieved a hug https://imgur.com/r9aU2xv`, `${targetmember} Recieved a hug https://tenor.com/LUqw.gif`, `${targetmember} Recieved a hug https://media.giphy.com/media/3ZnBrkqoaI2hq/giphy.gif`, `${targetmember} Recieved a hug https://tenor.com/1jRF.gif`, `${targetmember} Recieved a hug https://media.giphy.com/media/lrr9rHuoJOE0w/giphy.gif`]
var hugrandomform = huggifs[Math.floor(Math.random()*huggifs.length)];
message.channel.send(hugrandomform).then().catch(console.error);
}
}
Here, you can use message.mentions.users.first():
let user = message.mentions.users.first(); // As a shortcut to it
// Check if there is actually a mention
if(!user) {
return message.reply("You need to tag a user in order to hug them!");
}
// If there is a user, do this code
message.channel.send(`${user.toString()}, you just got a hug https://tenor.com/view/anime-cuddle-cute-gif-12668750`);
// user.toString() will convert the user object to a mention
Hope this helped!
Here is a simple version of the code. userID isn't defined, meaning you'd need to use the targetmember. Here, this is how it should be.
client.on('message', message => {
if (message.content === "L!hug") {
const targetmember = message.mentions.members.first()
if (!targetmember) return message.reply("you need to tag a user in order to hug them!!");
message.channel.send(`${targetmember} you just got a hug https://tenor.com/view/anime-cuddle-cute-gif-12668750`);
}
})
You can use this to create a mention (note that it will not work in pre, as no mention works in it)
'<#&' + user_id + '>'
Note the # and &.
Related
This is the code used, there is nothing (I think) that's causing it to repeat, matter of fact I added something so it stops repeating but it didn't do anything at all.
client.on('message', e =>{
if(e.member.roles.cache.has('12345678901')){
if(!e.content.startsWith(p) || e.author.bot) return;
console.log('successfully unmuted')
var ar = e.content.slice(p.length).split(/ +/)
var cmd = ar.shift().toLowerCase();
if(cmd === 'b'){
console.log('succesfully banned')
var member = e.mentions.users.first();
if(member){
var membertarget = e.guild.members.cache.get(member.id)
membertarget.ban();
var sbbed = new discord.MessageEmbed()
.setColor('GREEN')
.setTitle('success!')
.setDescription(`<#${membertarget.user.id}> has been successfully banned!`)
}else {
var bbed = new discord.MessageEmbed()
.setColor('RED')
.setTitle('invalid user!')
.setDescription('ban failed because there was not a valid member mentioned :(')
e.channel.send({ embeds: [bbed] })
}
}
} else {
var rolefb = new discord.MessageEmbed()
.setColor('RED')
.setTitle('failed!')
.setDescription('sorry! you dont have a high enough role to use this command, but this can change!')
if (e.author.bot) return;
e.channel.send({embeds: [rolefb]})
}
})
This code is supposed to just ban somebody but it keeps repeating itself whenever it fails:
Code:
client.on('message', e =>{
if (e.author.bot) return
if(e.member.roles.cache.has('960191891473829929')){
I have edited the code, but it still doesn't work.
Your code in the message event listener runs whenever a message is posted in your server so the bot sending the message will also be counted. So all you have to do is add an if statement in the start to check whether the author of the message was a bot:
if (message.author.bot) return
Try to add this statement to your code before if(e.member.roles.cache.has('12345678901')){
if (e.author == client.user) return;
Also, change the if(e.member.roles.cache.has('12345678901')){ to else if (e.member.roles.cache.has('12345678901')){.
I would recommend restructuring the entire code and make it into a command handler, though.
I want to know is it possible to stop specific users from using the bot, e.g. user b can not use any commands if they are in the blacklist of the config.json . thank you
Here is something you could use
const bannedUsers = ['userid1', 'userid2', 'userid3'];
client.on('message', msg => {
if(bannedUsers.includes(msg.author.id)) return;
//command execution code here
})
You will have to put this in all your client.on('message') listeners.
You don't show any code, but you could try something like this where you process commands..
//when bot receives a message
if (message.author.id === 'blacklisted ids'){
return;
} else {
//process commands
}
so what my bot is meant to do is that when someone joins a certain channel, it will send a message to log channel "SomeGuy123 joined the channel!". So I was constructing it for like an hour, and now I resolved all the errors, but it doesnt say anything, nor it doesnt give any errors. I can send the whole code if you want. Here is just the part about sending the message upon joining:
client.on("voiceStateUpdate", (oldState, newState) => {
const newUserChannel = newState.ChannelID;
const oldUserChannel = oldState.ChannelID
const textChannel = newState.guild.channels.cache.get('715141269395079208')
if(newUserChannel === '715141827644358707') {
textChannel.send(`${newState.user.username} (${newState.id}) has joined the channel`)
} else if (oldUserChannel === '715141827644358707' && newUserChannel !== '715141827644358707') {
textChannel.send(`${newState.user.username} (${newState.id}) has left the channel`)
}
})
Thank you in advance.
https://discord.js.org/#/docs/main/stable/class/Client?scrollTo=e-voiceStateUpdate
https://discord.js.org/#/docs/main/stable/class/VoiceState
<VoiceState>.ChannelID is undefined, its <VoiceState>.channelID, javascript is not pascal case except in classes
const channel = client.channels.cache.get('<channelid>');
const person1 = client.users.cache.get('<userid>');
const person = client.users.cache.get('<userid>');
client.on('message', message =>{
client.on('presenceUpdate', () =>{
if(person1.user.presence.status === 'dnd' || person1.user.presence.status === 'online'){
channelforstatus.send('person1 is now online');
}
else if(peron1.user.presence.status === 'offline' || person1.user.presence.status === 'idle'){
channel.send('person1 is offline');
}
client.on('message', message => {
client.on('presenceUpdate', () =>{
if(person.user.presence.status === 'dnd' || person.user.presence.status === 'online'){
channel.send('person is now on');
}
else if(person.user.presence.status === 'offline' || person.user.presence.status === 'idle'){
channel.send('person is now off');
}
});
});
});
});
This is what I've tried and the .send() the function is not working. I've looked everywhere and found nothing that could help me with this problem. I just need it so it checks every time if a specific person has went online, offline, etc. And sends a message to a specific channel.
First of all, one rule to abide with is that event listeners should always be in top level of your code and never nested. (Else you are subject to memory leaks and other issues like duplicated and unintended code execution).
client.on("message", (message) => {
...
});
client.on('presenceUpdate', (oldPresence, newPresence) => {
...
});
Now when looking at presenceUpdate event and Presence object documentation you can manage to see if a status evolved like that :
client.on('presenceUpdate', (oldPresence, newPresence) => {
let member = newPresence.member;
// User id of the user you're tracking status.
if (member.id === '<userId>') {
if (oldPresence.status !== newPresence.status) {
// Your specific channel to send a message in.
let channel = member.guild.channels.cache.get('<channelId>');
// You can also use member.guild.channels.resolve('<channelId>');
let text = "";
if (newPresence.status === "online") {
text = "Our special member is online!";
} else if (newPresence.status === "offline") {
text = "Oh no! Our special member is offline.";
}
// etc...
channel.send(text);
}
}
});
Be aware that presenceUpdate event is fire by EACH guild the user and bot share, meaning that if user status change and share two guilds with your bot, this code will be executed twice.
In case you use presence but get offline instead of the user being online I spent like.. 2 whole days looking for the answer so ill share it anywayz
Common mistakes on presence.status is forgetting to check these stuff at the the developer applications. which i have no idea what means
A screenshot
now on your message (command handler) function.. if you have one
message.guild.members.cache.get('userId').presence.status
or
${message.author.username} is now ${message.author.presence.status};
Ill update this if I found out how to presence all the users instead of just one
my first post... I SHALL REMEMBER THIS xD
To get the presence, you can use user.presence, which will get all kinds of info about the user, but you only need user.presence.clientStatus.desktop
so your code would, for example, be
bot.on('presenceUpdate', () =>{
let person1 = bot.users.cache.get('USERID')
console.log(person1.presence.clientStatus.desktop)
if(person1.presence.clientStatus.desktop === 'dnd' || person1.presence.clientStatus.desktop === 'online'){
channel.send('person1 is now online');
}
else if(person1.presence.clientStatus.desktop === 'offline' || person1.presence.clientStatus.desktop === 'idle'){
channel.send('person1 is offline');
}
})
I want to send a greeting message to an "welcome" text channel, whenever a new user joins the server (guild).
The problem I'm facing is that, when I find the wanted channel, I will receive the channel with the type GuildChannel.
Since GuildChannel has no send() function, I'm not able to send the message. But I can't find a way to find the TextChannel, so I'm stuck here.
How can I get to the TextChannel so that I'm able to use the send() message? Below the code I'm using by now:
// Get the log channel (change to your liking)
const logChannel = guild.channels.find(123456);
if (!logChannel) return;
// A real basic message with the information we need.
logChannel.send('Hello there!'); // Property 'send' does not exist on type 'GuildChannel'
I'm using version 11.3.0 of discord.js
Thanks to this GitHub issue I've found the solution to my problem.
I need to use a Type Guard to narrow down the correct type.
My code now is this:
// Get the log channel
const logChannel = member.guild.channels.find(channel => channel.id == 123456);
if (!logChannel) return;
// Using a type guard to narrow down the correct type
if (!((logChannel): logChannel is TextChannel => logChannel.type === 'text')(logChannel)) return;
logChannel.send(`Hello there! ${member} joined the server.`);
Maybe for latecomers who are still looking for an answer this worked for me
let channel = client.channels.get("channelid") as Discord.TextChannel;
channel.send("what you want to send to that channel");
You can use the GuildChannel#isText() method to type guard before invoking send.
Example:
if (channel.isText()) {
await channel.send('...');
}
Or:
if (!channel.isText()) return;
await channel.send('...');
Discord v14
const channel: TextChannel = client.channels.cache.get(channelId) as TextChannel;
channel.send('test')
If you have problems with cache, you can use
const channel: TextChannel = await client.channels.fetch(channel.channelId) as TextChannel;
I do this:
let channel = client.guilds.get('your-guild-id').channels.get('your-channel-id');
channel.send("it worked");
(client is the discord client). your code should work if you change find to get and put the channel id in some single quotes. Well, it works for me.
Maybe this can help you?
Code:
client.on('guildMemberAdd', member => {
let channel = member.guild.channels.find('name', 'welcome');
let memberavatar = member.user.avatarURL
if (!channel) return;
let embed = new Discord.RichEmbed()
.setColor('RANDOM')
.setThumbnail(memberavatar)
.addField(':bust_in_silhouette: | name : ', `${member}`)
.addField(':microphone2: | Welcome!', `Welcome to the server, ${member}`)
.addField(':id: | User :', "**[" + `${member.id}` + "]**")
.addField(':family_mwgb: | Your are the member', `${member.guild.memberCount}`)
.addField("Name", `<#` + `${member.id}` + `>`, true)
.addField('Server', `${member.guild.name}`, true )
.setFooter(`**${member.guild.name}**`)
.setTimestamp()
channel.sendEmbed(embed);
});