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
Related
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');
})
...
So I made this kick command and I finished coding it. Now I am getting this error and have literally no idea how to fix it. I searched through the internet for an hour now and have still no idea where the issue is.
Here is the error:
TypeError: options.getMember is not a function
at Object.execute (/Users/Aplex/Documents/Aplel/Commands/Moderation/kick.js:32:32)
at Object.execute (/Users/Aplex/Documents/Aplel/Events/Interaction/interactionCreate.js:21:21)
at Client.<anonymous> (/Users/Aplex/Documents/Aplel/Structures/Handlers/Events.js:18:54)
at Client.emit (node:events:538:35)
at InteractionCreateAction.handle (/Users/Aplex/Documents/Aplel/node_modules/discord.js/src/client/actions/InteractionCreate.js:74:12)
at Object.module.exports [as INTERACTION_CREATE] (/Users/Aplex/Documents/Aplel/node_modules/discord.js/src/client/websocket/handlers/INTERACTION_CREATE.js:4:36)
at WebSocketManager.handlePacket (/Users/Aplex/Documents/Aplel/node_modules/discord.js/src/client/websocket/WebSocketManager.js:351:31)
at WebSocketShard.onPacket (/Users/Aplex/Documents/Aplel/node_modules/discord.js/src/client/websocket/WebSocketShard.js:444:22)
at WebSocketShard.onMessage (/Users/Aplex/Documents/Aplel/node_modules/discord.js/src/client/websocket/WebSocketShard.js:301:10)
at WebSocket.onMessage (/Users/Aplex/Documents/Aplel/node_modules/ws/lib/event-target.js:199:18)
And here is my code:
const { Client, CommandInteraction } = require("discord.js");
module.exports = {
name: "kick",
description: "Kick a member",
userPermission: ["KICK_MEMBERS"],
options: [
{
name: "target",
description: "target to kick",
type: "USER",
required: true
},
{
name: "reason",
description: "reason for this kick",
type: "STRING",
required: false,
}
],
/**
*
* #param {Client} client
* #param {CommandInteraction} interaction
* #param {String} args
*/
execute: async(client, interaction, args) => {
const { options, member } = interaction;
const target = options.getMember("target");
const reason = options.getString("reason") || "No reason provided";
if(!target.roles.highest.position >= member.roles.highest.position) return interaction.followUp({content: "You can't take action on this user as their role is higher than yours!",
});
await target.send(`You have been kicked from ${interaction.guild.name}, reason ${reason}`);
target.kick(reason);
interaction.followUp({content: `Kicked ${target.user.tag} successfully! reason: ${reason}`});
},
};
Anyone know where the issue is here? It would be really appreciated if someone helped!
can I assume you are following lyxcode tutorials?
If so, in the line
execute(client, interaction, args)
change it to
execute(interaction, client, args)
this should then match your interactionCreate file.
also, change followUp to reply
hopefully this fixes it for you!
If you are trying to get the member's account cache, maybe you should try something like this:
client.members.cache.get('User ID');
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.
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,
},
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}}]}]
//})
}
}