-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrafficbot_pro.py
More file actions
178 lines (137 loc) · 4.81 KB
/
trafficbot_pro.py
File metadata and controls
178 lines (137 loc) · 4.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
#!/usr/bin/env python3
"""
TrafficBot Pro – CLI version for GitHub Actions
Automated multi-city traffic alerts with:
- RSS feeds
- Severity markers
- Smart summary
- Rotating fun facts
- Live traffic map
- Optional YouTube creator promotion
"""
import os
import requests
import feedparser
from datetime import datetime, timezone, timedelta
from email.utils import parsedate_to_datetime
# ---------------- CONFIG ---------------- #
CITY = os.getenv("CITY", "Pune")
TEAMS_WEBHOOK_URL = os.getenv("TEAMS_WEBHOOK_URL")
# Maps centering (default = Pune Baner)
CITY_MAPS = {
"pune": "https://www.google.com/maps/@18.5590,73.7799,15z/data=!5m1!1e1",
"mumbai": "https://www.google.com/maps/@19.0760,72.8777,14z/data=!5m1!1e1",
"bangalore": "https://www.google.com/maps/@12.9716,77.5946,14z/data=!5m1!1e1",
"delhi": "https://www.google.com/maps/@28.6139,77.2090,14z/data=!5m1!1e1",
}
LIVE_MAP = CITY_MAPS.get(CITY.lower(), CITY_MAPS["pune"])
RSS_FEEDS = [
f"https://news.google.com/rss/search?q={CITY}+Traffic&hl=en-IN&gl=IN&ceid=IN:en",
]
MAX_ARTICLES = 5
HOURS_FRESH = 24
# Rotating fun facts
FACTS = [
"Pune has more two-wheelers than any Indian city.",
"Balewadi High Street traffic peaks after 7 PM.",
"Hinjewadi sees Monday morning surges.",
"University Circle handles 1.2 lakh vehicles daily.",
"Illegal parking causes micro-jams in most cities."
]
# ---------------- HELPERS ---------------- #
def parse_datetime(entry):
for field in ("published", "updated", "pubDate"):
ts = entry.get(field)
if ts:
try:
dt = parsedate_to_datetime(ts)
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
return dt.astimezone(timezone.utc)
except Exception:
pass
return None
def severity(title):
text = title.lower()
if any(w in text for w in ["accident", "crash", "blocked", "jam", "closed"]):
return "🔴"
if any(w in text for w in ["slow", "delay", "snarl", "heavy"]):
return "🟡"
return "🟢"
def fetch_news():
cutoff = datetime.now(timezone.utc) - timedelta(hours=HOURS_FRESH)
articles = []
for url in RSS_FEEDS:
feed = feedparser.parse(url)
for entry in feed.entries:
dt = parse_datetime(entry) or datetime.now(timezone.utc)
if dt < cutoff:
continue
articles.append({
"title": entry.title,
"link": entry.link,
"published": dt,
})
articles.sort(key=lambda x: x["published"], reverse=True)
return articles
def generate_summary(titles):
text = " ".join(t.lower() for t in titles)
if "accident" in text:
return "🔍 Summary: Accident reported — expect delays."
if "baner" in text or "balewadi" in text:
return f"🔍 Summary: Moderate congestion around {CITY} hotspots."
if "metro" in text or "work" in text:
return "🔍 Summary: Roadwork/metro activity slowing traffic."
return "🔍 Summary: No major bottlenecks reported."
def rotate_fact():
idx = datetime.now().day % len(FACTS)
return f"💡 Fact: {FACTS[idx]}"
# ---------------- MESSAGE BUILDER ---------------- #
def build_message(articles):
timestamp = datetime.now().strftime("%d %b %Y • %I:%M %p")
header = f"🚦 TrafficBot Pro • {CITY.title()} • {timestamp}\n\n"
if not articles:
return (
f"{header}"
"🟢 No major updates found.\n\n"
f"{generate_summary([])}\n\n"
f"🗺️ Live Traffic Map: {LIVE_MAP}\n\n"
f"{rotate_fact()}"
)
lines = []
titles = []
for a in articles[:MAX_ARTICLES]:
sev = severity(a["title"])
lines.append(f"• {sev} [{a['title']}]({a['link']})")
titles.append(a["title"])
extra = ""
if len(articles) > MAX_ARTICLES:
extra = f"\n\n… and {len(articles) - MAX_ARTICLES} more updates."
summary = generate_summary(titles)
return (
f"{header}"
+ "\n".join(lines)
+ extra
+ f"\n\n{summary}"
+ f"\n\n🗺️ Live Traffic Map: {LIVE_MAP}"
+ f"\n\n{rotate_fact()}"
)
# ---------------- TEAMS POST ---------------- #
def send_to_teams(text):
if not TEAMS_WEBHOOK_URL:
print("❗ TEAMS_WEBHOOK_URL missing — printing output instead:\n")
print(text)
return
payload = {"text": text.replace("\n", "\n\n")}
try:
requests.post(TEAMS_WEBHOOK_URL, json=payload, timeout=10)
print("✔ Posted to Teams")
except Exception as e:
print("❗ Error posting:", e)
# ---------------- MAIN ---------------- #
def main():
articles = fetch_news()
msg = build_message(articles)
send_to_teams(msg)
if __name__ == "__main__":
main()