GithubHelp home page GithubHelp logo

cotestatnt / asynctelegram2 Goto Github PK

View Code? Open in Web Editor NEW
84.0 84.0 25.0 2.04 MB

Powerful, flexible and secure Arduino Telegram BOT library. Hardware independent, it can be used with any MCU capable of handling an SSL connection.

License: MIT License

C++ 89.59% C 10.41%

asynctelegram2's People

Contributors

cotestatnt avatar di-strix avatar neryaz avatar shafr avatar vvmusiienko avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

asynctelegram2's Issues

__FILENAME__ already defined warning using ESP32 SDK

Thanks for the great library.

Using the ESP32 SDK, installed using Espressif installation guide results in a FILENAME already defined warning:

.../Documents/Arduino/libraries/AsyncTelegram2/src/serial_log.h:10: warning: "__FILENAME__" redefined
 #define __FILENAME__ (strrchr(__FILE__, '\\') ? strrchr(__FILE__, '\\') + 1 : __FILE__)

The warning indicates it is already defined in the ESP32 SDK at:

...Arduino15/packages/esp32/hardware/esp32/2.0.1/tools/sdk/esp32/include/newlib/platform_include/assert.h:38: note: this is the location of the previous definition
 #define __FILENAME__ (__builtin_strrchr( "/" __FILE__, '/') + 1)

Please change the define in serial_log.h to something else, e.g. __FILE_NAME__

ESP8266 Unstable

  1. Sometimes reboots (20 times in day)
  2. Sometimes lost connection until manual reboot
  3. OTA 8266 cause cyclic reboot

Paraing Json to char* without deep copy

*I think there is a problem about parsing char * from JSON in function AsyncTelegram2::getNewMessage

I have 3 examples :

1 )

In MessageQuery when I print out
Serial.println(msg.callbackQueryData );
I got

XXXXXXXXX/sendMessage HTTP/1.0
Host: api.telegram.org
Connection: keep-alive
Content-Type: application/jso.....

But when I add 1 more member to struct TBMessage :
String callbackQueryData1;
And then I add 1 more line for parsing MessageQuery

message.callbackQueryData1 = updateDoc["result"][0]["callback_query"]["data"].as<String>();

Now Serial.println(msg.callbackQueryData1 ); print good result

2 )

In MessageText : I jot that JSON

{
  "ok": true,
  "result": [
    {
      "update_id": XXXXXXXX,
      "message": {
        "message_id": 123,
        "from": {
          "id": XXXXXXXX,
          "is_bot": false,
          "first_name": "XXXXXXXXXX",
          "language_code": "en"
        },
        "chat": {
          "id": -XXXXXXXX,
          "title": "XXXXXXXX",
          "type": "supergroup"
        },
        "date": XXXXXXXX,
        "text": "Gggh"
      }
    }
  ]
}

But when I tried to print msg.sender.firstName I got empty string and strlen(msg.sender.firstName) print 1

But when I add
String firstName1; to struct TBUser and then parse it
message.sender.firstName1 = updateDoc["result"][0]["message"]["from"]["first_name"].as<String>();;
I can print the first name as well

3 )

In MessageQuery when I tried to print callbackQueryID (char *)
Serial.println(msg.callbackQueryID); I got
back_data (what ???)

But if I convert callbackQueryID :
String callbackQueryID; in struct TBMessage
and parse as String :
message.callbackQueryID = updateDoc["result"][0]["callback_query"]["id"].as<String>();
I got right result.

So maybe there is a problem with parsing to char * ? can you please check it ? maybe we need to convert all char * to String in all structs ?

Maybe the error is because you only copy the pointer, you should deep copy with malloc and memcpy. But is better to use String more easy and more clean

Send photo to group possible?

Hi, thanks for this very useful library. I'm using it for a doorbell project. I am wondering if it is possible to send a photo to a group? I can't really see how looking through the source.

Thanks in advance.

is there an END for bots?

Hello,
is it possible to "end" a bot after beginning it?
i'd like to be able to enable/disable bot in runtime, is it possible?
thanks

ESP8266 reboots

I use your library AsyncTelegram2.h
Uploaded the lightBot.ino example. Through telegram, I turned on the LED and left it on. After a while I noticed that it went out. I turned it on again, but the situation repeated itself. Then I started the Serial Monitor and saw that after about 30-50 minutes the ESP8266 reboots with an Exception (2) error:
10:36:19.176 -> epc1=0x3ffed570 epc2=0x00000000 epc3=0x00000000 excvaddr=0x3ffed570 depc=0x00000000
or Soft WDT reset.
Here is the decoding of EspExceptionDecoder:

`Exception 2: InstructionFetchError: Processor internal physical address or data error during instruction fetch
PC: 0x3ffed570
EXCVADDR: 0x3ffed570

Decoding stack results
0x4020a61c: String::equals(char const*) const at C:\Users\Admin\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\cores\esp8266\WString.cpp line 505
0x402226bc: sha2big_out at src/inner.h line 582
0x40222414: sha2big_round at src/hash/sha2big.c line 131
0x40222c9b: br_sha2small_round at src/hash/sha2small.c line 113
0x4023125d: br_ghash_ctmul32 at src/inner.h line 585
0x40224669: br_ssl_engine_set_buffers_bidi at src/ssl/ssl_engine.c line 442
0x40225a59: br_ssl_hs_client_run at src/ssl/ssl_hs_client.c line 151
0x40222b8f: br_sha2small_round at src/hash/sha2small.c line 105
0x40231ca1: br_i15_reduce at /home/earle/Arduino/hardware/esp8266com/esp8266/tools/xtensa-lx106-elf/xtensa-lx106-elf/include/sys/pgmspace.h line 77
0x40223598: br_i15_montymul at src/int/i15_montmul.c line 39`

