ITCooky Recipes

Lets cooky it yammy things!

Smart house monitoring with TelegramBot in Node.js!

дата November 8, 2019

I continued to develop the theme “I want to know the temperature and humidity of my room from anywhere in the world” and what else to choose than Telegram, that is well known now thanks to government bullying, let’s go step by step.

I will OrangePi Zero 512mb this one

Обзор-тестирование[пришлось еще одну купить] Orange Pi Zero 512Mb с коробкой и платой расширения!


The weather station in Arduino still measures the temperature and the rest, and this despite my welding (the temperature is inflated, but this DHT22 sensor is probably scorched)

arduino_ch340_temp_ehernet_018
Мониторим по сети — свет, температуру, движение с Arduino Uno R3 CH340G и строим графики!

 

With the passage of time, the amount of OS images for OrenagePi decreased, I liked DietPi but they said “ hell knows what kind of WiFi module is here, it is not possible to code for it, go to… “. But Arambien still remains, they also say that “ hell knows what kind of WiFi module is here, it is not possible to code for it, he can have errors “. But those who like oranges are not easy to scare; It’s not like mimipc with step-by-step instructions for all occasions!

Download from this page www.armbian.com/orange-pi-zero/ Image Strech, size is not tpld, but must fit in a small 2GB file (uploaded).

I write on the SD card in my Ubuntu. We will connect the memory card and see where it is in the system
sudo lsblk
its in one which is 2 GB
You have to unmount it (but it will continue present in disks icons)
sudo umount /dev/sde1
we have to format it
sudo mkfs.vfat -I /dev/sde
and unmount
sudo umount /dev/sde
Unarchive the image and write on the card, it will take a few minutes
Again they have changed the archive type, the new one is 7z you have to install it in Ubuntu
sudo apt-get install p7zip
unarchive
p7zip -d Debian_stretch_next.7z
an write
sudo dd bs=1M if=Armbian_5.38_Orangepizero_Debian_stretch_next_4.14.14.img of=/dev/sde

Insert the card in the orange zero, if it does not load, you must try another card (this is actually 98% of the loading problems) to enter Log in as: root Password : 1234. And another 2% of problems are due to a bad recording of a flash drive … I don’t know why, I recorded it for a second time and it started, I have a lot of very bad quality SD. Transcenent 2Gb without indicating the speed – it worked for me.

The orange IP is seen by the router between those issued, I connect through SSH
sudo ssh root@192.168.1.218
Connecting to Wi-Fi is quick and easy, go to the Armbian menu
sudo armbian-config
I will not describe the entire connection process, connect to WiFi, save the settings, and it connects by itself after reboot!

Now I must choose what, where, how, in general, the Telegram Bot works. There is a lot to choose from, but since I am not fluent in any of the programming languages, that’s why I choose Node.JS, why not! It seems to me that JS d is JavaScript, but it’s very similar to C ++, I am not sure, but I’ve seen C.

At least there are instructions, I will start following steps of this wonderful article archakov.im/post/telegram-bot-on- nodejs.html and it immediately sends me to Google to install the Node.js, but that’s fine! By the way, nothing worked for me according to these instructions, but it inspired me a lot …

Installing Node.Js
We need two commnds
curl -sL https://deb.nodesource.com/setup_9.x | bash -
apt-get install -y nodejs

In Arambian there is no source for Node.JS repository so line one adds it. 56 megabytes were consumed, I fear my 2 Gb card its not good enough, how evere I found it in the trash, but it is new. And the funniest thing is that, as much as you want you can no longer buy a card less than 16 GB, you can buy 8 GB but at a price of 16 GB!

Verifying the versions of what was installed using commands
root@orangepizero:~# node --version
v9.11.1
root@orangepizero:~# npm --version
5.6.0

Lets add security
It’s always useful to hide your real IP from any public service, especially if it’s something smart and potentially interesting for piracy!

Install TOR
apt-get install tor

There is a bug in Debian,you cant not be paste with the left button of mouse en vim
that is corrected by creating a file
vi ~/.vimrc
with line

set mouse=

After that I can paste with mouse … sometimes the first line few symbols are not copied …

Add to file
vi /etc/tor/torrc
this line

SocksPort 127.0.0.1:9050

thats it

Lets install proxy server Privoxy
apt-get install privoxy
Add to file
vi /etc/privoxy/config
the line

forward-socks5 / localhost:9050 .

