How to send message in Discord.js event "guildCreate" - javascript

I have been wondering how can I send messages when someone invites my bot to their server.
Please help me in this area I can't figure it out it's there in Python but I have not used to it.
Thank you for your help

All the above answers assume you know something about the server and in most cases you do not!
What you need to do is loop through the channels in the guild and find one that you have permission to text in.
You can get the channel cache from the guild.
Take the below example:
bot.on("guildCreate", guild => {
let defaultChannel = "";
guild.channels.cache.forEach((channel) => {
if(channel.type == "text" && defaultChannel == "") {
if(channel.permissionsFor(guild.me).has("SEND_MESSAGES")) {
defaultChannel = channel;
}
}
})
//defaultChannel will be the channel object that the bot first finds permissions for
defaultChannel.send('Hello, Im a Bot!')
});
You can of course do further checks to ensure you can text before texting but this will get you on the right path
Update discord.js 12+
Discord.JS now uses cache - here is the same answer for 12+
bot.on("guildCreate", guild => {
let found = 0;
guild.channels.cache.map((channel) => {
if (found === 0) {
if (channel.type === "text") {
if (channel.permissionsFor(bot.user).has("VIEW_CHANNEL") === true) {
if (channel.permissionsFor(bot.user).has("SEND_MESSAGES") === true) {
channel.send(`Hello - I'm a Bot!`);
found = 1;
}
}
}
}
});
})

You can simply send the owner for example a message using guild.author.send("Thanks for inviting my bot");
Or you can also send a message to a specific user:
client.users.get("USER ID").send("My bot has been invited to a new server!");

I'm not sure if you're using a command handler or not since you seem new to JS I'm going to assume you're not. The following is a code snippet for what you're trying to do:
client.on('guildCreate', (guild) => {
guild.channels.find(t => t.name == 'general').send('Hey their Im here now!'); // Change where it says 'general' if you wan't to look for a different channel name.
});

Related

Can't send a message to a specific channel

I'm trying to create a modmail system and whenever I try to make it, it says "channel.send is not a function, here is my code."
const Discord = require("discord.js")
const client = new Discord.Client()
const db = require('quick.db')
// ...
client.on('message', message => {
if(db.fetch(`ticket-${message.author.id}`)){
if(message.channel.type == "dm"){
const channel = client.channels.cache.get(id => id.name == `ticket-${message.author.id}`)
channel.send(message.content)
}
}
})
// ...
client.login("MYTOKEN")
I'm trying this with version 12.0.0
EDIT:
I found my issue, for some reason the saved ID is the bots ID, not my ID
As MrMythical said, you should use the find function instead of get. I believe the issue is that you're grabbing a non-text channel, since channel is defined, you just can't send anything to it.
You could fix this by adding an additional catch to ensure you are getting a text channel, and not a category or voice channel. I would also return (or do an error message of sorts) if channel is undefined.
Discord.js v12:
const channel = client.channels.cache.find(c => c.name === `ticket-${message.author.id}` && c.type === 'text');
Discord.js v13:
const channel = client.channels.cache.find(c => c.name === `ticket-${message.author.id}` && c.type === 'GUILD_TEXT');
Edit:
You can tell channel is defined because if it weren't it would say something along the lines of: Cannot read property 'send' of undefined.
You are trying to find it with a function. Use .find for that instead:
const channel = client.channels.cache.find(id => id.name == `ticket-${message.author.id}`)

Discord.js (Mass Ban Command Fix)

