Discord.js Source server query - javascript

I'm trying to make a Discord.js bot that will get data from the CS:GO server and shows it in embed that will be edited and updated (for example every 2 minutes). I still have some problems with the code, currently I stuck with the error "TypeError: Cannot read property 'edit' of undefined"
const Discord = require("discord.js");
var SourceQuery = require('sourcequery');
const client = new Discord.Client();
const config = require("./config.json");
client.on("ready", () => {
console.log(`bot is ready`);
});
client.on("ready", (message, embed) => {
function queryserver(ip, port, sendChannel) {
let sq = new SourceQuery(1000);
console.log(ip + " " + port);
sq.open(ip, port);
sq.getInfo(function (err, info) {
if (!err) {
sq.getPlayers(function (err, players) {
if (!err) {
console.log(sq.address);
var counter = 0;
playersname = "";
for (i = 0; i < players.length; i++) {
playersname = playersname + players[i].name + "\n";
if (counter == players.length - 1) {
client.channels.cache.get(sendChannel).send({
embed: {
color: 3066993,
fields: [{
name: "Server name",
value: "**" + info.name + "**"
},
{
name: "IP",
value: ip + ":" + port,
"inline": true
},
{
name: "Mapa",
value: info.map,
"inline": true
},
{
name: "Max slots",
value: info.maxplayers,
"inline": true
},
{
name: "Online",
value: info.players,
"inline": true
},
{
name: "Player list",
value: "```" + playersname + "```"
}
],
timestamp: new Date(),
footer: {
icon_url: client.user.avatarURL,
text: "Last update:"
}
}
});
}
counter++;
}
}
else {
console.log("Error...");
message.channel.send("Error...");
}
});
}
else {
console.log("Error...");
message.channel.send("Error...");
}
});
};
setInterval(function() {
queryserver(`216.52.148.47`, `27015`, `834355545879347233`);
message.edit(embed)
}, 2000);
});
client.login(config.token);
Can anyone help me?

Related

Embed keeps adding the same fields. Discord.js

I have some commands like user-info in a command handler, here is my code
const Discord = require("discord.js");
const Uembed = new Discord.MessageEmbed();
const randomcolor = Math.floor(Math.random() * 16777214) + 1;
const moment = require("./IGNORE/moment.min.js");
module.exports = {
name: "user-info",
description: "Shows info about a user.",
execute(message, args) {
if (message.deletable) message.delete();
Uembed.setTitle(`${message.author.tag}'s information. `);
Uembed.setColor(randomcolor);
Uembed.setAuthor(message.author.tag, message.author.displayAvatarURL());
Uembed.setThumbnail(message.author.avatarURL());
Uembed.setFooter(
`Requested by : ${message.author.tag}`,
message.author.displayAvatarURL()
);
Uembed.addFields(
{ name: `Username:`, value: `${message.author.username}`, inline: true },
{ name: `Tag:`, value: `${message.author.discriminator}`, inline: true },
{ name: `ID:`, value: `${message.author.id}` },
{ name: `Last message:`, value: `${message.author.lastMessage + 1}` },
{
name: `Joined this server:`,
value: `${moment(message.member.joinedAt).format(
"MMMM Do YYYY, h:mm:ss a"
)}`,
},
{
name: `Account created:`,
value: `${moment(message.author.createdAt).format(
"MMMM Do YYYY, h:mm:ss a"
)}`,
}
);
message.channel.send(Uembed).then((m) => m.delete({ timeout: 60000 }));
},
};
I already tried to put it out of the execute function, but it didn't work either.
Found it! You just need to put this code after the Message.send().
Uembed.fields = [];
It sets the embed fields to an empty array, so it kind of resets the embed fields.

Discord JS - ssh.exec (i think)