Rn it
service tor start
service privoxy restart

Check
This our real IP
curl ident.me
and this one behinde proxy
curl -x http://localhost:8118 ident.me
If they are different then that thing works!
Lets add it to autostart
sudo update-rc.d privoxy enable
sudo update-rc.d tor enable

it sais something about perl, nut it works

Making telegrambot and token
You have to talk on Telegram with BotFather and create a name of the bot and nickname, and so it gives the token. There is a lot of instruction for that, maybe even in English(and if you think it’s a google translation, it’s a handjobe)!

Installing and runnig Telegram Bot’a
npm install node-telegram-bot-api
Lets see version
npm list node-telegram-bot-api
make dir and file
mkdir tbot
cd tbot
vi bot.js

add here

const TelegramBot = require('node-telegram-bot-api');

// replace the value below with the Telegram token you receive from @BotFather
const token = 'YOUR_TOKEN_YOUR_TOKEN’;

// Create a bot that uses 'polling' to fetch new updates
const bot = new TelegramBot(token, {polling: true,
request: {
  proxy: "http://localhost:8118"
 }
});

// Matches "/echo [whatever]"
bot.onText(/\/echo (.+)/, (msg, match) => {
  // 'msg' is the received Message from Telegram
  // 'match' is the result of executing the regexp above on the text content
  // of the message

  const chatId = msg.chat.id;
  const resp = match[1]; // the captured "whatever"

  // send back the matched "whatever" to the chat
  bot.sendMessage(chatId, resp);
});

// Listen for any kind of message. There are different kinds of
// messages.
bot.on('message', (msg) => {
  const chatId = msg.chat.id;

  // send a message to the chat acknowledging receipt of their message
  bot.sendMessage(chatId, 'Received your message');
});

run it
node bot.js
And here it is, we found it in our Telegram on phone by nickname or by the name ITCooky home and we chat with it: it can only reply “Received your message” and repeat the message if it starts with / echo

We add the temperature report function to the bot
I imagined that I was going to read the file, which is formed from the Arduino survey via http, and the last line, like the current temperature, will be shown by the bot in response … Well no, I don’t know how do this, but I know how to respond with an image, and I will make an image with ordinary scripts: the temperature in the graph for 5 minutes, per hour, per day!

I’m preparing the data and the graph, just like here SAP article , of course it differs from FreeBSD a bit!

We install the console browser
apt-get install lynx
make script
vi andmon.sh
add

#!/bin/bash
d=`/usr/bin/lynx -source -connect_timeout=10 192.168.1.177 | awk 'NR==2'`
if [ -z "$d" ]
then
t=`/bin/date +%Y"."%m"."%d"-"%H":"%M" "`
/bin/echo "${t} 0 0 0 0 0" >> /root/tbot/mon.log
exit
elif ! [ -z "$d" ]
then
t=`/bin/date +%Y"."%m"."%d"-"%H":"%M" "`
/bin/echo "${t}${d}" >> /root/tbot/mon.log
fi

make it exicutible
chmod +x andmon.sh
and lets add it to cron
crontab -e
la linea
*/1 * * * * /root/tbot/andmon.sh

I wait a few minutes and see if the file appears /root/tbot/mon.log is here, ok

Install a plotter that makes graphics
apt-get install gnuplot
make script
vi plot.sh
add

#!/bin/bash
/bin/cat /root/tbot/mon.log |/usr/bin/tail -n -5 | /usr/bin/xargs -n 6 /bin/echo > /root/tbot/temp5.log
/usr/bin/gnuplot << EOF
set terminal png size 800,500
set output '/root/tbot/temp5.png'
set autoscale y
set autoscale x
unset border
set xdata time
#set ytics 1
#set xtics 5 font "Verdana, 10" rotate 90
set grid
set timefmt "%Y.%m.%d-%H:%M"
set format x "%H:%M"
plot '/root/tbot/temp5.log' u 1:2 with lines linetype 1 t 'temperature C'
EOF
/bin/cat /root/tbot/mon.log |/usr/bin/tail -n -60 | /usr/bin/xargs -n 6 /bin/echo > /root/tbot/temph.log
/usr/bin/gnuplot << EOF
set terminal png size 800,500
set output '/root/tbot/temph.png'
set autoscale y
set autoscale x
unset border
set xdata time
#set ytics 1
#set xtics 5 font "Verdana, 10" rotate 90
set grid
set timefmt "%Y.%m.%d-%H:%M"
set format x "%H:%M"
plot '/root/tbot/temph.log' u 1:2 with lines linetype 1 t 'temperature C'
EOF
/bin/cat /root/tbot/mon.log |/usr/bin/tail -n -1440 | /usr/bin/xargs -n 6 /bin/echo > /root/tbot/tempd.log
/usr/bin/gnuplot << EOF
set terminal png size 800,500
set output '/root/tbot/tempd.png'
set autoscale y
set autoscale x
unset border
set xdata time
#set ytics 1
#set xtics 5 font "Verdana, 10" rotate 90
set grid
set timefmt "%Y.%m.%d-%H:%M"
set format x "%H"
plot '/root/tbot/tempd.log' u 1:2 with lines linetype 1 t 'temperature C'
EOF

