I am currently trying to script that when a person sends a message to a specific channel, that message is then automatically converted to an embed. For me the conversion works the first time but not the second time. I'm always getting an error after the messages was converted.
My Script:
const channel = "905504402276765766";
if(channel.includes(message.channel.id))
var test = message.content.slice(" ")
const tryembed = new Discord.MessageEmbed()
.setColor('DARK_RED')
.setTitle('Test')
.addFields(
{name: "Person who wants to report a bug:", value: `<#!${message.author.id}>`},
{name: "Bug that was reported:", value: test}
)
message.channel.send({embeds: [tryembed]})
message.delete()
My error Code:
C:\Discord Bots\Bot v13\node_modules\discord.js\src\util\Util.js:414
if (!allowEmpty && data.length === 0) throw new error(errorMessage);
^
RangeError [EMBED_FIELD_VALUE]: MessageEmbed field values must be non-empty strings.
at Function.verifyString (C:\Discord Bots\Bot v13\node_modules\discord.js\src\util\Util.js:414:49)
at Function.normalizeField (C:\Discord Bots\Bot v13\node_modules\discord.js\src\structures\MessageEmbed.js:441:19)
at C:\Discord Bots\Bot v13\node_modules\discord.js\src\structures\MessageEmbed.js:462:14
at Array.map (<anonymous>)
at Function.normalizeFields (C:\Discord Bots\Bot v13\node_modules\discord.js\src\structures\MessageEmbed.js:461:8)
at MessageEmbed.addFields (C:\Discord Bots\Bot v13\node_modules\discord.js\src\structures\MessageEmbed.js:283:42)
at Client.<anonymous> (C:\Discord Bots\Bot v13\index.js:44:2)
at Client.emit (node:events:394:28)
at MessageCreateAction.handle (C:\Discord Bots\Bot v13\node_modules\discord.js\src\client\actions\MessageCreate.js:23:14)
at Object.module.exports [as MESSAGE_CREATE] (C:\Discord Bots\Bot v13\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32) {
[Symbol(code)]: 'EMBED_FIELD_VALUE'
}
Using value: `** ** ${test}` will solve your problem, so you need to change your {name: "Bug that was reported:", value: test} to:
{name: "Bug that was reported:", value: `** ** ${test}`}
Related
I'm having trouble making my bot filter messages and respond with a local file from my computer. Here is the code:
client.on("message", msg => {
console.log(msg.content);
let wordArray = msg.content.split(" ")
console.log(wordArray)
let filterWords = ['test']
for(var i = 0; i < filterWords.length; i++) {
if(wordArray.includes(filterWords[i])) {
msg.delete()
// Create the attachment using MessageAttachment
const attachment = new MessageAttachment('cbcfilter.png');
msg.channel.send(attachment)
}
}
});
It gives me this error message:
ReferenceError: MessageAttachment is not defined
at Client.<anonymous> (/Users/DShirriff/cbcbot/bot.js:108:26)
at Client.emit (events.js:323:22)
at MessageCreateAction.handle (/Users/DShirriff/cbcbot/node_modules/discord.js/src/client/actions/MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (/Users/DShirriff/cbcbot/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (/Users/DShirriff/cbcbot/node_modules/discord.js/src/client/websocket/WebSocketManager.js:386:31)
at WebSocketShard.onPacket (/Users/DShirriff/cbcbot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:435:22)
at WebSocketShard.onMessage (/Users/DShirriff/cbcbot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:293:10)
at WebSocket.onMessage (/Users/DShirriff/cbcbot/node_modules/ws/lib/event-target.js:120:16)
at WebSocket.emit (events.js:311:20)
at Receiver.receiverOnMessage (/Users/DShirriff/cbcbot/node_modules/ws/lib/websocket.js:801:20)
Am I an idiot and missing a simple parentheses, or should I look for a different form of this line of code?
You need to import MessageAttachment.
If you're using require to import discord.js then you can do:
const Discord = require('discord.js')
const attachment = new Discord.MessageAttachment('cbcfilter.png');
If you're using import then you can do:
import { MessageAttachment } from 'discord.js'
const attachment = new MessageAttachment('cbcfilter.png');
Side note: you don't have to construct a MessageAttachment you can just do
msg.channel.send({files: ['cbcfilter.png']})
OR
msg.channel.send({
files: [{
attachment: 'entire/path/to/cbcfilter.png',
name: 'cbcfilter.png'
}]
})
This question already has an answer here:
How can I migrate my code to Discord.js v12 from v11?
(1 answer)
Closed 2 years ago.
I'm currently working on a Discord bot using discord.js for a server. While working on a command to display the server's information, I came across an error.
Here's the code:
const dateFormat = require('dateformat');
const Discord = require('discord.js');
const colors = require('../colors.json');
const date = new Date();
dateFormat(date, 'dddd, mmmm dS, yyyy, h:MM:ss TT');
exports.run = async (client, message, args, ops) => {
const millis = new Date().getTime() - message.guild.createdAt.getTime();
const days = millis / 1000 / 60 / 60 / 24;
const owner = message.guild.owner.user || {};
const verificationLevels = ['None ,(^.^),', 'Low ┬─┬ ノ( ゜-゜ノ)', 'Medium ヽ(ຈل͜ຈ)ノ︵ ┻━┻ ', 'High (╯°□°)╯︵ ┻━┻', 'Extreme ┻━┻彡 ヽ(ಠ益ಠ)ノ彡┻━┻'];
let embed = new Discord.MessageEmbed()
.setThumbnail(message.guild.iconURL)
.setFooter(`requested by ${message.author.username}#${message.author.discriminator}`, message.author.avatarURL)
.setColor(colors.cyan)
.addField('Server Name', message.guild.name, true)
.addField('Server ID', message.guild.id, true)
.addField('Owner',`${owner.username + "#" + owner.discriminator || '� Owner not found...'}`,true)
.addField('Owner ID', `${owner.id || '� Owner not found...'}`,true)
.addField('Created On',`${dateFormat(message.guild.createdAt)}`, true)
.addField('Days Since Creation', `${days.toFixed(0)}`, true)
.addField('Region',`${message.guild.region}`, true)
.addField('Verification Level',`${verificationLevels[message.guild.verificationLevel]}`,true)
.addField('Text Channels',`${message.guild.channels.filter(m => m.type === 'text').size}`,true)
.addField('Voice Channels',`${message.guild.channels.filter(m => m.type === 'voice').size}`,true)
.addField('Member Count',`${message.guild.members.filter(m => m.presence.status !== 'offline').size} / ${message.guild.memberCount}`, true)
.addField('Roles',`${message.guild.roles.size}`,true)
message.channel.send(embed);
}
And here's the error:
(node:17432) UnhandledPromiseRejectionWarning: TypeError: message.guild.channels.filter is not a function
at Object.exports.run (C:\Users\brigh\Desktop\XontavsBot\commands\serverinfo.js:29:73)
at Client.client.on (C:\Users\brigh\Desktop\XontavsBot\index.js:30:21)
at Client.emit (events.js:197:13)
at MessageCreateAction.handle (C:\Users\brigh\Desktop\XontavsBot\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (C:\Users\brigh\Desktop\XontavsBot\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (C:\Users\brigh\Desktop\XontavsBot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:386:31)
at WebSocketShard.onPacket (C:\Users\brigh\Desktop\XontavsBot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:435:22)
at WebSocketShard.onMessage (C:\Users\brigh\Desktop\XontavsBot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:293:10)
at WebSocket.onMessage (C:\Users\brigh\Desktop\XontavsBot\node_modules\ws\lib\event-target.js:120:16)
at WebSocket.emit (events.js:197:13)
(node:17432) 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:17432) [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.
If anybody knows what the problem is, please let me know.
In Discord.js v12, many things like Guild#channels got turned into a manager. Guild#channels is now a ChannelManager, so to get the collection of channels use message.guild.channels.cache. For example:
message.guild.channels.cache.filter(m => m.type === 'text').size
I'm trying to add a function to my discord bot xp-system by adding a user automatically to a role when hitting a certain level.
I have been trying all kind of solutions I can think of but none seem to work.
Have tried:
addrankup.addRole(fullmember).catch(console.error);
let addrankup.addRole(fullmember).catch(console.error);
addrankup.addRole(fullmember.id).catch(console.error);
Expected when users hit a set level to automatically get the rank:
let xpAdd = Math.floor(Math.random() * 5) + 10;
console.log(xpAdd);
if (!xp[message.author.username]) {
xp[message.author.username] = {
xp: 0,
level: 1
};
}
let curxp = xp[message.author.username].xp;
let curlvl = xp[message.author.username].level;
let nxtLvl = xp[message.author.username].level * 200;
xp[message.author.username].xp = curxp + xpAdd;
if (nxtLvl <= xp[message.author.username].xp) {
xp[message.author.username].level = curlvl + 1;
message.channel.send("Level Up!").then(msg => {
msg.delete(5000)
});
}
if (curlvl <= xp[message.author.username].level) {
xp[message.author.username].level = "2";
let addrankup = message.mentions.members.first();
let fullmember = message.guild.roles.find(`name`, "Full Member");
addrankup.addRole(fullmember.id).catch(console.error);
message.channel.send("You have received a new role!").then(msg => {
msg.delete(5000)
});
}
fs.writeFile("./xp.json", JSON.stringify(xp), (err) => {
if (err) console.log(err)
});
But instead this is what the console tells me:
(node:8460) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'addRole' of undefined
at Client.bot.on (E:\#DeathKillerNOR Discord Bots\DeathKillerBot\index.js:125:15)
at Client.emit (events.js:187:15)
at MessageCreateHandler.handle (E:\#DeathKillerNOR Discord Bots\DeathKillerBot\node_modules\discord.js\src\client\websocket\packets\handlers\MessageCreate.js:9:34)
at WebSocketPacketManager.handle (E:\#DeathKillerNOR Discord Bots\DeathKillerBot\node_modules\discord.js\src\client\websocket\packets\WebSocketPacketManager.js:103:65)
at WebSocketConnection.onPacket (E:\#DeathKillerNOR Discord Bots\DeathKillerBot\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:333:35)
at WebSocketConnection.onMessage (E:\#DeathKillerNOR Discord Bots\DeathKillerBot\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:296:17)
at WebSocket.onMessage (E:\#DeathKillerNOR Discord Bots\DeathKillerBot\node_modules\ws\lib\event-target.js:120:16)
at WebSocket.emit (events.js:182:13)
at Receiver._receiver.onmessage (E:\#DeathKillerNOR Discord Bots\DeathKillerBot\node_modules\ws\lib\websocket.js:137:47)
at Receiver.dataMessage (E:\#DeathKillerNOR Discord Bots\DeathKillerBot\node_modules\ws\lib\receiver.js:409:14)
(node:8460) 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:8460) [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.
The error tells you that addrankup is undefined which in turn means that message.mentions.members.first(); returns nothing. My guess is that instead of
let addrankup = message.mentions.members.first();
you're looking for
let addrankup = message.member;
I am working on mean stack application. I am using crypto for password encryption but it is throwing below error.
TypeError: Pass phrase must be a buffer
TypeError: Pass phrase must be a buffer
at pbkdf2 (crypto.js:702:20)
at Object.exports.pbkdf2Sync (crypto.js:687:10)
at model.userSchema.methods.setPassword (C:\CMT_Platform\server\models\user.model.js:24:24)
at Object.module.exports.register (C:\CMT_Platform\server\services\auth.service.js:16:13)
at exports.register (C:\CMT_Platform\server\controllers\auth.controller.js:22:39)
at Layer.handle [as handle_request] (C:\CMT_Platform\node_modules\express\lib\router\layer.js:95:5)
at next (C:\CMT_Platform\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\CMT_Platform\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\CMT_Platform\node_modules\express\lib\router\layer.js:95:5)
at C:\CMT_Platform\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\CMT_Platform\node_modules\express\lib\router\index.js:335:12)
at next (C:\CMT_Platform\node_modules\express\lib\router\index.js:275:10)
at Function.handle (C:\CMT_Platform\node_modules\express\lib\router\index.js:174:3)
at router (C:\CMT_Platform\node_modules\express\lib\router\index.js:47:12)
at Layer.handle [as handle_request] (C:\CMT_Platform\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\CMT_Platform\node_modules\express\lib\router\index.js:317:13) ::1
- - [11/Aug/2018:08:33:55 +0000] "POST /register HTTP/1.1" 400 42 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML,
like Gecko) Chrome/68.0.3440.106 Safari/537.36"
Code:
var custschema= new mongoose.Schema({
email: { type: String, unique: true, required: true },
name: { type: String, required: true },
role: { type: String },
hash: String,
salt: String
});
custschema.methods.setPassword = function(password) {
this.salt = crypto.randomBytes(16).toString('hex');
//this.hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64, 'sha512').toString('hex');
var buffer = new Buffer(this.salt, "binary");
console.log(this.salt);
console.log(buffer);
this.hash = crypto.pbkdf2Sync(password, buffer, 1000, 64, 'sha512').toString('hex');
};
custschema.methods.validPassword = function(password) {
//var hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64, 'sha512').toString('hex');
var hash = crypto.pbkdf2Sync(password, new Buffer(this.salt,'binary'), 1000, 64, 'sha512').toString('hex');
return this.hash === hash;
};
Can somebody please guide me or enlighten me whether they have face this issue or not. Let me know if you want any more details.
Thanks
crypto.pbkdf2Sync returns Buffer and you are storing in the string OR you can convert buffer to string and store.
You can change the hast type to the Buffer and try Check mongoose data types here
Client side code is as below
$scope.mbr= function(event){
var formdata = new FormData();
var reader = new FileReader();
var url = '/mbr_replace' ;
var upload_file = $(event.target[0].files[0];
formdata.append('mbrpdf',upload_file );
$http.post(url,formdata).success(function(response){alert("Got Response!!!!!!");
});
}
server side code is as below
app.post('/mbr_replace', isLoggedIn,upload.single('mbrpdf'),users.replace_pdf, maintain.userstudys, function(req,res){
res.send("Succeed !!!")
});
error
SyntaxError: Unexpected token -
at parse (D:\ManiKandan\Heta_Dev_3030\node_modules\body-parser\lib\types\json.js:82:15)
at D:\ManiKandan\Heta_Dev_3030\node_modules\body-parser\lib\read.js:116:18
at invokeCallback (D:\ManiKandan\Heta_Dev_3030\node_modules\raw-body\index.js:262:16)
at done (D:\ManiKandan\Heta_Dev_3030\node_modules\raw-body\index.js:251:7)
at IncomingMessage.onEnd (D:\ManiKandan\Heta_Dev_3030\node_modules\raw-body\index.js:307:7)
at emitNone (events.js:86:13)
at IncomingMessage.emit (events.js:185:7)
at endReadableNT (_stream_readable.js:974:12)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickDomainCallback (internal/process/next_tick.js:128:9)