This is the code to save group messages in a MySQL database using Telegram Bot API.
//Using Telegram Bot API for easy usage of telegram messages.
const TelegramBot = require('node-telegram-bot-api');
//Using Mysql to save mesages to mysql database
var mysql = require('mysql');
//initiate a mysql connection.
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'telegram'
});
//connect to mysql
connection.connect();
//CHange the Bot Token as per your Bot's Token
const token = '';
const bot = new TelegramBot(token, {polling: true});
//On Message event in group
bot.on("message", (msg) => {
//chat id of user and message id of the message
var chat_id = msg.chat.id;
var msg_id = msg.message_id;
//FROM PART
var user_id = msg.from.id;
var bot_check = msg.from.is_bot;
var first = msg.from.first_name;
var username = msg.from.username;
//GROUP DETAILS
var group_name = msg.chat.title;
var group_username = msg.chat.username;
//message send by the user
var message = msg.text
var date = msg.date;
console.log(msg);
if(bot_check == false){
//MYSQL Coding
var user_name = "null";
var group_user_name = "null";
var name_group = "null";
if(!isEmpty(username)){
user_name = username;
}
if(!isEmpty(group_username)){
group_user_name = group_username;
}
if(!isEmpty(group_name)){
name_group = group_name;
}
var post = {user_id: user_id , first: first , username: user_name, group_name: name_group , group_username: group_user_name , num_msg: "0" , date: date};
///Change Data structure as per your convenience
var query = connection.query('INSERT INTO users SET ?', post, function (error, results, fields) {
if (error) throw error;
});
});
}
});
bot.on('polling_error', (error) => {
console.log(error); // => 'EPARSE'
});
function isEmpty(value) {
return typeof value == 'string' && !value.replace(/\s/g,'') || typeof value == 'undefined' || value === null;
}
Join our Telegram Group to get more information .
https://t.me/Crypto_Cal_App
Congratulations @crypto-cal! You have completed some achievement on Steemit and have been rewarded with new badge(s) :
You published your First Post
You made your First Comment
You got a First Vote
Click on the badge to view your Board of Honor.
If you no longer want to receive notifications, reply to this comment with the word
STOP
Do not miss the last post from @steemitboard!
Participate in the SteemitBoard World Cup Contest!
Collect World Cup badges and win free SBD
Support the Gold Sponsors of the contest: @good-karma and @lukestokes