Make it exicutible
chmod +x plot.sh
add to cron
crontab -e
the line
*/1 * * * * /root/tbot/plot.sh

lets make bot script
vi bot0.js
add

process.env["NTBA_FIX_350"] = 1;
process.env["NTBA_FIX_319"] = 1;

const TelegramBot = require('node-telegram-bot-api');

// replace the value below with the Telegram token you receive from @BotFather
const token = 'YOUR_TOKEN';

// Create a bot that uses 'polling' to fetch new updates
const bot = new TelegramBot(token, {polling: true,
request: {
  proxy: "http://localhost:8118"
 }
});


// Matches "/echo [whatever]"
bot.onText(/[T/t]est/, (msg, match) => {
const chatId = msg.chat.id;
bot.sendMessage(chatId, 'I am working');
});


bot.onText(/[T/t]emp5/, (msg, match) => {
const chatId = msg.chat.id;

    const photo5 = 'temp5.png';
    bot.sendPhoto(chatId, photo5, {caption: 'Temp last 5 min'});

});
bot.onText(/[T/t]emph/, (msg, match) => {
const chatId = msg.chat.id;

   const photoh = 'temph.png';
    bot.sendPhoto(chatId, photoh, {caption: 'Temp last 60 min'});

});
bot.onText(/[T/t]empd/, (msg, match) => {
const chatId = msg.chat.id;

   const photod = 'tempd.png';
    bot.sendPhoto(chatId, photod, {caption: 'Temp last 24h'});

});

The first two lines are necessary so that there are no threatening errors … I do not know how it works, but they all put it and the errors do not appear

Bot commands, all uppercase and lowercase
test – it answers i am alive
temp5 – temp graph 5 min
temph – temp graph 1 h
tempd – temp graph 24 h

Simply running it is not enough, I would like it to start after restarting the system.

To do that, you have to install pm2

npm i pm2 -g

run
pm2 start bot0.js --name bot0
And one more command, now bot will start into boot
pm2 startup
So you can see that you don’t run
pm2 list

┌──────────┬────┬──────┬──────┬────────┬─────────┬────────┬─────┬───────────┬──────┬──────────┐
│ App name │ id │ mode │ pid  │ status │ restart │ uptime │ cpu │ mem       │ user │ watching │
├──────────┼────┼──────┼──────┼────────┼─────────┼────────┼─────┼───────────┼──────┼──────────┤
│ bot0     │ 0  │ fork │ 2376 │ online │ 0       │ 47m    │ 0%  │ 46.6 MB   │ root │ disabled │
└──────────┴────┴──────┴──────┴────────┴─────────┴────────┴─────┴───────────┴──────┴──────────┘
 Use `pm2 show <id|name>` to get more details about an app

Monitoring
pm2 monit

Commands to shut down and start
pm2 stop App-name
pm2 start App-name

Remove app from autostart
pm2 delete App-name

I reboot – and it works !!!!

Add avatar to bot
That must be done in telegram, tell @BotFather the phrase /setuserpic and answer his questions and send the image

Pending tasks Understand why OrangePi Zero freezes: overheating (unlikely), power supply (change to braded), WiFi module (switch to Ethernet), memory card Yes, due to the power, I replaced Auchanovskaya with a patented Xaomi– Make notifications under certain conditions – And understand how to restrict access to the bot (Oops!)

Make notification under certain conditions
Ufff it was hard, exciting, painful, but nice. Something remained incomprehensible, but there is a result! Brain goes around after learning a new language, syntax!

204/5000
The first thing I didn’t understand was how to get the second value from the line using the Node.js tools, it’s easy to do with console commands, so I insert the line into the file for the plotter

