Update main.py

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

54
main.py
View File

@@ -1,5 +1,4 @@
import time import time
import random
import requests import requests
from datetime import datetime from datetime import datetime
@@ -10,10 +9,11 @@ SMS_PASS = "Cupakabra17"
RECEIVE_URL = "https://sms.internet-master.cz/receive/" RECEIVE_URL = "https://sms.internet-master.cz/receive/"
SEND_URL = "https://sms.internet-master.cz/send/" SEND_URL = "https://sms.internet-master.cz/send/"
BASE_POLL_INTERVAL = 15 # seconds (was 3) POLL_INTERVAL = 1 # 🔥 1 second polling (worst-case ≤5s)
MAX_BACKOFF = 300 # 5 minutes MAX_ERRORS_BEFORE_SLEEP = 3
seen_offsets = set() seen_offsets = set()
error_count = 0
HEADERS = { HEADERS = {
"User-Agent": "weatherbot/1.0 (jakub@jimbuntu)" "User-Agent": "weatherbot/1.0 (jakub@jimbuntu)"
@@ -21,34 +21,38 @@ HEADERS = {
# ======================= # =======================
# Reuse TCP connections (important)
session = requests.Session() session = requests.Session()
session.headers.update(HEADERS) session.headers.update(HEADERS)
def fetch_inbox(): def fetch_inbox():
r = session.get(
RECEIVE_URL,
params={ params={
"username": SMS_USER, "username": SMS_USER,
"password": SMS_PASS, "password": SMS_PASS,
"limit": 5 "limit": 5
} },
r = session.get(RECEIVE_URL, params=params, timeout=10) timeout=5
)
r.raise_for_status() r.raise_for_status()
return r.json() return r.json()
def send_sms(number, message): def send_sms(number, message):
r = session.get(
SEND_URL,
params={ params={
"number": number, "number": number,
"message": message, "message": message,
"username": SMS_USER, "username": SMS_USER,
"password": SMS_PASS "password": SMS_PASS
} },
r = session.get(SEND_URL, params=params, timeout=10) timeout=5
)
r.raise_for_status() r.raise_for_status()
print("SEND RESPONSE:", r.text) print("📤 SEND:", r.text)
def get_weather(city): def get_weather(city):
url = f"https://wttr.in/{city}?format=j1" r = session.get(f"https://wttr.in/{city}?format=j1", timeout=5)
r = session.get(url, timeout=10)
if r.status_code != 200: if r.status_code != 200:
return f"❌ Weather unavailable for {city}" return f"❌ Weather unavailable for {city}"
@@ -65,28 +69,20 @@ def get_weather(city):
date = day["date"] date = day["date"]
avgtemp = day["avgtempC"] avgtemp = day["avgtempC"]
desc = day["hourly"][0]["weatherDesc"][0]["value"] desc = day["hourly"][0]["weatherDesc"][0]["value"]
weekday = datetime.strptime(date, "%Y-%m-%d").strftime("%a") weekday = datetime.strptime(date, "%Y-%m-%d").strftime("%a")
msg += f"{weekday}: {avgtemp}°C, {desc}\n" msg += f"{weekday}: {avgtemp}°C, {desc}\n"
return msg.strip() return msg.strip()
# ===== MAIN LOOP ===== # ===== MAIN LOOP =====
print("📡 SMS Weather Bot started (no API key)") print("📡 SMS Weather Bot started (≤5s reply mode)")
poll_interval = BASE_POLL_INTERVAL
while True: while True:
try: try:
data = fetch_inbox() data = fetch_inbox()
inbox = data.get("inbox", []) inbox = data.get("inbox", [])
# reset backoff on success error_count = 0 # reset on success
poll_interval = BASE_POLL_INTERVAL
if not inbox:
time.sleep(poll_interval)
continue
for sms in inbox: for sms in inbox:
offset = sms["offset"] offset = sms["offset"]
@@ -101,15 +97,17 @@ while True:
reply = get_weather(text) reply = get_weather(text)
send_sms(phone, reply) send_sms(phone, reply)
print(f"📤 Sent reply to {phone}")
seen_offsets.add(offset) seen_offsets.add(offset)
print(f"✅ Replied to {phone}")
except Exception as e: except Exception as e:
print("⚠ Error:", e) error_count += 1
print("⚠ ERROR:", e)
# exponential backoff + jitter # If gateway is unstable, slow down briefly
poll_interval = min(poll_interval * 2, MAX_BACKOFF) if error_count >= MAX_ERRORS_BEFORE_SLEEP:
print("⏳ Too many errors, sleeping 5s")
# jitter prevents perfectly periodic polling time.sleep(5)
time.sleep(poll_interval + random.randint(0, 5)) error_count = 0
time.sleep(POLL_INTERVAL)