import network, time
# นำไลบรารีสำหรับ ติดต่อเว็บ/อินเทอร์เน็ต มาใช้ใน MicroPython
import urequests as requests
from machine import Pin,PWM
SSID = "Wokwi-GUEST" # ชื่อ WiFi
PASSWORD = "" # รหัสผ่าน (Wokwi ไม่ต้องใส่)
# ตั้งใจฟังวิธีหา Bot_Token กับ CHAT_ID ดีดีนะ
BOT_TOKEN = "8339004546:AAG9P3oGVmKcabl8v2e5XuC2c3z8zXcInrs"
# การหา chat id ให้วาง token
# https://api.telegram.org/bot<YOUR_BOT_TOKEN>/getUpdates
CHAT_ID = "8297523819"
LED = Pin(18, Pin.OUT)
LED.value(0)
buzzer = PWM(Pin(25))
buzzer.duty(0)
# สร้างที่อยู่หลัก (Base URL) สำหรับเรียก Telegram Bot API
BASE = "https://api.telegram.org/bot{}".format(BOT_TOKEN)
# ส่วนของการเชื่อมต่อ WiFi ถ้าต่อสำเร็จจะแสดง เลข IP Address ด้านล่าง
def wifi_connect():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
wlan.connect(SSID, PASSWORD)
print("Connecting WiFi...", end="")
while not wlan.isconnected():
print(".", end="")
time.sleep(0.5)
print("\n WiFi:", wlan.ifconfig())
return wlan
# ส่งข้อความจาก ESP32 ไปแสดงในแชตของ Telegram
def send_message(text):
url = BASE + "/sendMessage"
data = {"chat_id": CHAT_ID, "text": text}
try:
r = requests.post(url, json=data)
r.close()
except Exception as e:
print("send_message error:", e)
# ไปถาม Telegram ว่า มีข้อความใหม่อะไรส่งมาหาบอทบ้าง? เหมือนคอยอัปเดตว่ามีข้อความอะไรมาบ้าง
def get_updates(offset=None):
url = BASE + "/getUpdates?timeout=10"
if offset is not None:
url += "&offset={}".format(offset)
try:
r = requests.get(url)
data = r.json()
r.close()
return data
except Exception as e:
print("get_updates error:", e)
return {"ok": False, "result": []}
wifi_connect()
send_message("ESP32 Ready")
last_update_id = None
while True:
# บอก Telegram ว่า ขอข้อความใหม่ที่ยังไม่เคยอ่าน
updates = get_updates(None if last_update_id is None else (last_update_id + 1))
if updates.get("ok"):
for item in updates["result"]:
# ขอข้อมูลใหม่เท่านั้น ไม่ต้องเอาของเก่ามาอีก
last_update_id = item["update_id"]
# ถ้าเหตุการณ์นี้ ไม่ใช่ข้อความใหม่ → ข้ามไป
if "message" not in item:
continue
# ดึงเฉพาะส่วน ข้อความ ออกมา
msg = item["message"]
# ข้อความนี้มาจากใคร
chat_id = str(msg["chat"]["id"])
# ข้อความที่ผู้ใช้พิมพ์
text = msg.get("text", "")
# ล็อกเฉพาะแชตที่อนุญาต
if chat_id != CHAT_ID:
continue
if text == "/on":
LED.value(1)
send_message("Opened")
print("Opened")
elif text == "/off":
LED.value(0)
send_message("Closed")
print("Closed")
elif text == "/status":
send_message("LED: {}".format("ON" if LED.value() else "OFF"))
print("LED: {}".format("ON" if LED.value() else "OFF"))
else:
send_message("I don't understand")
time.sleep(0.2)