Cannot read properties of undefined (reading 'GUILD') on Node.js v18.12.1 - discord.js

Here's my code:
require('dotenv').config();
const {REST} = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const { Client, Intents, Collection } = require('discord.js');
const { Player } = require("discord-player");
const fs = require('fs');
const path = require('path');
const client = new Client [{
intents: [
Intents.GUILD,
Intents.GUILD_MESSAGES,
Intents.GUILD_VOICE_STATES
]
}];
I've been working this for an hour now but I still cant fix it

Related

Getting error while integrating Socket io and cloudflare

Server-side code:
const express = require("express");
const app = express();
const http = require("http");
const { Server } = require("socket.io");
const cors = require("cors");
app.use(cors());
const server = http.createServer(app);
const io = new Server(server, {
cors: {
origin: "http://localhost:3000",
methods: ["GET", "POST"],
},
});
io.on("connection", (socket) => {
console.log(`User Connected: ${socket.id}`);
socket.on("join_room", (data) => {
socket.join(data);
});
Client-side code:
import io from "socket.io-client";
const socket = io.connect("http://localhost:8080");
function App() {
const joinRoom = () => {
if (room !== "") {
socket.emit("join_room", room);
}
};
But getting the following error after hosting it to cloudflare which works fine in local.:
polling.js:311 GET http://localhost:8080/socket.io/?EIO=4&transport=polling&t=OKgPK3u net::ERR_CONNECTION_REFUSED
I tried giving different port but still facing the same problem. Can anyone please help me?

How to send a direct message to a user using Discord.js? [duplicate]

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,
],
});

discrod.js REST is not a constructor

const config = require("./config.json");
const Discord = require('discord.js');
const { Intents } = Discord;
const client = new Discord.Client({
intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES]
})
const { REST, Routes } = require('discord.js');
const commands = [
{
name: 'test',
description: 'test',
},
];
const rest = new REST({ version: '10' }).setToken(config.BOT_TOKEN);
(async () => {
try {
console.log('Started refreshing application (/) commands.');
await rest.put(Routes.applicationCommands(config.CLIENT_ID), { body: commands });
console.log('Successfully reloaded application (/) commands.');
} catch (error) {
console.error(error);
}
})();
client.on('interactionCreate', async interaction => {
if (!interaction.isChatInputCommand()) return;
if (interaction.commandName === 'test') {
await interaction.reply('Hello boi!');
}
});
client.login(config.BOT_TOKEN)
const rest = new REST({ version: '10' }).setToken(config.BOT_TOKEN);
^
TypeError: REST is not a constructor
I followed the instructions to create a bot. I run it and then this error occurs. I 've been looking everywhere for a solution
You should probably change the following:
const { REST, Routes } = require('discord.js');
with the following lines:
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v10');
This can been verified by checking this.

Connecrint to Mongodb

I just can't connect to a mongodb. Here's what I tried
in node.js
console.log("001");
dotenv = require('dotenv');
dotenv.config();
const mongodb = require('mongodb').MongoClient;
const { MongoClient } = require("mongodb");
console.log("002");
const uri = process.env.CONNECTIONSTRING;
const client = new MongoClient(uri);
console.log("003");
async function run() {
console.log("004");
client.connect();
const db = client.db("blah");
console.log("005");
await const results = db.student.find();
console.log("006")
console.log(results)
console.log("007")
client.close()
};
//call function
run();
and I get this error
SyntaxError: Unexpected token 'const'
the CONNECTIONSTRING is in .env beside the original file node.js
The database is called 'blah' and the collection 'student'.
The error is on line 18,
await const results = db.student.find();
Thanks,

change code from template engine to next js

