#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include <ArduinoJson.h>

// Wi-Fi credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";

// Telegram bot credentials
const char* telegramToken = "5711693392:AAEUASm_bSmfnqUdoef3hN8ZjUnp4dWHV6A"; //"5992106882:AAFONXAkytzl5uF8-FDEai47tpvhV5M7g5Y";
UniversalTelegramBot bot(telegramToken);

// Chat ID for the user or group to send the message to
const char* chatId = "542689770";

void setup() {
  Serial.begin(9600);

  // Connect to Wi-Fi network
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");

  // Start the Telegram bot
  bot.begin();
}

void loop() {
  // Check for new incoming messages
  int numNewMessages = bot.getUpdates(bot.last_message_received + 1);

  // Process each new message
  for (int i = 0; i < numNewMessages; i++) {
    String chatId = String(bot.messages[i].chat_id);
    String text = bot.messages[i].text;

    // Parse JSON message
    DynamicJsonDocument jsonMessage(1024);
    deserializeJson(jsonMessage, text);

    // Get the value of the "message" key
    String message = jsonMessage["message"];

    // Send a response message
    bot.sendMessage(chatId, "You said: " + message);
  }

  delay(1000);
}