Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
285 lines (178 loc) · 5.6 KB
/
Copy pathapp.py
File metadata and controls
285 lines (178 loc) · 5.6 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
import json
import asyncio
import aiohttp
import discord
import logging
import os
import time
from dotenv import load_dotenv
# -------------------------------
# Environment
# -------------------------------
load_dotenv()
BOT_TOKEN = os.getenv("BOT_TOKEN")
if not BOT_TOKEN:
raise RuntimeError("BOT_TOKEN missing (.env not loaded)")
# -------------------------------
# Logging
# -------------------------------
os.makedirs("logs", exist_ok=True)
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s | %(levelname)s | %(message)s",
handlers=[
logging.FileHandler("logs/bot.log", encoding="utf-8"),
logging.StreamHandler()
]
)
# -------------------------------
# Load configuration
# -------------------------------
with open("config.json", "r", encoding="utf-8") as f:
config = json.load(f)
WEBHOOKS = config.get("webhooks", [])
ALERT_CHANNEL_ID = config.get("alert_channel_id")
CHECK_INTERVAL = config.get("check_interval_seconds", 60)
if not WEBHOOKS:
raise RuntimeError("No webhooks defined in config.json")
if not ALERT_CHANNEL_ID:
raise RuntimeError("alert_channel_id missing in config.json")
# -------------------------------
# Discord Client
# -------------------------------
intents = discord.Intents.default()
client = discord.Client(intents=intents)
# -------------------------------
# State / Cache
# -------------------------------
webhook_cache = {}
alerted = {}
CACHE_DURATION = 300 # seconds
monitor_task = None
# -------------------------------
# Pastebin Resolver
# -------------------------------
async def resolve_webhook_url(session: aiohttp.ClientSession, entry: dict) -> str:
name = entry["name"]
paste_url = entry["url"]
current_time = time.time()
# Use cached webhook if still valid
if name in webhook_cache:
cached = webhook_cache[name]
if current_time - cached["time"] < CACHE_DURATION:
return cached["url"]
async with session.get(paste_url) as resp:
if resp.status != 200:
raise RuntimeError(
f"Pastebin request failed ({name}): HTTP {resp.status}"
)
text = (await resp.text()).strip()
if not text.startswith("https://discord.com/api/webhooks/"):
raise RuntimeError(
f"Invalid webhook URL in Pastebin ({name})"
)
webhook_cache[name] = {
"url": text,
"time": current_time
}
return text
# -------------------------------
# Webhook Checker
# -------------------------------
async def check_single_webhook(
session: aiohttp.ClientSession,
entry: dict,
channel
):
name = entry["name"]
if name not in alerted:
alerted[name] = False
try:
webhook_url = await resolve_webhook_url(
session,
entry
)
async with session.get(webhook_url) as resp:
logging.info(
f"[{name}] HTTP status: {resp.status}"
)
# Webhook deleted or invalid
if resp.status in [401, 403, 404]:
if not alerted[name]:
await channel.send(
f"⚠️ @everyone **Webhook unavailable: `{name}`**"
)
alerted[name] = True
logging.warning(
f"[{name}] webhook unavailable ({resp.status})"
)
# Webhook is working
elif resp.status == 200:
if alerted[name]:
await channel.send(
f"✅ **Webhook restored: `{name}`**"
)
alerted[name] = False
logging.info(
f"[{name}] webhook active"
)
except Exception as e:
logging.error(
f"[{name}] error: {e}"
)
# -------------------------------
# Main Monitoring Loop
# -------------------------------
async def check_all_webhooks():
await client.wait_until_ready()
try:
channel = await client.fetch_channel(
ALERT_CHANNEL_ID
)
except Exception as e:
logging.error(
f"Failed to fetch alert channel: {e}"
)
return
logging.info(
f"Monitoring started for {len(WEBHOOKS)} webhooks"
)
timeout = aiohttp.ClientTimeout(
total=10
)
async with aiohttp.ClientSession(
timeout=timeout
) as session:
while True:
tasks = [
check_single_webhook(
session,
entry,
channel
)
for entry in WEBHOOKS
]
await asyncio.gather(
*tasks
)
await asyncio.sleep(
CHECK_INTERVAL
)
# -------------------------------
# Discord Events
# -------------------------------
@client.event
async def on_ready():
global monitor_task
logging.info(
f"Bot online as {client.user}"
)
# Prevent multiple monitoring tasks
if monitor_task is None:
monitor_task = asyncio.create_task(
check_all_webhooks()
)
# -------------------------------
# Start Bot
# -------------------------------
client.run(BOT_TOKEN)