/bin/cat /root/tbot/mon.log |/usr/bin/tail -n -5 | /usr/bin/awk '{print $2}' > /root/tbot/tw.log

155/5000
That makes file tw.log where in the column there are five temperature values for the last five minutes, and the same for humidity hw

finally I have two files with statistics to make graphics
plotmin.sh

#!/bin/bash
/bin/cat /root/tbot/mon.log |/usr/bin/tail -n -5 | /usr/bin/xargs -n 6 /bin/echo > /root/tbot/mon5.log
/bin/cat /root/tbot/mon.log |/usr/bin/tail -n -5 | /usr/bin/awk '{print $2}' > /root/tbot/tw.log
/bin/cat /root/tbot/mon.log |/usr/bin/tail -n -5 | /usr/bin/awk '{print $3}' > /root/tbot/hw.log

/usr/bin/gnuplot << EOF
set terminal png size 800,500
set output '/root/tbot/temp5.png'
set autoscale y
set autoscale x
unset border
set xdata time
#set ytics 1
#set xtics 5 font "Verdana, 10" rotate 90
set grid
set timefmt "%Y.%m.%d-%H:%M"
set format x "%H:%M"
plot '/root/tbot/mon5.log' u 1:2 with lines linetype 1 t 'temperature C'
EOF
/usr/bin/gnuplot << EOF
set terminal png size 800,500
set output '/root/tbot/hum5.png'
set autoscale y
set autoscale x
unset border
set xdata time
#set ytics 1
#set xtics 5 font "Verdana, 10" rotate 90
set grid
set timefmt "%Y.%m.%d-%H:%M"
set format x "%H:%M"
plot '/root/tbot/mon5.log' u 1:3 with lines linetype 2 t 'humidity %'
EOF

and plot.sh

#!/bin/bash
/bin/cat /root/tbot/mon.log |/usr/bin/tail -n -60 | /usr/bin/xargs -n 6 /bin/echo > /root/tbot/monh.log
/usr/bin/gnuplot << EOF
set terminal png size 800,500
set output '/root/tbot/temph.png'
set autoscale y
set autoscale x
unset border
set xdata time
set grid
set timefmt "%Y.%m.%d-%H:%M"
set format x "%H:%M"
plot '/root/tbot/monh.log' u 1:2 with lines linetype 1 t 'temperature C'
EOF
/bin/cat /root/tbot/mon.log |/usr/bin/tail -n -1440 | /usr/bin/xargs -n 6 /bin/echo > /root/tbot/mond.log
/usr/bin/gnuplot << EOF
set terminal png size 800,500
set output '/root/tbot/tempd.png'
set autoscale y
set autoscale x
unset border
set xdata time
set grid
set timefmt "%Y.%m.%d-%H:%M"
set format x "%H"
plot '/root/tbot/mond.log' u 1:2 with lines linetype 1 t 'temperature C'
EOF
/usr/bin/gnuplot << EOF
set terminal png size 800,500
set output '/root/tbot/humh.png'
set autoscale y
set autoscale x
unset border
set xdata time
set grid
set timefmt "%Y.%m.%d-%H:%M"
set format x "%H:%M"
plot '/root/tbot/monh.log' u 1:3 with lines linetype 2 t 'humidity %'
EOF
/usr/bin/gnuplot << EOF
set terminal png size 800,500
set output '/root/tbot/humd.png'
set autoscale y
set autoscale xи вставляю
unset border
set xdata time
set grid
set timefmt "%Y.%m.%d-%H:%M"
set format x "%H"
plot '/root/tbot/mond.log' u 1:3 with lines linetype 2 t 'humidity %'
EOF

se arrancar por el cron
crontab -e
la linea
*/1 * * * * /root/tbot/plotmin.sh
*/5 * * * * /root/tbot/plotmin.sh

I rewrote the bot, for some reason it didn’t work functions () , apparently something was inserted and passed parameters of the parentheses, so the code is repeated.

The bot itself is making a file
vi itchomebot.js
and add

process.env["NTBA_FIX_350"] = 1;
process.env["NTBA_FIX_319"] = 1;

const TelegramBot = require('node-telegram-bot-api');
// replace the value below with the Telegram token you receive from @BotFather
const token = '5YouR_b0t_tokEn_heAR';

const adminId = 1112t2333;