Decoding Soft WDT reset:
Decoding stack results 0x40208b16: BearSSL::WiFiClientSecure::_clearAuthenticationSettings() at C:\Users\Admin\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\libraries\ESP8266WiFi\src\WiFiClientSecureBearSSL.cpp line 98 0x402249aa: br_ssl_engine_recvrec_ack at src/ssl/ssl_engine.c line 743 0x40208d30: BearSSL::WiFiClientSecure::_run_until(unsigned int, bool) at C:\Users\Admin\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\libraries\ESP8266WiFi\src\WiFiClientSecureBearSSL.cpp line 436 0x40208f13: BearSSL::WiFiClientSecure::_write(unsigned char const*, unsigned int, bool) at C:\Users\Admin\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\libraries\ESP8266WiFi\src\WiFiClientSecureBearSSL.cpp line 287 0x4020a6a8: String::indexOf(String const&, unsigned int) const at C:\Users\Admin\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\cores\esp8266\WString.cpp line 659 0x4020acf6: __wrap_system_restart_local() at C:\Users\Admin\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\cores\esp8266\core_esp8266_postmortem.cpp line 212 0x40207b08: ClientContext::_write_from_source(DataSource*) at C:\Users\Admin\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\libraries\ESP8266WiFi\src/include/ClientContext.h line 443 0x40100294: __digitalWrite(uint8_t, uint8_t) at C:\Users\Admin\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\cores\esp8266\core_esp8266_wiring_digital.cpp line 85 0x40209031: BearSSL::WiFiClientSecure::_wait_for_handshake() at C:\Users\Admin\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\libraries\ESP8266WiFi\src\WiFiClientSecureBearSSL.cpp line 562 0x40201a97: AsyncTelegram2::getUpdates() at C:\Users\Admin\Documents\Arduino\libraries\AsyncTelegram2\src\AsyncTelegram2.cpp line 116 0x40201b35: AsyncTelegram2::getUpdates() at C:\Users\Admin\Documents\Arduino\libraries\AsyncTelegram2\src\AsyncTelegram2.cpp line 136 0x40207bc0: WiFiClient::write_P(char const*, unsigned int) at C:\Users\Admin\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\libraries\ESP8266WiFi\src/include/DataSource.h line 57 0x40100294: __digitalWrite(uint8_t, uint8_t) at C:\Users\Admin\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\cores\esp8266\core_esp8266_wiring_digital.cpp line 85 0x40202b08: ArduinoJson6191_F1::JsonDeserializer , ArduinoJson6191_F1::StringCopier>::parseVariant (ArduinoJson6191_F1::VariantData&, ArduinoJson6191_F1::AllowAllFilter, ArduinoJson6191_F1::NestingLimit) at C:\Users\Admin\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Json/JsonDeserializer.hpp line 66 0x40100228: millis() at C:\Users\Admin\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\cores\esp8266\core_esp8266_wiring.cpp line 188 0x40202de3: ArduinoJson6191_F1::JsonDeserializer , ArduinoJson6191_F1::StringCopier>::parseObject (ArduinoJson6191_F1::CollectionData&, ArduinoJson6191_F1::AllowAllFilter, ArduinoJson6191_F1::NestingLimit) at C:\Users\Admin\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Json/JsonDeserializer.hpp line 416 0x40202b08: ArduinoJson6191_F1::JsonDeserializer , ArduinoJson6191_F1::StringCopier>::parseVariant (ArduinoJson6191_F1::VariantData&, ArduinoJson6191_F1::AllowAllFilter, ArduinoJson6191_F1::NestingLimit) at C:\Users\Admin\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Json/JsonDeserializer.hpp line 66 0x40100294: __digitalWrite(uint8_t, uint8_t) at C:\Users\Admin\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\cores\esp8266\core_esp8266_wiring_digital.cpp line 85 0x40100a3f: realloc(void*, size_t) at C:\Users\Admin\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\cores\esp8266\umm_malloc\umm_malloc.cpp line 619 0x40204bf2: AsyncTelegram2::getNewMessage(TBMessage&) at C:\Users\Admin\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Variant/VariantRef.hpp line 107 0x40201332: _GLOBAL__sub_I_client() at C:\Users\Admin\Documents\Arduino\libraries\AsyncTelegram2\examples\lightBot/lightBot.ino line 125 0x40201332: _GLOBAL__sub_I_client() at C:\Users\Admin\Documents\Arduino\libraries\AsyncTelegram2\examples\lightBot/lightBot.ino line 125 0x40209480: BearSSL::CertStore::findHashedTA(void*, void*, unsigned int) at C:\Users\Admin\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\libraries\ESP8266WiFi\src\CertStoreBearSSL.cpp line 197 0x4020948c: BearSSL::CertStore::findHashedTA(void*, void*, unsigned int) at C:\Users\Admin\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\libraries\ESP8266WiFi\src\CertStoreBearSSL.cpp line 200 0x40209480: BearSSL::CertStore::findHashedTA(void*, void*, unsigned int) at C:\Users\Admin\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\libraries\ESP8266WiFi\src\CertStoreBearSSL.cpp line 197 0x40209751: HardwareSerial::peek() at C:\Users\Admin\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\cores\esp8266/HardwareSerial.h line 136 0x402099cd: IPAddress::printTo(Print&) const at C:\Users\Admin\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\cores\esp8266\IPAddress.cpp line 154 0x4020b6b9: uart_read(uart_t*, char*, size_t) at C:\Users\Admin\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\cores\esp8266\uart.cpp line 266 0x40100294: __digitalWrite(uint8_t, uint8_t) at C:\Users\Admin\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\cores\esp8266\core_esp8266_wiring_digital.cpp line 85 0x40209e2d: Stream::timedRead() at C:\Users\Admin\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\cores\esp8266\Stream.cpp line 38 0x40100196: esp_schedule() at C:\Users\Admin\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\cores\esp8266\core_esp8266_main.cpp line 125 0x402011ff: loop() at C:\Users\Admin\Documents\Arduino\libraries\AsyncTelegram2\examples\lightBot/lightBot.ino line 109

