Discord bot log - javascript

So, I created a discord.js bot and added the following into index.js:
client.on("guildCreate", guild = {
const logsServerJoin = client.channels.get('757945781352136794');
console.log(`The bot just joined to ${guild.name}, Owned by ${guild.owner.user.tag}`);
client.channels.cache.get('channel id paste here').send(`The bot just joined to ${guild.name}, Owned by ${guild.owner.user.tag}`);
var guildMSG = guild.channels.find('name', 'general');
if (guildMSG) {
guildMSG.send(` Hello there! My original name is \`Bryant\`!\n\ This bot created by **R 1 J 4 N#7686**\n\ For more info
type \`/help\`!\n\ \`Bryant - Official Server:\`
https://discord.gg/UsQFpzy`);
} else {
return;
}
});
// Logs of the bot leaves a server and changed the game of the bot
client.on("guildDelete", guild = {
client.channels.cache.get('757945781352136794').send(`The bot just
left ${guild.name}, Owned by ${guild.owner.user.tag}`);
console.log(`The bot has been left ${guild.name}, Owned by ${guild.owner.user.tag}`);
logsServerLeave.send(`The bot has been left ${guild.name}, Owned by ${guild.owner.user.tag}`);
});
It does not show any error in the terminal. It is supposed to log me where the bot joined and left in the mentioned channel but does not 🤷‍♂️. Can anyone help me out with this?

If you are getting no console log and no message in the channel / an error telling you that the channel could not be found, the issue is most likely in how you are registering the events, make sure client is an instance of the discord.js Client, below is a minimal working example
const { Client } = require("discord.js")
const client = new Client()
client.on("guildCreate", guild => {
console.log(`The bot just joined to ${guild.name}, Owned by ${guild.owner.user.tag}`)
})
client.login("yourtoken")

If you are trying to get the logs from your bot alert you in your home discord server you can do this multiple ways: Getting the channel from cache, Constructing the channel or Using webhooks. Currently you are trying to fetch the channel from cache. Although a decent solution it can fall down when using sharding later down the line. Personally I prefer webhooks as they are the easiest and most isolated.
Channel from cache
This technique is very similar to the way you were doing it.
const channel = client.channels.cache.get('757945781352136794')
channel.send('An Event occurred')
Just place this code anywhere you want to log something and you'll be fine.
Constructing the channel
const guild = new Discord.Guild(client, { id: '757945781352136794' });
const channel = new Discord.TextChannel(guild, { id: '757945781352136794' });
channel.send('An Event occurred')
This method is similar to fetching the channel from cache except it will be faster as you are constructing your home guild and channel and then sending to it. Mind you will need a client which you can get from message.client
Webhooks
My Favourite method uses webhooks. I recommend you read up on how discord webhooks work in both Discord and Discord.js
You will also need to create a webhook. This is very easy. Go into the channel you want the webhooks to be sent to and then go to integrations and create a new webhook. You can change the name and profile as you wish but copy the url and it should look something like this:
https://discord.com/api/webhooks/757945781352136794/OkMsuUHwdStR90k7hrfEi5*********
The last part of the path is the webhook token and the bit before is the channel ID
I recommend you create a helper function that can be called like this:
sendWebhook('An event occurred');
And then write the function to create and then send to the webhook
function sendWebhook(text) {
const webhook = new Discord.WebhookClient('757945781352136794', 'OkMsuUHwdStR90k7hrfEi5*********');
webhook.send(text);
webhook.destroy();
}
This will not be very dynamic and will be a pain to change the channel but for constant logging ( like guild joins and leaves ) I think it is the best solution

The problem is probably that you don't have "Privileged Gateway Intents" enabled. To turn them on, go to https://discord.com/developers, click on your application, then on "Bot" then scroll down and enable "PRESENCE INTENT" and "SERVER MEMBERS INTENT" and save. It should probably work for you now.

Related

Authentication System for Discord Bot Dashboard

