So I am trying to make a discord bot with 2 commands:
!addver {verification code} & !verify {code}
the codes will be stored in a MySQL database hosted on my computer using XAMPP. I have successfully gotten it to add the verification code to the database, but right now I am having trouble trying to get it to read the table, and do what I am telling it to.
This is the verify command that I have at the moment:
if (isCommand("verify",message)) {
if (err) throw err;
con.query("SELECT Code FROM verf", function (err, result, fields) {
if (err) throw err;
console.log(result[1].code);
});
}
And this is my database. Ignore Name, thats just for my own record of who makes a verification code:
https://gyazo.com/324b4537a975268e8c5ea38edd08767b
EDIT:
Got the code working to find the code that people enter, but cant get it to do anything afterwards. The final if is where the issue is at the moment
if (isCommand("verify",message)) {
var fsql = "SELECT * FROM `verf` WHERE `Code` LIKE ?";
var vals = [
[args[0]]
];
con.query(fsql, [vals], function (err, result) {
if (err) throw err;
console.log(result);
if (result.RowDataPacket.Code === (args[0])) return message.channel.send("You have entered an invalid code!")
message.member.addRole(WHITELISTED);
})}
Related
I have a discord bot and I'm working on a command that shows info about a character(by providing the character name) from a mysql database. It works fine but if I provide a name that doesn't exist in the database like !characterinfo asdasfefcdce, the bot crashes. So my question is How do I prevent it from crashing if I provide a wrong name?. Hopefully you understand what I mean.
Here's the code:
const Discord = require('discord.js');
const mysql = require('mysql');
const {stripIndents} = require("common-tags");
const { prefix, token } = require('../config.json');
module.exports.run = async (bot, message, args, connection3) => {
if (message.content == '!characterinfo') {
return message.reply('provide a character name!');
}
const name = args[0];
connection3.query('SELECT * FROM characters WHERE name = ?', [name], function(err, results, rows) {
if (err) throw err;
const embed = new Discord.RichEmbed()
.setColor('RANDOM')
.setTitle('**Character Information**')
.addField('Nickname:', results[0].name)
.addField('Level:', results[0].level)
.setFooter(`test`)
.setTimestamp();
message.channel.send(embed);
});
}
module.exports.help = {
name: "characterinfo",
}
If you need me to provide you more info, let me know.
Any help is appreciated!
The bot crashes at the moment because in this line
if (err) throw err;
you throw an error and don't handle it later, the simplest way to change this is to replace throw by console.log or console.error
if (err) console.error(err);
Or you could keep the throw and wrap the code with a try/catch.
try {
connection3.query('SELECT * FROM characters WHERE name = ?', [name], function (err, results, rows) {
if (err) throw err;
const embed = new Discord.RichEmbed()
.setColor('RANDOM')
.setTitle('**Character Information**')
.addField('Nickname:', results[0].name)
.addField('Level:', results[0].level)
.setFooter(`test`)
.setTimestamp();
message.channel.send(embed);
});
} catch(err) {
// Handle the error ...
console.log(err)
}
EDIT: So the error is actually coming from the results array not having any entries when the query doesn't find a result, so this solution should work.
You should check to see if there's a "results" before doing anything else.
try {
connection3.query('SELECT * FROM characters WHERE name = ?', [name], function (err, results, rows) {
if (err) throw err;
if (!results[0]) return;
const embed = new Discord.RichEmbed()
.setColor('RANDOM')
.setTitle('**Character Information**')
.addField('Nickname:', results[0].name)
.addField('Level:', results[0].level)
.setFooter(`test`)
.setTimestamp();
message.channel.send(embed);
});
} catch(err) {
// Handle the error ...
console.log(err)
}
I'm trying to build a server in node.js that'll take a request from a client, access a mysql server on the server, and send data from that server to the client. I am able to access the mysql server outside of the createServer but I can't put the sql query within the createServer method.
Example of what doesn't work:
var jellies;
http.createServer(function (req, res) {
var sql = "SQL STATEMENT";
sqlConnection.query(sql, function(err, result) {
if (err) throw err;
jellies = result;
}
res.write(JSON.stringify(jellies));
}).listen(port);
Example of what does work:
var jellies;
var sql = "SQL STATEMENT";
sqlConnection.query(sql, function(err, result) {
if (err) throw err;
jellies = result;
}
http.createServer(function (req, res) {
res.write(JSON.stringify(
}).listen(port);
console.log(jellies) after the query is made produces null for the first function. Are you just not allowed to do anything in http.createServer()? Any ideas to work around this?
The error I get is: TypeError: First argument must be a string or Buffer. It calls back the the line for htts.createServer();
Can you please try this?
http.createServer(function (req, res) {
var sql = "SQL STATEMENT";
sqlConnection.query(sql, function(err, result) {
if (err) throw err;
res.write(JSON.stringify(result));
}
}).listen(port);
Figures the problem I worked on all yesterday would get solved by a friend online in a few seconds.
For the next person that might struggle with this all that needs to be fixed is moving res.write() and res.end() into the sql query function.
I'm doing a monitoring system project in which I have Arduino sensors data being sent to a node.js server (thru GET requests) and then stored in a MySQL DB.
Whenvever I successfully send data to the server, it connects to the MySQL DB and queries the last 5 received records to do some processing.
Therefore, I need to store the rows of those 5 records in a variable for later use. Meaning that I have to get rows from a connection.query in a variable.
I read that the fact that I'm not able to do this is because node.js being async. So my questions are:
Is it possible to do the described tasks the way I'm trying?
If not, is there any other way to do so?
I'm not putting the whole code here but I'm running a separated test that also doesn't run properly. Here it is:
var mysql = require('mysql');
var con = mysql.createConnection({
host : "127.0.0.1",
user : "root",
password: "xxxx",
database: "mydb",
port : 3306
});
var queryString = "SELECT id, temp1, temp2, temp3, temp4, level_ice_bank, flow FROM tempdata ORDER BY id DESC LIMIT 5";
con.connect(function(err) {
if (err) throw err;
});
var result_arr = [];
function setValue (value) {
result_arr = value;
}
con.query(queryString, function (err, rows, fields) {
if (err) throw err;
else {
//console.log(rows);
setValue(rows);
}
});
console.log(result_arr);
It logs:
[]
But if I uncomment console.log(rows); it logs what I need to store in the variable result_arr.
Thanks in advance to all.
You're seeing this behaviour because con.query(...) is an asynchronous function. That means that:
console.log(result_arr);
Runs before:
con.query(queryString, function (err, rows, fields) {
if (err) throw err;
else {
//console.log(rows);
setValue(rows);
}
});
(Specifically, the setValue(rows) call)
To fix this in your example, you can just do:
con.query(queryString, function (err, rows, fields) {
if (err) throw err;
else {
setValue(rows);
console.log(result_arr);
}
});
If you want to do more than just log the data, then you can call a function which depends on result_arr from the con.query callback, like this:
con.query(queryString, function (err, rows, fields) {
if (err) throw err;
else {
setValue(rows);
doCleverStuffWithData();
}
});
function doCleverStuffWithData() {
// Do something with result_arr
}
I've improved my code a lot over the past few days but I'm finally stuck. My query is returning "unknown". I've attached the code and a screenshot of the database. I'm trying to use the discordid to pull the correspnding info from the hfuid column. I would greatly appreciate a point in the right direction (Looking for video tutorials preferably).
if (command == "hf") {
connection.connect();
connection.query("SELECT hfuid FROM cleaamwd_hfbot.users WHERE discorduid = 242037588586659850", function(err, rows) {
message.reply(rows);
connection.end();
})
}
This query would work to get the date from the cell you need
if (command === "hf") {
connection.connect();
connection.query("SELECT * FROM cleaamwd_hfbot.users WHERE discorduid = '242037588586659850'", (err, rows) {
if (err) throw err;
const hfuid = rows[0].hfuid
message.reply(hfuid);
})
connection.end();
}
where do i close the mysql connection?
I need to run queries in sequence. I am writing code that looks like this at present:
var sqlFindMobile = "select * from user_mobiles where mobile=?";
var sqlNewUser = "insert into users (password) values (?)";
//var sqlUserId = "select last_insert_id() as user_id";
var sqlNewMobile = "insert into user_mobiles (user_id, mobile) values (?,?)";
connection.connect(function(err){});
var query = connection.query(sqlFindMobile, [req.body.mobile], function(err, results) {
if(err) throw err;
console.log("mobile query");
if(results.length==0) {
var query = connection.query(sqlNewUser, [req.body.password], function(err, results) {
if(err) throw err;
console.log("added user");
var user_id = results.insertId;
var query = connection.query(sqlNewMobile, [user_id, req.body.mobile], function(err, results) {
if(err) throw err;
console.log("added mobile");
//connection.end();
});
});
}
});
//connection.end();
(I am a beginner with node, npm-express and npm-mysql. I have tried searching SO for "express mysql cannot enqueue" to find related questions and have not found them.)
I fixed this problem use this method:
connection.end() in your connection.query function
The fixed code is here
If you're using the node-mysql module by felixge then you can call connection.end() at any point after you've made all of the connection.query() calls, since it will wait for all of the queries to finish before it terminates the connection.
See the example here for more information.
If you're wanting to run lots of queries in series, you should look into the async module, it's great for dealing with a series of asynchronous functions (i.e. those that have a callback).
Maybe the problem is that the mySQL query is executed after the connection is already closed, due to the asynchronous nature of Node. Try using this code to call connection.end() right before the thread exits:
function exitHandler(options, err) {
connection.end();
if (options.cleanup)
console.log('clean');
if (err)
console.log(err.stack);
if (options.exit)
process.exit();
}
//do something when app is closing
process.on('exit', exitHandler.bind(null, {cleanup: true}));
Code adapted from #Emil Condrea, doing a cleanup action just before node.js exits
In my case connection.end was being called in a spot that was hard to notice, so an errant call to connection.end could be the problem with this error