Sending messages

Hi!
I continue to deal with your library and faced the fact that I can not send a message to the telegram when any events occur. For example, write the following code:
void loop() { TBMessage msg; if(digitalRead(button)==HIGH) myBot.sendMessage(msg, " button=1"); }
but nothing comes in telegram. What am I doing wrong? At the same time, there is a connection with telegram.

error in library

Thanks for library! But i have little problem (using esp32, core 1.0.6):
`AsyncTelegram2.cpp: 5:1: error: prototype for 'AsyncTelegram2::AsyncTelegram2(Client&)' does not match any in class 'AsyncTelegram2
AsyncTelegram2*: AsyncTelegram2(Client &client)

AsyncTelegram2.cpp:1: In file included from

AsyncTelegram2.h: 85:7: error: candidates are: AsyncTelegram2::AsyncTelegram2(const AsyncTelegram2&)
class AsyncTelegram2

AsyncTelegram2.h: 90:5: error: AsyncTelegram2::AsyncTelegram2(Client&, uint32_t)
AsyncTelegram2(Client &client, uint32_t bufferSize = BUFFER_BIG)

AsyncTelegram2.cpp: 62:6: error: prototype for 'bool AsyncTelegram2::sendCommand(const char* const&, const char*, bool)' does not match any in class 'AsyncTelegram2
bool AsyncTelegram2*: sendCommand(const char* const &command, const char* payload, bool blocking )

AsyncTelegram2.cpp:1: In file included from

AsyncTelegram2.h: 384:10: error: candidate is: bool AsyncTelegram2::sendCommand(const char*, const char*, bool)
bool sendCommand(const char* command, const char* payload, bool blocking = false)

AsyncTelegram2.cpp: 344:6: error: prototype for 'bool AsyncTelegram2::forwardMessage(const TBMessage&, int32_t)' does not match any in class 'AsyncTelegram2
bool AsyncTelegram2*: forwardMessage(const TBMessage &msg, const int32_t to_chatid)

AsyncTelegram2.cpp:1: In file included from

AsyncTelegram2.h: 157:10: error: candidate is: bool AsyncTelegram2::forwardMessage(const TBMessage&, int64_t)
bool forwardMessage(const TBMessage &msg, const int64_t to_chatid)`

Support photo messages

It would be great to support "photo" messages. The library currently supports "document", but it is not able to process a message such as the following one, when you send a photo to the bot. Thanks for your time building this lib, Tolentino.

{
  "ok": true,
  "result": [
    {
      "update_id": 123,
      "message": {
        "message_id": 29,
        "from": {
          "id": 123,
          "is_bot": false,
          "first_name": "XXX",
          "username": "xxx",
          "language_code": "en"
        },
        "chat": {
          "id": 1234,
          "first_name": "XXX",
          "username": "xxx",
          "type": "private"
        },
        "date": 1644678608,
        "photo": [
          {
            "file_id": "AgAredactedBA",
            "file_unique_id": "AQredactedB4",
            "file_size": 1739,
            "width": 64,
            "height": 90
          },
          {
            "file_id": "AgAredactedjBA",
            "file_unique_id": "AQredactedFB-",
            "file_size": 172225,
            "width": 909,
            "height": 1280
          }
        ]
      }
    }
  ]
}

Alternative to telegram-bot

Hi Tolentino, considering the "hot" moment that the world is going through, do you think that telegram servers or itself could be banned by the international community? Is there a valid and free alternative to telegram-bots that can be integrated into small iot projects?
Hello and thank very much

Light bot for specific user id

Hi, if you look at the examples, in the setup you find this:

int64_t user id = 123456789;
myBot.sendTo (userid, welcome_msg);

this means that only the telegam user with id = 123456789 will be able to receive replies from your bot. Similarly, you can do the same by telling your bot to receive and process responses only from one or more selected telegram ID.

Hello

Thankyou So much!! I found that code on the example and with little changes, it is working!! i have not changed anything just very minute changes. There are no errors but the message is continuously generating. Here is the code..

// i am reverifying the chatid by using simple operator and it is working!! but the bot is continuosly generating the message. the code that i have mentioned will work fine

#define USE_CLIENTSSL false  

#include <AsyncTelegram2.h>
// Timezone definition
#include <time.h>
#define MYTZ "CET-1CEST,M3.5.0,M10.5.0/3"

#ifdef ESP8266
  #include <ESP8266WiFi.h>
  BearSSL::WiFiClientSecure client;
  BearSSL::Session   session;
  BearSSL::X509List  certificate(telegram_cert);
  
#elif defined(ESP32)
  #include <WiFi.h>
  #include <WiFiClient.h>
  #if USE_CLIENTSSL
    #include <SSLClient.h>  
    #include "tg_certificate.h"
    WiFiClient base_client;
    SSLClient client(base_client, TAs, (size_t)TAs_NUM, A0, 1, SSLClient::SSL_ERROR);
  #else
    #include <WiFiClientSecure.h>
    WiFiClientSecure client;    
  #endif
#endif


AsyncTelegram2 myBot(client);
const char* ssid  =  "xxxxxxxx";     // SSID WiFi network
const char* pass  =  "xxxxxxxxxx";     // Password  WiFi network
const char* token =  "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";  // Telegram token

const int LED = 5;

void setup() {
  // initialize the Serial
  Serial.begin(115200);
  Serial.println("\nStarting TelegramBot...");

  // set the pin connected to the LED to act as output pin
  pinMode(LED, OUTPUT);
  digitalWrite(LED, LOW); // turn off the led (inverted logic!)

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, pass);
  delay(500);
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print('.');
    delay(500);
  }
  

