Discord.js | guild.iconURL not working in embed - javascript

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 :)

Related

Uncaught (in promise) TypeError: s.createConnection is not a function at n.register.c.connect

I'm currently tring to exploit a RSS feed to get latest articles from a website.
What I'm doing is to store these data in a MySQL DB. I do that with Javascript, to take informations from the RSS feed.
When I host the script on my server, it's not working anymore.
For the context of programming, on local, I used XAMPP, with a localhost. Then, I do a parcel build, the script being attached to a HTML page, so that I can call it just by loading the WebPage.
I got the error from the title :
Here is the code :
let Parser = require('rss-parser');
let parser = new Parser();
(async () => {
// Connecting to database
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'dataarticles'
});
connection.connect((err) => {
if (err) throw err;
console.log('Connected!');
});
let feed = await parser.parseURL('http://feedrinse.com/services/rinse/?rinsedurl=235e4f5244e1eeb21ce05fc3d4d68cc0');
//== Some console.log to check
// console.log(feed.items[0]['content:encoded']);
//== Some console.log to check
// console.log(feed.items[0].title + "\n"
// + feed.items[0].link + "\n"
// + feed.items[0].contentSnippet + "\n"
// + feed.items[0].pubDate);
// As the feed doesn't provide the minia of article, I take the first image in the content of the test, by searching it
let firstPos = feed.items[0]['content:encoded'].search("https://droidsoft.fr/wp-content/uploads/");
let SecondPos = feed.items[0]['content:encoded'].search('alt="');
let image = feed.items[0]['content:encoded'].substring(firstPos, SecondPos - 2);
let pubDate = feed.items[0].pubDate.substring(5, 16);
//== Some console.log to check
// console.log(image);
// console.log(pubDate);
// We take first item (items[0]) as it's the latest feed. This script is triggered only when there is a new element, so there shouldn't be
// any problem of duplication
connection.query('INSERT INTO `dataarticles` (`Titre`, `URL`, `Description`, `Image`, `date`) VALUES ("' + feed.items[0].title + '", "' + feed.items[0].link + '", "' + feed.items[0].contentSnippet + '", "' + image + '", "' + pubDate + '")', (err, rows) => {
// if (err) throw err;
console.log(rows);
});
})();

How to fix cannot read property "send" of undefined

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.

How do you send a DM using a discord bot using discord.js

So I am trying to make a bot that has a command to send a "ticket", which is like a warning except it sends a configurable message in a DM. Here's my code so far:
const bot = new Discord.Client()
const token = token here;
const PREFIX = '/';
const embed = new Discord.MessageEmbed()
const ping = require('minecraft-server-util')
bot.on('ready', async () => {
console.log('This bot is online! Created by #littleBitsman.');
})
bot.on('message', message => {
let args = message.content.substring(PREFIX.length).split(' ')
if(message.content.startsWith(PREFIX))
switch (args[0]) {
case 'ticket':
if (message.member.roles.highest == '701895573737046066') {
mention = message.mentions.users.first()
var thing = args.shift()
thing = args.shift()
thing = thing.replace(",", " ")
if(mention = null) {return}
var message = new Discord.MessageEmbed()
.setTitle('Ticket')
.setDescription('Hey ' + mention + '! You recieved this because of: ' + args +'.')
message.channel.type(`dm`) + message.channel.send(mentionMessage)
}
}
})
bot.login(token);
I took out all other code that did not have to do with this question.
To send a message to a specific user, you can do message.client.users.fetch(`insert_ID`).then(user => user.send('message')).
It seems like you're trying to send a message to a user that was mentioned. In that case:
message.client.users.fetch(`${mention.id}`).then(user => user.send('insert_message')).
Hope this helps!

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

Node JS and Coinbase

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!

Categories