create a channel on catch.error instead of dms - discord.js

i am tring to do that every time someone that joins my server blocks dms the bot will open a channel and send a verify link instead of a dm
what I stuck on (store the channel and stuff like that)
client.on('guildMemberAdd', member => {
const linkId = pool.createLink(member.id);
const embed = new Discord.MessageEmbed()
.setTitle('reCAPTCHA Verification')
.setDescription(`To gain access to this server you must solve a captcha. The link will expire in 15 minutes.\nhttp://${domain == '' ? 'localhost:8050' : domain}/verify/${linkId}`)
.setColor('YELLOW');
channel = client.channels.cache.get(`${logschannel}`);
channel.send('user has joined if you dont get another message in a few minutes please check if the user has verifyed ');
member.send(embed).catch(() => {message.guild.channels .create(member.id, { type: "text" }), channel.send('#here'); const errore = new Discord.MessageEmbed()
.setTitle('reCAPTCHA Verification')
.setDescription(`The user with the id ${member.id} is blocking dms please check on that!`)
.setColor('RED')
channel.send(errore)})
what I had
client.on('guildMemberAdd', member => {
const linkId = pool.createLink(member.id);
const embed = new Discord.MessageEmbed()
.setTitle('reCAPTCHA Verification')
.setDescription(`To gain access to this server you must solve a captcha. The link will expire in 15 minutes.\nhttp://${domain == '' ? 'localhost:8050' : domain}/verify/${linkId}`)
.setColor('YELLOW');
channel = client.channels.cache.get(`${logschannel}`);
channel.send('user has joined if you dont get another message in a few minutes please check if the user has verifyed ');
member.send(embed).catch(() => {channel.send('#here'); const errore = new Discord.MessageEmbed()
.setTitle('reCAPTCHA Verification')
.setDescription(`The user with the id ${member.id} is blocking dms please check on that!`)
.setColor('RED')
channel.send(errore)})

To create the channel you can just use GuildChannelManager#create (aka guild.channels.create).
member.guild.channels.create(`${member.author.username}-verification`, {
permissionOverwrites: [
{
id: member.author.id,
allow: ['VIEW_CHANNEL'],
},
{
id: member.guild.id,
deny: ['VIEW_CHANNEL'],
},
]
});
To send a message to the channel there are two ways you can do it.
A: Store the channel object.
const verifyChannel = member.guild.channels.create(`channel`);
verifyChannel.send('Message!')
B: Use .then() as creating as channel returns a promise.
member.guild.channels.create(`channel`)
.then(chan => {
chan.send('Message!');
});

Related

Discord bot join/leave channel change separately per guild

I am trying to find out how to make a command that detects a channel from separate guilds (etc. $setwelcome #channel). I have made the command but, instead of setting it for one guild its setting it for all guilds. this is my code
client.on('guildMemberAdd', member => {
console.log("New member joined.");
console.log(`Matching on joinChannel: ${joinChannel}`);
const channelID = joinChannel.toString().match(/\d+/)[0];
const channel = member.guild.channels.cache.get(channelID);
console.log(`Fetched channel with ${channelID}`);
// Do nothing if the channel wasn't found on this server
if (!channel){
console.log("The joinChannel does not exist.");
}else{
// Send the message, mentioning the member
channel.send(`Welcome to the server, ${member}`);
member.roles.add(member.guild.roles.cache.find(i => i.name === 'member'));
}
});
/*const channel = member.guild.channels.cach.find((ch) => {
console.log(ch.name);
return ch.name === joinChannel;*/
client.on('guildMemberRemove', member =>{
console.log(`Matching on joinChannel: ${joinChannel}`);
const channelID = joinChannel.toString().match(/\d+/)[0];
const channel = member.guild.channels.cache.get(channelID);
console.log(`Fetched channel with ${channelID}`);
// Do nothing if the channel wasn't found on this server
if (!channel) return;
// Send the message, mentioning the member
channel.send(`Goodbye ${member}, we will miss you :cry:`);
})
client.on("message", message => {
if (!message.author.bot){
const content = message.content;
if (content.toLowerCase().startsWith(`${prefix}setwelcome`)){
joinChannel = content.substring((`${prefix}setwelcome`).length).trim();
console.log(`Join channel changed to ${joinChannel}`);
}
}
});
I guess you could use JSON, best in a database, or different file:
//how the JSON should look like
{
"G123456789012345678": "123456789012345678"
}
//first part is the guild ID, second, is the id the channel you choose
Now you have to somehow modify this data, for this I will use fs, which assumes that this is in the file system. I’ll reference it as if it was in the same folder, and is named: welcomeChannels.json
const fs = require('fs');
//maybe other "requires"
client.on('message', msg => {
//checking message content etc
let ChansString = fs.readFileSync('./welcomeChannels.json');
let chans = JSON.parse(ChansString);
//you can get the channel for the guild with chans['G'+guild.id]
chans['G'+msg.guild.id] = msg.mentions.channels.first().id || msg.channel.id;
fs.writeFileSync('./welcomeChannels.json', JSON.stringify(chans));
})
//use chans[`G${guild.id}`] to get the welcome channel id
Warning: this could fill up your storage. You should use a database instead.

Send Server Message after Track Users Status (discord.js)

I try to send a Message in a Server. This Server ID is logged in MongoDB and the Channel ID too. But everytime i'll try it, it does not working. Here's my Code:
The Error is the return console.log Text
//This is the guildMemberUpdate file
const client = require("../index.js")
const {MessageEmbed} = require("discord.js")
const {RED, GREEN, BLUE} = require("../commands/jsons/colors.json")
const Schema = require("../models/StatusTracker.js")
client.on("guildMemberUpdate", async(member) => {
const data = await Schema.findOne({Guild: member.guild.id})
let channel = member.guild.channels.cache.get(data.Channel)
if(!channel) return console.log("Es wurde kein Channels gefunden");
if(member.user.presence.status === "offline") {
let offlineEmbed = new MessageEmbed()
.setColor(RED)
.setDescription(member.user.toString() + " ist jetzt offline!")
.setAuthor(member.user.tag, member.user.avatarURL({ dynamic: true }))
channel.send(offlineEmbed)
} else if(member.user.presence.status === "dnd" || member.user.presence.status === "online" || member.user.presence.status === "idle"){
let onlineEmbed = new MessageEmbed()
.setColor(GREEN)
.setDescription(member.user.toString() + " ist jetzt online!")
.setAuthor(member.user.tag, member.user.avatarURL({ dynamic: true }))
channel.send(onlineEmbed)
}
})```
//This is the MongoDB File
"Guild": "851487615358337065",
"Channel": "859444321975009290"
The problem is that you're using the guildMemberUpdate event, but that only tracks nickname and role changes. The one that you're looking for is presenceUpdate. That'll trigger when any user goes offline etc.
Check the docs for more details: here
Note: You'll probably need to enable 'Presence intent' in 'Privileged Gateway Intents' in your bot's settings page for this to work. (https://discord.com/developers/applications)

Discord.js problem searching in the roles of a user

I am trying to create a command, in this case it is activated with / attack, the mechanism I am looking for is that if the target user (mentioned) has the role (Lavander) which is a kind of shield, send an embed message saying defended and remove the role from you (break the shield) and if the target user (mentioned) does not have the shield role, just send a different message saying attacked. This is the code that I have been doing but it does not work for me even if it does not give errors, simply when using it, it ignores the role detection and sends both messages for some reason that I do not know, can someone help me?
if (message.content.startsWith('/attack')) {
let Lavander = message.guild.roles.cache.find(role => role.name == "Lavander");
let member = message.mentions.members.first();
if (message.member.roles.cache.has(Lavander)) return
member.roles.remove(Lavander);
message.channel.send(new Discord.MessageEmbed()
.setColor("GOLD")
.setTitle(message.author.username)
.setDescription("Defended"))
message.channel.send(new Discord.MessageEmbed()
.setColor("GOLD")
.setTitle(message.author.username)
.setDescription("Attacked"))
}
For me it seems like let Lavander = message.guild.roles.cache.find(role => role.name == "Lavander"); might be supposed to be let Lavander = message.guild.roles.cache.find(role => role.name === 'Lavander'); but without the info about the glitches and/or errors, I can't tell you anything else.
method collection.has require id as property. So you need somethink like this:
bot.on('message', (message) => {
if (message.content.startsWith('/attack')) {
let lavander = message.guild.roles.cache.find((role) => role.name === 'Lavander');
let member = message.mentions.members.first();
if (!member || !lavander) return message.reply('No role or member');
if (message.member.roles.cache.has(lavander.id)) {
member.roles.remove(lavander);
let embed = new Discord.MessageEmbed()
.setColor('GOLD')
.setTitle(message.author.username)
.setDescription('Defended');
} else {
let embed = new Discord.MessageEmbed()
.setColor('GOLD')
.setTitle(message.author.username)
.setDescription('Attacked');
message.channel.send(embed);
}
}
});

Finding Members with 2 Roles in Discord [Using Discordjs]

I am making a discord bot using discord.js, and what I want to do is to have the bot find members with Roles A and B, and list them in an embedded message. Currently, I have:
else if (message.content === (!'guns') && message.channel.id == '732740415056380044') {
let team = message.guild.roles.find('name', 'WindStar Team');
let awper = message.guild.roles.find('name', 'AWPer');
let rifler = message.guild.roles.find('name', 'Rifler');
const Members1 = awper = awper.filter(val => !team.includes(val)).map(member => member.displayName);
const Members2 = rifler = rifler.filter(val => !team.includes(val)).map(member => member.displayName);
const embedmesage = new Discord.MessageEmbed()
.setTitle('Preferred Guns')
.setColor(0x00AE86)
.addFields(
{ name: 'AWPers', value: `${Members1.join('\n')}` },
{ name: 'Riflers', value: `${Members2.join('\n')}` },
);
message.channel.send(embedmesage);
return console.log('Preferred gun roles command for windstar team executed');
}
Basically, I am trying to cross-check members who have the WindStar Team role and AWPer role, and send the list of all members who have those roles into an embed. I am also trying to cross-check members with the WindStar Team role and the Rifler role, and send the list of those members into an embed.
let awper = message.guild.roles.find('name', 'AWPer');
awper.members //Either .toArray() or .map(m => m.displayName)
I think, I dont have my bot in front of me to test
I think it is maybe too late at this point but I'll give my solution anyway. (using discord.js v12.5.1)
<Message> = your message instance
let roleMembers = <Message>.guild.roles.cache.filter(role => role.name === "AwPer" && role.name === "WindStar").members
// displaying the role members
roleMembers.map(member => member.user.username)
Basically you are getting all the roles in a guild a cache and filtering them to display the roles you want.
This should work ^. Unless you are using a breaking version of discord.js

I need a AutoRole command when somebody joins my server

I need a AutoRole command discord.js when somebody join my discord server he gets the Discord Member role.
Ive tryied some code but it doesnt work.
const discord = require("discord.js");
const config = require('../config.json');
module.exports.run = async (bot, message, args) => {
let target = message.guild.member(message.mentions.users.first() || message.guild.members.get(args[0]));
let reason = args.slice(1).join(' ');
let logs = message.guild.channels.find('name', config.logsChannel);
if (!message.member.hasPermission('BAN_MEMBERS')) return message.reply('you do not have permissions to use this command!s');
if (!target) return message.reply('please specify a member to ban!');
if (!reason) return message.reply('please specify a reason for this ban!');
if (!logs) return message.reply(`please create a channel called ${config.logsChannel} to log the bans!`);
let embed = new discord.RichEmbed()
.setColor('RANDOM')
.setThumbnail(target.user.avatarURL)
.addField('Banned Member', `${target.user.username} with an ID: ${target.user.id}`)
.addField('Banned By', `${message.author.username} with an ID: ${message.author.id}`)
.addField('Banned Time', message.createdAt)
.addField('Banned At', message.channel)
.addField('Banned Reason', reason)
.setFooter('Banned user information', target.user.displayAvatarURL);
message.channel.send(`${target.user.username} was banned by ${message.author} for ${reason}`);
target.ban(reason);
logs.send(embed);
};
module.exports.help = {
name: 'ban'
};
When they join they get the Discord Member role.
You can use the guildMemberAdd event to do actions on new users.
client.on("guildMemberAdd", (member) => {
member.addRole('ROLE ID HERE')
});

Resources