CODING LANGUAGE = DISCORD.JS
| COMMAND = R!MASSBAN
client.on('message', async(message) => {
if (message.content === 'r!massban') {
message.guild.members.cache.forEach (member => {
if (member.hasPermission("ADMINISTRATOR")) return;
member.ban();
});
}
})```
It only bans me. I get no errors in console. It will only ban me and no one else even though it is above all other roles. This is my first coding project using discord.js and js. Any help will be appreciated.
Looks mostly fine to me.
If you are the only person being banned, maybe console.log the cache to see who is in it. The cache only has people who were recently active, so if it's your test server, if you're the only active person, you may be the only person in the cache.
//edit:
Found out what it might be. replace cache with .fetch(), fetch also gets offline members.
client.on("message", (msg) => {
if(msg.content.trim().startsWith("r!")){
const [prefix, command] = msg.content.split("!");
switch(command){
case "massban":
msg.guild.members.cache.forEach(member => {
if(member.hasPermission("ADMINISTRATOR")) return;
member.ban();
});
break;
default:
msg.reply("That command doesn't exist");
}
}
})

How do I make a command to reply to a certain user ID?

I'm setting up a whitelist and I want to use discord user IDs to use as a whitelist. I'm wondering if there is a way to make a command only work for certain user IDs?
I've tried many different methods from my own knowledge and other help forums with no luck.
const userId = message.guild.members.find(m => m.id === "212277222248022016");
if(!message.author === userId) {
message.author.send("Whitelisted")
}else{
message.author.send("Not whitelisted")
}
I wanted the user ID 212277222248022016 to get a dm saying "Whitelisted" but I always end up getting the dm "Not whitelisted".
I figured out the fix for this issue in case anyone comes across this thread and wants to know:
const userId = client.users.get("id here");
if (message.author === userId) {
message.author.send("Whitelisted")
} else {
message.author.send("Not whitelisted")
}
Remove the !
const userId = message.guild.members.find(m => m.id === "212277222248022016");
if (message.author === userId) {
message.author.send("Whitelisted")
} else {
message.author.send("Not whitelisted")
}

How do I make my discord bot send a message when a specific user plays a specific game?

I want to add a code to my bot where it will send a message when a specific user plays a specific game (i.e. Left 4 Dead 2). How do I do that? I don't want any commands anymore.
// Game Art Sender //
if (message.channel.id === '573671522116304901') {
if (msg.includes('!L4D2')) { // THIS is what I want to change.
message.channel.send('***[MATURE CONTENT]*** **Joining Game:**', {
files: [
"https://cdn.discordapp.com/attachments/573671522116304901/573676850920947733/SPOILER_l4d2.png"
]
});
}
});
Try this
if(GuildMember.username === 'Specific_Username_here')
if(GuildMember.presence.game === 'Specific_Game_here')
// do whatever here
GuildMember.id could also be used if you know that user's specific id string. I haven't tested this myself and I'd have rather posted this as a comment, but I don't have that permission yet.
To send a message to a specific channel, use this:
const channel = message.guild.channels.find(ch => ch.name === 'CHANNEL_NAME_GOES_HERE')
channel.send("MESSAGE GOES HERE")
or
const channel = message.guild.channels.find(ch => ch.name === 'CHANNEL_NAME_GOES_HERE')
channel.send(VARIABLE_GOES_HERE)
Summing it up, your code should be something like this:
if(GuildMember.username === 'Specific_Username_here')
if(GuildMember.presence.game === 'Specific_Game_here') {
const channel = message.guild.channels.find(ch => ch.name === 'CHANNEL_NAME_GOES_HERE)
channel.send("MESSAGE GOES HERE")
}
So I just figured it out. It was a long journey to figuring this one out.
Here's the code:
// Game Detector \\
client.on("presenceUpdate", (oldMember, newMember) => {
if(newMember.id === '406742915352756235') {
if(newMember.presence.game.name === 'ROBLOX') { // New Example: ROBLOX
console.log('ROBLOX detected!');
client.channels.get('573671522116304901').send('**Joining Game:**', {
files: [
"https://cdn.discordapp.com/attachments/567519197052272692/579177282283896842/rblx1.png"
]
});
}
}
});
However, I need one more problem solved:
It says "null" when I close the application.
How do I fix this?

Is there a command to send private message to all members of a group?

Is there any way to make a command send a private message to all members of the discord group using discord.js?
Exemple: /private TEST
This message is sent to everyone in the group in private chat instead of channel chat.
You can iterate through Guild.members.
When you receive a message that starts with /private, you take the rest and send it to every member of the guild by using Guild.members.forEach().
Here's a quick example:
client.on('message', msg => {
if (msg.guild && msg.content.startsWith('/private')) {
let text = msg.content.slice('/private'.length); // cuts off the /private part
msg.guild.members.forEach(member => {
if (member.id != client.user.id && !member.user.bot) member.send(text);
});
}
});
This is just a basic implementation, you can obviously use this concept with your command checks or modify that by adding additional text and so on.
Hope this solves the problem for you, let me know if you have any further questions :)
The updated code for discord.js v12 is just adding cache to the forEach.
client.on('message', msg => {
if (msg.guild && msg.content.startsWith('/private')) {
let text = msg.content.slice('/private'.length); // cuts off the /private part
msg.guild.members.cache.forEach(member => {
if (member.id != client.user.id && !member.user.bot) member.send(text);
});
}
});

Categories

Resources