Having problems when making a ticket discord JS - node.js

haveing problem when makeing a ticket i dunno what i did everything looks right it would be nice for some help on. i dunno what i did wrong. it looks to me like something went wrong with "message.guild.channels.create" when it trys to create it, it gives me this error the code and the error is below
module.exports = {
name: "ticket",
aliases: [],
permissions: [],
description: "open a ticket!",
async execute(message, args, cmd, client, discord) {
const channel = await message.guild.channels.create(`ticket: ${message.author.tag}`);
channel.setParent("855596395783127081");
channel.updateOverwrite(message.guild.id, {
SEND_MESSAGE: false,
VIEW_CHANNEL: false,
});
channel.updateOverwrite(message.author, {
SEND_MESSAGE: true,
VIEW_CHANNEL: true,
});
const reactionMessage = await channel.send("Thank you for contacting support!");
try {
await reactionMessage.react("🔒");
await reactionMessage.react("â›”");
} catch (err) {
channel.send("Error sending emojis!");
throw err;
}
const collector = reactionMessage.createReactionCollector(
(reaction, user) => message.guild.members.cache.find((member) => member.id === user.id).hasPermission("ADMINISTRATOR"), { dispose: true }
);
collector.on("collect", (reaction, user) => {
switch (reaction.emoji.name) {
case "🔒":
channel.updateOverwrite(message.author, { SEND_MESSAGES: false });
break;
case "â›”":
channel.send("Deleting this channel in 5 seconds!");
setTimeout(() => channel.delete(), 5000);
break;
}
});
message.channel
.send(`We will be right with you! ${channel}`)
.then((msg) => {
setTimeout(() => msg.delete(), 7000);
setTimeout(() => message.delete(), 3000);
})
.catch((err) => {
throw err;
});
},
};
Heres the error
PS C:\Users\lolzy\OneDrive\Desktop\discordbot> node .
Cbs slave is online!
(node:19344) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'channels' of undefined
at Object.execute (C:\Users\lolzy\OneDrive\Desktop\discordbot\commands\ticket.js:7:45)
at module.exports (C:\Users\lolzy\OneDrive\Desktop\discordbot\events\guild\message.js:10:26)
at Client.emit (events.js:376:20)
at MessageCreateAction.handle (C:\Users\lolzy\OneDrive\Desktop\discordbot\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (C:\Users\lolzy\OneDrive\Desktop\discordbot\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (C:\Users\lolzy\OneDrive\Desktop\discordbot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:31)
at WebSocketShard.onPacket (C:\Users\lolzy\OneDrive\Desktop\discordbot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:444:22)
at WebSocketShard.onMessage (C:\Users\lolzy\OneDrive\Desktop\discordbot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:301:10)
at WebSocket.onMessage (C:\Users\lolzy\OneDrive\Desktop\discordbot\node_modules\ws\lib\event-target.js:132:16)
at WebSocket.emit (events.js:376:20)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:19344) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of
an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:19344) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that
are not handled will terminate the Node.js process with a non-zero exit code.

It says that the guild property is undefined, this might be because someone's using the command in DM's and that's why you're not getting the guild. So what you can do is add an if statement to check if the user is using the command in a server
Here's an example:
module.exports = {
name: "ticket",
aliases: [],
permissions: [],
description: "open a ticket!",
async execute(message, args, cmd, client, discord) {
if (!message.guild) return message.channel.send("You can't use this command in DM's");
// Rest of the code
}
};

Related

Expected 'port' to be a 'number', got 'object', minecraft server status check error