#ifdef ESP8266
  // Sync time with NTP, to check properly Telegram certificate
  configTime(MYTZ, "time.google.com", "time.windows.com", "pool.ntp.org");
  //Set certficate, session and some other base client properies
  client.setSession(&session);
  client.setTrustAnchors(&certificate);
  client.setBufferSizes(1024, 1024);
#elif defined(ESP32)
  // Sync time with NTP
  configTzTime(MYTZ, "time.google.com", "time.windows.com", "pool.ntp.org");
  #if USE_CLIENTSSL == false
    client.setCACert(telegram_cert);
  #endif
#endif

  // Set the Telegram bot properies
  myBot.setUpdateTime(1000);
  myBot.setTelegramToken(token);

  // Check if all things are ok
  Serial.print("\nTest Telegram connection... ");
  myBot.begin() ? Serial.println("OK") : Serial.println("NOK");

  Serial.print("Bot name: @");
  Serial.println(myBot.getBotName());

  char welcome_msg[128];
  snprintf(welcome_msg, 128, "BOT @%s online\n/help all commands avalaible.", myBot.getBotName());
  int64_t chat_id = 1234567890; // You can discover your own chat id, with "Json Dump Bot"
  myBot.sendTo(chat_id, welcome_msg);

   
}

void loop() {
  // local variable to store telegram message data
  TBMessage msg;
  // if there is an incoming message...
  if( myBot.getNewMessage(msg)); {
    String msgText = msg.text;

    if (msgText.equals("/light_on")) {                 // if the received message is "LIGHT ON"...
      digitalWrite(LED, HIGH);                          // turn on the LED (inverted logic!)
      myBot.sendMessage(msg, "Light is now ON");       // notify the sender
    }
    else if (msgText.equals("/light_off")) {           // if the received message is "LIGHT OFF"...
      digitalWrite(LED, LOW);                          // turn off the led (inverted logic!)
      myBot.sendMessage(msg, "Light is now OFF");       // notify the sender
    }
    else {                                              // otherwise...
      // generate the message for the sender
      String reply;
      reply = "Welcome " ;
      reply += msg.sender.username;
      reply += ".\nTry /light_on or /light_off ";
      myBot.sendMessage(msg, reply);                    // and send it
    }
  }

}

Originally posted by @muk3shb in #41 (comment)

motion detect & send picture

Ciao Tolentino, attravero un PIR il cui pin è gestito tramite interrupt, vorrei che quando viene rilevato un movimento, il sistemi mi invii un messaggio di allert con tanto di foto. Ho scritto questa funzione ma non va:

void motion_detect() {
TBMessage msg;
if (flag_auto_detect) { // modalità motion detect inserita
if (motionDetected) { // rilevo movimento
Serial.println("beccato!");
char* filename = "/frame.jpg";
if (savePicture(filename)) {
if (sendPicture(msg, filename))
Serial.println("Picture sent successfull");
}
}
}
}

Quando il PIR rileva il movimento, vedo il flash accendersi ma la foto non viene spedita. Nella funzione che ho scritto ci sono errori? Come faccio al di fuori della funzione di telegram a gestire l'invio di messaggi quando si concretizzano degli eventi?
Grazie

CI / DC

So i'm trying to add some actions to make life easier:

  • Build library
  • Build examples
  • CppLint

See my fork's actions for more details on that

Please share your thoughs on items below:

Build libarary:

What are the dependencies for Ardunio Uno ? The main issue was with functional - is that in <StandardCplusplus> library ?

Examples:

  • Explicit library import fails for some reason. I need to use full github repo path instead.
  • UNO fails, same reason as Library

CPP Lint:

not sure if linting is needed at this point (it fails with 197 issues). If you want, I can try to find some pull-request-review-style that would say which lines have isuses for easier processing.

Issues template

For easier troubleshooting (like instruction for stack trace decoding if present), board version, etc

Pull request template

  1. Probably also sketch size comparison on pull request.
    https://github.com/arduino/report-size-deltas

Send Bold messages

Hi Tolentino, is it possible to send messages using telegram markup? in any chat if you put anything between ** its sent as bold
Also tried these and didn't work: https://core.telegram.org/api/entities
It would help a lot with the clarity of the information presented.
Thanks

image

Feedback about sending messages - successful or not successful.

Hello.
Thank you very much for your work
AsyncTelegram2 and I'm very glad that there is no stopping the main code when working.
There is one important issue: when using myBot.sendTo(userid, welcome_msg) is there a feedback function that would return "true" to the controller if the message was successfully sent and "false" if the message was not sent?
For me it is very important that if the message was not sent, resend until it is successfully sent.
Thanks!

IL vecchio ESPTelegramBOT....

Ciao Tolentino
Usavo tantissimo il precedente ESPTelegramBOT che non so per quale ragione mi da sempre Message not delivered....mi viene il dubbio che ho aggiornato qualche libreria di IDE senza rendermi conto...
Lo hai eliminato? Forse perché usava ArduinoJson 5?
Mi sai aiutare?
Grazie
Mic

welcome message

Ciao Tolentino, nei vari esempi nel setup() trovo questo blocco:

char welcome_msg[128]; snprintf(welcome_msg, 128, "BOT @%s online\n/help all commands avalaible.", myBot.getBotName()); int32_t chat_id = 436865110; myBot.sendTo(chat_id, welcome_msg);

se volessi spedire questo "messaggio di benvenuto" a 2 utenti Telegram, sai come posso fare?

Grazie 1000!

USE_CLIENTSSL ESP32

Hi, When using ESP32 & USE_CLIENTSSL = true, flash memory exceedes 100% and compilation fails.
Can you please explain what does that option means ?

Works for about 30 minutes.

