113 lines
2.6 KiB
Python
113 lines
2.6 KiB
Python
import time
|
|
import requests
|
|
from datetime import datetime
|
|
|
|
# ===== SMS GATEWAY =====
|
|
SMS_USER = "weatherbot"
|
|
SMS_PASS = "Cupakabra17"
|
|
|
|
RECEIVE_URL = "https://sms.internet-master.cz/receive/"
|
|
SEND_URL = "https://sms.internet-master.cz/send/"
|
|
|
|
POLL_INTERVAL = 1 # 🔥 1 second polling (worst-case ≤5s)
|
|
MAX_ERRORS_BEFORE_SLEEP = 3
|
|
|
|
seen_offsets = set()
|
|
error_count = 0
|
|
|
|
HEADERS = {
|
|
"User-Agent": "weatherbot/1.0 (jakub@jimbuntu)"
|
|
}
|
|
|
|
# =======================
|
|
|
|
session = requests.Session()
|
|
session.headers.update(HEADERS)
|
|
|
|
def fetch_inbox():
|
|
r = session.get(
|
|
RECEIVE_URL,
|
|
params={
|
|
"username": SMS_USER,
|
|
"password": SMS_PASS,
|
|
"limit": 5
|
|
},
|
|
timeout=5
|
|
)
|
|
r.raise_for_status()
|
|
return r.json()
|
|
|
|
def send_sms(number, message):
|
|
r = session.get(
|
|
SEND_URL,
|
|
params={
|
|
"number": number,
|
|
"message": message,
|
|
"username": SMS_USER,
|
|
"password": SMS_PASS
|
|
},
|
|
timeout=5
|
|
)
|
|
r.raise_for_status()
|
|
print("📤 SEND:", r.text)
|
|
|
|
def get_weather(city):
|
|
r = session.get(f"https://wttr.in/{city}?format=j1", timeout=5)
|
|
|
|
if r.status_code != 200:
|
|
return f"❌ Weather unavailable for {city}"
|
|
|
|
data = r.json()
|
|
weather = data.get("weather", [])
|
|
|
|
if len(weather) < 3:
|
|
return f"❌ Weather unavailable for {city}"
|
|
|
|
msg = f"🌦 Weather for {city}:\n"
|
|
|
|
for day in weather[:3]:
|
|
date = day["date"]
|
|
avgtemp = day["avgtempC"]
|
|
desc = day["hourly"][0]["weatherDesc"][0]["value"]
|
|
weekday = datetime.strptime(date, "%Y-%m-%d").strftime("%a")
|
|
msg += f"{weekday}: {avgtemp}°C, {desc}\n"
|
|
|
|
return msg.strip()
|
|
|
|
# ===== MAIN LOOP =====
|
|
print("📡 SMS Weather Bot started (≤5s reply mode)")
|
|
|
|
while True:
|
|
try:
|
|
data = fetch_inbox()
|
|
inbox = data.get("inbox", [])
|
|
|
|
error_count = 0 # reset on success
|
|
|
|
for sms in inbox:
|
|
offset = sms["offset"]
|
|
if offset in seen_offsets:
|
|
continue
|
|
|
|
phone = sms["phone"]
|
|
text = sms["message"].strip()
|
|
|
|
print(f"📨 {phone}: {text}")
|
|
|
|
reply = get_weather(text)
|
|
send_sms(phone, reply)
|
|
|
|
seen_offsets.add(offset)
|
|
print(f"✅ Replied to {phone}")
|
|
|
|
except Exception as e:
|
|
error_count += 1
|
|
print("⚠ ERROR:", e)
|
|
|
|
# If gateway is unstable, slow down briefly
|
|
if error_count >= MAX_ERRORS_BEFORE_SLEEP:
|
|
print("⏳ Too many errors, sleeping 5s")
|
|
time.sleep(5)
|
|
error_count = 0
|
|
|
|
time.sleep(POLL_INTERVAL) |