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
Related
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.
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 :)
I'm attempting you Send Grid's NodeJS code in a CSHTML web page to use their mail send service. For some reason the setApiKey command is not working and does not even exist according to the error in the console. Any idea what I'm doing wrong here?
const sgMail = require(['##sendgrid/mail']);
sgMail.setApiKey('MYAPIKEY');
const msg = {
to: email_id.value,
from: send_email.value,
subject: 'Subject',
html: '<div>From: ' + send_first_name.value + ' ' + send_last_name.value + '</div><div>Email: ' + send_email.value + '</div><div>Message: ' + message + '</div>',
};
sgMail.send(msg).then((sent) => {
console.log('email sent');
})
And here are two of the error messages - Mismatched anonymous define() module and TypeError: sgMail.setApiKey is not a function
I am trying to integrate Coinbase with Node Js, but I am unable to execute the code given on the tutorial page. My code is
`var coinbase = require('coinbase');
var client = new coinbase.Client({'apiKey': mykey, 'apiSecret': mysecret});
client.getAccounts({}, function(err, accounts) {
accounts.forEach(function(acct) {
console.log('my bal: ' + acct.balance.amount + ' for ' + acct.name);
});
});`
I get t the following error:
accounts.forEach(account => {
^
typeError: Cannot read property 'forEach' of null
Looking forward to your answer! Thanks!
The error is clear: accounts is equal to null. You should check what's in err before working with accounts
hello you can use like this
client.getAccounts({}, function(err, accounts) {
accounts.forEach(function(acct) {
console.log(acct.name + ': ' + acct.balance.amount + ' ' + acct.id );
});
});
You could try with a different API keys and check if the keys are enabled.
var Client = require('coinbase').Client;
var client = new Client({
'apiKey': 'API KEY',
'apiSecret': 'API SECRET'
});
client.getAccounts({}, function (err, accounts) {
accounts.data.forEach(function (acct) {
console.log(acct.name + ': ' + acct.balance.amount + ' ' + acct.id);
});
});
Also accounts returns a lot of information but we are looking at the data block. Please refer the Coinbase API v2 documentation for complete sample response of the getAccounts() call - https://developers.coinbase.com/api/v2?javascript#account-resource
Let us know if this works. Good luck!
Just started using CoffeeScript and have hit a wall. In my code below I construct WebSocketServer with a number as the first argument and a function as the second argument. When the code is ran and the websocket receives a message, #msgHandler is now magically undefined. I tried to work around this by setting a variable handler to #msgHandler but that ended up being undefined as well. If anyone has any ideas I'd love to hear them, thanks!
main.coffee
#Used to communicate with browser interface
webSocketServ = new sio.WebSocketServer Sauce.Server.WebSocketPort, (data, socketId) ->
try
json = JSON.parse(data)
msgType = json.msgType
catch error
return
if (this.isAuthed(socketId))
switch msgType
when "auth"
else
io.websocket 'TODO: ' + cmd
else
if msgType is 'auth'
token = json.token
socket.coffee
class WebSocketServer
constructor: (#port, #msgHandler) ->
#webSockets = []
#handlers = {}
#test = []
#authedSockes = []
#listen(#port);
console.log #msgHandler #msgHandler is defined here as [ Function ]
listen: (port) ->
#wsServ = engine.listen port
#wsServ.on 'connection', #onConnect
io.socket "WebServer socket started on port #{port}"
onConnect: (client) ->
io.websocket 'New connection with id of ' + client.id
handler = #msgHandler ##msgHandler is undefined here?
client.on 'message', (data) ->
handler data, client.id
io.websocket '[' + this.id + '] ' + JSON.stringify(data)
client.on 'close', ->
io.websocket '[' + this.id + '] Disconnect'
client.on 'error', (err) ->
io.websocket "IO error: " + err
compiled socket.coffee
WebSocketServer = (function() {
function WebSocketServer(port, msgHandler) {
this.port = port;
this.msgHandler = msgHandler;
this.webSockets = [];
this.handlers = {};
this.test = [];
this.authedSockes = [];
this.listen(this.port);
console.log(this.msgHandler);
}
WebSocketServer.prototype.listen = function(port) {
this.wsServ = engine.listen(port);
this.wsServ.on('connection', this.onConnect);
return io.socket("WebServer socket started on port " + port);
};
WebSocketServer.prototype.onConnect = function(client) {
var handler;
io.websocket('New connection with id of ' + client.id);
handler = this.msgHandler;
client.on('message', function(data) {
handler(data, client.id);
return io.websocket('[' + this.id + '] ' + JSON.stringify(data));
});
client.on('close', function() {
return io.websocket('[' + this.id + '] Disconnect');
});
return client.on('error', function(err) {
return io.websocket("IO error: " + err);
});
};
WebSocketServer.prototype.isAuthed = function(socketId) {
return __indexOf.call(this.authedSockets, user) >= 0;
};
WebSocketServer.prototype.authSocket = function(socketId) {
this.authedSockets.push(socketId);
return io.websocket('Authed socket with ID of ' + socketId);
};
WebSocketServer.prototype.deauthSocket = function(socketId) {
return this.authedSockets = this.authedSockets.filter(function(word) {
return word !== socketId;
});
};
return WebSocketServer;
})();
It's not an undefined class variable, you mean that you cannot access an instance property. It's caused by the common this context issue in callbacks - you cannot just pass a method and expect it to know the instance.
Fortunately, this can be trivially fixed in CS using the fat arrow syntax for the method definition and other callbacks:
onConnect: (client) =>
# ^^
io.websocket 'New connection with id of ' + client.id
handler = #msgHandler # # is now the expected instance
client.on 'message', (data) =>
# ^^
handler data, client.id
io.websocket '[' + #id + '] ' + JSON.stringify(data)
# ^ or did you mean to use `client.` here?
client.on 'close', =>
# ^^
io.websocket '[' + #id + '] Disconnect'
client.on 'error', (err) ->
io.websocket "IO error: " + err
A different (and possibly better) approach might be to let your WebSocketServer class inherit from the engine's class, instead of building a wrapper around it. Since all callbacks are called on the server instance usually, you could access your properties directly without needing to bind the callbacks.