i've got an JS script and i really don't understand why it's not working. Here is the script:
if(params[1] == "info")
{
cmdexist = true;
let totalSeconds = (bot.uptime / 1000);
let days = Math.floor(totalSeconds / 86400);
let hours = Math.floor(totalSeconds / 3600);
totalSeconds %= 3600;
let minutes = Math.floor(totalSeconds / 60);
let uptime = `${days} days, ${hours} hours, ${minutes} minutes`;
var countservers = 0; bot.guilds.cache.forEach(g => { countservers++ });
message.channel.send(`Please wait... getting informations!`).then((message) => {
var ssh = new SSH({
host: ssh_host,
user: ssh_user,
pass: ssh_pass,
agent: process.env.SSH_AUTH_SOCK
});
ssh.exec('echo $PATH', {}).start();
ssh.exec('hostname', { out: function(serverhostname) {
ssh.exec('uptime -p', { out: function(serveruptime) {
ssh.exec('uptime -s', { out: function(serveruptimesince) {
ssh.exec('cat /etc/redhat-release', { out: function(serverversion) {
ssh.end();
serveruptime = serveruptime.slice(2);
const embed = new Discord.MessageEmbed()
.setTitle("Informations:")
.setThumbnail(bot.user.displayAvatarURL({dynamic : true, size : 2048}))
.setColor('#277ecd')
.addFields
(
{ name: "Developer:", value: `${developername}`, inline: false },
{ name: "Version:", value: `${version}`, inline: false },
{ name: "Invite link:", value: "", inline: false },
{ name: "Last update:", value: `${lastupdate}`, inline: false },
{ name: "BOT uptime:", value: `${uptime}`, inline: false },
{ name: "Last restart:", value: `${restartdate}`, inline: false },
{ name: "Currently in:", value: `${countservers} servers`, inline: false },
{ name: "Server hostname:", value: `${serverhostname}`, inline: false },
{ name: "Server uptime:", value: `${serveruptime}`, inline: false },
{ name: "Server uptime since:", value: `${serveruptimesince}`, inline: false },
{ name: "OS platform:", value: `${serverversion}`, inline: false },
)
.setFooter(copyright);
message.delete();
message.channel.send(embed);
}}); }}); }}); }});
});
}
When i write the command it says me Please wait... getting informations! but never pass.
I really don't understand why it's not working. It's hosted on "gaming VPS" and host , user , pass it's from MySQL VPS. Sorry for my bad english. :) Thanks in advance for help.

Check if a reacting user has a role

