#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include <ArduinoJson.h>
#include <DHT.h>
#define DHTPIN 4
#define DHTTYPE DHT22
#define LED 2
const char* ssid = "Wokwi-GUEST";
const char* password = "";
#define BOTtoken "8603625589:AAEpymDeDW8OZJrSXBTJfVtYOQIsKICHwk4"
#define CHAT_ID "809125822"
WiFiClientSecure client;
UniversalTelegramBot bot(BOTtoken, client);
DHT dht(DHTPIN, DHTTYPE);
unsigned long lastTimeBotRan;
int botRequestDelay = 2000;
bool ledState = false;
void setup() {
Serial.begin(115200);
pinMode(LED, OUTPUT);
digitalWrite(LED, LOW);
dht.begin();
WiFi.begin(ssid, password);
Serial.print("Connecting...");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nConnected to WiFi");
client.setInsecure(); // skip certificate verification
}
void handleNewMessages(int numNewMessages) {
for (int i = 0; i < numNewMessages; i++) {
String chat_id = String(bot.messages[i].chat_id);
String text = bot.messages[i].text;
if (text == "/start") {
bot.sendMessage(chat_id,
"Commands:\n"
"/on - Turn LED ON\n"
"/off - Turn LED OFF\n"
"/status - LED Status\n"
"/sensor - Get Temp & Humidity\n", "");
}
if (text == "/on") {
digitalWrite(LED, HIGH);
ledState = true;
bot.sendMessage(chat_id, "LED is ON", "");
}
if (text == "/off") {
digitalWrite(LED, LOW);
ledState = false;
bot.sendMessage(chat_id, "LED is OFF", "");
}
if (text == "/status") {
bot.sendMessage(chat_id, ledState ? "LED ON" : "LED OFF", "");
}
if (text == "/sensor") {
float temp = dht.readTemperature();
float hum = dht.readHumidity();
if (isnan(temp) || isnan(hum)) {
bot.sendMessage(chat_id, "Sensor error!", "");
return;
}
String msg = "🌡 Temp: " + String(temp) + " °C\n";
msg += "💧 Humidity: " + String(hum) + " %";
bot.sendMessage(chat_id, msg, "");
}
}
}
void loop() {
if (millis() - lastTimeBotRan > botRequestDelay) {
int numNewMessages = bot.getUpdates(bot.last_message_received + 1);
while (numNewMessages) {
handleNewMessages(numNewMessages);
numNewMessages = bot.getUpdates(bot.last_message_received + 1);
}
lastTimeBotRan = millis();
}
}