import network
import urequests
import time
import dht
from machine import Pin
# WiFi (Wokwi Virtual WiFi)
SSID = "Wokwi-GUEST"
PASSWORD = ""
# Telegram
BOT_TOKEN = ""
CHAT_ID = ""
# Sensor
sensor = dht.DHT22(Pin(15))
# Connect WiFi
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect(SSID, PASSWORD)
print("Connecting to WiFi...", end="")
while not wifi.isconnected():
print(".", end="")
time.sleep(0.5)
print("\nConnected!")
# ⚠️ Using HTTP instead of HTTPS (important for Pico W stability)
GET_URL = f"https://api.telegram.org/bot{BOT_TOKEN}/getUpdates"
SEND_URL = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"
last_update_id = 0
def get_updates():
global last_update_id
try:
url = GET_URL + "?offset=" + str(last_update_id + 1)
res = urequests.get(url)
data = res.json()
res.close()
if data["ok"]:
for item in data["result"]:
last_update_id = item["update_id"]
msg = item["message"]["text"]
chat = str(item["message"]["chat"]["id"])
return msg, chat
except Exception as e:
print("Get Error:", e)
return None, None
def send_message(text):
try:
payload = {
"chat_id": CHAT_ID,
"text": text
}
headers = {"Content-Type": "application/json"}
res = urequests.post(SEND_URL, json=payload, headers=headers)
print("Telegram response:", res.text) # Debug
res.close()
except Exception as e:
print("Send Error:", e)
# Main Loop
while True:
msg, chat = get_updates()
if msg:
print("Received:", msg)
if msg.lower() == "request":
try:
sensor.measure()
temp = sensor.temperature()
hum = sensor.humidity()
reply = f"Temp: {temp} C\nHumidity: {hum} %"
time.sleep(1) # small delay improves reliability
send_message(reply)
except Exception as e:
print("Sensor error:", e)
send_message("Sensor Error!")
time.sleep(2)