So, I was making a platform for a suggestion channel. The idea was that there is a voting, and when it reaches a such cap, it auto accepts or rejects. I was also making staff can approve or reject. Well, i had a problem in this.
An image of this platform (I censored out the nicknames):
The image
When it reaches the approve cap (10 white check marks), it is supposed to delete the embed and post a new one meaning that the suggestion is approved.
Reproducible sample of code:
client.on("messageReactionAdd", function (messageReaction, member) {
if (member.bot) return;
if (messageReaction.message.channel.id == "516263179446124555") {
if (messageReaction.emoji.name == "✅") {
if (messageReaction.count >= 10) {
messageReaction.message.channel.send("", {embed: {
title: "Suggestion Approved",
description: messageReaction.message.embeds[0].title + "\n" + messageReaction.message.embeds[0].description,
author: {
name: messageReaction.message.embeds[0].author.name,
icon_url: messageReaction.message.embeds[0].author.iconURL
},
color: 3394611,
footer: {
text: "Why: The message got 10 ✅ reactions."
}
}})
}
messageReaction.message.delete();
}
if (messageReaction.emoji.name == "516258169035554817") {
if (messageReaction.count >= 8) {
messageReaction.message.channel.send("", {embed: {
title: "Suggestion sent to Staff",
description: messageReaction.message.embeds[0].title + "\n" + messageReaction.message.embeds[0].description,
author: {
name: messageReaction.message.embeds[0].author.name,
icon_url: messageReaction.message.embeds[0].author.iconURL
},
color: 16764006,
footer: {
text: "Why: The message got 8 <:neutral:516258169035554817> reactions."
}
}})
}
messageReaction.message.guild.channels.get("517331518843125760").send("", {embed: {
title: "Suggestion to check",
description: messageReaction.message.embeds[0].title + "\n" + messageReaction.message.embeds[0].description,
author: {
name: messageReaction.message.embeds[0].author.name,
icon_url: messageReaction.message.embeds[0].author.iconURL
},
color: 16764006,
footer: {
text: "Approving/disapproving this won't change the embed in <#516263179446124555>."
}
}})
messageReaction.message.delete();
}
if (messageReaction.emoji.name == "516258587845328906") {
if (messageReaction.count >= 7) {
messageReaction.message.channel.send("", {embed: {
title: "Suggestion Rejected",
description: messageReaction.message.embeds[0].title + "\n" + messageReaction.message.embeds[0].description,
author: {
name: messageReaction.message.embeds[0].author.name,
icon_url: messageReaction.message.embeds[0].author.iconURL
},
color: 16724736,
footer: {
text: "Why: The message got 7 <:bad:516258587845328906> reactions."
}
}})
}
}
if (messageReaction.emoji.name == "☑") {
var staffMemberReacted = false;
messageReaction.message.guild.members.forEach(function(GuildMember) {
if (messageReaction.users.keyArray().includes(GuildMember.user) && (GuildMember.roles.has("501752627709870080") || GuildMember.roles.has("493436150019784704"))) {
staffMemberReacted = true;
}
})
console.log("reached manapprove")
if (staffMemberReacted) {
messageReaction.message.channel.send("", {embed: {
title: "Suggestion Approved",
description: messageReaction.message.embeds[0].title + "\n" + messageReaction.message.embeds[0].description,
author: {
name: messageReaction.message.embeds[0].author.name,
icon_url: messageReaction.message.embeds[0].author.iconURL
},
color: 3394611,
footer: {
text: "Why: A owner or co-owner manually approved it."
}
}})
messageReaction.message.delete();
}
}
if (messageReaction.emoji.name == "517327626373824522") {
var staffMemberReacted = false;
messageReaction.message.guild.members.forEach(function(GuildMember) {
if (messageReaction.users.keyArray().includes(GuildMember.user) && (GuildMember.id || GuildMember.roles.find)) {
staffMemberReacted = true;
}
})
if (staffMemberReacted) {
messageReaction.message.channel.send("", {embed: {
title: "Suggestion Rejected",
description: messageReaction.message.embeds[0].title + "\n" + messageReaction.message.embeds[0].description,
author: {
name: messageReaction.message.embeds[0].author.name,
icon_url: messageReaction.message.embeds[0].author.iconURL
},
color: 16724736,
footer: {
text: "Why: A owner or co-owner manually rejected it."
}
}})
messageReaction.message.delete();
}
}
}
})
When adding a console.log of it reaching, heroku logs don't put out anything. I was looking for the problem for over a hour.
Please never do this.
Discord.js has a guide on what to do in this situation https://discordjs.guide/#/popular-topics/reactions?id=awaiting-reactions
I would follow their example and use message.awaitReactions To sum it up, use the filter to set the possible reactions you will consider, makes everything much easier.
This is from that link.
message.react('👍').then(() => message.react('👎'));
const filter = (reaction, user) => {
return ['👍', '👎'].includes(reaction.emoji.name) && user.id === message.author.id;
};
message.awaitReactions(filter, { max: 1, time: 60000, errors: ['time'] })
.then(collected => {
const reaction = collected.first();
if (reaction.emoji.name === '👍') {
message.reply('you reacted with a thumbs up.');
}
else {
message.reply('you reacted with a thumbs down.');
}
})
.catch(collected => {
console.log(`After a minute, only ${collected.size} out of 4 reacted.`);
message.reply('you didn\'t react with neither a thumbs up, nor a thumbs down.');
});

How to deal with Unhandled rejection SequelizeConnectionError: connect ETIMEDOUT

