How do I format time and bypass server name? - javascript

So I am about to post ALOT but I have been cracking at this for days now and can't get passed it. Basically with the code below I am trying to change the time format and also trying to fix null error which I don't think I can with what I call.
ERROR #1 ------------------------------
(node:8844) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'name' of null
at Object.execute (C:\filepath\bot\commands\serverinfo.js:22:39)
at Client.<anonymous> (C:\filepath\bot\main.js:54:43)
at Client.emit (events.js:314:20)
at MessageCreateAction.handle (C:\filepath\bot\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (C:\filepath\bot\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (C:\filepath\bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:31)
at WebSocketShard.onPacket (C:\filepath\bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:444:22)
at WebSocketShard.onMessage (C:\filepath\bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:301:10)
at WebSocket.onMessage (C:\filepath\bot\node_modules\ws\lib\event-target.js:125:16)
at WebSocket.emit (events.js:314:20)
(node:8844) 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:8844) [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.
What I have come to conclude is that it can't pull the server name for a DM of course but I don't know how to break the below code where it only loads the DM portion and then the channel portion separate? I have tried 2 separate .js files and the DM one sends but not the server?
Error #2 ------------------------------
I am trying to change the time and date format so it is not so long. Below is what my output is currently and what I am trying to get. I have been trying to work with moment.js but it doesn't seem to work properly for me?
output I want to change
And what I am hoping to get is just MM/DD/YYYY. If someone could help me out I would be beyond grateful.
CODE -------------
const { prefix } = require('../config.json');
module.exports = {
name: 'serverinfo',
description: 'sends the serverinfo command',
execute(message, args) {
const Discord = require('discord.js');
const client = new Discord.Client();
const user = message.author;
var moment = require('moment'); // require
const keepinservercommandembed = new Discord.MessageEmbed()
.setColor('#FF0000')
.setTitle('**Im Sorry!**')
.setThumbnail('https://i.imgur.com/7Gvh8VL.png')
.addFields(
{ name: `**Can` + `'t accept: ${prefix}serverinfo**`, value: 'Please keep the commands to the server!' },
)
if(message.channel.type == "dm") {
message.channel.send(keepinservercommandembed);
}
const serverinfocommandembed = new Discord.MessageEmbed()
.setColor('#0000FF')
.setTitle(`**"${message.guild.name}" Server Information**`)
.setDescription('Per your request here is a little bit of information about the server we you invoked this command in:')
.setThumbnail(message.guild.iconURL())
.addFields(
{ name: '**Server Owner**:', value: `${message.guild.owner}`, inline: true },
{ name: '**Joined On**:', value: `${message.member.joinedAt}`, inline: true },
{ name: '**Total Members**:', value: `${message.guild.memberCount}`, inline: true },
{ name: '**Role Count**:', value: `${message.guild.roles.cache.size}`, inline: true },
)
if (message.channel) {
moment().format();
message.delete();
message.channel.send(serverinfocommandembed);
}
}
}

TypeError: Cannot read property 'name' of null
As you said, this is because DM channels are not in guilds, so dmChannel.guild will return null. The way you tried to fix it, by comparing the channel.type also works, except there is one problem: you are not stopping the execution after finding that the channel is a DM, so it just keeps on going.
Here's a simplified example of what you are doing:
function isTheNumberOne(num) {
if (num !== 1) console.log('The number is not one'); // even though the script knows the nuber isn't one
console.log('The number is one'); // it moves right forward into saying the number is 1
};
isTheNumberOne(2)
What you should do is either create an else statement, or just return right there.
function isTheNumberOne(num) {
if (num !== 1)
return console.log('The number is not one'); // stop execution
console.log('The number is one');
};
isTheNumberOne(2)
function isTheNumberOne(num) {
if (num !== 1)
return console.log('The number is not one'); // only moves forward if number is not 1
else console.log('The number is one');
};
isTheNumberOne(2)
You kind of tried something like this with your if (message.channel) statement before sending the embed, but the embed content has already loaded, and thus the bot had already run into an error, making that statement obsolete.
if(message.channel.type == "dm")
return message.channel.send(keepinservercommandembed);
I am hoping to get is just MM/DD/YYYY
You can use the npm package moment for that, which it looks like you've already imported to your file. Now all you need is to use the format function.
{
name: '**Joined On**:',
value: moment(message.member.joinedAt).format('MM/DD/YYYY'),
inline: true,
},

Related

Send websocket data to specific client

I made a websocket server using nodeJS, and my problem is as follow : two clients will connect to the server. When the client 1 send a data to the server, I want to forward it to client 2.
In order to do this, I took inspiration from this kind of solution :https://github.com/websockets/ws/issues/367
Looks great, but when I apply it, it gaves me the following error :
TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object. Received an instance of Object
at new NodeError (node:internal/errors:371:5)
at Function.from (node:buffer:323:9)
at toBuffer (/home/ttt/node_modules/ws/lib/buffer-util.js:95:18)
at Sender.send (/home/ttt/node_modules/ws/lib/sender.js:315:14)
at WebSocket.send (/home/ttt/node_modules/ws/lib/websocket.js:467:18)
at WebSocket.<anonymous> (/home/ttt/STT_project/sttproject/IHM_server/websocketServer.js:43:15)
at WebSocket.emit (node:events:526:28)
at Receiver.receiverOnMessage (/home/ttt/node_modules/ws/lib/websocket.js:1137:20)
at Receiver.emit (node:events:526:28)
at Receiver.dataMessage (/home/ttt/node_modules/ws/lib/receiver.js:528:14)
code: 'ERR_INVALID_ARG_TYPE'
I tried different methods, but the result remains the same. Does anyone can help me with this ? Or propose a better solution to my problem.
There is a sample of my code:
wss.on("connection", ws => {
ws.id = id++;
lookup[ws.id] = ws;
ws.on("message", data => {
if(data.toString() != "\n")
{
message = {
"message":
{
"text": data.toString(),
"end": false
}
}
}
else {
message = {
"message":
{
"text": "",
"end": true
}
}
}
lookup[0].send('message');
})
...

Read information from embed message Discord.JS

enter image description here
I want my keytritz bot to react to an embed when the title is naruto / Naruto but in the first one I got an error (# 1) but it did not affect the functionality but in the second embed (#2) I got an error that the keytritz bot did not react and did not commented
, I leave a link where is the code of both bots, the mudae bot is not mine.
https://mega.nz/folder/IIUHEabJ#IIaRNcMgUS2gC-d_lZXQZw
https://top.gg/bot/432610292342587392
CODE Keytritz:
for(var i = 0; i < message.embeds.length; i++) {
message.channel.send(message.content.embeds);
if(message.embeds[i].title.includes("naruto")){
message.react(" ")
message.channel.send("Detected");
break;
}
}
Embed lxXxandresxXxl
if(message.content.startsWith(prefix+"r")) {
message.channel.send({ embed: {
color: 3447003,
author: {
name: client.user.username,
icon_url: client.user.displayAvatarURL()
},
title: "This is an naruto embed",
url: "http://google.com",
description: "This is a test embed to showcase what they look like and what they can do.",
fields: [{
name: "Fields",
value: "They can have different fields with small headlines."
},
{
name: "Masked links",
value: "You can put [masked links](http://google.com) inside of rich embeds."
},
{
name: "Markdown",
value: "You can put all the *usual* **__Markdown__** inside of them."
}
],
timestamp: new Date(),
footer: {
icon_url: client.user.displayAvatarURL(),
text: "© Example"
}
}
});
}
Error 1#
(node:1744) UnhandledPromiseRejectionWarning: DiscordAPIError: Cannot send an empty message
at RequestHandler.execute (/rbd/pnpm-volume/8bd4e7c9-1711-40fc-be45-7d082848ec2a/node_modules/.registry.npmjs.org/discord.js/12.5.3/node_modules/discord.js/src/rest/RequestHandler.js:154:13)
at processTicksAndRejections (internal/process/task_queues.js:88:5)
at async RequestHandler.push (/rbd/pnpm-volume/8bd4e7c9-1711-40fc-be45-7d082848ec2a/node_modules/.registry.npmjs.org/discord.js/12.5.3/node_modules/discord.js/src/rest/RequestHandler.js:39:14)
(node:1744) 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:1744) [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.
Error 2#
if(message.embeds[i].title.includes("naruto")){
^
TypeError: Cannot read property 'includes' of null
at Client.<anonymous> (/app/server.js:90:36)
at Client.emit (events.js:196:13)
at MessageCreateAction.handle (/rbd/pnpm-volume/8bd4e7c9-1711-40fc-be45-7d082848ec2a/node_modules/.registry.npmjs.org/discord.js/12.5.3/node_modules/discord.js/src/client/actions/MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (/rbd/pnpm-volume/8bd4e7c9-1711-40fc-be45-7d082848ec2a/node_modules/.registry.npmjs.org/discord.js/12.5.3/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (/rbd/pnpm-volume/8bd4e7c9-1711-40fc-be45-7d082848ec2a/node_modules/.registry.npmjs.org/discord.js/12.5.3/node_modules/discord.js/src/client/websocket/WebSocketManager.js:384:31)
at WebSocketShard.onPacket (/rbd/pnpm-volume/8bd4e7c9-1711-40fc-be45-7d082848ec2a/node_modules/.registry.npmjs.org/discord.js/12.5.3/node_modules/discord.js/src/client/websocket/WebSocketShard.js:444:22)
at WebSocketShard.onMessage (/rbd/pnpm-volume/8bd4e7c9-1711-40fc-be45-7d082848ec2a/node_modules/.registry.npmjs.org/discord.js/12.5.3/node_modules/discord.js/src/client/websocket/WebSocketShard.js:301:10)
at WebSocket.onMessage (/rbd/pnpm-volume/8bd4e7c9-1711-40fc-be45-7d082848ec2a/node_modules/.registry.npmjs.org/discord.js/12.5.3/node_modules/discord.js/node_modules/ws/lib/event-target.js:132:16)
at WebSocket.emit (events.js:196:13)
at Receiver.receiverOnMessage (/rbd/pnpm-volume/8bd4e7c9-1711-40fc-be45-7d082848ec2a/node_modules/.registry.npmjs.org/discord.js/12.5.3/node_modules/discord.js/node_modules/ws/lib/websocket.js:983:20)
I evaluate some code to tries to basically replicated what you do. and i come up with this code. Might help you a little bit, and also i tried this with my other test bot and i also found out if you sends a link for example https://google.com it will have an embed but on discord it isnt meaning it just read actual embed like from other bot or smth, anyway here what i got so far.
Discord.js V13
client.on('messageCreate', message => {
if(message.embeds.length >= 0)
// Check if the Message has embed or not
{
let embed = message.embeds
// console.log(embed) just a console.log
for(let i = 0; i < embed.length; i++)
// Loop it since in v13 you can send multiple embed in single message
{
if(embed[i].title === null) return;
// check each embed if it has title or not, if it doesnt then do nothing
if(embed[i].title.toLowerCase().includes('hi'))
// check each embed if it includes word 'hi' or not
{
message.react('🔳')
message.react('🎉')
}
}
}
})
P.S. This code will read another bot message
P.S.S If someone has a better way explained the code or wants to make changes, feel free to edit it

Error when trying to instantiate a new Message Object in Discord.js

Problem
I am trying to create a [message object][1] in [discordjs][1] in order to send a message from my account. When I do this, I always get this error:
Cannot read property 'slice' of undefined
Code
Here is my code:
client.on("message", async message => {
if (message.author && message.author.bot) {
return;
}
try {
const myMessage = new Discord.Message(
client,
{ author: { id: "myID" }, content: "My new Message" },
message.channel
);
console.log(myMessage);
Additional Information
I have logged Discord, client and message, all exist and are valid objects. I also replaced the data part of the constructor with this:
{ author: message.author, content: message.content },
but to no avail. The error was the same. So what am I doing wrong here?
Solution
After hacking the source code of discord.js I discovered the culprit in the Message.js file. It is this line:
this.createdTimestamp = SnowflakeUtil.deconstruct(this.id).timestamp;
The problem is that I never passed any id to the constructor function in my data object. Just passing a fake id (a string of random numbers) did the trick.

Cloud function fails after changing Runtime to Node.js 10

I am trying to take firebase backup through a cloud function. The function was running completely fine when I was using Runtime: Node.js 8. However, since it is going to be deprecated soon, I now have to use Node.js 10. My fcloud function now fails with the below error:
Error: function execution failed. Details:
Cannot read property 'charCodeAt' of undefined
Detailed error log:
2020-05-27 11:01:21.820 IST
firestore_export
8kxlp9s867dy
TypeError: Cannot read property 'charCodeAt' of undefined at peg$parsetemplate (/workspace/node_modules/google-gax/build/src/pathTemplateParser.js:304:17) at Object.peg$parse [as parse] (/workspace/node_modules/google-gax/build/src/pathTemplateParser.js:633:18) at new PathTemplate (/workspace/node_modules/google-gax/build/src/pathTemplate.js:55:54) at segments.forEach.segment (/workspace/node_modules/google-gax/build/src/pathTemplate.js:120:29) at Array.forEach (<anonymous>) at PathTemplate.render (/workspace/node_modules/google-gax/build/src/pathTemplate.js:114:23) at FirestoreAdminClient.databasePath (/workspace/node_modules/#google-cloud/firestore/build/src/v1/firestore_admin_client.js:904:57) at exports.scheduledFirestoreBackup (/workspace/index.js:6:31) at Promise.resolve.then (/layers/google.nodejs.functions-framework/functions-framework/node_modules/#google-cloud/functions-framework/build/src/invoker.js:330:28) at process._tickCallback (internal/process/next_tick.js:68:7)
Expand all | Collapse all
{
insertId: "000000-f688386c-8f2b-4146-aaf7-1fe67c656fa2"
labels: {…}
logName: "projects/firestore-249705/logs/cloudfunctions.googleapis.com%2Fcloud-functions"
receiveTimestamp: "2020-05-27T05:31:31.171084310Z"
resource: {…}
severity: "ERROR"
textPayload: "TypeError: Cannot read property 'charCodeAt' of undefined
at peg$parsetemplate (/workspace/node_modules/google-gax/build/src/pathTemplateParser.js:304:17)
at Object.peg$parse [as parse] (/workspace/node_modules/google-gax/build/src/pathTemplateParser.js:633:18)
at new PathTemplate (/workspace/node_modules/google-gax/build/src/pathTemplate.js:55:54)
at segments.forEach.segment (/workspace/node_modules/google-gax/build/src/pathTemplate.js:120:29)
at Array.forEach (<anonymous>)
at PathTemplate.render (/workspace/node_modules/google-gax/build/src/pathTemplate.js:114:23)
at FirestoreAdminClient.databasePath (/workspace/node_modules/#google-cloud/firestore/build/src/v1/firestore_admin_client.js:904:57)
at exports.scheduledFirestoreBackup (/workspace/index.js:6:31)
at Promise.resolve.then (/layers/google.nodejs.functions-framework/functions-framework/node_modules/#google-cloud/functions-framework/build/src/invoker.js:330:28)
at process._tickCallback (internal/process/next_tick.js:68:7)"
timestamp: "2020-05-27T05:31:21.820Z"
trace: "projects/firestore-249705/traces/74e27700d135763bc4e7892ebb1a2333"
}
My index.js is as below:
const firestore = require('#google-cloud/firestore');
const client = new firestore.v1.FirestoreAdminClient();
// Replace BUCKET_NAME
const bucket = 'gs://gcp_firestore_ae2/firestore_export'
exports.scheduledFirestoreBackup = (event, context) => {
const databaseName = client.databasePath(
process.env.GCLOUD_PROJECT,
'(default)'
);
return client
.exportDocuments({
name: databaseName,
outputUriPrefix: bucket,
// Leave collectionIds empty to export all collections
// or define a list of collection IDs:
// collectionIds: ['users', 'posts']
collectionIds: ['most_valuable_items','nric_img','pay_slip','pic_of_ofc_entrance'],
})
.then(responses => {
const response = responses[0];
console.log(`Operation Name: ${response['name']}`);
return response;
})
.catch(err => {
console.error(err);
});
};
I had the same issue. I fixed it by changing:
process.env.GCLOUD_PROJECT
to my actual Project ID (e.g. "my_app_37274")
I had the same issue, It seems like in previous versions we don't need to GCLOUD_PROJECT in environment variable i.e it automatically detects it, but from node 10 onwards we need to pass this explicitly.
That's how I resolved it.
So instead of hardcoding it, try passing GCLOUD_PROJECT in cloud functions environment variables.
Note: GCLOUD_PROJECT is project id, not the project name.

How to fix "unhandled promise rejection error" in try/catch error handling

I'm trying to make use of the slack devkit located here (https://slack.dev/node-slack-sdk/webhook) to send strings to different slack channels. I'm just trying to include try/catch error handling to post to a static channel if the variable webhook fails.
I've tried all different variations of try/catch but I can't get any of the catch code to work properly. The try logic works fine and as expected. I am new to javascript/nodejs so it's probably a dumb error on my part. I've defined both SLACK_WEBHOOK_URL and SLACK_MONITORING_URL outside of this snippet
const TOTAL_GHE_ISSUES = "10" //pulled from DB
const GHE_ISSUE_NUMBERS = "90" //pulled from DB
const IncomingWebhook = require('#slack/webhook').IncomingWebhook; //function grabbed from slack webhook devkit library
var url = SLACK_WEBHOOK_URL //can change this to however we want to grab team's webhook
var webhook = new IncomingWebhook(url)
//timer
// Send the notification, if no webhook is present in owners table, skips
if (url != ""){
if (TOTAL_GHE_ISSUES != "0"){
try {
webhook.send({
text: "*Daily Overdue Nessus Vulnerability Alert*",
attachments: [{color: "#FF0000", blocks: [{type: "section",text: {type: "mrkdwn",text: "#here *" + TOTAL_GHE_ISSUES + "* Overdue Nessus Vulnerability issues reported \nOverdue Nessus Vulnerability GHE Issue Numbers: *" + GHE_ISSUE_NUMBERS + "*"}}]}]
})
}
catch(err){
console.log("Webhook Verification Failed")
//url = SLACK_MONITORING_URL;
//webhook = new IncomingWebhook(url)
//webhook.send({
//text: "*Nessus Webhook Verification, please investigate broken webhooks:*",
//attachments: [{color: "#FF0000", blocks: [{type: "section",text: {type: "mrkdwn",text: SLACK_WEBHOOK_URL}}]}]
//})
}
}
else {
try {
webhook.send({
text: "*Daily Overdue Nessus Vulnerability Alert*",
attachments: [{color: "#36a64f", blocks: [{type: "section",text: {type: "mrkdwn",text: "#here *NO* Overdue Nessus Vulnerabilities reported"}}]}]
})
}
catch(err){
//url = SLACK_MONITORING_URL
//webhook = new IncomingWebhook(url)
//webhook.send({
//text: "*Nessus Webhook Verification, please investigate broken webhooks:*",
//attachments: [{color: "#FF0000", blocks: [{type: "section",text: {type: "mrkdwn",text: SLACK_WEBHOOK_URL}}]}]
//})
}
}
}
else {
console.log("No webhook provided")}
I would expect the first catch(err) to post to console.log (and eventually add more functionality but I just want this basic test case) but instead I get this error
at Object.requestErrorWithOriginal (/Users/BrandonKonieczny/Documents/GitHub/node-slack-sdk/node_modules/#slack/webhook/dist/errors.js:25:33)
at IncomingWebhook.send (/Users/BrandonKonieczny/Documents/GitHub/node-slack-sdk/node_modules/#slack/webhook/dist/IncomingWebhook.js:54:32)
at processTicksAndRejections (internal/process/next_tick.js:81:5)
(node:65139) 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: 2)
(node:65139) [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.
In the try clause, the webhook.send returns a promise, not an error.
What returns an error is the result of the promise itself, so it won't be catched in the catch statement.
In order to cacth it you could make an async/await function and do...
async () => {
try {
await webhook.send({
text: "*Daily Overdue Nessus Vulnerability Alert*",
attachments: [{color: "#FF0000", blocks: [{type: "section",text: {type: "mrkdwn",text: "#here *" + TOTAL_GHE_ISSUES + "* Overdue Nessus Vulnerability issues reported \nOverdue Nessus Vulnerability GHE Issue Numbers: *" + GHE_ISSUE_NUMBERS + "*"}}]}]
})
}
catch(err){
console.log("Webhook Verification Failed")
//url = SLACK_MONITORING_URL;
//webhook = new IncomingWebhook(url)
//webhook.send({
//text: "*Nessus Webhook Verification, please investigate broken webhooks:*",
//attachments: [{color: "#FF0000", blocks: [{type: "section",text: {type: "mrkdwn",text: SLACK_WEBHOOK_URL}}]}]
//})
}
}

Categories