// Create a bot that uses 'polling' to fetch new updates
const bot = new TelegramBot(token, {polling: true,
request: {
  proxy: "http://localhost:8118"
 }
});

// start var
var fs = require('fs');
var readline = require('readline');
var stream = require('stream');
//for min max status
tw1 = 29;
alert1 = 0;
tw2 = 15;
alert2 = 0;
hw1 = 70;
alert3 = 0;
hw2 = 20;
alert4 = 0;
// end var

//start all 


bot.onText(/[T/t]est/, (msg, match) => {
bot.sendMessage(msg.chat.id, 'I am working');
});

//start help
bot.onText(/\/help/, (msg, match) => {
bot.sendMessage(msg.chat.id, 'Manual:\n/start - start and subscribe for warnings\n/help - this manual\n/toadmin text - send message to bot admin\n/touser 111222333 "text" - send message to user(only for admin)\nTest - test\nTemp5 - temp stat for 5 min\nTemph - temp stat for last 60 min\nTempd - temp stat for last 24h\nHum5 - humidity stat for 5 min\nHumh - humidity stat for last 60 min\nHumd - humidity stat for last 24h\nKkk -to run inline keybord\n/warnings off - warnings off\n/warnings on - warnings on');
});
//end help

//start send message to bot admin
bot.onText(/\/toadmin (.+)/, (msg, match) => {
  const fromUser = msg.from.id;
  const resp = match[1]; // the captured "whatever"
  bot.sendMessage(adminId, 'Message from ' + fromUser + ' "' + resp + '"');
});
//ens send message to bot admin

//start send message to user 
bot.onText(/\/touser (.+) "(.+)"/, (msg, match) => {
  const fromUser = msg.from.id;
 const touserId = match[1]
 const touserText = match[2]
if (fromUser == adminId) {
  bot.sendMessage(touserId, 'Message from bot admin: "' + touserText + '"');
} else {
bot.sendMessage(fromUser, 'You are not athtorised');
};
});
//ens send message to user 

//start send pic stat
bot.onText(/[H/h]um5/, (msg, match) => {
  bot.sendPhoto(msg.chat.id, 'hum5.png', {caption: 'Humidity last 5 min'});
});
bot.onText(/[H/h]umh/, (msg, match) => {
  bot.sendPhoto(msg.chat.id, 'humh.png', {caption: 'Humidity last 60 min'});
});
bot.onText(/[H/h]umd/, (msg, match) => {
  bot.sendPhoto(msg.chat.id, 'humd.png', {caption: 'Humidity last 24h'});
});
bot.onText(/[T/t]emp5/, (msg, match) => {
  bot.sendPhoto(msg.chat.id, 'temp5.png', {caption: 'Temp last 5 min'});
});
bot.onText(/[T/t]emph/, (msg, match) => {
  bot.sendPhoto(msg.chat.id, 'temph.png', {caption: 'Temp last 60 min'});
});
bot.onText(/[T/t]empd/, (msg, match) => {
  bot.sendPhoto(msg.chat.id, 'tempd.png', {caption: 'Temp last 24h'});
});
//end send pic stat

//start start 
bot.onText(/\/start/, (msg, match) => {
bot.sendMessage(msg.chat.id, 'Welcome! This is ItCooky.com TelegramBot running on OrangePi PC Plus 1Gb RAM 8Gb eMMC\n\n For recieve warnings run:\n/warnings on');
});
//end start 



//start warnigs 

//start find midscope by file name
function midscope(arg1, callback) {
var arrreadfile = [];
readline.createInterface(fs.createReadStream(arg1), new stream).on('line', function(line) {
arrreadfile.push(line);
});
readline.createInterface(fs.createReadStream(arg1), new stream).on('close', function() {
var arrvaluesfromfile = arrreadfile.map(function (x) {
return parseInt(x, 10);
});
const reducer = (accumulator, currentValue) => accumulator + currentValue;
 var midscopevalue = (arrvaluesfromfile.reduce(reducer) / arrvaluesfromfile.length);
callback (midscopevalue);
});
};
//stop find midscope by file name

//start send messages to id in list file
function sendtoidfromfile (arg1,arg2,arg3,arg4) {
readline.createInterface(fs.createReadStream(arg1), new stream).on('line', function(line) {
bot.sendMessage(line, '' + arg2 + arg3 + arg4 + '');
});
readline.createInterface(fs.createReadStream(arg1), new stream).on('close', function() {
});
}


//end send messages to id in list file



