How to fix cannot read property "send" of undefined - javascript

This question might have a few duplicates, but the code there is different and none of the answers work for me. I'm new to discord.js so it might just be a silly mistake.
This is my code -
var Discord = require('discord.io');
var logger = require('winston');
var auth = require('./auth.json');
// Configure logger settings
logger.remove(logger.transports.Console);
logger.add(new logger.transports.Console, {
colorize: true
});
logger.level = 'debug';
// Initialize Discord Bot
var bot = new Discord.Client({
token: auth.token,
autorun: true
});
bot.on('ready', function (evt) {
logger.info('Connected');
logger.info('Logged in as: ');
logger.info(bot.username + ' - (' + bot.id + ')');
});
client.on('message', function(message) {
if (message.startsWith('^')) { //condition is false, even though message starts with ^
if (message.startsWith('^ping')) {
message.mentions.users.forEach((k, v) => {
message.channel.send('Hello,' + v + '!');
});
} else if (message.startsWith('^dice')) {
message.channel.send('You rolled a a' + Math.floor((Math.random() * 100) + 1) + "!");
} else {
message.channel.send("Command not found.");
}
} else {
message.channel.send("debug") //error in this line
}
});
I really don't know how to fix this, so all the solutions I have tried lead to this error.
Also if you see any other fixes to this code please point it out. Here is the error:
message.channel.send("debug")
^
TypeError: Cannot read property 'send' of undefined
at DiscordClient.<anonymous> (C:\Users\user\Documents\UltraBot\bot.js:32:25)
at DiscordClient.emit (events.js:315:20)
at DiscordClient.handleWSMessage (C:\Users\user\Documents\UltraBot\node_modules\discord.io\lib\index.js:1854:11)
at WebSocket.emit (events.js:315:20)
at Receiver.ontext (C:\Users\user\Documents\UltraBot\node_modules\ws\lib\WebSocket.js:841:10)
at C:\Users\user\Documents\UltraBot\node_modules\ws\lib\Receiver.js:536:18
at Receiver.applyExtensions (C:\Users\user\Documents\UltraBot\node_modules\ws\lib\Receiver.js:371:5)
at C:\Users\user\Documents\UltraBot\node_modules\ws\lib\Receiver.js:508:14
at Receiver.flush (C:\Users\user\Documents\UltraBot\node_modules\ws\lib\Receiver.js:347:3)
at Receiver.finish (C:\Users\user\Documents\UltraBot\node_modules\ws\lib\Receiver.js:541:12)

The problem is that you are using code for Discord.js, while using the Discord.io package. The ways that you send and receive messages is vastly different. I suggest that you switch to discord.js, as that is what you are writing the code to work for.

Related

Discord.js | guild.iconURL not working in embed

I've been trying to show the server's icon in the serverinfo embed, but it won't show up.
var serverIcon = message.guild.iconURL;
const serverInfoEmbed = new Discord.MessageEmbed()
.setTitle('server info')
.setColor(0x348a58)
.addField('owner', message.guild.owner, true)
.addField('name', '`' + message.guild.name + '`', true)
.addField('members', '`' + message.guild.memberCount + '`', true)
.setThumbnail(serverIcon)
.setFooter('very bootiful server');
setTimeout(() => { message.channel.send(serverInfoEmbed) }, 200);
console.log(serverIcon);
in the console, it says:
[Function: iconURL]
I tried to put it directly as the thumbnail .setThumbnail(message.guild.iconURL) but it still didn't work.
It's because guild.iconURL() is a function, and you would need to replace your line :
var serverIcon = message.guild.iconURL;
with :
var serverIcon = message.guild.iconURL();
I also suggest you to read the docs for more info :)

Discord.js error = "message is not defined"