My project uses an esp8266 to do two things, announce via broadcast UDP and via telegram message that the doorbell button was pressed. The UDP part works every time, but the telegram bot always work at startup but around 30 minutes after start, telegram messages are no longer delivered.
Check the screen capture, time is in 24hs format and I wrote the last message to simply show the timestamp.

Is there something I need to do to keep the telegram bot session alive?

Messages are sent using: myBot.sendTo(userid, "Timbre...!");

Thanks!

image

Unicode Command Option

Hello,
How can we use Unicode in command?
When I use Unicode, the command disappear, it shows as normal text.

For example: /\u2010\u2030

Serial prints

Hi I noticed the code has Serial.prints dotted about the place. I've moved them into ifdef DEBUG ENABLE blocks to stop spillover into the Serial when not required.

Few questions about usages with Esp8266

I have esp8266 and I want to understand how to use this library.

  1. How can I listen and send message to telegram group by group id ? I saw that example https://github.com/cotestatnt/AsyncTelegram2/blob/main/examples/echoBot/echoBot.ino and that send message to channel , not group

2)How can I send message with inline keyboard like :
https://github.com/witnessmenow/Universal-Arduino-Telegram-Bot/blob/master/src/UniversalTelegramBot.cpp#L607

3)What is the difference between that library and https://github.com/witnessmenow/Universal-Arduino-Telegram-Bot in esp8266 please>

4)When I add user to group there is automatically message "You added XXX" How can I handle that message and send to group "Welcome XXX" ?

5)With esp8266 can I really by async and not blocking another job while I send message or get message from Telegram? Esp8266 has only 1 core.
I ask because in Universal-Arduino-Telegram-Bot I got lot of software watchdog reset ,and I think it's because this library is not async.

Thank you!

In connection with closed #28 issue

Finally I got a time for testing the sketch. It has been accommodated for GSM network usage. The Telegram connection test was passed successfully (local terminal report). The "welcome" interactive message reaches to the bot. But the actual update always falls, being treated as "File is unavailable. Maybe size limit 20MB was reached or file deleted", due to boolean "msg.document.file_exists" being false. In meantime the test print of the string "msg.document.file_path" variable on monitor return blank string.

https://github.com/cotestatnt/AsyncTelegram2/issues/28

AsyncTelegram2::getNewMessage and loading in inline_keyboard

Hi !
About AsyncTelegram2::getNewMessage :

1- Do you get each time 1 message only and the next message will come in the next loop?

2- https://github.com/cotestatnt/AsyncTelegram2/blob/master/src/AsyncTelegram2.cpp#L190
Please make 12 as constant strlen(""update_id":")

3- Why do you comment out
https://github.com/cotestatnt/AsyncTelegram2/blob/master/src/AsyncTelegram2.cpp#L198

4- Why do you use "6"
https://github.com/cotestatnt/AsyncTelegram2/blob/master/src/AsyncTelegram2.cpp#L192
Can you please do that with constant value with name ?

About inline_keyboard :

When I use:

      String keyboardJson = "{\"inline_keyboard\": [[{ \"text\" : \" press here please \", \"callback_data\" : \"press1\" },{ \"text\" : \" press here please \", \"callback_data\" : \"press2\" }]]}";

      myBot.sendMessage(msg, "This is inline keyboard:", keyboardJson);

So when the user press on "press here please" in Telegram I see the "loading cycle" around 20 seconds even the message already arrived to esp. Maybe is there any ack you should send back to Telegram to stop this loading cycle?

Loading cycle like here

By the way , I saw important commits after last release , when do you make new release ?

Not issue, only questions about SSL

Hi,
i ve given a look on LIGHTBOT AsyncTelegram2 and before to begin i ve some questions:

  1. on AsyncTelegram1 library you wrote to read https://sites.google.com/a/usapiens.com/opnode/time-zones to set the correct time zone, shall i do the same with AsyncTelegram2 ?
  2. #define USE_CLIENTSSL true -> i dont know if i must use external SSL library or not, what could be difference?
  3. what are the most used classes or functions of this library? example, i think:
    -> msg.sender.username; // userID and is it as String?
    -> msg.text; //text message, as String?
    if i already have userID, how can i send message to him without answering to a message at Restart?
    is it correct:

myBot.sendMessage([sender_id], "NodeMCU restarted!");

and if so, is Sender_id a String or a int64_t or what else?

i m going using NodeMCU esp8266 and ESP32 for my sketch.
Thank you for help and sorry for my silly questions, i m trying to improve

EDIT: i see in other example EchoBot other commands:

myBot.sendTo(userid, welcome_msg);
myBot.sendToChannel(channel, message, true);
myBot.getBotName()

what's difference between sendTo and sendMessage? how to chose between them?
can we have a list of these commands?

Question about chat id

Hi,
I see that if the bot have 1000 users, so any messages from all users will be sent to all devices.

My purpose is to have multiple users using the same Bot(same token) and devices are assigned to different chat_id(users) rather than 1 device one Bot. This is too tedious.

I want to use the same token to manage 20+ esp8266 relay.
But it shows conflict error in getUpdates().
"error_code": 409, "description": "Conflict: terminated by other getUpdates request; make sure that only one bot instance is running"

Is there any way to filter update based on chat_id(user_id)?

Thanks;

Light Bot Problem 2

How can we implement TOTP on our bot ? For that there is TOTP library in Arduino and then it is saying to generate "hmac" key. or how can we limit the IP access like telegram_ip_lower or telegram_ip_upper are there any such function under Async library to limit the IP's ?

Next, can we limit the ESP32 board to sepcific IP's ? as telegram bots can be accessed by any user around the world hence, all we can do is to limit the IP access or is there any other method ?

Why sendMessage need pass an TBMessage Object?

I believe it would be much better if this had a more flexible and clear implementation.

