NodeMCU и Telegram

Oksymoron
Offline
Зарегистрирован: 28.01.2017

Добрый вечер!! помогите изменить код, на просторах нашел рабочий код, но не могу его переделать на работу с массивом CHAT_ID.

#include <ESP8266WiFi.h>

001#include <WiFiClientSecure.h>
002#include <UniversalTelegramBot.h>
003 
004// Wifi network station credentials
005#define WIFI_SSID "xxx"
006#define WIFI_PASSWORD "xxx"
007// Telegram BOT Token (Get from Botfather)
008#define BOT_TOKEN "xxx"
009 
010const unsigned long BOT_MTBS = 1000; // mean time between scan messages
011 
012X509List cert(TELEGRAM_CERTIFICATE_ROOT);
013WiFiClientSecure secured_client;
014UniversalTelegramBot bot(BOT_TOKEN, secured_client);
015unsigned long bot_lasttime; // last time messages' scan has been done
016 
017const int ledPin = LED_BUILTIN;
018int ledStatus = 0;
019 
020void handleNewMessages(int numNewMessages)
021{
022  Serial.print("handleNewMessages ");
023  Serial.println(numNewMessages);
024 
025  for (int i = 0; i < numNewMessages; i++)
026  {
027    String chat_id = bot.messages[i].chat_id;
028    String text = bot.messages[i].text;
029 
030    String from_name = bot.messages[i].from_name;
031    if (from_name == "")
032      from_name = "Guest";
033 
034    if (text == "/ledon")
035    {
036      digitalWrite(ledPin, LOW); // turn the LED on (HIGH is the voltage level)
037      ledStatus = 1;
038      bot.sendMessage(chat_id, "Led is ON", "");
039    }
040 
041    if (text == "/ledoff")
042    {
043      ledStatus = 0;
044      digitalWrite(ledPin, HIGH); // turn the LED off (LOW is the voltage level)
045      bot.sendMessage(chat_id, "Led is OFF", "");
046    }
047 
048    if (text == "/status")
049    {
050      if (ledStatus)
051      {
052        bot.sendMessage(chat_id, "Led is ON", "");
053      }
054      else
055      {
056        bot.sendMessage(chat_id, "Led is OFF", "");
057      }
058    }
059 
060    if (text == "/start")
061    {
062      String welcome = "Welcome to Universal Arduino Telegram Bot library, " + from_name + ".\n";
063      welcome += "This is Flash Led Bot example.\n\n";
064      welcome += "/ledon : to switch the Led ON\n";
065      welcome += "/ledoff : to switch the Led OFF\n";
066      welcome += "/status : Returns current status of LED\n";
067      bot.sendMessage(chat_id, welcome, "Markdown");
068    }
069  }
070}
071 
072 
073void setup()
074{
075  Serial.begin(115200);
076  Serial.println();
077 
078  pinMode(ledPin, OUTPUT); // initialize digital ledPin as an output.
079  delay(10);
080  digitalWrite(ledPin, HIGH); // initialize pin as off (active LOW)
081 
082  // attempt to connect to Wifi network:
083  configTime(0, 0, "pool.ntp.org");      // get UTC time via NTP
084  secured_client.setTrustAnchors(&cert); // Add root certificate for api.telegram.org
085  Serial.print("Connecting to Wifi SSID ");
086  Serial.print(WIFI_SSID);
087  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
088  while (WiFi.status() != WL_CONNECTED)
089  {
090    Serial.print(".");
091    delay(500);
092  }
093  Serial.print("\nWiFi connected. IP address: ");
094  Serial.println(WiFi.localIP());
095 
096  // Check NTP/Time, usually it is instantaneous and you can delete the code below.
097  Serial.print("Retrieving time: ");
098  time_t now = time(nullptr);
099  while (now < 24 * 3600)
100  {
101    Serial.print(".");
102    delay(100);
103    now = time(nullptr);
104  }
105  Serial.println(now);
106}
107 
108void loop()
109{
110  if (millis() - bot_lasttime > BOT_MTBS)
111  {
112    int numNewMessages = bot.getUpdates(bot.last_message_received + 1);
113 
114    while (numNewMessages)
115    {
116      Serial.println("got response");
117      handleNewMessages(numNewMessages);
118      numNewMessages = bot.getUpdates(bot.last_message_received + 1);
119    }
120 
121    bot_lasttime = millis();
122  }
123}

 

b707
Offline
Зарегистрирован: 26.05.2017

вы прям так уверены. что любой знает, где тут должен быть этот массив?

Oksymoron
Offline
Зарегистрирован: 28.01.2017

b707 пишет:

вы прям так уверены. что любой знает, где тут должен быть этот массив?

отсюда пытаюсь взять строки https://randomnerdtutorials.com/telegram-control-esp32-esp8266-nodemcu-outputs/

Oksymoron
Offline
Зарегистрирован: 28.01.2017

b707 пишет:

вы прям так уверены. что любой знает, где тут должен быть этот массив?