function warningtemp(arg1,arg2) {
midscope ('./tw.log', function (num) {
if (num >= arg1 &&  alert1 == 0 )
{

sendtoidfromfile ('./warning_users.id','WARNING: Height Temp in badroom! More than ',tw1,'C!');

alert1 = 1;
} else {
if (num < arg1 && alert1 == 1 )
{
sendtoidfromfile ('./warning_users.id','RELAX: Normal temp in badroom! Less than ',tw1,'C!');
alert1 = 0;
};
};
if (num <= arg2 &&  alert2 == 0 )
{

sendtoidfromfile ('./warning_users.id','WARNING: Low Temp in badroom! Less than ',arg2,'C!');

alert2 = 1;
} else {
if (num > arg2 && alert2 == 1 )
{
sendtoidfromfile ('./warning_users.id','RELAX: Normal temp in badroom! More than ',arg2,'C!');
alert2 = 0;
};
};
});


};
setInterval(warningtemp, 300500, tw1, tw2);

function warninghum(arg1,arg2) {
midscope ('./hw.log', function (num) {
if (num >= arg1 &&  alert3 == 0 )
{

sendtoidfromfile ('./warning_users.id','WARNING: Height humidity in badroom! More than ',arg1,'%!');

alert3 = 1;
} else {
if (num < arg1 && alert3 == 1 )
{sendtoidfromfile ('./warning_users.id','RELAX: Normal humuduty in badroom! Less than ',arg1,'%!');
alert3 = 0;
};
};
if (num <= arg2 &&  alert4 == 0 )
{

sendtoidfromfile ('./warning_users.id','WARNING: Low humidity in badroom! Less than ',arg2,'%!');

alert4 = 1;
} else {
if (num > arg2 && alert4 == 1 )
{sendtoidfromfile ('./warning_users.id','RELAX: Normal humidity in badroom! More than ',arg2,'%!');
alert4 = 0;
};
};
});


};
setInterval(warninghum, 290000, hw1, hw2);


//end warnigs


//set warnings on
bot.onText(/\/[W/w]arnings on/, (msg, match) => {
var users = msg.from.id;
var dubl = 0;
var instream = fs.createReadStream('./warning_users.id');
var rl = readline.createInterface(instream, new stream);
rl.on('line', function(line) {
console.log(line);
if ( line == users) {
dubl = dubl + 1;
};
});
rl.on('close', function() {
 if (dubl == 0) {
var fs = require('fs');
fs.appendFile('warning_users.id', `${users}\n`, (error) => { console.log("Error!");
});
bot.sendMessage(msg.chat.id, 'Youv bin subscribed to warnings');
};
if (dubl != 0) {
bot.sendMessage(msg.chat.id, 'You are allready subcribed to warnings');
};
});
});
//end set warnings on



//delete form warnings function arg file name and word

function delstring(arg1,arg2) {
var value = arg2 + '\n';
var datafromfile = fs.readFileSync('./' + arg1, 'utf-8');
var newDataFile = datafromfile.replace(value, '');
fs.writeFileSync('./' + arg1, newDataFile, 'utf-8');
};

//end delete functions


//start warnigs off 
bot.onText(/[W/w]arnings off/, (msg, match) => {
var user = msg.from.id;
filename = 'warning_users.id';
delstring(filename, user);

});

Del ald bot from pm2
pm2 delete bot0
and add new one
pm2 start itchomebot.js --name ITCooky
and repiat
pm2 startup
The pieces of code are signed. You cannot send notifications without knowing user IDs, you must collect them. The event to collect /start is executed for all new logins in the bot. If you want to receive notifications, tell the bot / warnings on