I don't know much about programming, so I apologize in advance for my overuse of strings and possible bugs in the code, but here's an example idea to make the implementation clearer.

bool AsyncTelegramBot::sendTextMessage(int64_t chat_id, String text, String parse_mode = "Default", String entities = "", bool disable_web_page_preview = false, bool disable_notification = false, int32_t reply_to_message_id = 0, bool force_reply = false, bool allow_sending_without_reply = true, String reply_markup = "")
{
    if (!strlen(text.c_str()))
        return false;

    if (chat_id == 0)
        return false;

    DynamicJsonDocument root(BUFFER_BIG);
    // Backward compatibility
    root["chat_id"] = chat_id;
    root["text"] = text;

    if (parse_mode != "Default")
        if (parse_mode == "Markdown" || parse_mode == "MarkdownV2" || parse_mode == "HTML")
            root["parse_mode"] = parse_mode;

    if (disable_web_page_preview)
        root["disable_web_page_preview"] = disable_web_page_preview;

    if (disable_notification)
        root["disable_notification"] = disable_notification;

    if (reply_to_message_id != 0)
        root["reply_to_message_id"] = reply_to_message_id;

    if (allow_sending_without_reply)
        root["allow_sending_without_reply"] = allow_sending_without_reply;

    if (strlen(entities.c_str()))
    {
        StaticJsonDocument<BUFFER_MEDIUM> doc;
        deserializeJson(doc, entities);
        JsonObject myEntities = doc.as<JsonObject>();
        root["entities"] = myEntities;
    }

    if (strlen(reply_markup.c_str()) || force_reply)
    {
        StaticJsonDocument<BUFFER_MEDIUM> doc;
        deserializeJson(doc, reply_markup);
        JsonObject myKeyb = doc.as<JsonObject>();
        root["reply_markup"] = myKeyb;
        if (force_reply)
        {
            root["reply_markup"]["selective"] = true,
            root["reply_markup"]["force_reply"] = true;
        }
    }

    root.shrinkToFit();

    size_t len = measureJson(root);
    char payload[len];
    serializeJson(root, payload, len);

    debugJson(root, Serial);
    const bool result = sendCommand("sendMessage", payload);
    return result;
}

Error replaying a message

When replaying a message that the bot sent, it stops working, not responding to any more messages.

Looking at the serial, the following information is printed:

{"ok":true,"result":[{"update_id":289757217,
"message":{"message_id":50,"from":{"id":251360319,"is_bot":false,"first_name":"Kwecko","username":"kwecko","language_code":"pt-br"},"chat":{"id":251360319,"first_name":"Kwecko","username":"kwecko","type":"private"},"date":1645725307,"reply_to_message":{"message_id":47,"from":{"id":5254501027,"is_bot":true,"first_name":"Kdesenvbot","username":"kdesenvbot"},"chat":{"id":251360319,"first_name":"Kwecko","username":"kwecko","type":"private"},"date":1645725268,"text":"Os comandos dispon\u00edveis s\u00e3o:\n\n /temperatura : Para verificar a temperatura\n /humidade : Para verificar a humidade\n /pressao : Para verificar a press\u00e3o\n /gas : Para verificar o g\u00e1s\n /mac : Para verificar o endere\u00e7o MAC\n /ip : Para verificar o endere\u00e7o IP do ESP32\n /timeboot : Tempo em que o ESP est\u00e1 ligado\n /version : Informa a vers\u00e3o do Sistema\n /esptemp : Informa a temperatura do ESP\n /help : Listar os comandos dispon\u00edveis","entities":[{"offset":31,"length":12,"type":"bot_command"},{"offset":31,"length":12,"type":"bold"},{"offset":76,"length":9,"type":"bot_command"},{"offset":76,"length":9,"type":"bold"},{"offset":115,"length":8,"type":"bot_command"},{"offset":115,"length":8,"type":"bold"},{"offset":152,"length":4,"type":"bot_command"},{"offset":152,"length":4,"type":"bold"},{"offset":181,"length":4,"type":"bot_command"},{"offset":181,"length":4,"type":"bold"},{"offset":219,"length":3,"type":"bot_command"},{"offset":219,"length":3,"type":"bold"},{"offset":264,"length":9,"type":"bot_command"},{"offset":264,"length":9,"type":"bold"},{"offset":308,"length":8,"type":"bot_command"},{"offset":308,"length":8,"type":"bold"},{"offset":348,"length":8,"type":"bot_command"},{"offset":348,"length":8,"type":"bold"},{"offset":389,"length":5,"type":"bot_command"},{"offset":389,"length":5,"type":"bold"}]},"text":"/help","entities":[{"offset":0,"length":5,"type":"bot_command"}]}}]}

this message is printed constantly. Does anyone have any suggestions on how to get around this problem?

Thanks

languageCode

Please add the variable languageCode to AsyncTelegram2.cpp :: line 210+

message.sender.languageCode = updateDoc["result"][0]["message"]["from"]["language_code"];

lightbot Problem

i tried to run your example code & i succesfully created the bot but on serial monitor i am it is saying "Unable to connect to telegram server" i have tried changing library version and Pin configuration but still the error is same. Can you please look into it ?

Esp8266 reboot because hardware watchdog twice in 5 minutes

