bot server implementation

This commit is contained in:
Dobromir Popov
2024-02-28 15:51:21 +02:00
parent 349c2ca24c
commit 1643e1125b
6 changed files with 156 additions and 9 deletions

2
.env
View File

@ -43,3 +43,5 @@ EMAIL_FROM=noreply@example.com
GMAIL_EMAIL_USERNAME= GMAIL_EMAIL_USERNAME=
GMAIL_EMAIL_APP_PASS= GMAIL_EMAIL_APP_PASS=
TELEGRAM_BOT_TOKEN=7050075088:AAH6VRpNCyQd9x9sW6CLm6q0q4ibUgYBfnM

View File

@ -0,0 +1,6 @@
[
{
"chatId": 777826553,
"phoneNumber": "+359883351579"
}
]

View File

@ -1,7 +1,17 @@
{ {
"verbose": true, "verbose": true,
"ignore": ["node_modules", ".next"], "ignore": [
"watch": ["server/**/*", "server.js","src/helpers.js","src/**/*", "next.config.js"], "node_modules",
".next",
"content/**/*",
"public/**/*"
],
"watch": [
"server/**/*",
"server.js",
"src/helpers.js",
"src/**/*",
"next.config.js"
],
"ext": "js json" "ext": "js json"
} }

View File

@ -23,10 +23,11 @@ const ContactsPage = () => {
</a> </a>
</div> </div>
</div > */ </div > */
} <a href="https://t.me/mwhitnessing_bot" className="inline-flex items-center ml-4" target="_blank"> }
{/* <a href="https://t.me/mwhitnessing_bot" className="inline-flex items-center ml-4" target="_blank">
<img src="content/icons/telegram-svgrepo-com.svg" alt="Телеграм" width="32" height="32" className="align-middle" /> <img src="content/icons/telegram-svgrepo-com.svg" alt="Телеграм" width="32" height="32" className="align-middle" />
<span className="align-middle">Телеграм</span> <span className="align-middle">Телеграм</span>
</a> </a> */}
</div > </div >

View File

@ -614,6 +614,8 @@ const generateWordFile = async (outputFilename, data, templateSrc) => {
// #################### statistics #################### // #################### statistics ####################
const telegramBot = require('./src/telegram');
async function Stat() { async function Stat() {
var date = new Date(); var date = new Date();
@ -641,7 +643,7 @@ async function Stat() {
} }
telegramBot.Initialize();
console.log( console.log(
"found " + previousShifts.length + " shifts for previous 2 months" "found " + previousShifts.length + " shifts for previous 2 months"
@ -649,6 +651,16 @@ async function Stat() {
} }
Stat(); Stat();
exports.baseUrlGlobal = baseUrlGlobal; exports.baseUrlGlobal = baseUrlGlobal;
exports.default = app;

116
src/telegram.js Normal file
View File

@ -0,0 +1,116 @@
const fs = require('fs');
const path = require('path');
const TelegramBot = require('node-telegram-bot-api');
const filePath = path.join(__dirname, '../content/telegram_users.json');
const token = process.env.TELEGRAM_BOT_TOKEN;
const bot = new TelegramBot(token, { polling: true });
const telegramBot = {
Initialize: function () {
bot.on('message', handleMessage);
bot.on('new_chat_members', handleNewChatMembers);
bot.on('contact', handleContact);
bot.onText(/start/, handleStartCommand);
},
updateUserDetails: function (chatId, phoneNumber) {
// Function body remains the same
}
};
function initializeBot() {
bot.on('message', handleMessage);
bot.on('new_chat_members', handleNewChatMembers);
bot.on('contact', handleContact);
bot.onText(/start/, handleStartCommand);
}
function handleMessage(msg) {
const chatId = msg.chat.id;
console.log("received message from chatId = " + chatId);
}
function handleNewChatMembers(msg) {
const chatId = msg.chat.id;
msg.new_chat_members.forEach(member => {
greetNewMember(chatId, member);
});
}
function greetNewMember(chatId, member) {
const userId = member.id;
const welcomeMessage = `Welcome, ${member.first_name}!`;
bot.restrictChatMember(chatId, userId, { can_send_messages: false });
bot.sendMessage(chatId, welcomeMessage);
}
function handleContact(msg) {
const chatId = msg.chat.id;
if (msg.contact && msg.contact.phone_number) {
updateUserDetails(chatId, msg.contact.phone_number);
} else {
bot.sendMessage(chatId, "You did not share your phone number.");
}
}
function handleStartCommand(msg) {
const chatId = msg.chat.id;
const options = {
reply_markup: {
one_time_keyboard: true,
keyboard: [
[{ text: "Разбира се!", request_contact: true, one_time_keyboard: true }],
["Не сега"]
],
resize_keyboard: true
},
parse_mode: 'Markdown'
};
bot.sendMessage(chatId, "Моля, потвърдете вашия телефонен номер:", options);
}
function updateUserDetails(chatId, phoneNumber) {
fs.readFile(filePath, 'utf8', (err, data) => {
let users = [];
if (err && err.code !== 'ENOENT') {
console.error("Error reading the file:", err);
return;
}
try {
if (!err) {
users = JSON.parse(data);
}
} catch (e) {
//failed to parse json. delete the file and create a new one
console.error("Error parsing the file:", e);
console.log("Deleting the file and creating a new one...");
fs.unlinkSync(filePath);
}
const userIndex = users.findIndex(user => user.phoneNumber === phoneNumber);
if (userIndex !== -1) {
users[userIndex].chatId = chatId;
} else {
users.push({ chatId, phoneNumber });
}
fs.writeFile(filePath, JSON.stringify(users, null, 2), 'utf8', (writeErr) => {
if (writeErr) {
console.error("Error writing to the file:", writeErr);
return;
}
console.log("User details updated.");
});
});
}
module.exports = { initializeBot, updateUserDetails };
module.exports = telegramBot;