TypeError: throw new TypeError('CLIENT_MISSING_INTENTS'); Issue - node.js

I am recieving this message even though I added intents to my Index.js
Discord.js version: 13.3.1
Node: 16.6.1
Code of my Index.js
const config = require('../config.json');
const mongoose = require('mongoose');
const Discord = require("discord.js");
const bot = new Discord.Client();
const { Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
bot.on("ready", () => {
console.log(`Bot is online!\n${bot.users.size} users, in ${bot.guilds.size} servers connected.`);
});
// HERE IS MONGODB BUT NOT SHOWING
const Client = require('./Structures/Client');
const WelcomeSchema = require(`../src/Models/welcome`)
bot.on("guildMemberAdd", async (member, guil) => {
WelcomeSchema.findOne({ guildId: member.guild.id }, async (err, data) => {
if(!data) return;
const user = member.user;
const channel = member.guild.channels.cache.get(data.channelId);
channel.send({embed: {color: "BLUE", description: `sd`}})
})
})
const client = new Client(config);
client.start();
Would mean a lot if you could help me find the issue. Thanks!

I now realise that there are quite a few issues with the code you have provided.
No. 1 - Client Definitions
It looks like you're defining three different clients. (bot, client, and possibly Client.)
You should organise your code in such a way that all events and commands are tied to one client object, as having multiple clients running can lead to rate-limiting and performance issues. (as well as being completely and utterly pointless.)
The error seems to be stating that bot is not given any intents during its creation, which could be fixed with the use of...
// ...
const bot = new Discord.Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
// ...
No. 2: Reference to an Undefined Variable
On the line where you define client at the start of the file, you use new Client, despite the fact that Client has not been imported yet, and is imported later in the file. This won't work, as Client is undefined at that point in the program.
No. 3: Re-assignment of a constant
It also seems that you re-assign another const client near the end of your file. This will cause an error, as client is already a defined constant which cannot be over-written.
No. 4: Access to Message Intents (maybe???)
As of recently, discord requires that you enable Gateway Intents to be able to access certain events and data (such as Server Messages and Members).
To enable the intents, head to the Discord Developer Dashboard for your bot, select "Bot" from the sidebar, and enable the intents you need access to.
While this intent is not required to be able to read messages until April 30th, 2022, if your bot specifies the GUILD_MESSAGES intent, this option needs to be enabled.
If your bot is in more than 100 servers, you will need to verify your bot to be able to continue accessing data which requires these intents. More about that here.

Related

Websocket + Redis: multiple channels, specific subscriptions/publishing

I'm new to websockets, and am wondering how best to go about this.
My scenario: I have a server that handles different classes of users. For this example, let's say the classes are "mice", "cats", and "dogs"
Each of those classes should have their own channels to listen to for changes e.g. "mice-feed", "cat-feed", and "dog-feed"
My question is: after the server authenticates and determines the class of the current user, what's the best way to have them subscribed to a specific channel, or channel(s), so that when I broadcast messages to said channel(s), I can make sure that only members of particular classes get them (as against everyone currently connected to that server)?
My current code setup looks like this:
var ws = require('ws');
var redis = require('redis');
/* LOCATION 1 */
// prep redis, for websocket channels
var pub = redis.createClient();
var sub = redis.createClient();
// subscribe to our channels
sub.subscribe('mice-feed');
sub.subscribe('cat-feed');
sub.subscribe('dog-feed');
// declare the server
const wsServer = new ws.Server({
noServer: true,
path: "/",
});
/* ... removing some code for brevity... */
wsServer.on("connection", function connection(websocketConnection, connectionRequest) {
/* LOCATION 2 */
});
Do I put the redis declarations in LOCATION 1 (where it currently is), or in LOCATION 2 (when a successful connection is established)? Or neither of the above?
(also: I know it's possible to do this on the websocket end directly i.e. iterate through every client and ws.send if some criterion is matched, but iteration can become costly, and I'm wondering if I can do it on a redis-channel wide operation instead)
If I were building this, my first approach would be this:
// connect to Redis
const client = createClient();
client.on('error', (err) => console.log('Redis Client Error', err));
await client.connect();
// declare the server
const wsServer = new ws.Server(...elided...);
// handle connection
wsServer.on('connection', async (websocketConnection, connectionRequest) => {
const sub = client.duplicate()
// figure out the feed
const feed = 'animal-feed';
await sub.subscribe(feed, message => {
...do stuff...
});
});
It's pretty straightforward but would result in ever user having a dedicated connect to Redis. That may or may not matter depending on how many users you anticipate having.

Discord.js - Without using Client EventEmitter cannot get channels property

I still have yet to get a better grasp of Node.js, but as I was tinkering around with my Discord bot, I couldn't seem to find a way to get the list of channels the bot was in without putting it in an EventEmitter. I'm rather confused as to why this wouldn't work, is there something that I'm missing?
Code:
const Discord = require("discord.js");
const client = new Discord.Client();
require('dotenv').config();
//this works
client.on('ready', ()=> {
const channelID = '803359668054786118';
const channel = client.channels.cache.get(channelID);
channel.send('working'); //this works
});
//this doesn't work
//intially tried using a wait function to see if the reason was because bot didn't have enough time to log on properly
setTimeout(function() {
const channelID = '803359668054786118';
const channel = client.channels.cache.get(channelID);
console.log(client.channels); //this is telling me that there's no channels in the collection...
//channel.send('working');
}, 500);
This is because the client is not logged in at that point of your code. At the compile stage of your file, the compiler runs through your code and compiles everything outside of event listeners. Once Client#login() is called, this is when the client has it's context. All of it's event listeners (ready, message ect.) are binded to the client.
In other words, the Discord client is not logged in when code outside of events being is compiled. Code inside events are executed once the client is logged in & the event itself is emitted.

Discord bot stopped sending welcome messages

So, my code for making the bot greet new users stopped working, and i have no idea why or how
this is the code that im using for the welcome event itself ```module.exports = (client) => {
const channelId = '757493821251649608' // welcome channel
const targetChannelId = '757521186929246219' // rules and info
client.on('guildMemberAdd', (member) => {
const message = `Hi, hope you enjoy your stay <#${
member.id
}> , Oh i almost forgot to tell you, check out! ${member.guild.channels.cache
.get(targetChannelId)
.toString()}`
const channel = member.guild.channels.cache.get(channelId)
channel.send(message)
})
}```
And this is how i make the bot execute it
const hi = require('./events/hi')
const hello = require('./events/hello')
const yo = require('./events/yo')
const whatsup = require('./events/whatsUp')
const bye = require('./events/bye')
client.once('ready', () =>{
console.log('Aiko is working!');
client.user.setActivity(' your orders!|Prefix is +', { type: "LISTENING" });
hi(client)
hello(client)
yo(client)
whatsup(client)
bye(client)
welcome(client)
});```
The event that should also send a message when someone leaves the server also doesn't go off, anyone any idea why?
This is most likely a privileged intents problem, which recently became required. Check out this question to see if it solves it. Also read the discord API docs for privileged intents

keep fetching data up to date

I have just a question I want to ask if anybody have an idea about it.
I'm building a full stack application backed by nodejs and using typescript for it, in my nodejs app I'm making a fetch for an API that later on I will serve it to the user but I have one small issue, I'm using node-fetch for now but the data which are fetched are changing all the time eg. now I have 10 entries, after 5 seconds I have 30 entries, so is there a way or mechanism to make my fetching to the data with nodejs up to date by fetching them in the background?
Thanks in advance!
Easiest solution to implement and good in actual sense for making your web app realtime https://pusher.com/
This is how you can handle pusher within your NodeJS App
import Pusher from 'pusher'
//Below are the keys that you will get from pusher when you go to getting started
// within your Dashboard
const pusher = new Pusher({
appId: "<Your app id provided by pusher>",
key: "<Key id provided by pusher>",
secret: "<Secret key given by pusher>",
cluster: "<cluster given by pusher",
useTLS: true
});
Now you want to setup a changeStream for your Collection in MongoDB
const db = mongoose.collection;
db.once('open', ()=>{
const postCollection = db.collection('posts')//This will be dependent on the collection you want to watch
const changeStream = postCollection.watch()//Make sure the collection name above are acurate
changeStream.on('change', (change)=>{
const post = change.fullDocument;//Change bring back content that change in DB Collection
if (change.operationType === 'insert'){
pusher.triger('<write channel for your pusher>', '<event in this case inser>', {
newPost:post
})
}
})
})
By that setup your pusher and backend is working now is time to setup frontend
If your usin VanillaJS the Pusher getting started has code for you
If your using ReactJS here's is the code below
import Pusher from 'pusher-js'
useEffect(()=>{
Pusher.logToConsole = true;
var pusher = new Pusher('<Key received from pusher>', {
cluster: '<cluster received from pusher>'
});
var channel = pusher.subscribe('<channel name that you wrote in server');
channel.bind('<event that you wrote in sever',(data)=> {
alert(JSON.stringify(data)); // This will be the data entries coming as soon as they enter DB then you can update your state by using spread operators to maintain what you have and also add new contents
});
//Very important to have a clean-up function to render this once
return ()=>{
pusher.unbind();
pusher.unsubscribe_all();
}
})
Now like this you have everything being realtime

How to make a ping-pong discord bot with websocket in Nodejs?

Im trying to make a simple ping-pong discord bot in Nodejs without any lib like discord.js in Nodejs
I think that using websockets with the rest api of discord is the best solution but I cant find any help or any code example to do it
I found this course : https://courses.cs.washington.edu/courses/cse154/17au/exploration/websockets/slides.html#/
with this "solution" that I can't understant : https://courses.cs.washington.edu/courses/cse154/17au/exploration/websockets/solution/
And this is an extract from the course :
const BOT_TOKEN = "xxx";
// Discord Gateway url
const GATEWAY_URL = "wss://gateway.discord.gg/?v=6&encoding=json";
// Websocket object
let ws = null;
connect();
// connect to gateway
function connect() {
ws = new WebSocket(GATEWAY_URL); // opens the websocket connection and creates WS object
ws.onmessage = messageHandler; // on message event
ws.onclose = connect; // reopen websockets when closed by discord
}
What I want to do can be simply done with this code using discord.js :
const Discord = require('discord.js');
const bot = new Discord.Client();
bot.on('ready', function () {
console.log("Connected !")
})
bot.on('message', message => {
if (message.content === 'ping') {
message.reply('pong !')
}
})
bot.login(token)
Any help please ?
I'm the one who provided this talk. While the lecture code does interact with Discord, it is not the most optimal method of doing so. Personally I would suggest using discord.js to create a bot that would respond to your ping.
For reference, the lecture I demonstrated in class is to showcase the functionality of websockets. It is executed within the browser and not with the help of node.js.
Under the hood, discord.js handles connection to Discord websocket gateway well. It responds to things like heartbeats and make sure Discord gateway does not boot the client from inactivity. The code I have demonstrated in lecture can only run for about 30 seconds at a time before being booted from Discord for inactivity.
However, if you are curious about the lecture, the session from Spring 18 is recorded live and can be viewable here.
I hope this help!

Resources