Skip to content

Commit 5f61bf0

Browse files
authored
Merge pull request witnessmenow#10 from rusboard/master
Created bulk message example. Also small changes in original code, removed unneeded and correct use of Wifi.begin for ESP8266
2 parents 19d7aa5 + b954cad commit 5f61bf0

File tree

7 files changed

+265
-24
lines changed

7 files changed

+265
-24
lines changed
Lines changed: 218 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,218 @@
1+
/*******************************************************************
2+
* An example of how to use a bulk messages to subscribed users. *
3+
* *
4+
* *
5+
* written by Vadim Sinitski *
6+
*******************************************************************/
7+
#include <ESP8266WiFi.h>
8+
#include <WiFiClientSecure.h>
9+
#include <UniversalTelegramBot.h>
10+
#include <FS.h>
11+
#include <ArduinoJson.h>
12+
13+
// Initialize Wifi connection to the router
14+
char ssid[] = "xxxxxxx"; // your network SSID (name)
15+
char password[] = "yyyyyyyy"; // your network key
16+
17+
// Initialize Telegram BOT
18+
#define BOTtoken "XXXXXXXXX:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" // your Bot Token (Get off Botfather)
19+
20+
WiFiClientSecure client;
21+
UniversalTelegramBot bot(BOTtoken, client);
22+
23+
int Bot_mtbs = 1000; //mean time between scan messages
24+
long Bot_lasttime; //last time messages' scan has been done
25+
26+
int bulk_messages_mtbs = 1500; //mean time between send messages, 1.5 seconds
27+
int messages_limit_per_second = 25; // Telegram API have limit for bulk messages ~30 messages in 1 second
28+
29+
void handleNewMessages(int numNewMessages) {
30+
Serial.println("handleNewMessages");
31+
Serial.println(String(numNewMessages));
32+
33+
for(int i=0; i<numNewMessages; i++) {
34+
String chat_id = String(bot.messages[i].chat_id);
35+
String text = bot.messages[i].text;
36+
37+
if (text == "/start") {
38+
if (addSubscribedUser(chat_id)) {
39+
bot.sendMessage(chat_id, "Welcome!", "");
40+
} else {
41+
bot.sendMessage(chat_id, "Something wrong, please try again", "");
42+
}
43+
}
44+
45+
if (text == "/stop") {
46+
bot.sendMessage(chat_id, "Thank you, we always waiting you back", "");
47+
removeSubscribedUser(chat_id);
48+
}
49+
50+
if (text == "/testbulkmessage") {
51+
sendMessageToAllSubscribedUsers("Current temperature is 0.0C");
52+
}
53+
54+
if (text == "\/showallusers") {
55+
File subscribedUsersFile = SPIFFS.open("/subscribed_users.json", "r");
56+
57+
if (!subscribedUsersFile) {
58+
bot.sendMessage(chat_id, "No subscription file", "");
59+
}
60+
61+
size_t size = subscribedUsersFile.size();
62+
63+
if (size > 1024) {
64+
bot.sendMessage(chat_id, "Subscribed users file is too large", "");
65+
} else {
66+
String file_content = subscribedUsersFile.readString();
67+
bot.sendMessage(chat_id, file_content, "");
68+
}
69+
}
70+
71+
if (text == "\/removeallusers") {
72+
SPIFFS.remove("/subscribed_users.json");
73+
}
74+
}
75+
}
76+
77+
JsonObject& getSubscribedUsers(JsonBuffer& jsonBuffer) {
78+
File subscribedUsersFile = SPIFFS.open("/subscribed_users.json", "r");
79+
80+
if (!subscribedUsersFile) {
81+
82+
Serial.println("Failed to open subscribed users file");
83+
84+
// Create empyt file (w+ not working as expect)
85+
File f = SPIFFS.open("/subscribed_users.json", "w");
86+
f.close();
87+
88+
JsonObject& users = jsonBuffer.createObject();
89+
90+
return users;
91+
} else {
92+
93+
size_t size = subscribedUsersFile.size();
94+
95+
if (size > 1024) {
96+
Serial.println("Subscribed users file is too large");
97+
//return users;
98+
}
99+
100+
String file_content = subscribedUsersFile.readString();
101+
102+
JsonObject& users = jsonBuffer.parseObject(file_content);
103+
104+
if (!users.success()) {
105+
Serial.println("Failed to parse subscribed users file");
106+
return users;
107+
}
108+
109+
subscribedUsersFile.close();
110+
111+
// Serial.println("Test");
112+
// users.printTo(Serial);
113+
114+
return users;
115+
}
116+
117+
}
118+
119+
bool addSubscribedUser(String chat_id) {
120+
StaticJsonBuffer<200> jsonBuffer;
121+
JsonObject& users = getSubscribedUsers(jsonBuffer);
122+
123+
File subscribedUsersFile = SPIFFS.open("/subscribed_users.json", "w+");
124+
125+
if (!subscribedUsersFile) {
126+
Serial.println("Failed to open subscribed users file for writing");
127+
//return false;
128+
}
129+
130+
users.set(chat_id, 1);
131+
users.printTo(subscribedUsersFile);
132+
133+
subscribedUsersFile.close();
134+
135+
return true;
136+
}
137+
138+
bool removeSubscribedUser(String chat_id) {
139+
StaticJsonBuffer<200> jsonBuffer;
140+
JsonObject& users = getSubscribedUsers(jsonBuffer);
141+
142+
File subscribedUsersFile = SPIFFS.open("/subscribed_users.json", "w");
143+
144+
if (!subscribedUsersFile) {
145+
Serial.println("Failed to open subscribed users file for writing");
146+
return false;
147+
}
148+
149+
users.remove(chat_id);
150+
users.printTo(subscribedUsersFile);
151+
152+
subscribedUsersFile.close();
153+
154+
return true;
155+
}
156+
157+
void sendMessageToAllSubscribedUsers(String message) {
158+
int users_processed = 0;
159+
160+
StaticJsonBuffer<200> jsonBuffer;
161+
JsonObject& users = getSubscribedUsers(jsonBuffer);
162+
163+
for(JsonObject::iterator it=users.begin(); it!=users.end(); ++it)
164+
{
165+
users_processed++;
166+
167+
if (users_processed < messages_limit_per_second) {
168+
const char* chat_id = it->key;
169+
bot.sendMessage(chat_id, message, "");
170+
} else {
171+
delay(bulk_messages_mtbs);
172+
users_processed = 0;
173+
}
174+
}
175+
}
176+
177+
void setup() {
178+
Serial.begin(9600);
179+
180+
if (!SPIFFS.begin()) {
181+
Serial.println("Failed to mount file system");
182+
return;
183+
}
184+
185+
// Set WiFi to station mode and disconnect from an AP if it was Previously
186+
// connected
187+
WiFi.disconnect();
188+
delay(100);
189+
// attempt to connect to Wifi network:
190+
Serial.print("Connecting Wifi: ");
191+
Serial.println(ssid);
192+
WiFi.begin(ssid, password);
193+
194+
while (WiFi.status() != WL_CONNECTED) {
195+
Serial.print(".");
196+
delay(500);
197+
}
198+
199+
Serial.println("");
200+
Serial.println("WiFi connected");
201+
Serial.println("IP address: ");
202+
IPAddress ip = WiFi.localIP();
203+
Serial.println(ip);
204+
}
205+
206+
void loop() {
207+
if (millis() > Bot_lasttime + Bot_mtbs) {
208+
int numNewMessages = bot.getUpdates(bot.last_message_recived + 1);
209+
210+
while(numNewMessages) {
211+
Serial.println("got response");
212+
handleNewMessages(numNewMessages);
213+
numNewMessages = bot.getUpdates(bot.last_message_recived + 1);
214+
}
215+
216+
Bot_lasttime = millis();
217+
}
218+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
#ESP8266 - Bulk Messages (Send Message to all users who /start using your Telegram bot)
2+
3+
This is a basic example of how to use UniversalTelegramBot on ESP8266 based boards.
4+
5+
The application will echo bulk messages to subscribed users.
6+
7+
NOTE: You will need to enter your SSID, password and bot Token for the example to work.
8+
9+
Tested on 5 subscribed users. I don't know what will be with 10 000 users, but 10 000 users better work with DB or something :)
10+
Just for little community, for example send some data from your Arduino device to all your family or friends who using your Telegram bot.
11+
12+
## License
13+
14+
You may copy, distribute and modify the software provided that modifications are described and licensed for free under [LGPL-3](http://www.gnu.org/licenses/lgpl-3.0.html). Derivatives works (including modifications or anything statically linked to the library) can only be redistributed under [LGPL-3](http://www.gnu.org/licenses/lgpl-3.0.html), but applications that use the library don't have to be.

examples/ESP8266/CustomKeyboard/CustomKeyboard.ino

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,8 @@ void setup() {
7979
// attempt to connect to Wifi network:
8080
Serial.print("Connecting Wifi: ");
8181
Serial.println(ssid);
82-
while (WiFi.begin(ssid, password) != WL_CONNECTED) {
82+
WiFi.begin(ssid, password);
83+
while (WiFi.status() != WL_CONNECTED) {
8384
Serial.print(".");
8485
delay(500);
8586
}

examples/ESP8266/EchoBot/EchoBot.ino

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,8 @@ void setup() {
4040
// Attempt to connect to Wifi network:
4141
Serial.print("Connecting Wifi: ");
4242
Serial.println(ssid);
43-
while (WiFi.begin(ssid, password) != WL_CONNECTED) {
43+
WiFi.begin(ssid, password);
44+
while (WiFi.status() != WL_CONNECTED) {
4445
Serial.print(".");
4546
delay(500);
4647
}

examples/ESP8266/FlashledBot/FlashledBot.ino

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,8 @@ void setup() {
7676
// attempt to connect to Wifi network:
7777
Serial.print("Connecting Wifi: ");
7878
Serial.println(ssid);
79-
while (WiFi.begin(ssid, password) != WL_CONNECTED) {
79+
WiFi.begin(ssid, password);
80+
while (WiFi.status() != WL_CONNECTED) {
8081
Serial.print(".");
8182
delay(500);
8283
}

src/UniversalTelegramBot.cpp

Lines changed: 26 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ String UniversalTelegramBot::sendGetToTelegram(String command) {
3535
bool avail;
3636
// Connect with api.telegram.org
3737
if (client->connect(HOST, SSL_PORT)) {
38-
// Serial.println(".... connected to server");
38+
if (_debug) Serial.println(".... connected to server");
3939
String a="";
4040
char c;
4141
int ch_count=0;
@@ -53,9 +53,11 @@ String UniversalTelegramBot::sendGetToTelegram(String command) {
5353
avail=true;
5454
}
5555
if (avail) {
56-
// Serial.println();
57-
// Serial.println(mess);
58-
// Serial.println();
56+
if (_debug) {
57+
Serial.println();
58+
Serial.println(mess);
59+
Serial.println();
60+
}
5961
break;
6062
}
6163
}
@@ -102,9 +104,11 @@ String UniversalTelegramBot::sendPostToTelegram(String command, JsonObject& payl
102104
responseRecieved=true;
103105
}
104106
if (responseRecieved) {
105-
// Serial.println();
106-
// Serial.println(response);
107-
// Serial.println();
107+
if (_debug) {
108+
Serial.println();
109+
Serial.println(response);
110+
Serial.println();
111+
}
108112
break;
109113
}
110114
}
@@ -145,14 +149,16 @@ bool UniversalTelegramBot::getMe() {
145149

146150
int UniversalTelegramBot::getUpdates(long offset) {
147151

148-
//Serial.println("GET Update Messages ");
152+
if (_debug) Serial.println("GET Update Messages ");
149153
String command="bot"+_token+"/getUpdates?offset="+String(offset)+"&limit="+String(HANDLE_MESSAGES);
150154
String response = sendGetToTelegram(command); //recieve reply from telegram.org
151155
if (response != "") {
152-
// Serial.print("incoming message length");
153-
// Serial.println(response.length());
154-
// Serial.print("Creating StaticJsonBuffer of size: ");
155-
// Serial.println(MAX_BUFFER_SIZE);
156+
if (_debug) {
157+
Serial.print("incoming message length");
158+
Serial.println(response.length());
159+
Serial.print("Creating StaticJsonBuffer of size: ");
160+
Serial.println(MAX_BUFFER_SIZE);
161+
}
156162

157163
// Parse response into Json object
158164
//StaticJsonBuffer<MAX_BUFFER_SIZE> jsonBuffer;
@@ -161,7 +167,7 @@ int UniversalTelegramBot::getUpdates(long offset) {
161167

162168
if(root.success()) {
163169
// root.printTo(Serial);
164-
// Serial.println();
170+
if (_debug) Serial.println();
165171
if (root.containsKey("result")) {
166172
int resultArrayLength = root["result"].size();
167173
if(resultArrayLength > 0) {
@@ -186,14 +192,14 @@ int UniversalTelegramBot::getUpdates(long offset) {
186192
}
187193
return newMessageIndex;
188194
} else {
189-
//Serial.println("no new messages");
195+
if (_debug) Serial.println("no new messages");
190196
}
191197
} else {
192-
Serial.println("Response contained no 'result'");
198+
if (_debug) Serial.println("Response contained no 'result'");
193199
}
194200
} else {
195201
// Buffer may not be big enough, increase buffer or reduce max number of messages
196-
Serial.println("Failed to parse update, the message could be too big for the buffer");
202+
if (_debug) Serial.println("Failed to parse update, the message could be too big for the buffer");
197203
}
198204

199205
return 0;
@@ -207,13 +213,13 @@ int UniversalTelegramBot::getUpdates(long offset) {
207213
bool UniversalTelegramBot::sendSimpleMessage(String chat_id, String text, String parse_mode) {
208214

209215
bool sent=false;
210-
Serial.println("SEND Simple Message ");
216+
if (_debug) Serial.println("SEND Simple Message ");
211217
long sttime=millis();
212218
if (text!="") {
213219
while (millis()<sttime+8000) { // loop for a while to send the message
214220
String command="bot"+_token+"/sendMessage?chat_id="+chat_id+"&text="+text+"&parse_mode="+parse_mode;
215221
String response = sendGetToTelegram(command);
216-
//Serial.println(response);
222+
if (_debug) Serial.println(response);
217223
sent = checkForOkResponse(response);
218224
if(sent){
219225
break;
@@ -281,13 +287,13 @@ bool UniversalTelegramBot::sendMessageWithReplyKeyboard(String chat_id, String t
281287
bool UniversalTelegramBot::sendPostMessage(JsonObject& payload) {
282288

283289
bool sent=false;
284-
Serial.println("SEND Post Message ");
290+
if (_debug) Serial.println("SEND Post Message ");
285291
long sttime=millis();
286292
if (payload.containsKey("text")) {
287293
while (millis()<sttime+8000) { // loop for a while to send the message
288294
String command = "bot"+_token+"/sendMessage";
289295
String response = sendPostToTelegram(command, payload);
290-
//Serial.println(response);
296+
if (_debug) Serial.println(response);
291297
sent = checkForOkResponse(response);
292298
if(sent){
293299
break;

0 commit comments

Comments
 (0)