I am trying to log whenever a invite is created and want this to apply per guild (meaning that whenever a invite is created in guild a, it logs it. If a guild is created in guild b, it only logs it in that server.)
I am having a issue,
Issue: ReferenceError: maxAge is not defined
Here is my code:
const Discord = require("discord.js");
let config = require("../config.json");
const { MessageEmbed } = require("discord.js");
const client = new Discord.Client();
module.exports = {
name: `printinvs`,
description: `Prints invites created.`,
async execute(message, args){
message.guild.fetchInvites()
.then
(invites => {
const printinvites = new Discord.MessageEmbed()
.setTitle(`Invite Information`)
.addField(`Max Age: ${maxAge}`)
.addField(`Max Uses: ${maxUses}`)
.addField(`Temporary: ${temporary}`)
.addField(`Invite URL: ${inviteurl}`)
.addField(`Invite created by: ${inviter}`)
.addField(`Channel: ${invite.channel}`)
.addField(`Time invited created: ${invite.createdAT}`)
.setColor(`RANDOM`)
message.client.channels.cache.get(channelid).send(printinvites);
})
}
}
This error is occuring because you never declared the latest invite, and you're using its properties without the actual invite.
Try this code:
let config = require("../config.json");
const { MessageEmbed } = require("discord.js");
const client = new Discord.Client();
module.exports = {
name: `printinvs`,
description: `Prints invites created.`,
async execute(message, args){
message.guild.fetchInvites()
.then
(invites => {
let latestInvite = invites.last();
const printinvites = new Discord.MessageEmbed()
.setTitle(`Invite Information`)
.addField(`Max Age: ${latestInvite.maxAge}`)
.addField(`Max Uses: ${latestInvite.maxUses}`)
.addField(`Temporary: ${latestInvite.temporary}`)
.addField(`Invite URL: ${latestInvite.url}`)
.addField(`Invite created by: ${latestInvite.inviter}`)
.addField(`Channel: ${latestInvite.channel}`)
.addField(`Time invited created: ${latestInvite.createdAt}`)
.setColor(`RANDOM`)
message.client.channels.cache.get(channelid).send(printinvites);
})
}
}
Related
I'm trying to build a discord bot that sends data to an airtable. This one sends user info when they join my server. I have the following code, but every time I try to run it, I get the following error:
TypeError: Cannot read properties of undefined (reading 'GUILDS')at Object.
This is the code:
const { Intents } = require('discord.js');
const Discord = require('discord.js');
const Airtable = require('airtable');
const client = new Discord.Client({
token: 'TOKEN_ID',
intents: [Intents.GUILDS, Intents.GUILD_MEMBERS]
});
Airtable.configure({ apiKey: 'API_KEY' });
const base = Airtable.base('BASE_ID');
client.on('guildMemberAdd', member => {
base('New Members').create({
'Username': member.user.username,
'Time Joined': new Date().toISOString()
}, function(err, record) {
if (err) {
console.error(err);
return;
}
console.log(`Added new record with ID ${record.getId()}`);
});
});
client.login();
Using Discord.js v14, the way to declare intents is as follows:
import { Client, GatewayIntentBits } from "discord.js";
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMembers
]
});
and your token should be put in client.login
client.login("your-bot-token");
I am trying to code a Discord bot for my personal server. I am using Discord.js and I have been following the discord.js guide.
I have now an event handler but when I add a file for another event, the code of this module is not executing. The event I am trying to trigger is the join of a new member in my server.
I have 2 important files : index.js which runs the corpse of my code and guildMemberAdd.js which is my event module for when a new member joins the server.
index.js:
// Require the necessary discord.js classes
const fs = require('node:fs');
const path = require('node:path');
const { Client, Collection, GatewayIntentBits } = require('discord.js');
const { token } = require('./config.json');
// Create a new client instance
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
const eventsPath = path.join(__dirname, 'events');
const eventFiles = fs.readdirSync(eventsPath).filter(file => file.endsWith('.js'));
for (const file of eventFiles) {
const filePath = path.join(eventsPath, file);
const event = require(filePath);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args));
} else {
client.on(event.name, (...args) => event.execute(...args));
}
}
// Log in to Discord with your client's token
client.login(token);
guildMemberAdd.js:
const { Events } = require('discord.js');
module.exports = {
name: Events.GuildMemberAdd,
async execute(member) {
console.log(member);
},
};
If you only have the GatewayIntentBits.Guilds intent enabled, the GuildMemberAdd event won't fire. You'll need to add the GatewayIntentBits.GuildMembers (and probably GatewayIntentBits.GuildPresences) too:
const { Client, GatewayIntentBits } = require('discord.js');
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildPresences,
],
});
In discord.js v13, it should be:
const { Client, Intents } = require('discord.js');
const client = new Client({
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MEMBERS,
Intents.FLAGS.GUILD_PRESENCES,
],
});
i'm new to coding bots and i need help on how to add a command on messaging a certain person a customized message. this is what i have so far. what should i do?
const Discord = require('discord.js');
const config = require("./Data/config.json")
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] })
client.once('ready', () => {
console.log('Ready!');
});
client.login('TOKEN');
client.on('message', async message => {
if (message.author.bot) return;
let prefix = '??'
if (!message.content.startsWith(prefix)) return;
let args = message.content.slice(prefix.length).trim().split("/ +/g");
let msg = message.content.toLowerCase();
let cmd = args.shift().toLowerCase();
if (msg.startsWith(prefix + 'ping')) {
message.channel.send('pong');
}
if (msg.startsWith(prefix + 'hello')) {
message.channel.send('hewwo uwu');
}
});
To fetch a user by id, you can use bot.users.fetch()
To direct message a user, you can use User.send():
const user = await client.users.fetch(userId);
user.send("This is a DM!");
This simple function will easily resolve the user (you can provide a user object or user ID so it’s very helpful)
async function DMUser(resolvable, content, client) {
const user = client.users.resolve(resolvable)
return user.send(content)
}
//returns: message sent, or error
//usage: DMUser(UserResolvable, "content", client)
Related links:
UserManager.resolve
User.send
UserResolvable
I want to make a report command for my discord bot, so I want it to tell me who is doing the report. In other words, who executed the command. My current code is:
const Discord = require('discord.js');
const { User, ClientUser, GuildMember, TeamMember, Message} = require("discord.js");
const client = new Discord.Client({ partials: ["MESSAGE", "CHANNEL", "USER", "REACTION"]});
const guild = client.guilds.cache.get(process.env.DISCORD_SERVER_ID);
module.exports = {
name: 'report',
description: "report a naughty person",
execute(message, args){
message.channel.send(`#${String(GuildMember.User)} reported:`);
}}
But when you use the command it says:
#undefined reported:
How do I make it define who it is?
You can use message.author to get the user and
`${message.author}`
to mention them.
message.channel.send(`${message.author} reported:`)
This is pretty simple, you just have to create a new const, which will be the following:
const author = message.author.tag
After that, just replace this statement.
message.channel.send(`${author} reported:`);
And your code should end up looking like this:
const Discord = require('discord.js');
const { User, ClientUser, GuildMember, TeamMember, Message} = require("discord.js");
const client = new Discord.Client({ partials: ["MESSAGE", "CHANNEL", "USER", "REACTION"]});
const guild = client.guilds.cache.get(process.env.DISCORD_SERVER_ID);
const author = message.author.tag
module.exports = {
name: 'report',
description: "report a naughty person",
execute(message, args){
message.channel.send(${author} reported:);
}
}
I hope this helped!
I would like to log when my bot joins servers (i already have the base code) I just need to know how to define the owner of the server! if you know how to do this please help me!
Well, from the "guildCreate" event, you recieve a Guild class. From which you can access the owner GuildMember class. Then you can get the information about the owner that.
Here is an example:
const Discord = require("discord.js");
const client = new Discord.Client();
client.on("guildCreate", (guild) => {
console.log(`I have been added to a new guild! ${guild.name}
Owner name: ${guild.owner.user.username}`);
})
client.login("yourToken")
It's the best to read thru the docs.
For checking who invited :
const Discord = require("discord.js");
const client = new Discord.Client();
client.on("guildCreate", async guild => {
const fetchedLogs = await guild.fetchAuditLogs({
limit: 1,
type: "BOT_ADD"
});
const auditlog = fetchedLogs.entries.first();
let myChannel = client.channels.cache.find(channel => channel.id == YOUR_CHANNEL_ID);
myChannel.send(auditlog.executor.tag + " added bot in "+ guild.name+"\nOwner is:
"guild.owner.user.username);
});
Also you can check for VIEW_AUDIT_LOGS permission