Logging messages from one channel - javascript

I've tried several times to work this and I don't understand the error, I am receiving but I'll explain what I'm trying to do: Basically I want to log the messages from one channel and paste those messages onto a different channel. Here is the code I have so far;
client.on(`message`, message => {
if (message.author.bot) return; // If the message is by a bot return.
if (!message.guild) return; // If the message isn't in a guild return.
if (message.guild) {
const msgLog = `[MESSAGE] [${message.guild.name}] [#${message.channel.name}] ${message.author.username}#${message.author.discriminator}: ${message.content}\n` // You can change this to whatever you want.
client.channels.get(`814685640088223795`).send(msgLog); // Replace CHANNEL ID with the channel ID you want the logs to go to.
return;
}
})
The error I am receiving goes as follows:
(node:17260) UnhandledPromiseRejectionWarning: ReferenceError: client is not defined
at Object.<anonymous> (D:\stuff\S1 Discord Bot\s1-bot\src\events\message\message.js:1:1)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Module.require (internal/modules/cjs/loader.js:952:19)
at require (internal/modules/cjs/helpers.js:88:18)
at registerEvents (D:\stuff\S1 Discord Bot\s1-bot\src\utils\registry.js:33:21)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:17260) 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:17260) [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.
Thanks

You are missing this from your index file:
const Discord = require("discord.js");
//under const Discord etc
const client = new Discord.Client();
If you are trying to only allow guildMessages, you do it like this:
if (message.channel.type === "dm") return; //dont react to dms
Finally, to send a message to a channel by id:
message.guild.channels.cache.get('814685640088223795').send(msglog); //using 'cache' since v12 uses managers

You seem to be missing two important lines of code:
const Discord = require('discord.js');
const client = new Discord.Client();
Appending these two lines from the discord.js documentation in the beginning of your index.js file should make it work.

Related

Weird Error When My Discord Mod Tried Banning Someone with discord.js

so I just joined Stack Overflow but I have a problem with my discord.js bot.
My Moderator Tried Banning Someone with my bot and A error came up in my console. And he didn't get banned. (node:5420) UnhandledPromiseRejectionWarning: DiscordAPIError: Missing Permissions at RequestHandler.execute (C:\Users\i7pc\node_modules\discord.js\src\rest\RequestHandler.js:170:25) at processTicksAndRejections (internal/process/task_queues.js:93:5) (Use `node --trace-warnings ...` to show where the warning was created) (node:5420) 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:5420) [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.
Edit: My Code Is
module.exports = {
name: 'ban',
description: "Damn, some people are idiots",
execute(message, args){
const target = message.mentions.users.first();
if(target){
const memberTarget = message.guild.members.cache.get(target.id);
memberTarget.ban();
message.channel.send("User has been banned by Fish Bot");
}else{
message.channel.send(`Fish Bot coudn't ban that member!`);
}
}
}
If you read the first line from the end it says Missing Permissions which means that your discord bot does not have the permission to ban/kick anyone.

Making a new channel discord.js v11.3

I'm trying to make a ticket bot, but I'm not sure what is wrong with my !new command. Please help. I'm using what discord has in their docs The code is below.
const Discord = require('discord.js');
module.exports.run = async (bot, message, args) => {
message.react('✅');
let modrole = message.guild.roles.cache.find(r => r.name === 'Staff');
if (!modrole) {
console.log('Err: ModRole Not Found');
}
message.reply(`${message.author.username}#${message.author.discriminator}`);
message.guild.createChannel(`${message.author.username}#${message.author.discriminator}`, {
parent: '',
topic: message.author.id,
type: '',
permissionOverwrites: [
{ id: message.guild.id, deny: ['VIEW_CHANNEL'] },
{ id: modrole.id, allow: ['VIEW_CHANNEL', 'SEND_MESSAGES'] },
{ id: message.author.id, allow: ['VIEW_CHANNEL', 'SEND_MESSAGES'] }
]
}).then(c => {
message.reply(`, <#Staff>`)
const embed = new Discord.message.embed()
.setTitle('**New Ticket**')
.setDescription(`Thank you for opening a ticket *<#${message.author.id}>, a staff member will be with you shortly!`)
})
}
//name this whatever the command name is.
module.exports.help = {
name: "new"
}
These are the errors:
(node:1664) UnhandledPromiseRejectionWarning: TypeError: message.guild.createChannel is not a function
at Object.module.exports.run (C:\Users\8fwbu\Desktop\CodeTProj\Molten Dev\commands\new.js:20:19)
at Client.<anonymous> (C:\Users\8fwbu\Desktop\CodeTProj\Molten Dev\main.js:42:31)
at Client.emit (events.js:315:20)
at MessageCreateAction.handle (C:\Users\8fwbu\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (C:\Users\8fwbu\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (C:\Users\8fwbu\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:31)
at WebSocketShard.onPacket (C:\Users\8fwbu\node_modules\discord.js\src\client\websocket\WebSocketShard.js:444:22)
at WebSocketShard.onMessage (C:\Users\8fwbu\node_modules\discord.js\src\client\websocket\WebSocketShard.js:301:10)
at WebSocket.onMessage (C:\Users\8fwbu\node_modules\ws\lib\event-target.js:132:16)
at WebSocket.emit (events.js:315:20)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:1664) 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:1664) [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.
Chances are you're not running Discord.js V11. If you installed Discord.js using the following command (Or updated it using the same command)
npm install discord.js
You're working on Discord.js V12. In Discord.js V12, <Guild>.createChannel is not a function. Instead, you'll use <Guild>.channels.create(). If you wish to return to Discord.js V11, you can use this command. This will overwrite the current Discord.js package with the most recent Discord.js V11 update.
npm install discord.js#11
The #11 indicates that you want V11, not V12.
Additionally, I would like to point out that putting a hashtag (#) in the title is not recommended or allowed by Discord. The channel will be created, except the hashtag will be excluded from the channel name which will result in something like this: User#0000 => #user0000. Also keep in mind that certain unicode characters are prohibited from Discord and will not be accepted.

How to handle the unhandelable errors?

I'm facing a problem with error handling in NodeJS,
While I was testing an application that I made, I noticed that if I passed undefined by mistake to the mongoose.connect() it will give you an error, unfortunately, this error is not being caught by the callback function, not either by try & catch blocks:
const envVariable = undefined;
try {
mongoose.connect(envVariable, (err) => {
if (err) return console.log("There was an error");
console.log("success");
});
} catch (error) {
console.log("Hah! I caught you");
}
You see the error is not being caught, see the output:
(node:36807) UnhandledPromiseRejectionWarning: MongooseError: The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()` is a string.
at NativeConnection.Connection.openUri (.../nodeJS/tests/node_modules/mongoose/lib/connection.js:680:11)
at .../nodeJS/tests/node_modules/mongoose/lib/index.js:345:10
at .../nodeJS/tests/node_modules/mongoose/lib/helpers/promiseOrCallback.js:31:5
at new Promise (<anonymous>)
at promiseOrCallback (.../nodeJS/tests/node_modules/mongoose/lib/helpers/promiseOrCallback.js:30:10)
at Mongoose._promiseOrCallback (.../nodeJS/tests/node_modules/mongoose/lib/index.js:1135:10)
at Mongoose.connect (.../nodeJS/tests/node_modules/mongoose/lib/index.js:344:20)
at Object.<anonymous> (.../nodeJS/tests/server.js:8:12)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
at internal/main/run_main_module.js:17:47
(Use `node --trace-warnings ...` to show where the warning was created)
(node:36807) 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:36807) [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.
I've faced these kinds of problems many times in my application, but this time I caught one here to open the discussion, how can I stop these kinds of errors to show in my face? and instead, handle them in a nice way?
handle = to catch when this problem happens, and to send a nice response to the client that there was a problem from the server side.
The moongoose.connect function takes the callback as its third argument, after connection string and options object. It returns a promise, which is getting rejected on the error, but you are never handling that.
The proper syntax is either
try {
await mongoose.connect(envVariable);
console.log("success");
} catch (error) {
console.log("Hah! I caught you");
}
or
mongoose.connect(envVariable).then(() => {
console.log("success");
}, (err) => {
console.log("Hah! I caught you");
});

Error with Heroku/Discord.js "Service Unavailable"

I found a weird error when trying to start my discord bot on heroku. So, earlier I decided to make a command handler for my bot so I can store commands in separate files, but I had several errors in the code. After posting a question here, one member helped me fix every single error that I got, but then I got a very unusual error that I have no idea what it means.
Here's the heroku log:
2020-11-09T15:09:58.846760+00:00 app[worker.1]: (node:4) UnhandledPromiseRejectionWarning: Response: Service Unavailable
2020-11-09T15:09:58.846780+00:00 app[worker.1]: at RequestHandler.execute (/app/node_modules/discord.js/src/rest/RequestHandler.js:161:15)
2020-11-09T15:09:58.846780+00:00 app[worker.1]: at processTicksAndRejections (internal/process/task_queues.js:97:5)
2020-11-09T15:09:58.846781+00:00 app[worker.1]: at async RequestHandler.push (/app/node_modules/discord.js/src/rest/RequestHandler.js:39:14)
2020-11-09T15:09:58.847016+00:00 app[worker.1]: (node:4) 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)
2020-11-09T15:09:58.847172+00:00 app[worker.1]: (node:4) [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's the "index.js":
const Discord = require('discord.js');
const { Client, Collection } = require ('discord.js');
const client = new Discord.Client();
const token = 'TOKEN';
const PREFIX = '-';
const fs = require('fs');
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
for(const file of commandFiles){
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
client.on('ready', () =>{
console.log('This bot is online');
})
client.on('message', message=>{
let args = message.content.substring(PREFIX.length).split(" ")
switch(args[0]){
case 'help':
client.commands.get('help').execute(message, args);
}
})
client.login(token);
And "help.js" within my "commands" folder:
const Discord = require('discord.js');
module.exports = {
name: 'help',
execute(message, args){
const embed = new Discord.MessageEmbed()
.setTitle(':scroll: │ Help List')
.addField("Here is a list of commands:\n\n', '$save [name] ➝ Saves the current server template \n $load [link] ➝ Loads a template via link \n $cc [name] ➝ Creates a channel \n $dc [name] ➝ Deletes a channel \n $config [name]➝ Changes the server's name \n $mod [name] ➝ Adds/Removes the member from the moderator role \n $admin [name] ➝ Adds/Removes someone from the admin list")
message.channel.send(embed)
}
}
I do not understand what this error comes from and it has no additional information. I restarted my dynos several times and also checked the status page of heroku, but everything seems file.
Any ideas on how to fix it?
Discord had a pretty bad incident yesterday, which made it unavailable for most people.
Give it a try again today, it should work normally :)

I Got A "UnhandledPromiseRejectionWarning" And A "DeprecationWarning" When Trying To Run The Code For The Bot, Any Solution To Fix This Problem?

Im Trying To Make A Discord Bot For A Server, I Entered "node ." into the terminal to run the bot and i got this error:
(node:17632) UnhandledPromiseRejectionWarning: Error: Incorrect login details were provided.
at WebSocketConnection.<anonymous> (C:\Users\Thela\code\node_modules\discord.js\src\client\ClientManager.js:48:41)
at Object.onceWrapper (events.js:300:26)
at WebSocketConnection.emit (events.js:210:5)
at WebSocketConnection.onClose (C:\Users\Thela\code\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:390:10)
at WebSocket.onClose (C:\Users\Thela\code\node_modules\ws\lib\event-target.js:124:16)
at WebSocket.emit (events.js:210:5)
at WebSocket.emitClose (C:\Users\Thela\code\node_modules\ws\lib\websocket.js:191:10)
at TLSSocket.socketOnClose (C:\Users\Thela\code\node_modules\ws\lib\websocket.js:850:15)
at TLSSocket.emit (events.js:215:7)
at net.js:658:12
(node:17632) 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:17632) [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 Terminal.
This Is The index.js file:
const Discord = require('discord.js');
const config = require('./config.json');
const client = new Discord.Client();
client.once('ready', () => {
console.log('Ready!');
});
client.on('message', message => {
if (message.content === '!ping') {
message.channel.send('Pong.');
}
});
client.login(config.token);
And Here Is The config.json:
{
"prefix": "!",
"token": "7F2x4ct0AMuBeJKZUGmtIz_RZVKve-N4"
}
i realised i didnt put the full error
oops
What you are using as "token" is actually your client secret, the token should look something like this:
NjQwOTM2MjE3MTg5Mjg1ODg4.XcGSOQ.3dgX4GbvEDZKYHnCb6nJORuvL1w

Categories