How do I convert my app that is made with .pug to next app ? I have an app using .pug engine and I want to convert it into next.
This is the app.js but as I know next is different how do I do it? Because here my files are in views, and in views the files are in pages etc how do I do it? Is there any way or I have to code it all again?
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
const middleware = require('./middleware')
const path = require('path')
const bodyParser = require("body-parser")
const mongoose = require("./database");
const session = require("express-session");
const http = require('http');
const server = app.listen(port, () => console.log("Server listening on port " + port));
const io = require("socket.io")(server, { pingTimeout: 60000 });
app.set("view engine", "pug");
app.set("views", "views");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, "public")));
app.use(session({
secret: "#########",
resave: true,
saveUninitialized: false
}))
// Routes
const loginRoute = require('./routes/loginRoutes');
const registerRoute = require('./routes/registerRoutes');
const logoutRoute = require('./routes/logout');
const postRoute = require('./routes/postRoutes');
const profileRoute = require('./routes/profileRoutes');
const uploadRoute = require('./routes/uploadRoutes');
const searchRoute = require('./routes/searchRoutes');
const messagesRoute = require('./routes/messagesRoutes');
const notificationsRoute = require('./routes/notificationRoutes');
// Api routes
const postsApiRoute = require('./routes/api/posts');
const usersApiRoute = require('./routes/api/users');
const chatsApiRoute = require('./routes/api/chats');
const messagesApiRoute = require('./routes/api/messages');
const notificationsApiRoute = require('./routes/api/notifications');
app.use("/login", loginRoute);
app.use("/register", registerRoute);
app.use("/logout", logoutRoute);
app.use("/posts", middleware.requireLogin, postRoute);
app.use("/profile", middleware.requireLogin, profileRoute);
app.use("/uploads", uploadRoute);
app.use("/search", middleware.requireLogin, searchRoute);
app.use("/messages", middleware.requireLogin, messagesRoute);
app.use("/notifications", middleware.requireLogin, notificationsRoute);
app.use("/api/posts", postsApiRoute);
app.use("/api/users", usersApiRoute);
app.use("/api/chats", chatsApiRoute);
app.use("/api/messages", messagesApiRoute);
app.use("/api/notifications", notificationsApiRoute);
app.get("/", middleware.requireLogin, (req, res, next) => {
var payload = {
pageTitle: "Home",
userLoggedIn: req.session.user,
userLoggedInJs: JSON.stringify(req.session.user),
}
res.status(200).render("home", payload);
})
io.on("connection", socket => {
socket.on("setup", userData => {
socket.join(userData._id);
socket.emit("connected");
})
socket.on("join room", room => socket.join(room));
socket.on("typing", room => socket.in(room).emit("typing"));
socket.on("stop typing", room => socket.in(room).emit("stop typing"));
socket.on("notification received", room => socket.in(room).emit("notification received"));
socket.on("new message", newMessage => {
var chat = newMessage.chat;
if(!chat.users) return console.log("Chat.users not defined");
chat.users.forEach(user => {
if(user._id == newMessage.sender._id) return;
socket.in(user._id).emit("message received", newMessage);
})
});
})
If you don't want to refactor all your pug template engine pages to next.js pages, then you can make the pug pages coexist with the next.js. You can make the next.js the default route, and place next.js code after all pug page routes. And you also need to refactor app.get("/", middleware.requireLogin, (req, res, next) => {...} to make sure next.js is the default route.
To apply this rule, you need a custom next.js server.
sample code
const express = require('express');
const next = require('next');
const port = 3000;
const dev = process.env.NODE_ENV !== 'production'; // use default NodeJS environment variable to figure out dev mode
const app = next({dev, conf});
const handle = app.getRequestHandler();
const server = express();
// all your pug page routes should be declared before `server.get('*'`.
server.get('*', authMiddleware(false), (req, res) => {
// pass through everything to NextJS
return handle(req, res);
});
app.prepare().then(() => {
server.listen(port, (err) => {
if (err) throw err;
console.log('NextJS is ready on http://localhost:' + port);
});
}).catch(e => {
console.error(e.stack);
process.exit(1);
});

Resources