ID is added to the file, but first it is verified if it is already there. It will be necessary to remove it from this list at the request of the user, but then later. To disable notifications / warnings off
Also (at the end of the bot with // start warnigs for height temp ) the average value of the tw.log file is calculated, here the decimals are lost, but I don’t need such precision, then compared to the value of tw , if there is higher, a file with ID is opened and a message is sent to them.
That function starts with that command

setInterval(warning, 300000);

It works every 300 seconds (for subsequent warnings add half a second to this deadline, so that everything is not processed at the same time). A notification arrives when it works and the second when the condition stops working. I used to recive it every 5 minutes and it was stressful.

You can send a message to the bot administrator / toadmin text . You must designate a bot administrator for this, you must register your 9-digit number at the beginning in cons = 111222333 you don’t see the id so easy from the teelgram app, but it is written in warnings_users.id. The administrator can also send / touser 111222333 “text”

UPD
I rewrote it again, to the bot. I don’t know why, it will be because I don’t understand asynchronous programming (most likely), or just because it’s not suitable for what I do. I managed to put in the midscope function (the path to the file argument) the median calculation of the 5 values – to get this value from the function did not work, so everything works in this function . I managed to send messages by ID from a file in the sendtoidfromfile function (argument path to a file with ID, first part of the message, metric value, end of the message). There is some kind of problem with the global variables in Node.Js, but if you declare them like this at the beginning ( alert1 and so on) then they work, they go through functions, the values are not extracted from the functions, although they are extracted in training examples … Well, nothing, the bot is working again, the bot sends warnings when the temperature or humidity in the bedroom is too high or low!

UPD: Add an on-screen keyboard to TelegramBot

Everyone says it’s easy, of course if there were examples in the telegram manual, yes! But there are no examples!

Add this to the end of the bot.

//custome keyboard settings
const keyMYboard = {
   reply_markup: {
       inline_keyboard: [
           [
{text: `Temperature`, callback_data:'t'},
{text: `5m`, callback_data:'temp5'},
{text: `1h`, callback_data:'temph'},
{text: `24h`, callback_data:'tempd'}
  ],[
{text: `Humidity`, callback_data:'h'},
{text: `5m`, callback_data:'hum5'},
{text: `1h`, callback_data:'humh'},
{text: `24h`, callback_data:'humd'}
]]}}

//this runs inline keyboard
bot.onText(/[K/k]kk/, (msg, match) => {
bot.sendMessage(msg.chat.id, 'ITChomeBot Keyboard', keyMYboard);
});

//this start button press reader - only once ofr all inline_keyboards imho
bot.on('callback_query', function (msg) {
if (msg.data === 'temp5'){
bot.sendPhoto(msg.from.id, 'temp5.png', {caption: 'Temp last 5 min'});
bot.answerCallbackQuery(msg.id, "Done", false);
}
if (msg.data === 'temph'){
bot.sendPhoto(msg.from.id, 'temph.png', {caption: 'Temp last 60 min'});
bot.answerCallbackQuery(msg.id, "Done", false);
}
if (msg.data === 'tempd'){
bot.sendPhoto(msg.from.id, 'tempd.png', {caption: 'Temp last 24h'});
bot.answerCallbackQuery(msg.id, "Done", false);
}
if (msg.data === 'hum5'){
bot.sendPhoto(msg.from.id, 'hum5.png', {caption: 'Humidity last 5 min'});
bot.answerCallbackQuery(msg.id, "Done", false);
}
if (msg.data === 'humh'){
bot.sendPhoto(msg.from.id, 'humh.png', {caption: 'Humidity last 60 min'});
bot.answerCallbackQuery(msg.id, "Done", false);
}
if (msg.data === 'humd'){
bot.sendPhoto(msg.from.id, 'humd.png', {caption: 'Humidity last 24h'});
bot.answerCallbackQuery(msg.id, "Done", false);
}
});


Restart bot
pm2 stop ITCooky
pm2 start ITCooky

Really, everything is easy. First, create a constant name (any) keyMYboard, then describe the text that will be on the button and what it will send. It turns out that you cannot simply send text messages to the button, but you must send something, no matter if you only need a button with text.

To call the keyboard, we write to Kkk or kkk bot. He responds, as always, but at the end of the command after the text appears the keyboard.

Next, we got the answers of the buttons with bot.on and if – here I just wanted to send the text of the command to which the bot should respond, no, it didn’t work, I had to describe it completely. After clicking on the button in your left corner, something turns and continues to spin for a while, even when the answer is received, that’s annoying. It turned out that this does not happen in all the examples of the Internet, but it is a mistake: after taking the answer of the button, we must answer the button so that it does not wait and does not turn. To do this, put

bot.answerCallbackQuery(msg.id, "Done", false);

– if set to true, the Done will be displayed in full screen and will be forced to click OK again.

There was a mystery that when he threw the keyboard once after he got an answer, the second time he got two answers with the click of a button, and so on. I took out the key handler from the keyboard call, it is enough to run it separately once and it will process everything, otherwise, there were as many keyboards as keystrokes, therefore, the responses multiplied.


Leave a Reply

Your email address will not be published. Required fields are marked *