Skip to content

Commit 45ff68f

Browse files
committed
First & simple version of Inline Keyboard Markup example. Right now only URL button.
1 parent ba70fbc commit 45ff68f

File tree

4 files changed

+162
-50
lines changed

4 files changed

+162
-50
lines changed
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
/*******************************************************************
2+
* An example of how to use a custom reply keyboard markup. *
3+
* *
4+
* *
5+
* written by Vadim Sinitski *
6+
*******************************************************************/
7+
#include <ESP8266WiFi.h>
8+
#include <WiFiClientSecure.h>
9+
#include <UniversalTelegramBot.h>
10+
11+
// Initialize Wifi connection to the router
12+
char ssid[] = "XXXXXX"; // your network SSID (name)
13+
char password[] = "YYYYYY"; // your network key
14+
15+
// Initialize Telegram BOT
16+
#define BOTtoken "XXXXXXXXX:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" // your Bot Token (Get from Botfather)
17+
18+
WiFiClientSecure client;
19+
UniversalTelegramBot bot(BOTtoken, client);
20+
21+
int Bot_mtbs = 1000; //mean time between scan messages
22+
long Bot_lasttime; //last time messages' scan has been done
23+
24+
void handleNewMessages(int numNewMessages) {
25+
Serial.println("handleNewMessages");
26+
Serial.println(String(numNewMessages));
27+
28+
for (int i=0; i<numNewMessages; i++) {
29+
String chat_id = String(bot.messages[i].chat_id);
30+
String text = bot.messages[i].text;
31+
String from_name = bot.messages[i].from_name;
32+
33+
if (text == "/options") {
34+
String keyboardJson = "[[\{ \"text\" : \"Go to Google\", \"url\" : \"https://www.google.com\" \} ]]";
35+
bot.sendMessageWithInlineKeyboard(chat_id, "Choose from one of the following options", "", keyboardJson);
36+
}
37+
38+
if (text == "/start") {
39+
String welcome = "Welcome to Universal Telegram Bot library, " + from_name + ".\n";
40+
welcome += "This is Inline Keyboard Markup example.\n\n";
41+
welcome += "/options : returns the inline keyboard\n";
42+
43+
bot.sendMessage(chat_id, welcome, "Markdown");
44+
}
45+
}
46+
}
47+
48+
void setup() {
49+
Serial.begin(115200);
50+
51+
// Set WiFi to station mode and disconnect from an AP if it was Previously connected
52+
WiFi.mode(WIFI_STA);
53+
WiFi.disconnect();
54+
delay(100);
55+
56+
// attempt to connect to Wifi network:
57+
Serial.print("Connecting Wifi: ");
58+
Serial.println(ssid);
59+
WiFi.begin(ssid, password);
60+
61+
while (WiFi.status() != WL_CONNECTED) {
62+
Serial.print(".");
63+
delay(500);
64+
}
65+
66+
Serial.println("");
67+
Serial.println("WiFi connected");
68+
Serial.print("IP address: ");
69+
Serial.println(WiFi.localIP());
70+
}
71+
72+
void loop() {
73+
if (millis() > Bot_lasttime + Bot_mtbs) {
74+
int numNewMessages = bot.getUpdates(bot.last_message_received + 1);
75+
76+
while(numNewMessages) {
77+
Serial.println("got response");
78+
handleNewMessages(numNewMessages);
79+
numNewMessages = bot.getUpdates(bot.last_message_received + 1);
80+
}
81+
82+
Bot_lasttime = millis();
83+
}
84+
}

examples/ESP8266/CustomKeyboard/README.md

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,12 @@ The application will turn on and off an LED based on commands received via teleg
1010

1111
This is an example of how to use reply keyboard markup on a ESP8266 based board.
1212

