Skip to content

Commit 7f885c0

Browse files
committed
Merge branch 'master' of github.com:solcer/Universal-Arduino-Telegram-Bot
2 parents 2984a06 + 1fb713f commit 7f885c0

File tree

4 files changed

+219
-4
lines changed

4 files changed

+219
-4
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ Here is a list of features that this library covers. (Note: The examples link to
5959
|*Location*|Your bot can receive location data, either from a single location data point or live location data. |Check the example.| [Location](https://github.com/witnessmenow/Universal-Arduino-Telegram-Bot/tree/master/examples/ESP8266/Location/Location.ino)|
6060
|*Channel Post*|Reads posts from channels. |Check the example.| [ChannelPost](https://github.com/witnessmenow/Universal-Arduino-Telegram-Bot/tree/master/examples/ESP8266/ChannelPost/ChannelPost.ino)|
6161
|*Long Poll*|Set how long the bot will wait checking for a new message before returning now messages. <br><br> This will decrease the amount of requests and data used by the bot, but it will tie up the arduino while it waits for messages |`bot.longPoll = 60;` <br><br> Where 60 is the amount of seconds it should wait | [LongPoll](https://github.com/witnessmenow/Universal-Arduino-Telegram-Bot/tree/master/examples/ESP8266/LongPoll/LongPoll.ino)|
62+
|*Update Firmware and SPIFFS*|You can update firmware and spiffs area through send files as a normal file with a specific caption. |`update firmware` <br>or<br>`update spiffs`<br> These are captions for example. | [telegramOTA](https://github.com/solcer/Universal-Arduino-Telegram-Bot/blob/master/examples/ESP32/telegramOTA/telegramOTA.ino)|
6263

6364
The full Telegram Bot API documentation can be read [here](https://core.telegram.org/bots/api). If there is a feature you would like added to the library please either raise a Github issue or please feel free to raise a Pull Request.
6465

Lines changed: 179 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,179 @@
1+
/*******************************************************************
2+
An example of bot that can update firmware or spiffs and write file to spiffs.
3+
4+
written by Brian Lough
5+
*******************************************************************/
6+
#include <WiFi.h>
7+
#include <WiFiClientSecure.h>
8+
#include <UniversalTelegramBot.h>
9+
#include <HTTPUpdate.h>
10+
#include <SD.h>
11+
#include <FS.h>
12+
#include <SPIFFS.h>
13+
14+
15+
// Initialize Wifi connection to the router
16+
char ssid[] = "SSID"; // your network SSID (name)
17+
char password[] = "password"; // your network key
18+
19+
// Initialize Telegram BOT
20+
#define BOTtoken "XXXXXXXXX:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" // your Bot Token (Get from Botfather)
21+
22+
WiFiClientSecure client;
23+
UniversalTelegramBot bot(BOTtoken, client);
24+
25+
int Bot_mtbs = 1000; //mean time between scan messages
26+
long Bot_lasttime; //last time messages' scan has been done
27+
28+
void setup() {
29+
Serial.begin(115200);
30+
if (!SPIFFS.begin(true))
31+
{
32+
Serial.println("An Error has occurred while mounting SPIFFS");
33+
}
34+
// Attempt to connect to Wifi network:
35+
Serial.print("Connecting Wifi: ");
36+
Serial.println(ssid);
37+
38+
// Set WiFi to station mode and disconnect from an AP if it was Previously
39+
// connected
40+
WiFi.mode(WIFI_STA);
41+
WiFi.begin(ssid, password);
42+
43+
while (WiFi.status() != WL_CONNECTED) {
44+
Serial.print(".");
45+
delay(500);
46+
}
47+
48+
Serial.println("");
49+
Serial.println("WiFi connected");
50+
Serial.print("IP address: ");
51+
Serial.println(WiFi.localIP());
52+
}
53+
54+
void loop() {
55+
if (millis() > Bot_lasttime + Bot_mtbs) {
56+
int numNewMessages = bot.getUpdates(bot.last_message_received + 1);
57+
58+
while (numNewMessages) {
59+
Serial.println("got response");
60+
for (int i = 0; i < numNewMessages; i++) {
61+
if (bot.messages[i].type == "message") {
62+
if (bot.messages[i].hasDocument == true)
63+
{
64+
httpUpdate.rebootOnUpdate(false);
65+
t_httpUpdate_return ret = (t_httpUpdate_return)3;
66+
if (bot.messages[i].file_caption == "write spiffs")
67+
{
68+
size_t spiffsFreeSize = SPIFFS.totalBytes() - SPIFFS.usedBytes();
69+
if (bot.messages[i].file_size < spiffsFreeSize)
70+
{
71+
bot.sendMessage(bot.messages[i].chat_id, "File downloading.", "");
72+
HTTPClient http;
73+
if (http.begin(client, bot.messages[i].file_path))
74+
{
75+
int code = http.GET();
76+
if (code == HTTP_CODE_OK)
77+
{
78+
int total = http.getSize();
79+
int len = total;
80+
uint8_t buff[128] = {0};
81+
WiFiClient *tcp = http.getStreamPtr();
82+
if (SPIFFS.exists("/" + bot.messages[i].file_name))
83+
SPIFFS.remove(("/" + bot.messages[i].file_name));
84+
File fl = SPIFFS.open("/" + bot.messages[i].file_name, FILE_WRITE);
85+
if (!fl)
86+
{
87+
bot.sendMessage(bot.messages[i].chat_id, "File open error.", "");
88+
}
89+
else
90+
{
91+
while (http.connected() && (len > 0 || len == -1))
92+
{
93+
size_t size_available = tcp->available();
94+
Serial.print("%");
95+
Serial.println(100 - ((len * 100) / total));
96+
if (size_available)
97+
{
98+
int c = tcp->readBytes(buff, ((size_available > sizeof(buff)) ? sizeof(buff) : size_available));
99+
fl.write(buff, c);
100+
if (len > 0)
101+
{
102+
len -= c;
103+
}
104+
}
105+
delay(1);
106+
}
107+
fl.close();
108+
if (len == 0)
109+
bot.sendMessage(bot.messages[i].chat_id, "Success.", "");
110+
else
111+
bot.sendMessage(bot.messages[i].chat_id, "Error.", "");
112+
}
113+
}
114+
http.end();
115+
}
116+
}
117+
else
118+
{
119+
bot.sendMessage(bot.messages[i].chat_id, "SPIFFS size to low (" + String(spiffsFreeSize) + ") needed: " + String(bot.messages[i].file_size), "");
120+
}
121+
}
122+
else
123+
{
124+
if (bot.messages[i].file_caption == "update firmware")
125+
{
126+
bot.sendMessage(bot.messages[i].chat_id, "Firmware writing...", "");
127+
ret = httpUpdate.update(client, bot.messages[i].file_path);
128+
}
129+
if (bot.messages[i].file_caption == "update spiffs")
130+
{
131+
bot.sendMessage(bot.messages[i].chat_id, "SPIFFS writing...", "");
132+
ret = httpUpdate.updateSpiffs(client, bot.messages[i].file_path);
133+
}
134+
switch (ret)
135+
{
136+
case HTTP_UPDATE_FAILED:
137+
bot.sendMessage(bot.messages[i].chat_id, "HTTP_UPDATE_FAILED Error (" + String(httpUpdate.getLastError()) + "): " + httpUpdate.getLastErrorString(), "");
138+
break;
139+
140+
case HTTP_UPDATE_NO_UPDATES:
141+
bot.sendMessage(bot.messages[i].chat_id, "HTTP_UPDATE_NO_UPDATES", "");
142+
break;
143+
144+
case HTTP_UPDATE_OK:
145+
bot.sendMessage(bot.messages[i].chat_id, "UPDATE OK.\nRestarting...", "");
146+
numNewMessages = bot.getUpdates(bot.last_message_received + 1);
147+
ESP.restart();
148+
break;
149+
default:
150+
break;
151+
}
152+
}
153+
}
154+
if (bot.messages[i].text == "/dir")
155+
{
156+
File root = SPIFFS.open("/");
157+
File file = root.openNextFile();
158+
String files = "";
159+
while (file)
160+
{
161+
files += String(file.name()) + " " + String(file.size()) + "B\n";
162+
file = root.openNextFile();
163+
}
164+
bot.sendMessage(bot.messages[i].chat_id, files, "");
165+
} else if (bot.messages[i].text == "/format")
166+
{
167+
bool res = SPIFFS.format();
168+
if (!res)
169+
bot.sendMessage(bot.messages[i].chat_id, "Format unsuccessful", "");
170+
else
171+
bot.sendMessage(bot.messages[i].chat_id, "SPIFFS formatted.", "");
172+
}
173+
}
174+
}
175+
numNewMessages = bot.getUpdates(bot.last_message_received + 1);
176+
}
177+
Bot_lasttime = millis();
178+
}
179+
}

src/UniversalTelegramBot.cpp

Lines changed: 32 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -452,14 +452,22 @@ bool UniversalTelegramBot::processResult(JsonObject result, int messageIndex) {
452452
messages[messageIndex].date = message["date"].as<String>();
453453
messages[messageIndex].chat_id = message["chat"]["id"].as<String>();
454454
messages[messageIndex].chat_title = message["chat"]["title"].as<String>();
455-
455+
messages[messageIndex].hasDocument = false;
456456
if (message.containsKey("text")) {
457457
messages[messageIndex].text = message["text"].as<String>();
458458

459459
} else if (message.containsKey("location")) {
460460
messages[messageIndex].longitude = message["location"]["longitude"].as<float>();
461461
messages[messageIndex].latitude = message["location"]["latitude"].as<float>();
462-
}
462+
} else if (message.containsKey("document")) {
463+
String file_id = message["document"]["file_id"].as<String>();
464+
messages[messageIndex].file_caption = message["caption"].as<String>();
465+
messages[messageIndex].file_name = message["document"]["file_name"].as<String>();
466+
if (getFile(&messages[messageIndex].file_path, &messages[messageIndex].file_size, file_id) == true)
467+
messages[messageIndex].hasDocument = true;
468+
else
469+
messages[messageIndex].hasDocument = false;
470+
}
463471
} else if (result.containsKey("channel_post")) {
464472
JsonObject message = result["channel_post"];
465473
messages[messageIndex].type = F("channel_post");
@@ -673,8 +681,6 @@ String UniversalTelegramBot::sendPhotoByBinary(
673681
return response;
674682
}
675683

676-
677-
678684
String UniversalTelegramBot::sendPhoto(String chat_id, String photo,
679685
String caption,
680686
bool disable_notification,
@@ -753,3 +759,25 @@ void UniversalTelegramBot::closeClient() {
753759
client->stop();
754760
}
755761
}
762+
763+
bool UniversalTelegramBot::getFile(String *file_path, long *file_size, String file_id)
764+
{
765+
String command = "bot" + _token + "/getFile?file_id=" + file_id;
766+
String response =
767+
sendGetToTelegram(command); // receive reply from telegram.org
768+
DynamicJsonBuffer jsonBuffer;
769+
JsonObject &root = jsonBuffer.parseObject(response);
770+
771+
closeClient();
772+
773+
if (root.success())
774+
{
775+
if (root.containsKey("result"))
776+
{
777+
*file_path = "https://api.telegram.org/file/bot" + _token + "/" + root["result"]["file_path"].as<String>();
778+
*file_size = root["result"]["file_size"].as<long>();
779+
return true;
780+
}
781+
}
782+
return false;
783+
}

src/UniversalTelegramBot.h

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,11 @@ struct telegramMessage {
4949
String from_name;
5050
String date;
5151
String type;
52+
String file_caption;
53+
String file_path;
54+
String file_name;
55+
bool hasDocument;
56+
long file_size;
5257
float longitude;
5358
float latitude;
5459
int update_id;
@@ -100,13 +105,15 @@ class UniversalTelegramBot {
100105
String userName;
101106
int longPoll = 0;
102107
int waitForResponse = 1500;
108+
int _lastError;
103109

104110
private:
105111
// JsonObject * parseUpdates(String response);
106112
String _token;
107113
Client *client;
108114
void closeClient();
109115
const int maxMessageLength = 1500;
116+
bool getFile(String *, long *, String);
110117
bool processResult(JsonObject result, int messageIndex);
111118
};
112119

0 commit comments

Comments
 (0)