получилось так но выкидывает ошибку при компилировании 'text' was not declared in this scope

001#include <ESP8266WiFi.h>
002#include <WiFiClientSecure.h>
003#include <UniversalTelegramBot.h>
004 
005// Wifi network station credentials
006#define WIFI_SSID "D9"
007#define WIFI_PASSWORD "хххх"
008// Telegram BOT Token (Get from Botfather)
009#define BOT_TOKEN "хххх"
010#define CHAT_ID "XXXXXXXXXX"
011 
012 
013const unsigned long BOT_MTBS = 1000; // mean time between scan messages
014 
015X509List cert(TELEGRAM_CERTIFICATE_ROOT);
016WiFiClientSecure secured_client;
017UniversalTelegramBot bot(BOT_TOKEN, secured_client);
018unsigned long bot_lasttime; // last time messages' scan has been done
019 
020const int ledPin = LED_BUILTIN;
021int ledStatus = 0;
022 
023void handleNewMessages(int numNewMessages)
024{
025  Serial.print("handleNewMessages ");
026  Serial.println(numNewMessages);
027 
028  for (int i = 0; i < numNewMessages; i++)
029  {
030   String chat_id = String(bot.messages[i].chat_id);
031    if (chat_id != CHAT_ID){
032      bot.sendMessage(chat_id, "Unauthorized user", "");
033      continue;
034     
035    String from_name = bot.messages[i].from_name;
036    if (from_name == "")
037      from_name = "Guest";
038 
039    if (text == "/ledon")
040    {
041      digitalWrite(ledPin, LOW); // turn the LED on (HIGH is the voltage level)
042      ledStatus = 1;
043      bot.sendMessage(chat_id, "Led is ON", "");
044    }
045 
046    if (text == "/ledoff")
047    {
048      ledStatus = 0;
049      digitalWrite(ledPin, HIGH); // turn the LED off (LOW is the voltage level)
050      bot.sendMessage(chat_id, "Led is OFF", "");
051    }
052 
053    if (text == "/status")
054    {
055      if (ledStatus)
056      {
057        bot.sendMessage(chat_id, "Led is ON", "");
058      }
059      else
060      {
061        bot.sendMessage(chat_id, "Led is OFF", "");
062      }
063    }
064 
065    if (text == "/start")
066    {
067      String welcome = "Welcome to Universal Arduino Telegram Bot library, " + from_name + ".\n";
068      welcome += "This is Flash Led Bot example.\n\n";
069      welcome += "/ledon : to switch the Led ON\n";
070      welcome += "/ledoff : to switch the Led OFF\n";
071      welcome += "/status : Returns current status of LED\n";
072      bot.sendMessage(chat_id, welcome, "Markdown");
073    }
074  }
075}
076 
077 
078void setup()
079{
080  Serial.begin(115200);
081  Serial.println();
082 
083  pinMode(ledPin, OUTPUT); // initialize digital ledPin as an output.
084  delay(10);
085  digitalWrite(ledPin, HIGH); // initialize pin as off (active LOW)
086 
087  // attempt to connect to Wifi network:
088  configTime(0, 0, "pool.ntp.org");      // get UTC time via NTP
089  secured_client.setTrustAnchors(&cert); // Add root certificate for api.telegram.org
090  Serial.print("Connecting to Wifi SSID ");
091  Serial.print(WIFI_SSID);
092  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
093  while (WiFi.status() != WL_CONNECTED)
094  {
095    Serial.print(".");
096    delay(500);
097  }
098  Serial.print("\nWiFi connected. IP address: ");
099  Serial.println(WiFi.localIP());
100 
101  // Check NTP/Time, usually it is instantaneous and you can delete the code below.
102  Serial.print("Retrieving time: ");
103  time_t now = time(nullptr);
104  while (now < 24 * 3600)
105  {
106    Serial.print(".");
107    delay(100);
108    now = time(nullptr);
109  }
110  Serial.println(now);
111}
112 
113void loop()
114{
115  if (millis() - bot_lasttime > BOT_MTBS)
116  {
117    int numNewMessages = bot.getUpdates(bot.last_message_received + 1);
118 
119    while (numNewMessages)
120    {
121      Serial.println("got response");
122      handleNewMessages(numNewMessages);
123      numNewMessages = bot.getUpdates(bot.last_message_received + 1);
124    }
125 
126    bot_lasttime = millis();
127  }
128}
b707
Offline
Зарегистрирован: 26.05.2017

всегда цитируйте сообщение об ошибках ПОЛНОСТЬЮ!

SergeiL
SergeiL аватар
Offline
Зарегистрирован: 05.11.2018

Строка 028 кода из первого поста потеряна в коде из #3

1String text = bot.messages[i].text;

От этого  ошибка. Дальше не смотрел.

 

Oksymoron
Offline
Зарегистрирован: 28.01.2017

Все получилось спасибо, еще вопросик а как добавить несколько CHAT_ID???