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'
}]
})
Related
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}`}
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
Whenever I use my checkwarns command to check the number of warns a user has it gives me this error:
2019-03-20T23:55:35.590941+00:00 app[worker.1]: (node:4)
UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'warns' of
undefined
2019-03-20T23:55:35.590958+00:00 app[worker.1]: at
Object.module.exports.run (/app/commands/checkwarns.js:10:35)
I don't know how to fix this I can't find any problems with my code.
const Discord = require("discord.js");
const fs = require("fs");
const ms = require("ms");
let warns = JSON.parse(fs.readFileSync("./warnings.json", "utf8"));
module.exports.run = async(bot, message, args) => {
if (!message.member.hasPermission("MANAGE_MESSAGES")) return
message.reply("You don't have permssion to use this command");
let wUser = message.guild.member(message.mentions.users.first()) ||
message.guild.members.get(args[0])
if (!wUser) return message.reply("Couldn't find that user");
let warnlevel = warns[wUser.id].warns;
if (!warns[wUser.id]) warns[wUser.id] = {
warns: 0
};
message.delete().catch();
let warnembed = new Discord.RichEmbed()
.setTitle("**warns**")
.setColor("#0xff80ff")
.addField("User Warns", warnlevel, true);
message.channel.send(warnembed);
}
module.exports.help = {
name: "checkwarns"
}
I'm using Heroku to host the bot.
Your issue might be occuring here:
let warnlevel = warns[wUser.id].warns;
If the key wUser.id doesn't exist, the value of warns[wUser.id] would be undefined, which doesn't contain any user-defined properties. Hence, you get an error trying to read the value of warns (a user-defined property) in undefined.
To get around this, you want to check whether an object at warns[wUser.id] actually exists first. An easy way to do this is by doing the following:
var warnLevel;
if (warns[wUser.id] != undefined) {
warnLevel = warns[wUser.id].warns
}
else {
// Do something else to initialize either warnLevel or warns[wUser.id] here
}
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;
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)