Creating invite on guildCreate - javascript

I'm trying to create a Discord bot that'll create an invite to the first channel of a Guild when it's added to the aforementioned guild and sending it to the console.
My code (it doesn't work):
client.on("guildCreate", guild => {
const channel = Array.from(guild.channels).sort((a, b) => a.calculatedPosition - b.calculatedPosition)[0];
channel.createInvite({
unique: true
})
.then(invite => {
console.log(`Joined to: ${guild.name} Invite: https://discord.gg/${invite.code}`);
})
});

// Listeing to the guildCreate event.
client.on("guildCreate", guild => {
// Filtering the channels to get only the text channels.
const Channels = guild.channels.cache.filter(channel => channel.type == "text");
// Creating an invite.
Channels.first().createInvite({
maxUses: 1,
unique: true
}).then(invite => {
console.log(`[INVITE] I've created an invite for ${guild.id}:${guild.name} - ${invite.url}`);
});
});

Related

How can I show every voice channel ID/name of a guild with DiscordJS?

I'm trying to get and show all the voice channels name from guild.
That's my code, that not working
client.on('ready', () => {
client.channels.fetch().then(channel =>
{
console.log(channel.name)
});
}
I'd like to list all names of voice channels (not text).
Filter the channels by type ChannelType.GuildVoice then map them to their name and id.
// import or require ChannelType from discord.js
const allChannels = await client.channels.fetch();
const voiceChannels = allChannels
.filter(ch => ch.type === ChannelType.GuildVoice);
console.log(
voiceChannels
.map(ch => `${ch.id} | ${ch.name}`)
.join('\n')
);
First you have to retrieve all channels using the channel cache of your client object. Then you filter by their type:
let voiceChannels = client.channels.cache.filter(m => m.type === 'voice');
voiceChannels.forEach(channel => console.log(channel.name));

Member Status command shows number of people streaming

I made a member status command for my discord bot. Here is my code:
const { stripIndent } = require('common-tags');
client.on("message", (message) => {
if (message.content.toLocaleLowerCase().startsWith("+members")) {
const members = message.guild.members.cache.array();
const online = members.filter((m) => m.presence.status === 'online').length;
const offline = members.filter((m) => m.presence.status === 'offline').length;
const dnd = members.filter((m) => m.presence.status === 'dnd').length;
const afk = members.filter((m) => m.presence.status === 'idle').length;
const streaming = members.filter((m) => m.presence.status === 'streaming').length;
const embed = new MessageEmbed()
.setTitle(`Member Status [${message.guild.members.cache.size}]`)
.setThumbnail(message.guild.iconURL({ dynamic: true }))
.setDescription(stripIndent`
**Online:** \`${online}\` members
**Busy:** \`${dnd}\` members
**AFK:** \`${afk}\` members
**Offline:** \`${offline}\` members
**Streaming:** \`${streaming}\` members
`)
.setFooter(message.member.displayName, message.author.displayAvatarURL({ dynamic: true }))
.setTimestamp()
.setColor(message.guild.me.displayHexColor);
message.channel.send(embed);
}
});
I want the number the number of people who are streaming to be shown too. However even when there are users who are streaming my bot shows 0 at the Streaming People count. Anyway to fix this out?
Thanks in Advance
PresenceStatus via member.presence.status can only be online, idle, offline or dnd.
To check if a user is streaming, you need to use the activities of a Presence.
member.presence.activities returns an Array<Activity>. You can use the ActivityType to check if a member is streaming.
To put it all together:
member.presence.activities.forEach(activity => {
if (activity.type == "STREAMING") {
// member is currently streaming
}
});

How to add permissions to user to channel by command? Discord.js

How to give permissions to a specific channel by command? Sorry, I’m new at discord.js so any help would be appreciated.
const Discord = require('discord.js');
module.exports = {
name: 'addrole',
run: async (bot, message, args) => {
//!addrole #user RoleName
let rMember =
message.guild.member(message.mentions.users.first()) ||
message.guild.members.cache.get(args[0]);
if (!rMember) return message.reply("Couldn't find that user, yo.");
let role = args.join(' ').slice(22);
if (!role) return message.reply('Specify a role!');
let gRole = message.guild.roles.cache.find((r) => r.name === role);
if (!gRole) return message.reply("Couldn't find that role.");
if (rMember.roles.has(gRole.id));
await rMember.addRole(gRole.id);
try {
const oofas = new Discord.MessageEmbed()
.setTitle('something')
.setColor(`#000000`)
.setDescription(`Congrats, you have been given the role ${gRole.name}`);
await rMember.send(oofas);
} catch (e) {
message.channel.send(
`Congrats, you have been given the role ${gRole.name}. We tried to DM `
);
}
},
};
You can use GuildChannel.updateOverwrites() to update the permissions on a channel.
// Update or Create permission overwrites for a message author
message.channel.updateOverwrite(message.author, {
SEND_MESSAGES: false
})
.then(channel => console.log(channel.permissionOverwrites.get(message.author.id)))
.catch(console.error);
(From example in the discord.js docs)
Using this function, you can provide a User or Role Object or ID of which to update permissions (in your case, you can use gRole).
Then, you can list the permissions to update followed by true, to allow, or false, to reject.
Here is a full list of permission flags you can use
This method is outdated and doesn't work on V13+ the new way is doing this:
channel.permissionOverwrites.edit(role, {SEND_MESSAGES: true }
channel.permissionOverwrites.edit(member, {SEND_MESSAGES: true }

Discord.js how can I create an invite for every guild my bot is in?

I am trying to make a command, where I can get every guild invite that the bot is currently in.
Current code:
client.on('message', async (message) => {
if (message.content.startsWith(prefix + 'invite')) {
let invite = client.guilds
.createInvite({
maxAge: 0, // 0 = infinite expiration
maxUses: 0, // 0 = infinite uses
})
.catch(console.error);
message.channel.send(invite);
}
});
Error:
DiscordAPIError: Cannot send an empty message
Try this:
var invites = []; // starting array
message.client.guilds.cache.forEach(async (guild) => { // iterate loop on each guild bot is in
// get the first channel that appears from that discord, because
// `.createInvite()` is a method for a channel, not a guild.
const channel = guild.channels.cache
.filter((channel) => channel.type === 'text')
.first();
if (!channel || guild.member(client.user).hasPermission('CREATE_INSTANT_INVITE') return;
await channel
.createInvite({ maxAge: 0, maxUses: 0 })
.then(async (invite) => {
invites.push(`${guild.name} - ${invite.url}`); // push invite link and guild name to array
})
.catch((error) => console.log(error));
console.log(invites);
});
As an example, this is what I got after running the command:
GuildChannel.createInvite()
Array.prototype.forEach()

Retrieve responsible user for channel delete in discord.js

I am making a alert system where if someone deletes a channel it sends a message with the name of the channel that was deleted and the Deleter, so i tried making it by coding this :
client.on('channelDelete', channel => {
var channelDeleteAuthor = channelDelete.action.author
const lChannel = message.channels.find(ch => ch.name === 'bot-logs')
if (!channel) return; channel.send(`Channel Deleted by ${channelDeleteAuthor}`)
.then(message => console.log(`Channel Deleted by ${channelDeleteAuthor}`))
.catch(console.error)
})
and it didn't work, how do i achieve that action?
To find the author of the deletion, you need to parse the guild audit log.
client.on('channelDelete', channel => {
// get the channel ID
const channelDeleteId = channel.id;
// finds all channel deletions in the log
channel.guild.fetchAuditLogs({'type': 'CHANNEL_DELETE'})
// find the log entry for this specific channel
.then( logs => logs.entries.find(entry => entry.target.id == channelDeleteId) )
.then (entry => {
// get the author of the deletion
author = entry.executor;
// do whatever you want
console.log(`channel ${channel.name} deleted by ${author.tag}`);
})
.catch(error => console.error(error));
})

Categories