Repository navigation
Expand file tree
/
Copy pathbot.py
More file actions
877 lines (745 loc) · 32.4 KB
/
Copy pathbot.py
File metadata and controls
877 lines (745 loc) · 32.4 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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
import discord
from discord.ext import commands, tasks
import aiohttp
from aiohttp import web
import asyncio
import difflib
import os
import json
import urllib.parse
import time
import xml.etree.ElementTree as ET
from email.utils import parsedate_to_datetime
from dotenv import load_dotenv
from datetime import datetime, timezone, timedelta
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
BREATHE_API_URL = "https://api.breatheoss.app/aqi/{zone_id}"
BLOG_URL = "https://blogs.breatheoss.app"
BLOG_FEED_URL = os.getenv("BLOG_FEED_URL", f"{BLOG_URL}/rss.xml")
BLOG_UPDATES_CHANNEL_ID = int(os.getenv("BLOG_UPDATES_CHANNEL_ID", "1463469778311319563"))
BLOG_STATE_FILE = os.getenv("BLOG_STATE_FILE", "blog_seen.json")
BLOG_POLL_MINUTES = 10
BLOG_FRESH_WINDOW = timedelta(hours=48)
DC_CREATOR = "{http://purl.org/dc/elements/1.1/}creator"
# Load zone data from JSON
with open('zones.json', 'r', encoding='utf-8') as f:
ZONE_DATA = json.load(f)
def format_pollutant(pollutant):
"""Convert pollutant names to use Unicode subscript characters"""
pollutant_upper = pollutant.upper()
if 'PM2.5' in pollutant_upper:
return pollutant_upper.replace('PM2.5', 'PM₂.₅')
elif 'PM2_5' in pollutant_upper:
return pollutant_upper.replace('PM2_5', 'PM₂.₅')
elif 'PM10' in pollutant_upper:
return pollutant_upper.replace('PM10', 'PM₁₀')
elif 'NO2' in pollutant_upper:
return pollutant_upper.replace('NO2', 'NO₂')
elif 'SO2' in pollutant_upper:
return pollutant_upper.replace('SO2', 'SO₂')
elif 'CH4' in pollutant_upper:
return pollutant_upper.replace('CH4', 'CH₄')
else:
return pollutant_upper
class LocationSelect(discord.ui.Select):
def __init__(self, zones_chunk, placeholder="Select a region..."):
options = [
discord.SelectOption(label=zone["name"], value=zone["id"], emoji=zone["emoji"])
for zone in zones_chunk
]
super().__init__(placeholder=placeholder, min_values=1, max_values=1, options=options)
async def callback(self, interaction: discord.Interaction):
zone_id = self.values[0]
await interaction.response.defer()
try:
data = await fetch_aqi_data(zone_id)
if data:
embed = await create_aqi_embed(data)
await interaction.followup.send(embed=embed)
else:
await interaction.followup.send("⚠️ Could not fetch data for this location")
except Exception as e:
await interaction.followup.send(f"⚠️ Error fetching data: {e}")
class DropdownView(discord.ui.View):
def __init__(self):
super().__init__()
chunk_size = 25
chunks = [ZONE_DATA[i:i + chunk_size] for i in range(0, len(ZONE_DATA), chunk_size)]
for chunk in chunks:
if len(chunks) == 1:
placeholder = "Select a region..."
else:
first_name = chunk[0]["name"]
last_name = chunk[-1]["name"]
placeholder = f"Select a region ({first_name} - {last_name})..."
self.add_item(LocationSelect(chunk, placeholder=placeholder))
async def healthcheck_handler(request):
return web.Response(text="OK", status=200)
class BreatheBot(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.session: aiohttp.ClientSession | None = None
self.runner: web.AppRunner | None = None
async def setup_hook(self):
# Persistent HTTP session with a 5 second timeout for requests
timeout = aiohttp.ClientTimeout(total=5)
self.session = aiohttp.ClientSession(timeout=timeout)
# Health check HTTP server for Pterodactyl
port = os.getenv("SERVER_PORT") or os.getenv("PORT") or os.getenv("HEALTH_CHECK_PORT")
if port:
try:
app = web.Application()
app.router.add_get("/", healthcheck_handler)
app.router.add_get("/health", healthcheck_handler)
self.runner = web.AppRunner(app)
await self.runner.setup()
site = web.TCPSite(self.runner, "0.0.0.0", int(port))
await site.start()
print(f"✅ Health check HTTP server listening on port {port}", flush=True)
except Exception as e:
print(f"⚠️ Failed to start health check HTTP server: {e}", flush=True)
try:
synced = await self.tree.sync()
print(f"✅ Synced {len(synced)} slash command(s)", flush=True)
except Exception as e:
print(f"⚠️ Failed to sync commands: {e}", flush=True)
if not blog_watcher.is_running():
blog_watcher.start()
print(f"✅ Blog watcher checking {BLOG_FEED_URL} every {BLOG_POLL_MINUTES} minutes", flush=True)
async def close(self):
if self.runner:
await self.runner.cleanup()
if self.session and not self.session.closed:
await self.session.close()
await super().close()
async def check_proxy_health(proxy_url: str) -> bool:
"""Verify if the proxy is online and can reach Discord API"""
try:
timeout = aiohttp.ClientTimeout(total=4)
async with aiohttp.ClientSession(timeout=timeout) as session:
async with session.get("https://discord.com/api/v10/gateway", proxy=proxy_url) as resp:
return resp.status == 200
except Exception:
return False
def get_proxy():
proxy_url = os.getenv("DISCORD_PROXY")
if not proxy_url:
host = os.getenv("PROXY_HOST")
port = os.getenv("PROXY_PORT", "8888")
user = os.getenv("PROXY_USER")
password = os.getenv("PROXY_PASS")
if host:
if user and password:
proxy_url = f"http://{user}:{password}@{host}:{port}"
else:
proxy_url = f"http://{host}:{port}"
if not proxy_url:
return None
# Test proxy connectivity before launching the bot
print("Testing Discord proxy connection...", flush=True)
is_healthy = asyncio.run(check_proxy_health(proxy_url))
if is_healthy:
print("Proxy healthy, Connecting to Discord via proxy.", flush=True)
return proxy_url
else:
print("Proxy is unreachable or failing. Falling back to direct connection.", flush=True)
return None
intents = discord.Intents.default()
intents.message_content = True
ACTIVE_PROXY = get_proxy()
bot = BreatheBot(command_prefix=".", intents=intents, proxy=ACTIVE_PROXY)
async def fetch_aqi_data(zone_id):
"""Fetch AQI data for a specific zone using persistent session and timeout"""
url = BREATHE_API_URL.format(zone_id=zone_id)
session = bot.session
try:
if session and not session.closed:
async with session.get(url) as response:
if response.status != 200:
return None
return await response.json()
else:
timeout = aiohttp.ClientTimeout(total=5)
async with aiohttp.ClientSession(timeout=timeout) as temp_session:
async with temp_session.get(url) as response:
if response.status != 200:
return None
return await response.json()
except (aiohttp.ClientError, asyncio.TimeoutError):
return None
async def fetch_sensor_info():
"""Fetch all sensor hardware information using persistent session and timeout"""
url = "https://api.breatheoss.app/sensor-info"
session = bot.session
try:
if session and not session.closed:
async with session.get(url) as response:
if response.status != 200:
return None
return await response.json()
else:
timeout = aiohttp.ClientTimeout(total=5)
async with aiohttp.ClientSession(timeout=timeout) as temp_session:
async with temp_session.get(url) as response:
if response.status != 200:
return None
return await response.json()
except (aiohttp.ClientError, asyncio.TimeoutError):
return None
class MoreInfoView(discord.ui.View):
def __init__(self, zone_names):
super().__init__(timeout=None)
self.zone_names = [z.lower() for z in zone_names]
@discord.ui.button(label="Sensor Information", style=discord.ButtonStyle.secondary, emoji="📊")
async def more_info(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.defer(ephemeral=True)
data = await fetch_sensor_info()
if not data or "sensors" not in data:
await interaction.followup.send("⚠️ Could not fetch sensor information.", ephemeral=True)
return
matching_sensors = [s for s in data["sensors"] if s.get("zone", "").lower() in self.zone_names]
if not matching_sensors:
await interaction.followup.send("No detailed hardware info available for these locations.", ephemeral=True)
return
embed = discord.Embed(title="📊 Sensor Hardware Details", color=0x3498db)
for s in matching_sensors:
name = s.get("name", "Unknown Node")
provider = s.get("provider", "N/A")
model = s.get("model", "N/A")
date = s.get("installation_date", "N/A")
embed.add_field(name=f"📍 {name}", value=f"**Provider:** {provider}\n**Model:** {model}\n**Installed:** {date}", inline=False)
await interaction.followup.send(embed=embed, ephemeral=True)
def get_us_aqi_category(us_aqi):
"""Generate US AQI category label"""
if not isinstance(us_aqi, int):
return "N/A"
if us_aqi <= 50:
return "Good"
elif us_aqi <= 100:
return "Moderate"
elif us_aqi <= 150:
return "Unhealthy for Sensitive Groups"
elif us_aqi <= 200:
return "Unhealthy"
elif us_aqi <= 300:
return "Very Unhealthy"
else:
return "Hazardous"
async def create_aqi_embed(data):
"""Create an embed from AQI data"""
zone_name = data.get('zone_name', 'Unknown Location')
aqi = data.get('aqi', 'N/A')
us_aqi = data.get('us_aqi', 'N/A')
pollutant = format_pollutant(data.get('main_pollutant', 'N/A'))
us_units = data.get('concentrations_us_units', {})
# Get latest temp and humidity from history
history = data.get('history', [])
if history and len(history) > 0:
latest = history[-1]
temp = latest.get('temp', 'N/A')
humidity = latest.get('humidity', 'N/A')
else:
temp = 'N/A'
humidity = 'N/A'
pm2_5 = us_units.get('pm2_5')
pm10 = us_units.get('pm10')
no2 = us_units.get('no2')
so2 = us_units.get('so2')
co = us_units.get('co')
ch4 = us_units.get('ch4')
# Color based on US AQI
if isinstance(us_aqi, int):
if us_aqi <= 50: color = 0x00e400
elif us_aqi <= 100: color = 0xffff00
elif us_aqi <= 150: color = 0xff7e00
elif us_aqi <= 200: color = 0xff0000
elif us_aqi <= 300: color = 0x8f3f97
else: color = 0x7e0023
else:
color = 0x808080
embed = discord.Embed(title=f"Breathe AQI: {zone_name}", url="https://breatheoss.app", color=color)
embed.add_field(name="NAQI", value=f"**{aqi}**", inline=True)
embed.add_field(name="US AQI", value=f"**{us_aqi}**", inline=True)
embed.add_field(name="Primary Pollutant", value=f"**{pollutant}**", inline=True)
# Add AQI category
category = get_us_aqi_category(us_aqi)
if category != "N/A":
embed.add_field(name=category, value="*Label based on US AQI*", inline=False)
concentrations = []
if pm2_5 is not None:
concentrations.append(f"**PM₂.₅**: `{pm2_5:.1f}` µg/m³")
if pm10 is not None:
concentrations.append(f"**PM₁₀**: `{pm10:.1f}` µg/m³")
if no2 is not None:
concentrations.append(f"**NO₂**: `{no2 * 1.88:.1f}` µg/m³")
if so2 is not None:
concentrations.append(f"**SO₂**: `{so2 * 2.62:.1f}` µg/m³")
if co is not None:
concentrations.append(f"**CO**: `{co * 1.145:.2f}` mg/m³")
if ch4 is not None:
concentrations.append(f"**CH₄**: `{ch4 * 0.654:.2f}` mg/m³")
if concentrations:
embed.add_field(name="Pollutant Concentrations", value="\n".join(concentrations), inline=False)
# Calculate cigarette equivalence
pm2_5_24h = data.get('averages_24h', {}).get('pm2_5')
cig_pm2_5 = pm2_5_24h if pm2_5_24h is not None else pm2_5
if cig_pm2_5 is not None:
cigarettes = cig_pm2_5 / 22
embed.add_field(
name="Equivalent PM₂.₅ inhalation today",
value=f"🚬 **≈ {cigarettes:.2f}** cigarettes",
inline=False
)
if isinstance(temp, float):
embed.add_field(name="Temperature", value=f"{temp:.1f}°C", inline=True)
if isinstance(humidity, (int, float)):
embed.add_field(name="Humidity", value=f"{humidity}%", inline=True)
# Display warning message if present in API response
warning = data.get('warning')
if warning:
if isinstance(warning, list):
warning_val = "\n".join([f"⚠️ {w}" for w in warning])
else:
warning_val = f"⚠️ {warning}"
embed.add_field(name="⚠️ Warning", value=warning_val, inline=False)
nodes = data.get('nodes', {})
if nodes:
for node_name, node_data in nodes.items():
node_aqi = node_data.get('aqi', 'N/A')
node_us_aqi = node_data.get('us_aqi', 'N/A')
node_pm25 = node_data.get('pm2_5', 'N/A')
node_pm10 = node_data.get('pm10', 'N/A')
pm25_str = f"{node_pm25:.1f}" if isinstance(node_pm25, (int, float)) else str(node_pm25)
pm10_str = f"{node_pm10:.1f}" if isinstance(node_pm10, (int, float)) else str(node_pm10)
node_text = f"NAQI: **{node_aqi}** • US AQI: **{node_us_aqi}**\nPM₂.₅: `{pm25_str}` µg/m³ • PM₁₀: `{pm10_str}` µg/m³"
embed.add_field(name=f"📍 {node_name}", value=node_text, inline=False)
# Add last updated timestamp in IST
timestamp = data.get('timestamp_unix')
if timestamp:
# Convert to IST
ist = timezone(timedelta(hours=5, minutes=30))
dt_ist = datetime.fromtimestamp(timestamp, tz=ist)
time_str = dt_ist.strftime('%I:%M:%S %p')
date_str = dt_ist.strftime('%d %b %Y')
embed.add_field(name="Last Updated", value=f"{date_str}\n{time_str} IST", inline=True)
chart_url = await fetch_quickchart_url(data)
if chart_url:
embed.set_image(url=chart_url)
embed.set_footer(text="Visit breatheoss.app for more info")
return embed
NODE_COLORS = ["#e74c3c", "#2ecc71", "#f1c40f", "#9b59b6", "#e67e22", "#1abc9c", "#e84393"]
async def fetch_quickchart_url(data) -> str | None:
history = data.get('history', [])
if not history or len(history) < 2:
return None
ist = timezone(timedelta(hours=5, minutes=30))
times = [datetime.fromtimestamp(h['ts'], tz=ist).strftime('%H:%M') for h in history]
zone_name = data.get('zone_name', 'Location')
zone_us_aqi = [h.get('us_aqi', 0) for h in history]
source = data.get('source', '').lower()
is_airgradient = 'airgradient' in source
nodes = data.get('nodes', {})
node_count = len(nodes) if isinstance(nodes, dict) else 0
if is_airgradient:
if node_count > 1:
primary_label = "Overall Zone Avg"
elif node_count == 1:
primary_label = list(nodes.keys())[0]
else:
primary_label = zone_name
else:
primary_label = "Overall Zone Avg"
has_multiple_nodes = is_airgradient and node_count > 1
datasets = [{
"label": primary_label,
"data": zone_us_aqi,
"borderColor": "#3498db",
"backgroundColor": "rgba(52, 152, 219, 0.08)",
"borderWidth": 4,
"pointRadius": 0,
"fill": True,
"tension": 0.35
}]
if has_multiple_nodes:
ts_map = {h['ts']: i for i, h in enumerate(history)}
for idx, (node_name, node_info) in enumerate(nodes.items()):
node_history = node_info.get('history', []) if isinstance(node_info, dict) else []
if not node_history:
continue
node_data = [None] * len(history)
for nh in node_history:
ts = nh.get('ts')
if ts in ts_map:
node_data[ts_map[ts]] = nh.get('us_aqi')
color = NODE_COLORS[idx % len(NODE_COLORS)]
datasets.append({
"label": f"{node_name} Node",
"data": node_data,
"borderColor": color,
"borderWidth": 2,
"pointRadius": 2,
"pointBackgroundColor": color,
"fill": False,
"tension": 0.35,
"spanGaps": True
})
has_nodes = len(datasets) > 1
chart_config = {
"type": "line",
"data": {
"labels": times,
"datasets": datasets
},
"options": {
"title": {
"display": True,
"text": f"24-Hour US AQI Trend — {data.get('zone_name', 'Location')}",
"fontColor": "#ffffff",
"fontSize": 14
},
"legend": {
"display": has_nodes,
"position": "bottom",
"labels": {
"fontColor": "#ffffff",
"fontSize": 11,
"boxWidth": 12
}
},
"scales": {
"xAxes": [{
"gridLines": {"color": "rgba(255, 255, 255, 0.1)"},
"ticks": {"fontColor": "#aaaaaa", "maxTicksLimit": 8}
}],
"yAxes": [{
"gridLines": {"color": "rgba(255, 255, 255, 0.1)"},
"ticks": {"fontColor": "#aaaaaa", "beginAtZero": True}
}]
}
}
}
payload = {
"backgroundColor": "#1e1f22",
"width": 650,
"height": 300,
"format": "png",
"chart": chart_config
}
session = bot.session
try:
if session and not session.closed:
async with session.post("https://quickchart.io/chart/create", json=payload, timeout=aiohttp.ClientTimeout(total=3)) as resp:
if resp.status == 200:
res_data = await resp.json()
if res_data.get("success") and "url" in res_data:
return res_data["url"]
except Exception:
pass
encoded_config = urllib.parse.quote(json.dumps(chart_config, separators=(',', ':')))
fallback_url = f"https://quickchart.io/chart?c={encoded_config}&bg=1e1f22&w=650&h=300&v=2.9"
if len(fallback_url) <= 2048:
return fallback_url
return None
def find_zone_by_name(location_name):
"""Find a zone by matching location name, ID using exact substring or fuzzy matching"""
if not location_name:
return None
location_lower = location_name.strip().lower()
for zone in ZONE_DATA:
if zone["name"].lower() == location_lower or zone["id"].lower() == location_lower:
return zone["id"]
for zone in ZONE_DATA:
zname = zone["name"].lower()
zid = zone["id"].lower()
if zname.startswith(location_lower) or zid.startswith(location_lower) or location_lower in zname or location_lower in zid:
return zone["id"]
zone_names_map = {zone["name"].lower(): zone["id"] for zone in ZONE_DATA}
matches = difflib.get_close_matches(location_lower, zone_names_map.keys(), n=1, cutoff=0.6)
if matches:
return zone_names_map[matches[0]]
return None
def create_zones_embed():
"""Create an embed showing all available zones"""
embed = discord.Embed(
title="🌍 Available Locations",
url="https://breatheoss.app",
description="List of all the locations you can check for air quality data:",
color=0x3498db
)
zones_text = "\n".join([f"{zone['emoji']} **{zone['name']}**" for zone in ZONE_DATA])
embed.add_field(name="Regions", value=zones_text, inline=False)
embed.set_footer(text="Visit breatheoss.app for more info")
return embed
@bot.command()
@commands.cooldown(15, 60, commands.BucketType.user)
async def aqi(ctx, *locations):
"""Check AQI for one or more locations. Usage: .aqi OR .aqi jammu srinagar OR .aqi zones"""
if not locations:
view = DropdownView()
await ctx.send("Select a region to check the real-time air quality:", view=view)
elif len(locations) == 1 and locations[0].lower() == "zones":
embed = create_zones_embed()
await ctx.send(embed=embed)
else:
if len(locations) > 3:
await ctx.send("⚠️ You can only request up to 3 locations at a time.")
return
embeds = []
zone_names_found = []
has_ag = False
not_found = False
fetch_error = False
for location in locations:
zone_id = find_zone_by_name(location)
if not zone_id:
not_found = True
continue
zone_name = next((z["name"] for z in ZONE_DATA if z["id"] == zone_id), location)
try:
data = await fetch_aqi_data(zone_id)
if data:
embeds.append(await create_aqi_embed(data))
zone_names_found.append(zone_name)
if "airgradient" in data.get("source", "").lower():
has_ag = True
else:
fetch_error = True
except Exception:
fetch_error = True
if embeds:
view = MoreInfoView(zone_names_found) if has_ag else discord.utils.MISSING
for i, embed in enumerate(embeds):
if i == len(embeds) - 1:
await ctx.send(embed=embed, view=view)
else:
await ctx.send(embed=embed)
if not_found:
await ctx.send("⚠️ One or more requested locations were not found. Please check the spelling or use the `/zones` command to see the available list.")
elif fetch_error:
await ctx.send("⚠️ Error fetching data for one or more locations.")
@aqi.error
async def aqi_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
await ctx.send(f"⏳ **Slow down!** Please wait {error.retry_after:.1f} seconds before checking the AQI again.")
_autocomplete_last_keystroke: dict[int, float] = {}
async def location_autocomplete(
interaction: discord.Interaction,
current: str,
) -> list[discord.app_commands.Choice[str]]:
user_id = interaction.user.id
now = time.monotonic()
_autocomplete_last_keystroke[user_id] = now
await asyncio.sleep(0.15)
if _autocomplete_last_keystroke.get(user_id) != now:
return []
current_clean = current.strip().lower()
if not current_clean:
return [
discord.app_commands.Choice(name=f"{zone['emoji']} {zone['name']}", value=zone["name"])
for zone in ZONE_DATA[:25]
]
starts_with = []
contains = []
for zone in ZONE_DATA:
zname_lower = zone["name"].lower()
zid_lower = zone["id"].lower()
if zname_lower.startswith(current_clean) or zid_lower.startswith(current_clean):
starts_with.append(zone)
elif current_clean in zname_lower or current_clean in zid_lower:
contains.append(zone)
matched_zones = (starts_with + contains)[:25]
return [
discord.app_commands.Choice(name=f"{zone['emoji']} {zone['name']}", value=zone["name"])
for zone in matched_zones
]
@bot.tree.command(name="aqi", description="Check real-time air quality for locations")
@discord.app_commands.describe(location="Select a location to check air quality")
@discord.app_commands.autocomplete(location=location_autocomplete)
@discord.app_commands.allowed_installs(guilds=True, users=True)
@discord.app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
@discord.app_commands.checks.cooldown(15, 60, key=lambda i: i.user.id)
async def aqi_slash(interaction: discord.Interaction, location: str = None):
"""Slash command to check AQI with autocomplete"""
if not location:
view = DropdownView()
await interaction.response.send_message("Select a region to check the real-time air quality:", view=view)
else:
await interaction.response.defer()
zone_id = find_zone_by_name(location)
if not zone_id:
await interaction.followup.send(f"⚠️ Location '{location}' not found. Please check the spelling or use the `/zones` command to see the available list.")
else:
try:
data = await fetch_aqi_data(zone_id)
if data:
embed = await create_aqi_embed(data)
zone_name = next((z["name"] for z in ZONE_DATA if z["id"] == zone_id), location)
view = MoreInfoView([zone_name]) if "airgradient" in data.get("source", "").lower() else discord.utils.MISSING
await interaction.followup.send(embed=embed, view=view)
else:
await interaction.followup.send(f"⚠️ Could not fetch data for {location}")
except Exception as e:
await interaction.followup.send(f"⚠️ Error fetching data for {location}: {e}")
@aqi_slash.error
async def aqi_slash_error(interaction: discord.Interaction, error: discord.app_commands.AppCommandError):
if isinstance(error, discord.app_commands.CommandOnCooldown):
await interaction.response.send_message(f"⏳ **Slow down!** Please wait {error.retry_after:.1f} seconds before checking the AQI again.", ephemeral=True)
@bot.tree.command(name="zones", description="List all available locations for air quality monitoring")
@discord.app_commands.allowed_installs(guilds=True, users=True)
@discord.app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
async def zones_slash(interaction: discord.Interaction):
"""Slash command to show all available zones"""
embed = create_zones_embed()
await interaction.response.send_message(embed=embed)
@bot.tree.error
async def on_app_command_error(interaction: discord.Interaction, error: discord.app_commands.AppCommandError):
original = getattr(error, 'original', error)
if isinstance(original, discord.errors.HTTPException):
if original.status == 429 or original.code in (10062, 40060):
return
# Check cooldowns if not already caught
if isinstance(error, discord.app_commands.CommandOnCooldown):
try:
if not interaction.response.is_done():
await interaction.response.send_message(
f"⏳ **Slow down!** Please wait {error.retry_after:.1f} seconds.",
ephemeral=True
)
except Exception:
pass
return
print(f"⚠️ App command error: {error}", flush=True)
def parse_blog_feed(text):
"""Parse the blog RSS feed into a list of posts, newest first"""
try:
root = ET.fromstring(text)
except ET.ParseError:
return None
posts = []
for item in root.iter('item'):
link = (item.findtext('link') or '').strip()
guid = (item.findtext('guid') or '').strip() or link
if not guid:
continue
published = None
pub_date = item.findtext('pubDate')
if pub_date:
try:
published = parsedate_to_datetime(pub_date)
except (TypeError, ValueError):
published = None
posts.append({
"guid": guid,
"title": (item.findtext('title') or 'New post').strip(),
"link": link,
"description": (item.findtext('description') or '').strip(),
"author": (item.findtext(DC_CREATOR) or '').strip(),
"categories": [c.text.strip() for c in item.findall('category') if c.text],
"published": published,
})
return posts
async def fetch_blog_posts():
"""Fetch the blog RSS feed using persistent session and timeout"""
session = bot.session
try:
if session and not session.closed:
async with session.get(BLOG_FEED_URL) as response:
if response.status != 200:
print(f"⚠️ Blog feed returned HTTP {response.status}", flush=True)
return None
text = await response.text()
else:
timeout = aiohttp.ClientTimeout(total=5)
async with aiohttp.ClientSession(timeout=timeout) as temp_session:
async with temp_session.get(BLOG_FEED_URL) as response:
if response.status != 200:
print(f"⚠️ Blog feed returned HTTP {response.status}", flush=True)
return None
text = await response.text()
except (aiohttp.ClientError, asyncio.TimeoutError) as e:
print(f"⚠️ Could not fetch blog feed: {e}", flush=True)
return None
posts = parse_blog_feed(text)
if posts is None:
print("⚠️ Blog feed could not be parsed", flush=True)
return posts
def load_seen_posts():
try:
with open(BLOG_STATE_FILE, 'r', encoding='utf-8') as f:
return set(json.load(f))
except (FileNotFoundError, json.JSONDecodeError):
return None
def save_seen_posts(seen):
with open(BLOG_STATE_FILE, 'w', encoding='utf-8') as f:
json.dump(sorted(seen), f, indent=2)
def create_blog_embed(post):
embed = discord.Embed(
title=post["title"],
url=post["link"],
description=post["description"],
color=0xa8c7fa,
timestamp=post["published"],
)
embed.set_author(name="Breathe Blog", url=BLOG_URL, icon_url=f"{BLOG_URL}/images/apple-touch-icon.png")
if post["author"]:
embed.add_field(name="Author", value=post["author"], inline=True)
if post["categories"]:
embed.add_field(name="Tags", value=", ".join(post["categories"]), inline=True)
return embed
async def get_blog_channel():
channel = bot.get_channel(BLOG_UPDATES_CHANNEL_ID)
if channel:
return channel
try:
return await bot.fetch_channel(BLOG_UPDATES_CHANNEL_ID)
except discord.DiscordException as e:
print(f"⚠️ Could not find blog updates channel {BLOG_UPDATES_CHANNEL_ID}: {e}", flush=True)
return None
@tasks.loop(minutes=BLOG_POLL_MINUTES)
async def blog_watcher():
posts = await fetch_blog_posts()
if posts is None:
return
seen = load_seen_posts()
if seen is None:
# First run: remember what is already out so old posts are not announced
now = datetime.now(timezone.utc)
seen = {
post["guid"] for post in posts
if not post["published"] or now - post["published"] > BLOG_FRESH_WINDOW
}
save_seen_posts(seen)
new_posts = [post for post in reversed(posts) if post["guid"] not in seen]
if not new_posts:
return
channel = await get_blog_channel()
if not channel:
return
for post in new_posts:
try:
message = await channel.send(content="📰 **New on the Breathe Blog!**", embed=create_blog_embed(post))
except discord.HTTPException as e:
print(f"⚠️ Failed to announce blog post {post['link']}: {e}", flush=True)
return
# Push it out to servers following the channel
if getattr(channel, "is_news", lambda: False)():
try:
await message.publish()
except discord.HTTPException:
pass
seen.add(post["guid"])
save_seen_posts(seen)
print(f"✅ Announced blog post: {post['title']}", flush=True)
@blog_watcher.before_loop
async def before_blog_watcher():
await bot.wait_until_ready()
@blog_watcher.error
async def blog_watcher_error(error):
print(f"⚠️ Blog watcher error: {error}", flush=True)
@bot.event
async def on_ready():
print(f"Logged in as {bot.user}", flush=True)
print("Bot is ready and connected to Discord Gateway.", flush=True)
if __name__ == "__main__":
bot.run(TOKEN)