const Discord = require('discord.js');
exports.run = async (bot, message, args) => {
let userInfMent = message.guild.member(message.mentions.users.first() || message.guild.members.get(args[0]))
message.channel.send(userInfo(userInfMent));
}
function userInfo(user) {
const Discord = require('discord.js');
let userInfMent = message.guild.member(message.mentions.users.first() || message.guild.members.get(args[0]))
var userCreated = userInfMent.createdAt.toString().split(' ');
var lastMsg = userInfMent.lastMessage.createdAt.toString().split(' ')
const userInfoEmbed = new Discord.RichEmbed()
.addField('Никнейм: ', userInfMent.username)
.addField('Тег: ', userInfMent.tag)
.addField('ID: ', userInfMent.id)
.addField('Аккаунт был создан: ', userCreated[1] + ', ' + userCreated[2] + ', ' + userCreated[3])
.addField('Последнее сообщение: ', userInfMent.lastMessage + ' в ' + lastMsg[1] + ', ' + lastMsg[2] + ', ' + lastMsg[3] + ', ' + lastMsg[4])
.addField('Статус: ', userInfMent.presence.status)
.setColor('RANDOM')
.setThumbnail(userInfMent.avatarURL);
return userInfoEmbed
}
Hi. I'm a Node.js beginner.
When i start the command, in console i see the error:
(node:6312) UnhandledPromiseRejectionWarning: ReferenceError: message
is not defined
at userInfo (C:\Users\deris\Desktop\Проекты\Node.js\discord.js\JSBot-master\commands\userinfo.js:10:23)
at Object.exports.run (C:\Users\deris\Desktop\Проекты\Node.js\discord.js\JSBot-master\commands\userinfo.js:5:26)
message is only defined in the message event itself. So you can simply pass the message object as a parameter into your function.
// new function
function userInfo(user, message) {
//code here
}
Just remember that you'll have to add the additional parameter when you call the function.
message.channel.send(userInfo(userInfMent, message));
Message is not defined because you did not put the code in a Message Event.
I just been learning and found this one out.
Message.channel.send will not work inside a function. The function will read it as a variable. And since message hasn't been defined we draw the error.
outside the function the command will again work fine. I'm not sure if it's an error with the current builds or intentional. But there is your fix
Your using message.guild.member inside of the function and didn't define member which is causing the problem. Consider placing the function inside of the export

How do I send a file using a discord bot?