I have a working discord bot and I decided to write a dashboard for it.
Dashboard runs on the separate server then the bot, so it has to make a lot of calls to the express server (where the bot lives as well) to retrieve necessary information, like api/me, api/me/guilds, api/guild/<guild_id>, api/guild/<guild_id>/members etc.
I have the following middleware, that runs before every call on api/guild route and checks if user belongs to the guild he's trying to access.
function isInGuild(req, res, next) {
// I'm storing the OAuth2 token from the login in the session
const token = req.session.token;
const guild_id = req.params.id;
try {
// this function calls discord API /#me/guilds route to retrieve user's guilds with their permissions
const data = await DC.getUserGuilds(token);
const guild = data.find(o => o.id === guild_id);
if(!guild) {
res.status(404).send({ code: 0, message: "Not in the guild" });
return;
}
req.guild = guild;
next();
} catch(error: any) {
res.status(error.status);
res.send({ code: error.data.code, message: error.data.message });
}
}
The problem is that the #me/guilds discord API call has 1 second rate limit, so making it every time I want to get some guild information is very slow. It's the slowest when the user reloads the guild overview or members site, because it has to make api/me/guilds, api/guild/<guild_id> and maybe even api/guild/<guild_id>/members, and all of them will make #me/guilds call, which will take at least few seconds, because of the rate limit.
Bot itself runs with the usage of DiscordJS, so I'm aware that I could check the cache to see if bot is in the guild, and if not just return an error, but I would like to first check if the user itself belongs to the guild (and check their permission, to decide if they even should have access to the dashboard or not) to display some additional information, and I can't check that with the discordjs, if the bot isn't in the guild.
My question is: does making #me/guilds call to authenticate the user every single API call is the only way of authentication and I have to find some way to make fewer calls on the client side, or is there a quicker way to check if user is authenticated, that won't take several seconds every time?

Getting the channel name in discord.js

I'm trying to specify the channel my discord bot is posting in using the following code:
client.on("message", message => {
if message.content.includes("?chan") {
const channel = client.channels.cache.get('CHANNEL_ID_HERE')
console.log(channel)
channel.send("pong")
}
})
Upon sending the message "?chan", I want the discord bot to print whatever "channel" contains into the console, as well as send the message "pong" to the specified channel. It does neither of these things, and I'm not sure why. Also the rest of the code runs fine, including the parts with code from discord.js.

Welcome message not sending through Discord.js

So I am coding a discord bot with discord.js and one of the features is that when a new user joins the server the bot sends a message. I am not making it an embed for now, I can do that myself later.
Here is my main welcome.js file specifically made for this feature:
module.exports = (client) => {
const channelId = '868192573011931185' //welcome channel
client.on('guildMemberAdd', (member) => {
console.log(member.name)
const message = `Hello <#${member.id}> and welcome to ${guild.name}!
Please verify through the Server Captcha Bot in your DMs,
then read the rules in <#868192573263605884>
and lastly pick your roles in <#868192573263605880>!`
const channel = member.guild.channels.cache.get(channelId)
channel.send(message)
})
}
And in my index.js file I just imported the file, and added welcome(client).
But for some reason my code is not showing up in the Welcome channel... Any help will be appreciated.
Check your intents are open and check this post for further information:
I don't know the context of your index.js but I suggest reading through this handy guide where they explain how you can handle events in seperate files.
Basically they loop through an events folder(where your welcome.js would be).
Then they dynamically register the events that the client object receives to execute through those event files.
Link: Event handling.
In your code, instead of saying
const channel = member.guild.channels.cache.get(channelId)
try say:
const channel = Client.channels.cache.get(channelId)
Hope it works :)

How do I make my discord bot only read content in a certain channel

I need help making my discord bot only read messages in a certain channel
So let's say you put !+!Verify in the verification channel I want it to verify you
But lets say you put it in the general channel I want it to not verify you
You can get the channel ID with channel.id and if you get the channel from a message (message.channel.id) you can use it in an if statement to filter channels
// client.on etc...
if (message.channel.id === 'CHANNEL-ID') {
// When it is in the right channel
}

How would I make a Purge Command that logs to a channel of what was purged

I'm looking to create a command that purges the chat but also log what was purged in said chat to a mod-logs channel that only Mods/Admins and above can see.
I am looking for something similar to Dyno BOT's purge command but without the webapp side of things.
Also I'm doing my code like so:
if(command==="purge){
message.delete()// This deletes the command
// CODE GOES HERE
}else{
// This mentions the commanding person if they do not have the following permission MANAGE_MESSAGES
message.reply("Nice try, you do not have MANAGE_MESSAGES permission.")
}
}
I think the only option is to use channel.fetchMessages, and send each message before deletion.
This example might work:
async function purgeMessages(count, channel, logChannel) {
const messages = await channel.fetchMessages({ limit: count }).catch(console.error);
for (const message of messages.values()) {
await logChannel.send(message.content).catch(console.error);
await message.delete().catch(console.error);
}
}
Note that this will not send attachments or embeds. If you want to send those as well, you will need to loop through message.embeds and message.attachments.
Another option might be to monitor the messageDeleteBulk event, and send the messages that were deleted using a similar method.

Categories

Resources