The following code is a project which parses directories of CSV files to input into a MySQL database. It often works, however I am plagued by an ETIMEDOUT error. I am a junior developer and am unsure how to handle this situation, or why it is occurring. It may be because I am parsing too much information at once. Any advise on how to handle this would be greatly appreciated.
const app = require('express')();
var fs = require('fs');
var Papa = require('papaparse');
var Sequelize = require('sequelize');
var _ = require('underscore');
var mainDirectory = ['./Relay-Data'];
var sequelize = new Sequelize('relay_cloud','root','admin',{
host: 'localhost',
dialect: 'mysql',
logging: false,
pool: {
max: 5,
min: 0,
idle: 50000,
acquire: 50000,
evict: 50000,
handleDisconnects: true
}
});
var Relay = sequelize.define('relay',{
Timestamp:{
type: Sequelize.DATE,
field: 'Timestamp',
},
Identifier:{
type: Sequelize.INTEGER,
field: 'Identifier',
},
Building:{
type: Sequelize.STRING,
field: 'Building',
},
Device_Type:{
type: Sequelize.STRING,
field: 'Device_Type'
},
Unit:{
type: Sequelize.STRING,
field: 'Unit'
},
Energy:{
type: Sequelize.DECIMAL,
field: 'Energy'
},
Volume:{
type: Sequelize.DECIMAL,
field: 'Volume'
},
File_Name:{
type: Sequelize.STRING,
field: 'File_Name'
}
},{
timestamps: false,
freezeTableName: true
});
Promise.all(mainDirectory.map(function(main) {
return new Promise(function(resolve, reject) {
fs.readdir(main, function(er,dirs){
if (er) {
return reject(er);
}
for(var i = 0; i < dirs.length; i++){
dirs[i] = mainDirectory + "/" + dirs[i];
}
resolve(dirs);
});
}).then(function(dirs){
return Promise.all(dirs.map(function(dir) {
return new Promise(function(resolve, reject) {
fs.readdir(dir, function(er, files) {
if (er) {
return reject(er);
}
resolve(files);
});
}).then(function(files) {
return Promise.all(files.map(function(file) {
return new Promise(function(resolve, reject) {
fs.readFile(dir + '/' + file, 'utf-8', function(er, content) {
if (er) {
return reject(er);
}
var data_obj = Papa.parse(content,{
quotes: false,
delimiter: ";",
});
data_array = data_obj.data;
output_data_array = [];
for(var i = 10; i < data_array.length; i++){
if(data_array[i][0] !== "" ){
output_data_array.push({
"Timestamp" : data_array[i][0],
"Identifier" : data_array[i][1],
"Building" : file.split( "_" )[ 1 ],
"Device_Type" : data_array[i][3],
"Unit" : data_array[i][5],
"Energy" : parseFloat(data_array[i][11].replace(',','.').replace(' ', '')) || 0 ,
"Volume" : parseFloat(data_array[i][13].replace(',','.').replace(' ', '')) || 0,
"File_Name" : file
});
}
}
Relay.bulkCreate(output_data_array);
});
resolve();
});
}));
});
}));
});
})).catch(function(er) {
console.log(er);
});
app.listen(process.env.PORT || 3000, process.env.IP, function(){
console.log("Server is listening");
})
I've been facing this issue today, and this worked for me:
let sequelize = new Sequelize(dbName, dbUsername, dbPassword, {
host: dbHost,
// the rest of your sequelize configuration...
retry: {
match: [
/ETIMEDOUT/,
/EHOSTUNREACH/,
/ECONNRESET/,
/ECONNREFUSED/,
/ETIMEDOUT/,
/ESOCKETTIMEDOUT/,
/EHOSTUNREACH/,
/EPIPE/,
/EAI_AGAIN/,
/SequelizeConnectionError/,
/SequelizeConnectionRefusedError/,
/SequelizeHostNotFoundError/,
/SequelizeHostNotReachableError/,
/SequelizeInvalidConnectionError/,
/SequelizeConnectionTimedOutError/
],
max: 5
}
});
I was able to prevent the ETIMEDOUT error by doing the following:
setTimeout(function() {
Relay.bulkCreate(output_data_array);
}, 2);