This is currently my bot.js
var Discord = require('discord.io');
var logger = require('winston');
var auth = require('./auth.json');
// Configure logger settings
logger.remove(logger.transports.Console);
logger.add(logger.transports.Console, {
colorize: true
});
logger.level = 'debug';
// Initialize Discord Bot
var bot = new Discord.Client({
token: auth.token,
autorun: true
});
bot.on('ready', function (evt) {
logger.info('Connected');
logger.info('Logged in as: ');
logger.info(bot.username + ' - (' + bot.id + ')');
});
bot.on('message', function (user, userID, channelID, message, evt) {
// Our bot needs to know if it will execute a command
// It will listen for messages that will start with `!`
if (message.substring(0, 1) == ';') {
var args = message.substring(1).split(' ');
var cmd = args[0];
args = args.splice(1);
console.info(cmd);
switch(cmd) {
// !ping
case 'killerbean':
// bot.sendFile({
// to: channelID,
// files: ['./emojis/killerbean.png']
// });
logger.info(bot.channels);
User.sendFile('./emojis/killerbean.png');
//bot.channels[0].send('', new Discord.Attachment( './emojis/killerbean.png'));
break;
// Just add any case commands if you want to..
}
}
});
The commented code is some stuff that I tried that hasn't worked. bot.sendFile is apparently not a method. I'm currently looking at using User.send, but I cannot figure out how to use it.
How do I go about sending an image when someone types in the command ';killerbean'
Edit: Throwing in the package.json in case the dependencies or anything else there matters
{
"name": "emoji-bot",
"version": "1.0",
"description": "Emojis+",
"main": "bot.js",
"author": "Joshua",
"dependencies": {
"discord-irc": "^2.5.1",
"discord.io": "github:woor/discord.io#gateway_v6",
"winston": "^2.4.0"
}
}
The emoji-bot user is also called emoji-bot.
You're on the right track, but you should change two things:
Send attachments via a channel instance, if you want the image to show up in the same channel where the command ;killerbean was sent. You can get the channel from the sent message using message.channel.
Use .send instead of .sendFile. In the docs you can see that .sendFile is deprecated.
Here's how to send the image in the same channel where the command was sent (don't send an empty string '' in the first parameter):
message.channel.send(new Discord.Attachment('./emojis/killerbean.png', 'killerbean.png') )
.catch(console.error);
Also, your bot.on('message'... listener should only have one parameter - message (as seen in the example usage in the docs). I would be surprised if you don't run into errors with your many parameters (user, userID, channelID, message, evt).
So your final command should look something like this:
// ...
bot.on('message', function (message) {
// Our bot needs to know if it will execute a command
// It will listen for messages that will start with `!`
if (message.substring(0, 1) == ';') {
var args = message.substring(1).split(' ');
var cmd = args[0];
args = args.splice(1);
switch(cmd) {
case 'killerbean':
message.channel.send(new Discord.Attachment('./emojis/killerbean.png', 'killerbean.png') )
.then(msg => {
// do something after message sends, if you want
})
.catch(console.error);
break;
}
}
});
Edit: The discord.io tag had not been added to the question when I added this answer. Now I know the old syntax was allowed, but the syntax in my answer works for basic discord.js code.
bot.sendFile({
to: channelID,
file: "killerbean.png"
})

Why is bot undefined?

I am developing a Discord bot using the Discord.js API. So far so good, but I thought it would be nice to have the newest post on a relevant subreddit be announced in the chat by my bot every couple of minutes. Now I have managed to make the script pull the relevant data out of the Reddit JSON API, but this error is thrown:
TypeError: Cannot read property 'sendMessage' of undefined
at /data/app/app.js:810:7
at Array.forEach (native)
at IncomingMessage.<anonymous> (/data/app/app.js:808:36)
at emitNone (events.js:72:20)
at IncomingMessage.emit (events.js:166:7)
at endReadableNT (_stream_readable.js:913:12)
at nextTickCallbackWith2Args (node.js:442:9)
at process._tickCallback (node.js:356:17)
/data/app/app.js:810
bot.sendMessage(channel,"https://www.reddit.com" + child.data.permalink);
This is my code:
var Discord = require("discord.js");
var bot = new Discord.Client();
var redditSubModule = "pics";
function getRedditPosts(bot, msg) {
var url = "http://www.reddit.com/r/" + redditSubModule + "/new/.json?limit=2";
var request = http.get(url, function(response) {
var json = "";
response.on("data", function(chunk) {
json += chunk;
});
response.on("end", function() {
var redditResponse = JSON.parse(json);
redditResponse.data.children.forEach(function(child) {
console.log("https://www.reddit.com" + child.data.permalink);
bot.sendMessage(msg.channel,"https://www.reddit.com" + child.data.permalink);
});
});
});
request.on("error", function(err) {
console.log(err);
});
setTimeout(getRedditPosts, 60000);
}
getRedditPosts();
Why is bot undefined?
It seems like you're expecting getRedditPosts to be called with attributes (bot, msg), but you are calling it with no attributes getRedditPosts();
So basically you are passing undefined as the bot variable.
undefined has no functions on it and you are trying to call sendMessage
and that is the meaning of Cannot read property 'sendMessage' of undefined
You will also need to call the function getRedditPosts() when a user runs a command. Something like:
bot.on('message', (msg)=>{
if(message.content.toLowerCase().startsWith("!redditcommand")) {
getRedditPosts(msg.client, msg)
}
}
At the end of your code in place of the getRedditPosts(); should do the trick.

Javascript Chrome API- cannot read property of undefined

I'm writing a little javascript application trying to use the Chrome sockets API. The code doesn't seem terribly relevant, though, because I'm getting an error on the very first line:
var socket = chrome.sockets.udp;
On that line, I get an Uncaught TypeError: cannot read property 'udp' of undefined. So chrome.sockets isn't being defined for some reason, but for the life of me I can't seem to figure out what. Is there something I need to include or import to use Chrome APIs? The API doc hasn't been helpful in that regard.
EDIT: background.js file:
var socket = chrome.sockets.udp;
var PORT = 5005;
var HOST = '127.0.0.1';
var sockInfo;
chrome.app.runtime.onLaunched.addListener(function() {
chrome.app.window.create('window.html', {
'bounds': {
'width': 400,
'height': 500
}
});
init();
});
function init(){
socket.create({}, function(_sockInfo){
sockInfo = _sockInfo;
socket.bind(sockInfo.socketId, HOST, PORT, function(result){
if(result < 0){
throw "Bind failed"
}
console.log("Socket created and bound.");
socket.onReceive.addListener(function(info){
console.log('Received packet from ' + info.remoteAddress +
' : ' + info.remotePort + ', length ' + info.data.length);
});
});
});
}

Categories