Welcome message not sending through Discord.js - javascript

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 :)

Related

Discord.js not logging in

I cannot figure out why my bot is not working. Can someone please tell me why it is not logging in?? It shows the logo (the last console.log line), but does not say, "logged in as foo#1234". (I am not getting any errors as well.)
code removed because of answered question. the code worked fine ;)
Use client.once(‘ready’, async () => {//code here}); as a a pose to client.on()
As mentioned on discord.js Guide, here's the base code to get you started:
// Require the necessary discord.js classes
const { Client, Intents } = require('discord.js');
const { token } = require('./config.json');
// Create a new client instance
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
// When the client is ready, run this code (only once)
client.once('ready', () => {
console.log('Ready!');
});
// Login to Discord with your client's token
client.login(token);
Open your terminal and run node index.js (assuming that your file name is index.js) to start the process. If you see "Ready!" after a few seconds, you're good to go!
I recommend for you to follow this guide, it helped me a lot with the first steps with the discord bot.
The Token had reset for some reason, I do not remember resetting it, but after updating the token, it worked fine. Thank you for your answers and helpful comments.
If somebody else is having this problem, try resetting the token again.

New Discord Slash Commands

Recently, discord added support for slash commands for your own application. I read through the documentation for it, and I've tried to search for some videos (however the feature did JUST come out) but I do not understand what I actually have to do to get it working. I am using WebStorm (js, node.js). Has anyone successfully made a slash command, and if so, how?
Documentation
You can use the regular discord.js, by now its v12.5.1.
This is just a sample, but worked for me.
const Discord = require('discord.js');
const client = new Discord.Client();
client.on('ready', () => {
client.api.applications(client.user.id).guilds(YOUR_GUILD_ID_HERE).commands.post({
data: {
name: "hello",
description: "hello world command"
// possible options here e.g. options: [{...}]
}
});
client.ws.on('INTERACTION_CREATE', async interaction => {
const command = interaction.data.name.toLowerCase();
const args = interaction.data.options;
if (command === 'hello'){
// here you could do anything. in this sample
// i reply with an api interaction
client.api.interactions(interaction.id, interaction.token).callback.post({
data: {
type: 4,
data: {
content: "hello world!!!"
}
}
})
}
});
});
client.login(token);
Of course you can have options, see documentation...
IDE won't register the new code...at least my php storm currently does'nt :)
However, its important to give the bot the correct permissions to use this type of command!
So go to Discord.com/developers, select your application, go to OAuth2 and select
application.commands
from the scope section. This should be at the bottom of the middle column. You should select bot as well and under Bot Permissionsyou set some other specific permissions. Then use that new invite link to reinvite the bot.
Without application.commands permission, the command won't work and you will receive some error like Missing Access or some similar.
IMPORTANT THINGS
Use .guilds('11231...').comma to test these commands. When not using this, it takes round about 1h to get active. Using it will activate it immediately.
Give the bot the correct permission. application.commands
Hi I don't usually work with discord.js but I was able to find some good documentation on this. You should be able to do it like this with "client" defined.
const interactions = require("discord-slash-commands-client");
const client = new interactions.Client(
"you unique bot token",
"your bots user id"
);
If the client is defined as shown, then a /command should work if defined like this.
// will create a new command and log its data.
//If a command with this name already exist will that be overwritten.
client.createCommand({
name: "your command name",
description: "description for this command",
})
.catch(console.error)
.then(console.log);

Discord bot log

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.

Node JS Discord Bot | Reading and Writing Config File

I am having a problem with figuring out how my NodeJS bot can read and write data to a config.json file. Apart from that, I do not know how to detect arguments sent with a Bot Command. Therefore my Questions are as following:
How to Read / Write Data to a config.json?
How to detect args sent with Bot Command?
Thank you in Advance :)
-Luis
I have a NodeJS discord bot as well and for importing settings I use the following. I have not found the need to write to a json file, though hopefully this helps solve the first part of your question.
Code sample
fs.readFile(file, 'utf8', (err, data) => {
var tree = JSON.parse(data);
token = tree.token;
});
config file
{
"token":""
}
For getting arguments from a command, you can do something like this:
client.on("message", async message => {
const param = message.content.split(' ');
const command = param[0].substr('!'.length);
const arguments = param.slice(1);
})
Here is my main discord bot file with such code bits. It is pretty cluttered with other stuff so beware. https://github.com/NicholasLKSharp/DiscordJSMusicBot-SpotifyPuller/blob/master/main.js

Slack web-api returning channel not found chat.postMessage to a private channel

I have the following code which returns me the following error. The error says channel not found, howerver I am following the docs for a private channel to either use the name of the channel or to use the string that is in the url with a G at the beginning. I have given the correct chat write permissions to the bot for the channel and am using the correct bot api generated toekn, I was able to post via webhook before but I want to use the web-api.
This is the docs I am referring to https://api.slack.com/methods/chat.postMessage#channels
const { WebClient } = require('#slack/web-api');
const token = process.env.SLACK_BOT_TOKEN;
const web = new WebClient(token);
const conversationId = 'private-channel-name'; & tried this instead 'GCV2FGELX'
const result = await web.chat.postMessage({
text: 'Hello world!',
channel: conversationId,
});
This is the error response I am getting
{
code: 'slack_webapi_platform_error',
data: {
ok: false,
error: 'channel_not_found',
response_metadata: { scopes: [Array], acceptedScopes: [Array] }
}
}
I'm not quite sure what I am doing wrong, but doing a little digging, even when I try to use the tester get request for groups.list here https://api.slack.com/methods/groups.list/test with a auth token with the correct permissions I just get a empty response back, vs a list of groups.
Not sure here.
I did note that it said this Post into any channel it has access to for what the bot can do how do I know what channel's the bot has access to. I have given it write permissions to my whole orginization?
any help would be appreciated
I too had faced the same issue.
Did you trying adding the BOT/APP to the private channel (You find this under the Channel Details >> More >> Add Apps.
Once you have added your BOT/APP to the channel. Your messages will be getting posted into the channel.
Hope this will solve your issue.
Still ran into this in 2022 with slack bolt.
The error slack_webapi_platform_error with error channel_not_found seems to mean that there is no ACCESS to this channel because app needs to be specifically added to this private channel. Thanks #Anumoy Sutradhar
Here a newer screenshot (not possible to add in comments):
The modal opens when you click on the channel name.

Categories

Resources