REST API call works only once

I have written a Nodejs REST API application with a number of functions. However when I consume one of the APIs it returns me the excel file it is supposed to return and everything is fine until there. After that the application stops responding and all the other functions stop working. The cde for the problematic function is following:
app.get('/api/Export', function (req, res) {
UsageData.aggregate([{
$match: {
$and: [{
GroupName: {
$ne: "Group1"
}
}, {
GroupName: {
$ne: "Group2"
}
}]
}
}
, {
$group: {
_id: '$ToolType'
, count: {
$sum: 1
}
}
}]
, function (err, usagedata) {
usagedata = getJSON(usagedata);
// if there is an error retrieving, send the error. nothing after res.send(err) will execute
if (err)
res.send(err)
var wb = new xl.WorkBook();
var ws = wb.WorkSheet('Usage');
ws.Column(2).Width(35);
var headercell1 = ws.Cell(2, 2);
headercell1.String('Tool');
var headercell2 = ws.Cell(2, 3);
headercell2.String('Usage');
var myStyle = wb.Style();
myStyle.Font.Bold();
myStyle.Fill.Color('#CCCCCC');
myStyle.Border({
top: {
style: 'thick'
, color: '000000'
}
, right: {
style: 'thick'
, color: '000000'
}
, bottom: {
style: 'thick'
, color: '000000'
}
, left: {
style: 'thick'
, color: '000000'
}
});
myStyle.Font.Alignment.Horizontal('center');
var borderstyle = wb.Style();
borderstyle.Border({
top: {
style: 'thin'
, color: '000000'
}
, right: {
style: 'thin'
, color: '000000'
}
, bottom: {
style: 'thin'
, color: '000000'
}
, left: {
style: 'thin'
, color: '000000'
}
});
borderstyle.Font.Alignment.Horizontal('center');
headercell1.Style(myStyle);
headercell2.Style(myStyle);
for (var i = 0; i < usagedata.length; i++) {
var cell = ws.Cell(2 + i + 1, 2);
cell.String(usagedata[i].Tool);
cell.Style(borderstyle);
var cell1 = ws.Cell(2 + i + 1, 3);
cell1.Number(usagedata[i].Count);
cell1.Style(borderstyle);
}
UsageData.aggregate([{
$match: {
$and: [{
GroupName: {
$ne: ""
}
}, {
GroupName: {
$ne: "Group1"
}
}, {
GroupName: {
$ne: "Group2"
}
}]
}
}
, {
$group: {
_id: '$GroupName'
, count: {
$sum: 1
}
}
}]
, function (err, data) {
// if there is an error retrieving, send the error. nothing after res.send(err) will execute
if (err)
res.send(err)
var wsg = wb.WorkSheet("Group Usage");
wsg.Column(2).Width(35);
var headercell = wsg.Cell(2, 2);
headercell.String('Group');
headercell.Style(myStyle);
var headercell = wsg.Cell(2, 3);
headercell.String('Usage');
headercell.Style(myStyle);
for (var i = 0; i < data.length; i++) {
var cell = wsg.Cell(2 + i + 1, 2);
cell.String(data[i]._id);
cell.Style(borderstyle);
var cell1 = wsg.Cell(2 + i + 1, 3);
cell1.Number(data[i].count);
cell1.Style(borderstyle);
}
wb.write('Report.xlsx', res);
var filename = "Report.xlsx";
res.setHeader('Content-disposition', 'attachment; filename=' + filename);
res.setHeader('Content-type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
res.pipe(res);
});
return;
});
return;
});
I am using Node4Excel to generate an excel file from the data I get from my Mongodb. The API returns the excel file for the first time. Second time onwards, it doesnt return anything and neither does the other APIs. Please help.
I finally fixed it by using the following lines:
wb.write('Report.xlsx', res,function(){
var filename = "Report.xlsx";
res.setHeader('Content-disposition', 'attachment; filename=' + filename);
res.setHeader('Content-type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
res.pipe(res);
});

Categories