13-
![alt text](https://core.telegram.org/file/811140659/1/RRJyulbtLBY/ea6163411c7eb4f4dc "Inline Keyboard example")
1413

15-
The application will turn on and off an LED based on commands received via telegram.
14+
![alt text](https://core.telegram.org/file/811140999/1/2JSoUVlWKa0/4fad2e2743dc8eda04 "Inline Keyboard example")
15+
16+
Right now working only URL redirection button. Other features will be added later.
17+
18+
-----------------
1619

1720
NOTE: You will need to enter your SSID, password and bot Token for the example to work.
1821

src/UniversalTelegramBot.cpp

Lines changed: 71 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
21
/*
32
Copyright (c) 2015 Giancarlo Bacchio. All right reserved.
43
@@ -21,7 +20,6 @@ License along with this library; if not, write to the Free Software
2120
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
2221
*/
2322

24-
2523
#include "UniversalTelegramBot.h"
2624

2725
UniversalTelegramBot::UniversalTelegramBot(String token, Client &client) {
@@ -30,9 +28,10 @@ UniversalTelegramBot::UniversalTelegramBot(String token, Client &client) {
3028
}
3129

3230
String UniversalTelegramBot::sendGetToTelegram(String command) {
33-
String mess="";
31+
String mess = "";
3432
long now;
3533
bool avail;
34+
3635
// Connect with api.telegram.org
3736
if (client->connect(HOST, SSL_PORT)) {
3837
if (_debug) Serial.println(".... connected to server");
@@ -42,7 +41,7 @@ String UniversalTelegramBot::sendGetToTelegram(String command) {
4241
client->println("GET /"+command);
4342
now=millis();
4443
avail=false;
45-
while (millis()-now<1500) {
44+
while (millis() - now<1500) {
4645
while (client->available()) {
4746
char c = client->read();
4847
//Serial.write(c);
@@ -53,15 +52,16 @@ String UniversalTelegramBot::sendGetToTelegram(String command) {
5352
avail=true;
5453
}
5554
if (avail) {
56-
if (_debug) {
57-
Serial.println();
58-
Serial.println(mess);
59-
Serial.println();
60-
}
55+
if (_debug) {
56+
Serial.println();
57+
Serial.println(mess);
58+
Serial.println();
59+
}
6160
break;
6261
}
6362
}
6463
}
64+
6565
return mess;
6666
}
6767

@@ -70,6 +70,7 @@ String UniversalTelegramBot::sendPostToTelegram(String command, JsonObject& payl
7070
String response = "";
7171
long now;
7272
bool responseReceived;
73+
7374
// Connect with api.telegram.org
7475
if (client->connect(HOST, SSL_PORT)) {
7576
// POST URI
@@ -78,6 +79,7 @@ String UniversalTelegramBot::sendPostToTelegram(String command, JsonObject& payl
7879
client->print("Host:"); client->println(HOST);
7980
// JSON content type
8081
client->println("Content-Type: application/json");
82+
8183
// Content length
8284
int length = payload.measureLength();
8385
client->print("Content-Length:"); client->println(length);
@@ -104,11 +106,11 @@ String UniversalTelegramBot::sendPostToTelegram(String command, JsonObject& payl
104106
responseReceived=true;
105107
}
106108
if (responseReceived) {
107-
if (_debug) {
108-
Serial.println();
109-
Serial.println(response);
110-
Serial.println();
111-
}
109+
if (_debug) {
110+
Serial.println();
111+
Serial.println(response);
112+
Serial.println();
113+
}
112114
break;
113115
}
114116
}
@@ -117,12 +119,12 @@ String UniversalTelegramBot::sendPostToTelegram(String command, JsonObject& payl
117119
return response;
118120
}
119121

120-
121122
bool UniversalTelegramBot::getMe() {
122-
String command="bot"+_token+"/getMe";
123-
String response = sendGetToTelegram(command); //receive reply from telegram.org
123+
String command = "bot"+_token+"/getMe";
124+
String response = sendGetToTelegram(command); //receive reply from telegram.org
124125
DynamicJsonBuffer jsonBuffer;
125126
JsonObject& root = jsonBuffer.parseObject(response);
127+
126128
if(root.success()) {
127129
if (root.containsKey("result")) {
128130
String _name = root["result"]["first_name"];
@@ -141,39 +143,35 @@ bool UniversalTelegramBot::getMe() {
141143
* (Argument to pass: the last+1 message to read) *
142144
* Returns the number of new messages *
143145
***************************************************************/
144-
145-
// JsonObject * UniversalTelegramBot::parseUpdates(String response) {
146-
// DynamicJsonBuffer jsonBuffer;
147-
// return *jsonBuffer.parseObject(response);
148-
// }
149-
150146
int UniversalTelegramBot::getUpdates(long offset) {
151147

152148
if (_debug) Serial.println("GET Update Messages");
153-
String command="bot"+_token+"/getUpdates?offset="+String(offset)+"&limit="+String(HANDLE_MESSAGES);
154-
String response = sendGetToTelegram(command); //receive reply from telegram.org
149+
150+
String command = "bot"+_token+"/getUpdates?offset="+String(offset)+"&limit="+String(HANDLE_MESSAGES);
151+
String response = sendGetToTelegram(command); //receive reply from telegram.org
152+
155153
if (response != "") {
156154
if (_debug) {
157-
Serial.print("incoming message length");
158-
Serial.println(response.length());
159-
Serial.println("Creating DynamicJsonBuffer");
155+
Serial.print("incoming message length");
156+
Serial.println(response.length());
157+
Serial.println("Creating DynamicJsonBuffer");
160158
}
161159

162160
// Parse response into Json object
163161
DynamicJsonBuffer jsonBuffer;
164162
JsonObject& root = jsonBuffer.parseObject(response);
165163

166-
if(root.success()) {
164+
if (root.success()) {
167165
// root.printTo(Serial);
168166
if (_debug) Serial.println();
169167
if (root.containsKey("result")) {
170168
int resultArrayLength = root["result"].size();
171-
if(resultArrayLength > 0) {
169+
if (resultArrayLength > 0) {
172170
int newMessageIndex = 0;
173-
for(int i=0; i < resultArrayLength; i++){
171+
for (int i=0; i < resultArrayLength; i++) {
174172
JsonObject& message = root["result"][i]["message"];
175173
int update_id = root["result"][i]["update_id"];
176-
if(last_message_received != update_id) {
174+
if (last_message_received != update_id) {
177175
last_message_received = update_id;
178176
String text = message["text"];
179177
String date = message["date"];
@@ -213,16 +211,17 @@ int UniversalTelegramBot::getUpdates(long offset) {
213211
***********************************************************************/
214212
bool UniversalTelegramBot::sendSimpleMessage(String chat_id, String text, String parse_mode) {
215213

216-
bool sent=false;
214+
bool sent = false;
217215
if (_debug) Serial.println("SEND Simple Message");
218-
long sttime=millis();
216+
long sttime = millis();
217+
219218
if (text!="") {
220-
while (millis()<sttime+8000) { // loop for a while to send the message
219+
while (millis() < sttime+8000) { // loop for a while to send the message
221220
String command="bot"+_token+"/sendMessage?chat_id="+chat_id+"&text="+text+"&parse_mode="+parse_mode;
222221
String response = sendGetToTelegram(command);
223222
if (_debug) Serial.println(response);
224223
sent = checkForOkResponse(response);
225-
if(sent){
224+
if (sent) {
226225
break;
227226
}
228227
}
@@ -233,12 +232,13 @@ bool UniversalTelegramBot::sendSimpleMessage(String chat_id, String text, String
233232

234233
bool UniversalTelegramBot::sendMessage(String chat_id, String text, String parse_mode) {
235234

236-
237235
DynamicJsonBuffer jsonBuffer;
238236
JsonObject& payload = jsonBuffer.createObject();
237+
239238
payload["chat_id"] = chat_id;
240239
payload["text"] = text;
241-
if(parse_mode != ""){
240+
241+
if (parse_mode != "") {
242242
payload["parse_mode"] = parse_mode;
243243
}
244244

@@ -247,14 +247,16 @@ bool UniversalTelegramBot::sendMessage(String chat_id, String text, String parse
247247

248248
bool UniversalTelegramBot::sendMessageWithReplyKeyboard(String chat_id, String text, String parse_mode, String keyboard, bool resize, bool oneTime, bool selective) {
249249

250-
251250
DynamicJsonBuffer jsonBuffer;
252251
JsonObject& payload = jsonBuffer.createObject();
252+
253253
payload["chat_id"] = chat_id;
254254
payload["text"] = text;
255-
if(parse_mode != ""){
255+
256+
if (parse_mode != "") {
256257
payload["parse_mode"] = parse_mode;
257258
}
259+
258260
JsonObject& replyMarkup = payload.createNestedObject("reply_markup");
259261

260262
// Reply keyboard is an array of arrays.
@@ -266,21 +268,41 @@ bool UniversalTelegramBot::sendMessageWithReplyKeyboard(String chat_id, String t
266268
replyMarkup["keyboard"] = keyboardBuffer.parseArray(keyboard);
267269

268270
//Telegram defaults these values to false, so to decrease the size of the payload we will only send them if needed
269-
if(resize){
271+
if (resize) {
270272
replyMarkup["resize_keyboard"] = resize;
271273
}
272274

273-
if(oneTime){
275+
if (oneTime) {
274276
replyMarkup["one_time_keyboard"] = oneTime;
275277
}
276278

277-
if(selective){
279+
if (selective) {
278280
replyMarkup["selective"] = selective;
279281
}
280282

281283
return sendPostMessage(payload);
282284
}
283285

286+
bool UniversalTelegramBot::sendMessageWithInlineKeyboard(String chat_id, String text, String parse_mode, String keyboard) {
287+
288+
DynamicJsonBuffer jsonBuffer;
289+
JsonObject& payload = jsonBuffer.createObject();
290+
291+
payload["chat_id"] = chat_id;
292+
payload["text"] = text;
293+
294+
if (parse_mode != "") {
295+
payload["parse_mode"] = parse_mode;
296+
}
297+
298+
JsonObject& replyMarkup = payload.createNestedObject("reply_markup");
299+
300+
DynamicJsonBuffer keyboardBuffer;
301+
replyMarkup["inline_keyboard"] = keyboardBuffer.parseArray(keyboard);
302+
303+
return sendPostMessage(payload);
304+
}
305+
284306
/***********************************************************************
285307
* SendPostMessage - function to send message to telegram *
286308
* (Arguments to pass: chat_id, text to transmit and markup(optional)) *
@@ -290,13 +312,14 @@ bool UniversalTelegramBot::sendPostMessage(JsonObject& payload) {
290312
bool sent=false;
291313
if (_debug) Serial.println("SEND Post Message");
292314
long sttime=millis();
315+
293316
if (payload.containsKey("text")) {
294-
while (millis()<sttime+8000) { // loop for a while to send the message
317+
while (millis() < sttime+8000) { // loop for a while to send the message
295318
String command = "bot"+_token+"/sendMessage";
296319
String response = sendPostToTelegram(command, payload);
297320
if (_debug) Serial.println(response);
298321
sent = checkForOkResponse(response);
299-
if(sent){
322+
if (sent) {
300323
break;
301324
}
302325
}
@@ -307,8 +330,9 @@ bool UniversalTelegramBot::sendPostMessage(JsonObject& payload) {
307330

308331
bool UniversalTelegramBot::checkForOkResponse(String response) {
309332
int responseLength = response.length();
310-
for (int m=5; m<responseLength+1; m++) {
311-
if (response.substring(m-10,m)=="{\"ok\":true") { //Chek if message has been properly sent
333+
334+
for (int m=5; m < responseLength+1; m++) {
335+
if (response.substring(m-10,m)=="{\"ok\":true") { //Chek if message has been properly sent
312336
return true;
313337
}
314338
}

0 commit comments

Comments
 (0)