Update main.py

This commit is contained in:
2026-02-01 14:57:37 +00:00
parent 363797db36
commit 91df268a57

58
main.py
View File

@@ -1,5 +1,4 @@
import time
import random
import requests
from datetime import datetime
@@ -10,10 +9,11 @@ SMS_PASS = "Cupakabra17"
RECEIVE_URL = "https://sms.internet-master.cz/receive/"
SEND_URL = "https://sms.internet-master.cz/send/"
BASE_POLL_INTERVAL = 15 # seconds (was 3)
MAX_BACKOFF = 300 # 5 minutes
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)"
@@ -21,34 +21,38 @@ HEADERS = {
# =======================
# Reuse TCP connections (important)
session = requests.Session()
session.headers.update(HEADERS)
def fetch_inbox():
params = {
r = session.get(
RECEIVE_URL,
params={
"username": SMS_USER,
"password": SMS_PASS,
"limit": 5
}
r = session.get(RECEIVE_URL, params=params, timeout=10)
},
timeout=5
)
r.raise_for_status()
return r.json()
def send_sms(number, message):
params = {
r = session.get(
SEND_URL,
params={
"number": number,
"message": message,
"username": SMS_USER,
"password": SMS_PASS
}
r = session.get(SEND_URL, params=params, timeout=10)
},
timeout=5
)
r.raise_for_status()
print("SEND RESPONSE:", r.text)
print("📤 SEND:", r.text)
def get_weather(city):
url = f"https://wttr.in/{city}?format=j1"
r = session.get(url, timeout=10)
r = session.get(f"https://wttr.in/{city}?format=j1", timeout=5)
if r.status_code != 200:
return f"❌ Weather unavailable for {city}"
@@ -65,28 +69,20 @@ def get_weather(city):
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 (no API key)")
poll_interval = BASE_POLL_INTERVAL
print("📡 SMS Weather Bot started (≤5s reply mode)")
while True:
try:
data = fetch_inbox()
inbox = data.get("inbox", [])
# reset backoff on success
poll_interval = BASE_POLL_INTERVAL
if not inbox:
time.sleep(poll_interval)
continue
error_count = 0 # reset on success
for sms in inbox:
offset = sms["offset"]
@@ -101,15 +97,17 @@ while True:
reply = get_weather(text)
send_sms(phone, reply)
print(f"📤 Sent reply to {phone}")
seen_offsets.add(offset)
print(f"✅ Replied to {phone}")
except Exception as e:
print("⚠ Error:", e)
error_count += 1
print("⚠ ERROR:", e)
# exponential backoff + jitter
poll_interval = min(poll_interval * 2, MAX_BACKOFF)
# jitter prevents perfectly periodic polling
time.sleep(poll_interval + random.randint(0, 5))
# 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)