i have this simple code in my discord bot to check mc server.
const Discord = require('discord.js')
const client = new Discord.Client()
const { MessageButton, MessageButtonStyles } = require('discord-buttons')
require('discord-buttons')(client)
const db = require('quick.db')
let mineutil = require('minecraft-server-util')
client.on('ready', () => {
console.log('Started!\n---')
client.user.setPresence({
status: 'online',
activity: {
type: 'LISTENING',
name: '!help'
}
})
})
client.on('message', async (message) => {
if (message.content == 'привет') {
message.reply('привет')
}
//more code
const SERVER_ADDRESS = 'adress'
const SERVER_PORT = 25565
const STATUS_ONLINE = '**Сервер включен** - '
const STATUS_PLAYERS = '**{online}** **человек(a) онлайн!**'
const STATUS_EMPTY = '**никто не играет**'
const cacheTime = 15 * 1000; // 15 sec cache time
let data, lastUpdated = 0;
function statusCommand(message) {
getStatus().then(data => {
let status = STATUS_ONLINE;
status += data.onlinePlayers ?
STATUS_PLAYERS.replace('{online}', data.onlinePlayers) : STATUS_EMPTY;
let statuspanel = new Discord.MessageEmbed()
.setColor('2ecc71')
.setDescription(status)
send(statuspanel)
}).catch(err => {
console.error(err)
let statuserror = new Discord.MessageEmbed()
.setColor('ff0000')
.setDescription('**Сервер выключен**')
send(statuserror)
})
}
function getStatus() {
if (Date.now() < lastUpdated + cacheTime) return Promise.resolve(data);
return mineutil.status(SERVER_ADDRESS, { port: SERVER_PORT })
.then(res => {
data = res;
lastUpdated = Date.now();
return data;
})
}
if (message.content == '!server') {
statusCommand(message)
}
})
client.login(TOKEN)
And it works in Visual studio, but i just placed it on Replit and it catches this error:
(node:172) UnhandledPromiseRejectionWarning: AssertionError [ERR_ASSERTION]: Expected 'port' to be a 'number', got 'object'
at Object.status (/home/runner/Makak-discord-bot/node_modules/minecraft-server-util/dist/status.js:23:26)
at getStatus (/home/runner/Makak-discord-bot/index.js:210:21)
at statusCommand (/home/runner/Makak-discord-bot/index.js:192:5)
at Client.<anonymous> (/home/runner/Makak-discord-bot/index.js:219:5)
at Client.emit (events.js:314:20)
at Client.EventEmitter.emit (domain.js:483:12)
at MessageCreateAction.handle (/home/runner/Makak-discord-bot/node_modules/discord.js/src/client/actions/MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (/home/runner/Makak-discord-bot/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (/home/runner/Makak-discord-bot/node_modules/discord.js/src/client/websocket/WebSocketManager.js:384:31)
at WebSocketShard.onPacket (/home/runner/Makak-discord-bot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:444:22)
(node:172) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:172) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
And if i change, for example { port: SERVER_PORT } to 25565, it always says that server is off, even if server online(
PS sorry for my english, and russian text in code
EDIT Just saw the question's last line about the server being reported as offline when using a number rather than an object. That actually confirms my suspicion below, as you're no longer getting an error from the SDK itself (ie, it seems to be "working," in that it's at least making the network call). I would double-check your address and port number, and ensure the server is accessible from replit.
--- Original response below ---
Difficult to say for sure without knowing the mineutil API you're using, but it looks like you may be sending more than you need to the mineutil.status() function (And if you're using this library, I'm fairly certain you are).
I'm guessing that the following line:
return mineutil.status(SERVER_ADDRESS, { port: SERVER_PORT })
which is sending an object `{port: SERVER_PORT}' as its second parameter, should just be sending the number itself. For example:
return mineutil.status(SERVER_ADDRESS, SERVER_PORT )
This is Replit server side error, it can not be repaired(

Mongoose query not running - "cursor.toArray is not a function"

MongoDB beginner, having trouble getting queries to work. Was following a tutorial of sorts and it was a demo notes app. Their syntax for saving new notes works fine.
However when it comes to printing out the list of notes, there seems to be something wrong in the syntax given to me or something im doing wrong.
const mongoose = require("mongoose");
const url =
"mongodb+srv://Saif:<password>#cluster0.8d2lb.mongodb.net/notes-app?retryWrites=true&w=majority";
mongoose.connect(url, {
useNewUrlParser: true,
});
const noteSchema = new mongoose.Schema({
content: String,
date: Date,
important: Boolean,
});
const Note = mongoose.model("Note", noteSchema);
Note.find({}).then((result) => {
result.forEach((note) => {
console.log(note);
});
mongoose.connection.close();
});
After looking up documentation, the actual syntax of find is a little different where they pass in a callback instead of using promises. But changing that block to use a callback still doesnt work
Note.find({}, (error, data) => {
if (error) {
console.log(error);
} else {
data.forEach((note) => {
console.log(note);
})
}
mongoose.connection.close()
})
Error
TypeError: cursor.toArray is not a function
at model.Query.<anonymous> (D:\Folders\Documents\CS.........
(Use `node --trace-warnings ...` to show where the warning was created)
(node:27108) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:27108) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
.find method from model returns Query object not Cursor
For cursor you need to do .exec
Note.find({}).exec((error, data) => {
if (error) {
console.log(error);
} else {
data.forEach((note) => {
console.log(note);
})
}
mongoose.connection.close()
})

I have a problem with my Discord bot (Minecraft server status bot)

This is the index.js script of the bot:
const { Client, RichEmbed } = require('discord.js')
const bot = new Client()
const util = require('minecraft-server-util')
const token = 'bot_token'
const PREFIX = 'l.'
bot.on('ready', () => {
console.log('Bot has come online.')
})
bot.on('message', message => {
let args = message.content.substring(PREFIX.length).split(' ')
switch (args[0]) {
case 'status':
util.status('IP', (PORT), (error, reponse) => {
if (error) throw error
const Embed = new RichEmbed()
.setTitle('Server Status')
.addField('Server IP', reponse.host)
.addField('Server Version', reponse.version)
.addField('Online Players', reponse.onlinePlayers)
.addField('Max Players', reponse.maxPlayers)
message.channel.send(Embed)
})
break
}
})
bot.login(token)
When I type node . in the console and I type l.status on the Discord server, it shows this error on the console:
(node:3300) UnhandledPromiseRejectionWarning: AssertionError [ERR_ASSERTION]: Expected 'options' to
be an object or undefined, got number
at C:\Users\HNRK\Desktop\LightSide\node_modules\minecraft-server-util\dist\status.js:46:25
at Generator.next (<anonymous>)
at C:\Users\HNRK\Desktop\LightSide\node_modules\minecraft-server-util\dist\status.js:8:71
at new Promise (<anonymous>)
at __awaiter (C:\Users\HNRK\Desktop\LightSide\node_modules\minecraft-server-util\dist\status.js:4:12)
at status (C:\Users\HNRK\Desktop\LightSide\node_modules\minecraft-server-util\dist\status.js:40:12)
at Object.<anonymous> (C:\Users\HNRK\Desktop\LightSide\node_modules\minecraft-server-util\dist\status.js:113:17)
at Generator.next (<anonymous>)
at C:\Users\HNRK\Desktop\LightSide\node_modules\minecraft-server-util\dist\status.js:8:71
at new Promise (<anonymous>)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:3300) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the
CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:3300) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Can anybody help? I also tried a lot of different solutions, but none of them worked.
You are using an outdatet version of discord.js. Type npm i discord.js#latest into your terminal. In the latest version of discord.js, RichEmbed() has been removed and replaced by MessageEmbed().
This is an answer based on assumption since I've never used minecraft-server-util before. Also assuming that you're using the latest minecraft-server-util,
Based on the error;
Expected 'options' to be an object or undefined, got number
And, based on this commit, You should pass the 2nd argument as an object instead of PORT since it's a type of StatusOptions instead of a number.
So, instead of;
util.status('IP', (PORT), (error, reponse) => {
You should be doing;
util.status('IP', {
port: (PORT)
}, (error, reponse) => {

TypeError data.forEach is not a function

So when I send a get request in postman I am catching my 404 error in postman saying the "scream not found" ok great, but in my terminal I am getting this.
TypeError: data.forEach is not a function
at F:\dev\stfu-functions\functions\handlers\screams.js:68:18
at processTicksAndRejections (internal/process/task_queues.js:97:5)
i functions: Finished "api" in ~2s
(node:6672) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:526:11)
at ServerResponse.header (F:\dev\stfu-functions\functions\node_modules\express\lib\response.js:771:10)
at ServerResponse.send (F:\dev\stfu-functions\functions\node_modules\express\lib\response.js:170:12)
at ServerResponse.json (F:\dev\stfu-functions\functions\node_modules\express\lib\response.js:267:15)
at F:\dev\stfu-functions\functions\handlers\screams.js:75:29
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:6672) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by
rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:6672) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Here is my code where the error is happening Any Help is greatly apreciated.
exports.getScream =(req, res) => {
let screamData = {};
db.doc(`/screams/${req.params.screamId}`)
.get()
.then((doc) => {
if(!doc.exists){
return res.status(404).json({ error: 'Scream not found' });
}
screamData = doc.data();
screamData.screamId = doc.id;
return db
.collection('comments')
.where('screamId', '==', req.params.screamId)
.get();
})
.then((data) => {
screamData.comments = [];
data.forEach((doc) => {
screamData.comments.push(doc.data());
});
return res.json(screamData);
})
.catch((err) => {
console.error(err);
res.status(500).json({ error: err.code });
})
};

proxyReq.setHeader can not set headers after they are sent

i am building a node.js proxy and i want to add a conditional header
proxy.on('proxyReq', (proxyReq, req, res) => {
const realIP = parseHttpHeader(req.headers['x-real-ip'])[0];
const path = parseHttpHeader(req.headers['x-original-uri'])[0];
pAny([
check_ip(realIP) ,
check_path(path) ,
check_geo(realIP)
]).then(result => {
console.log (result , "result " )
if (result) {
proxyReq.setHeader('namespace' , 'foo');
} else {
proxyReq.setHeader('namespace' , 'bar'); }
console.log('sending req ')
});
});
.
async function check_ip(realIP) {
try {
const result = await ipModel.findOne({ip: realIP}).exec()
console.log(realIP , result , "ip")
if (result) {
return true
} else {
return false
}
} catch (e) {
throw e;
}
}
and it works just fine till i use the methos check_ip then i get the error
(node:3793) UnhandledPromiseRejectionWarning: Error: Can't set headers after they are sent.
at validateHeader (_http_outgoing.js:491:11)
at ClientRequest.setHeader (_http_outgoing.js:498:3)
at /home/master/IPS/server.js:109:14
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:189:7)
(node:3793) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:3793) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
as the error clearly states i am handeling a promise in the wrong way but i don't know how to fix it i tried using callbacks i tried using await
make the check_ip return a promise and try
function check_ip(realIP) {
return ipModel.findOne({ ip: realIP }).exec();
}

Resources