I run this library in esp8266 and I got reboot 2 reboot in 5 minutes (I don't know how to print core dump) but here is the log of Hardware WDT Timeout when the library cannot connect to Telegram server.
That happened in idle ...I didn't get any new message.

I know that is Hardware WDT Timeout because of this function that run in setup

void send_startup_reason() {
  String doc = "Startup  ";
  struct rst_info* pRstInfo = system_get_rst_info();
  switch (pRstInfo->reason) {
    default: doc += "Unknown"; break;
    case REASON_DEFAULT_RST: doc += "Power On (normal)"; break;
    case REASON_WDT_RST: doc += "Hardware WDT Timeout"; break;
    case REASON_EXCEPTION_RST: doc += "Exception"; break;
    case REASON_SOFT_WDT_RST: doc += "Software WDT Timeout"; break;
    case REASON_SOFT_RESTART: doc += "Soft Restart"; break;
    case REASON_DEEP_SLEEP_AWAKE: doc += "Deep Sleep Awake"; break;
    case REASON_EXT_SYS_RST: doc += "External System Reset"; break;
  }
  myBot.sendTo(MY_USER_ID, doc);

Hers is the log :


[D][AsyncTelegram2.cpp:144] getUpdates():	Connection closed from server
[D][AsyncTelegram2.cpp:28] checkConnection():	Start handshaking...
[D][AsyncTelegram2.cpp:34] checkConnection():	Connected using Telegram hostname
Last connection was 304 seconds ago

[D][AsyncTelegram2.cpp:144] getUpdates():	Connection closed from server
[D][AsyncTelegram2.cpp:28] checkConnection():	Start handshaking...
[D][AsyncTelegram2.cpp:34] checkConnection():	Connected using Telegram hostname
Last connection was 300 seconds ago

[D][AsyncTelegram2.cpp:144] getUpdates():	Connection closed from server
[D][AsyncTelegram2.cpp:28] checkConnection():	Start handshaking...

Unable to connect to Telegram server

[D][AsyncTelegram2.cpp:28] checkConnection():	Start handshaking...

Unable to connect to Telegram server

[D][AsyncTelegram2.cpp:28] checkConnection():	Start handshaking...
[D][AsyncTelegram2.cpp:34] checkConnection():	Connected using Telegram hostname
Last connection was 361 seconds ago

[D][AsyncTelegram2.cpp:54] reset():	Restart Telegram connection

[D][AsyncTelegram2.cpp:28] checkConnection():	Start handshaking...
[D][AsyncTelegram2.cpp:34] checkConnection():	Connected using Telegram hostname
Last connection was 82 seconds ago

[D][AsyncTelegram2.cpp:54] reset():	Restart Telegram connection

[D][AsyncTelegram2.cpp:28] checkConnection():	Start handshaking...

Unable to connect to Telegram server


########################################################
################Startup  Hardware WDT Timeout
########################################################


⸮⸮⸮⸮T⸮9⸮⸮Starting TelegramBot...
.......................................................................192.168.1.126

Test Telegram connection... 
[D][AsyncTelegram2.cpp:28] checkConnection():	Start handshaking...
[D][AsyncTelegram2.cpp:34] checkConnection():	Connected using Telegram hostname
Last connection was 12 seconds ago

[D][AsyncTelegram2.cpp:323] getMe():	
{
  "ok": true,
  "result": {
    "id": XXXXXXX,
    "is_bot": true,
    "first_name": "XXXXXXXX",
    "username": "XXXXXXXX",
    "can_join_groups": true,
    "can_read_all_group_messages": false,
    "supports_inline_queries": false
  }
}
OK


[D][AsyncTelegram2.cpp:54] reset():	Restart Telegram connection

[D][AsyncTelegram2.cpp:28] checkConnection():	Start handshaking...
[D][AsyncTelegram2.cpp:34] checkConnection():	Connected using Telegram hostname
Last connection was 53 seconds ago

[D][AsyncTelegram2.cpp:54] reset():	Restart Telegram connection

[D][AsyncTelegram2.cpp:28] checkConnection():	Start handshaking...

Unable to connect to Telegram server

[D][AsyncTelegram2.cpp:28] checkConnection():	Start handshaking...
[D][AsyncTelegram2.cpp:34] checkConnection():	Connected using Telegram hostname
Last connection was 41 seconds ago

[D][AsyncTelegram2.cpp:54] reset():	Restart Telegram connection

[D][AsyncTelegram2.cpp:28] checkConnection():	Start handshaking...
[D][AsyncTelegram2.cpp:34] checkConnection():	Connected using Telegram hostname
Last connection was 23 seconds ago

[D][AsyncTelegram2.cpp:54] reset():	Restart Telegram connection

[D][AsyncTelegram2.cpp:28] checkConnection():	Start handshaking...
[D][AsyncTelegram2.cpp:34] checkConnection():	Connected using Telegram hostname
Last connection was 46 seconds ago

[D][AsyncTelegram2.cpp:54] reset():	Restart Telegram connection

[D][AsyncTelegram2.cpp:28] checkConnection():	Start handshaking...

Unable to connect to Telegram server

########################################################
################Startup  Hardware WDT Timeout
########################################################

⸮؁�Z⸮�⸮⸮0�Starting TelegramBot...
..............................................192.168.1.126

Test Telegram connection... 
[D][AsyncTelegram2.cpp:28] checkConnection():	Start handshaking...
[D][AsyncTelegram2.cpp:34] checkConnection():	Connected using Telegram hostname
Last connection was 8 seconds ago

[D][AsyncTelegram2.cpp:323] getMe():	
{
  "ok": true,
  "result": {
    "id": xxxxxx,
    "is_bot": true,
    "first_name": "xxxxxxx",
    "username": "xxxxxx",
    "can_join_groups": true,
    "can_read_all_group_messages": false,
    "supports_inline_queries": false
  }
}
OK


[D][AsyncTelegram2.cpp:54] reset():	Restart Telegram connection

[D][AsyncTelegram2.cpp:28] checkConnection():	Start handshaking...
[D][AsyncTelegram2.cpp:34] checkConnection():	Connected using Telegram hostname
Last connection was 82 seconds ago

[D][AsyncTelegram2.cpp:54] reset():	Restart Telegram connection

[D][AsyncTelegram2.cpp:28] checkConnection():	Start handshaking...
[D][AsyncTelegram2.cpp:34] checkConnection():	Connected using Telegram hostname
Last connection was 64 seconds ago

[D][AsyncTelegram2.cpp:144] getUpdates():	Connection closed from server
[D][AsyncTelegram2.cpp:28] checkConnection():	Start handshaking...
[D][AsyncTelegram2.cpp:34] checkConnection():	Connected using Telegram hostname
Last connection was 334 seconds ago



esp8266 is blocked

when receiving invalid JSON, ESP is blocked for about 15 minutes

00:13:45.169 -> [E][AsyncTelegram2.cpp:183] getNewMessage():	deserializeJson() failed
00:13:45.169 -> 
00:13:45.169 -> 
00:13:45.169 -> [E][AsyncTelegram2.cpp:184] getNewMessage():	IncompleteInput
00:13:45.169 -> {"ok":true,"result":{"message_id":16672,"from":{"id":2056******,"is_bot":true,"first_name":"smp***","username":"smp******"},"chat":{"id":-611******,"title":"Test \u0410\u041d\u0414-02","type":"group","all_members_are_administrators":true},"date":1642965225,"text":"\u2139 \u0410\u0432\u0430\u0440\u0438\u044f \u043d\u0438\u0437\u043a\u043e\u0439 \u0442\u0435\u043c\u043f\u0435\u0440\u0430\u0442\u0443\u0440\u044b! \u2744\n\ud83c\udf21\u0422\u0435\u043c\u043f\u0435\u0440\u0430\u0442\u0443\u0440\u0430 \u043a\u043e\u0442\u043b\u0430: 0.0\u00b0\u0421\n\ud83d\udd25\u041c\u0430\u043a\u0441.\u0442\u0435\u043c\u043f\u0435\u0440\u0430
00:28:45.226 -> 
00:28:45.226 -> 
00:28:45.226 -> [E][AsyncTelegram2.cpp:156] getUpdates():	
00:28:47.240 -> [D][AsyncTelegram2.cpp:28] checkConnection():	Start handshaking...
00:28:51.632 -> [D][AsyncTelegram2.cpp:34] checkConnection():	Connected using Telegram hostname
00:28:51.632 -> Last connection was 995 seconds ago

How to interface PIR (HIGH when movement is detected)

Thank you for your new library, the old one was already good but this is even better.
You can answer in italian if you want, I understand it but can't write it very well.

I have some of these PIR in the photos and the output goes HIGH for up to 5min (user regulated) after movement is detected.

Do I just need to change the following lines or is there a better way?

// PIR Motion Sensor setup
  pinMode(PIR_PIN, INPUT);

and

// PIR motion detected 
    // could be on interrupt, but PIR sensor usually keep signal HIGH for enough time
    if(digitalRead(PIR_PIN) == HIGH) {   
      currentPict = 0;
      waitPhotoTime = 0;
      char message[50];
      time_t now = time(nullptr);
      tInfo = *localtime(&now);
      strftime(message, 50, "%d/%m/%Y %H:%M:%S - Motion detected!", &tInfo);
      Serial.println(message);
      myBot.sendTo(userid, message);
    }

1390
schematic

Info version library

Ciao Tolentino, ben ritrovato e auguri di buon Natale e anno nuovo!

Volevo dirti che l'IDE arduino non notifica l'aggiornamento della tua libreria alla versione 2.0.5 e che quindi l'update va fatto manualmente. Effettuando l'aggiormento alla versione 2.0.5 e scaricando lo zip "AsyncTelegram2-2.0.5.zip" arduino però mi notifica che la versione installata è ancora la 2.0.4. Come mai?
Inoltre nel file "library.properties" leggo 2.0.4.
So cercando di usare la formattazione bold nel testo di risposta di un messaggio, ma sia in html che markdown v2, i messaggi così formattati non vengono inviati.
Grazie e ciao

Hello Tolentino, welcome back and best wishes for a Merry Christmas and New Year!

I wanted to tell you that the arduino IDE does not notify the update of your library to version 2.0.5 and that therefore the update must be done manually. By upgrading to version 2.0.5 and downloading the zip "AsyncTelegram2-2.0.5.zip" arduino, however, notifies me that the installed version is still 2.0.4. How come?
Also in the "library.properties" file I read 2.0.4.
I know trying to use bold formatting in the reply text of a message, but in both html and markdown v2, messages so formatted are not sent.
Thanks and bye

lost messages

Ciao Tolentino, provando l'esempio ESP32-CAM che hai aggiornato qualche giorno fa (ma succedeva anche con le precedenti versioni), noto che se si inviano messaggi molto ravvicivati (qualche secondo) la scheda (ESP-32 CAM) pur ricevendo il messaggio non scatta e di conseguenza non invia la foto. E' come se si perdesse dei messaggi. Idee?

Hi Tolentino, trying the ESP32-CAM example that you updated a few days ago (but it also happened with the previous versions), I notice that if you send very close messages (a few seconds) the card (ESP-32 CAM) while receiving the message does not take and consequently does not send the photo. It's like missing messages. Ideas?

Bot Not receiving Channel Messages

Good day Tolentino,
I dont know if anyone had the same issue, I found no info, so I thought to ask you directly.

When I use
myBotgetNewMessage(msg)

I do not receive messages on my ESP8266 from a groupchat where my bot is an admin. Also my bot's privacy was set as public, even if I start the message with "/xxxxx" or "@MYBOT" I do not receive any message typed in a group.

I do receive the messages on the esp8266 from direct message to my bot.
I would like to be able to use a group, for transparency and to have all messages in one place, as a security and automation of my home where me and my family can message the bot to open door or gates or get alarms.

Thank you.

How to disable the bot?

When for some reason the connection to the bot router is lost when trying to connect, the ESP 32 cycle becomes 20 seconds. How can I turn it off when there is no connection?

P.S. I don’t know English well, translated through Google )

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.