Files
IoTManager/src/Telegram.cpp

70 lines
2.4 KiB
C++
Raw Normal View History

2020-11-04 23:48:21 +03:00
#include "Telegram.h"
2020-11-05 17:27:18 +03:00
2020-11-04 23:48:21 +03:00
CTBot* myBot{ nullptr };
void telegramInit() {
2020-11-05 02:23:08 +03:00
if (isTelegramEnabled()) {
telegramInitBeen = true;
sCmd.addCommand("telegram", sendTelegramMsg);
String token = jsonReadStr(configSetupJson, "telegramApi");
if (!myBot) {
myBot = new CTBot();
}
myBot->setTelegramToken(token);
myBot->enableUTF8Encoding(true);
if (myBot->testConnection()) {
SerialPrint("I", "Telegram", "Connected");
}
else {
SerialPrint("E", "Telegram", "Not connected");
}
2020-11-04 23:48:21 +03:00
}
}
void handleTelegram() {
2020-11-05 02:23:08 +03:00
if (telegramInitBeen) {
if (isTelegramEnabled()) {
TBMessage msg;
static unsigned long prevMillis;
unsigned long currentMillis = millis();
unsigned long difference = currentMillis - prevMillis;
2020-11-05 17:27:18 +03:00
if (difference >= 5000) {
2020-11-05 02:23:08 +03:00
prevMillis = millis();
if (myBot->getNewMessage(msg)) {
SerialPrint("->", "Telegram", "chat ID: " + String(msg.sender.id) + ", msg: " + String(msg.text));
jsonWriteInt(configSetupJson, "chatId", msg.sender.id);
saveConfig();
2020-11-05 17:27:18 +03:00
telegramMsgParse(String(msg.text));
2020-11-05 02:23:08 +03:00
}
}
2020-11-05 17:27:18 +03:00
}
}
}
void telegramMsgParse(String msg) {
SerialPrint("<-", "Telegram", "chat ID: " + String(jsonReadInt(configSetupJson, "chatId")) + ", msg: " + String(msg));
if (msg.indexOf("order") != -1) {
msg = deleteBeforeDelimiter(msg, " ");
orderBuf += String(msg) + ",";
myBot->sendMessage(jsonReadInt(configSetupJson, "chatId"), "order done");
}
else if (msg.indexOf("get") != -1) {
msg = deleteBeforeDelimiter(msg, " ");
myBot->sendMessage(jsonReadInt(configSetupJson, "chatId"), jsonReadStr(configLiveJson, msg));
}
else {
myBot->sendMessage(jsonReadInt(configSetupJson, "chatId"), "wrong order, use 'get id' to get value, or 'order id value' to send order");
2020-11-05 02:23:08 +03:00
}
}
2020-11-04 23:48:21 +03:00
2020-11-05 02:23:08 +03:00
void sendTelegramMsg() {
String msg = sCmd.next();
2020-11-05 17:27:18 +03:00
msg.replace("#", " ");
2020-11-05 02:23:08 +03:00
myBot->sendMessage(jsonReadInt(configSetupJson, "chatId"), msg);
SerialPrint("<-", "Telegram", "chat ID: " + String(jsonReadInt(configSetupJson, "chatId")) + ", msg: " + msg);
}
2020-11-04 23:48:21 +03:00
2020-11-05 02:23:08 +03:00
bool isTelegramEnabled() {
return jsonReadBool(configSetupJson, "telegonof");
2020-11-04 23:48:21 +03:00
}