Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
361 lines (299 loc) · 14.3 KB
/
Copy pathmain.py
File metadata and controls
361 lines (299 loc) · 14.3 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
"""PlexMonitor bot entrypoint.
Cogs load in setup_hook, which runs once before the gateway connects, so a
reconnect never loads them twice. Logging always reaches stdout, which is
what `docker compose logs` shows.
"""
from __future__ import annotations
import asyncio
import hashlib
import json
import logging
import os
import platform
import re
import sys
from logging.handlers import TimedRotatingFileHandler
import discord
from discord import app_commands
from discord.ext import commands
from dotenv import load_dotenv
from util import ratelimit
from util.auth import is_admin
from util.jsonfile import data_dir
if platform.system() == "Windows":
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
RUNNING_IN_DOCKER = os.getenv("RUNNING_IN_DOCKER", "false").lower() == "true"
if not RUNNING_IN_DOCKER:
load_dotenv()
TOKEN = os.getenv("DISCORD_TOKEN")
if not TOKEN:
raise ValueError("DISCORD_TOKEN must be set")
# ------------------------------------------------------------------ logging
LOG_LEVEL = getattr(logging, os.getenv("LOG_LEVEL", "INFO").upper(), logging.INFO)
# Settings whose values must never reach a log line. Some services take
# their key in the URL (Tautulli, SABnzbd, Plex), and an HTTP error's text
# can include that URL.
SECRET_SETTINGS = (
"DISCORD_TOKEN", "TAUTULLI_API_KEY", "PLEX_TOKEN", "SABNZBD_API_KEY",
"QBITTORRENT_PASSWORD", "NZBGET_PASSWORD", "TRANSMISSION_PASSWORD",
"DELUGE_PASSWORD", "RTORRENT_PASSWORD",
"UPTIME_API_KEY", "UPTIME_PASSWORD", "UPTIMEROBOT_API_KEY",
"RADARR_API_KEY", "SONARR_API_KEY", "SEERR_API_KEY", "AI_API_KEY",
)
# Logins sent as HTTP basic auth: (username setting, password setting).
BASIC_LOGINS = (
("NZBGET_USERNAME", "NZBGET_PASSWORD"),
("QBITTORRENT_USERNAME", "QBITTORRENT_PASSWORD"),
("TRANSMISSION_USERNAME", "TRANSMISSION_PASSWORD"),
("RTORRENT_USERNAME", "RTORRENT_PASSWORD"),
("UPTIME_USERNAME", "UPTIME_PASSWORD"),
)
# key=value in a URL or a form, and "key": value in JSON or a header.
_SECRET_PARAM = re.compile(
r"(?i)\b(apikey|api_key|x-plex-token|access_token|token|key|password)"
r"=([^&\s'\"]+)")
_SECRET_FIELD = re.compile(
r"(?i)([\"']?\b(?:apikey|api_key|api-key|x-api-key|x-plex-token|"
r"access_token|password)[\"']?\s*:\s*[\"']?)([^\s'\",}]+)")
def secret_forms() -> list:
"""Every secret setting as it could appear in a log line: as is,
URL-encoded, and inside a basic-auth header."""
import base64
from urllib.parse import quote
forms = set()
for name in SECRET_SETTINGS:
value = os.getenv(name, "").strip()
# Very short values would blank ordinary words all over the log (a
# password "plex" in every logger name); those are still caught
# in password=..., "apikey": ... and header forms below.
if len(value) >= 6:
forms.update({value, quote(value, safe="")})
for user, password in BASIC_LOGINS:
user, password = os.getenv(user, ""), os.getenv(password, "")
if user and password:
forms.add(base64.b64encode(
f"{user}:{password}".encode()).decode())
return sorted(forms, key=len, reverse=True)
# The token in a Discord webhook or interaction route
# (/webhooks/<app id>/<token>/..., /interactions/<id>/<token>/callback).
_DISCORD_TOKEN_PATH = re.compile(
r"(/(?:webhooks|interactions)/\d+/)[^/?#\s'\"]+")
# Control characters (tab aside) and Unicode line breaks. Titles, names and
# release names end up in log messages; one of these could fake extra log
# lines or move the cursor in whoever's terminal shows the log.
_CONTROL = re.compile("[\x00-\x08\x0a-\x1f\x7f-\x9f\u2028\u2029]")
def _escape_control(text: str) -> str:
return _CONTROL.sub(lambda m: m.group().encode("unicode_escape")
.decode("ascii"), text)
class RedactingFormatter(logging.Formatter):
"""Formats as usual, then blanks out secrets, tracebacks included.
Control characters in the message itself are shown escaped, so one
record is always one line (tracebacks keep their line breaks)."""
def __init__(self, fmt: str) -> None:
super().__init__(fmt)
self.secrets = secret_forms()
def format(self, record: logging.LogRecord) -> str:
message = record.getMessage()
safe = _escape_control(message)
if safe != message:
record = logging.makeLogRecord(record.__dict__)
record.msg, record.args = safe, None
text = super().format(record)
for secret in self.secrets:
text = text.replace(secret, "***")
text = _SECRET_PARAM.sub(r"\1=***", text)
text = _DISCORD_TOKEN_PATH.sub(r"\1***", text)
return _SECRET_FIELD.sub(r"\1***", text)
formatter = RedactingFormatter(
"%(asctime)s - %(name)s - %(levelname)s - %(message)s")
# One handler, on the root logger, so everything that logs -- this bot,
# discord.py, and the libraries under them (asyncio, aiohttp) -- goes
# through the redactor. The bot's own lines from LOG_LEVEL up, everyone
# else's warnings and errors.
console = logging.StreamHandler(sys.stdout)
console.setFormatter(formatter)
logging.getLogger().addHandler(console)
logging.getLogger().setLevel(logging.WARNING)
bot_logger = logging.getLogger("plexmonitor")
bot_logger.setLevel(LOG_LEVEL)
# discord.py logs through its own "discord" logger -- and that includes
# exceptions raised inside view/button callbacks and gateway problems.
# Without a handler those vanish silently, which once made a dead pager
# button look like nothing happened at all.
discord_logger = logging.getLogger("discord")
discord_logger.setLevel(logging.WARNING)
class _DropRateLimitChatter(logging.Filter):
"""Silence discord.py's own "We are being rate limited" warnings.
They duplicate what util.ratelimit already records -- and records
better, with scope, bucket and an aggregated summary instead of one
line per retry. At steady state that was two log lines per scheduled
edit saying the same thing. Everything else discord.http reports
(gateway trouble, callback exceptions) still comes through.
"""
def filter(self, record: logging.LogRecord) -> bool:
return "We are being rate limited" not in record.getMessage()
logging.getLogger("discord.http").addFilter(_DropRateLimitChatter())
if not RUNNING_IN_DOCKER:
os.makedirs("logs", exist_ok=True)
file_handler = TimedRotatingFileHandler(
filename=os.path.join("logs", "plex-monitor.log"),
when="midnight", interval=1, backupCount=7, encoding="utf-8",
)
file_handler.setFormatter(formatter)
logging.getLogger().addHandler(file_handler)
# --------------------------------------------------------------------- bot
# Only the intents actually needed. Intents.all() requests the privileged
# members and presence intents, which refuse to connect unless they are also
# ticked in the Discord developer portal.
intents = discord.Intents.default()
intents.message_content = False
COGS_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "cogs")
# Cog files from older versions, and what replaced them.
RETIRED_COGS = {"sabnzbd": "downloads"}
DATA_DIR = data_dir()
class SharedTree(app_commands.CommandTree):
"""The command tree, tolerant of sharing its bot token.
Another program signed in with the same bot token (a watch party bot,
say) has its commands delivered here too. Those are its to answer, so an
unknown command is only logged at debug level instead of as an error.
"""
async def on_error(self, interaction: discord.Interaction,
error: app_commands.AppCommandError) -> None:
if isinstance(error, app_commands.CommandNotFound):
bot_logger.debug("Ignoring /%s: not one of this bot's commands "
"(another program on this token may answer "
"it, or its cog isn't loaded)", error.name)
return
await super().on_error(interaction, error)
class PlexMonitorBot(commands.Bot):
def __init__(self) -> None:
# Watch Discord's rate-limit headers on every REST response. discord.py
# accepts an aiohttp TraceConfig here, so the dashboard can pace itself
# from the budget Discord reports rather than inferring it from 429s.
self.rate_limits = ratelimit.RateLimitObserver()
super().__init__(
command_prefix="!",
intents=intents,
tree_cls=SharedTree,
http_trace=ratelimit.make_trace(self.rate_limits),
)
async def setup_hook(self) -> None:
"""Runs once before the gateway connects -- not on every reconnect."""
for filename in sorted(os.listdir(COGS_DIR)):
if not filename.endswith(".py") or filename.startswith("__"):
continue
name = filename[:-3]
if name in RETIRED_COGS:
# Left behind by an update that copied files over the old
# ones instead of replacing the folder.
bot_logger.info("Skipping cogs/%s -- replaced by cogs/%s.py; "
"it can be deleted", filename, RETIRED_COGS[name])
continue
try:
await self.load_extension(f"cogs.{name}")
bot_logger.info("Loaded cog: %s", name)
except commands.ExtensionError:
bot_logger.exception("Failed to load cog %s", name)
# Sync only when the commands Discord would receive actually
# changed. Command writes are rate limited, and a crash-looping
# container syncing on every start burns that quota. The fingerprint
# is the exact payload (names, descriptions, options, choices,
# limits, default permissions) plus the application it belongs to,
# so switching to another bot token syncs too.
try:
payload = sorted(
(cmd.to_dict(self.tree) for cmd in self.tree.get_commands()),
key=lambda item: item["name"])
digest = hashlib.sha256(json.dumps(
[self.application_id, payload], sort_keys=True,
default=str).encode()).hexdigest()
marker = os.path.join(DATA_DIR, "command_sync.json")
previous = None
try:
with open(marker, encoding="utf-8") as handle:
previous = json.load(handle).get("digest")
except (OSError, ValueError):
pass
if previous == digest:
bot_logger.info("Command tree unchanged -- skipping sync")
else:
await self.tree.sync()
bot_logger.info("Command tree synced globally")
try:
with open(marker, "w", encoding="utf-8") as handle:
json.dump({"digest": digest}, handle)
except OSError as exc:
# A read-only or full data/ must not stop the bot --
# it only means the next start syncs again.
bot_logger.warning("Could not record command sync: %s",
exc)
except discord.HTTPException:
bot_logger.exception("Failed to sync command tree")
async def on_ready(self) -> None:
bot_logger.info("Bot is online as %s", self.user)
# This bot's commands are global. Server-level commands are left
# alone: another program sharing the token may have registered them.
bot = PlexMonitorBot()
tree = bot.tree
async def is_authorized(interaction: discord.Interaction) -> bool:
"""Bot admins only: DISCORD_AUTHORIZED_USERS, else the bot's owner."""
return await is_admin(bot, interaction.user)
def cog_names() -> list:
"""The cogs that can be loaded: files in cogs/, less retired ones."""
return [f[:-3] for f in sorted(os.listdir(COGS_DIR))
if f.endswith(".py") and not f.startswith("__")
and f[:-3] not in RETIRED_COGS]
async def _manage(interaction: discord.Interaction, cog: str, action: str) -> None:
await interaction.response.defer(ephemeral=True)
if not await is_authorized(interaction):
await interaction.followup.send("You are not authorized to run this command.")
return
cog = cog.strip().removesuffix(".py")
if cog in RETIRED_COGS:
await interaction.followup.send(
f"`{cog}` was replaced by `{RETIRED_COGS[cog]}`.")
return
if cog not in cog_names():
await interaction.followup.send(
"No cog by that name. `/cogs` lists them.")
return
handler = {
"load": bot.load_extension,
"unload": bot.unload_extension,
"reload": bot.reload_extension,
}[action]
try:
await handler(f"cogs.{cog}")
await interaction.followup.send(f"Cog `{cog}` {action}ed.")
bot_logger.info("Cog %s %sed by %s", cog, action, interaction.user)
except commands.ExtensionError as exc:
await interaction.followup.send(f"Error: `{exc}`")
bot_logger.error("Error during %s of %s: %s", action, cog, exc)
@tree.command(name="load", description="Load a specific cog")
async def load(interaction: discord.Interaction, cog: str) -> None:
await _manage(interaction, cog, "load")
@tree.command(name="unload", description="Unload a specific cog")
async def unload(interaction: discord.Interaction, cog: str) -> None:
await _manage(interaction, cog, "unload")
@tree.command(name="reload", description="Reload a specific cog")
async def reload(interaction: discord.Interaction, cog: str) -> None:
await _manage(interaction, cog, "reload")
@tree.command(name="cogs", description="List all available cogs")
async def list_cogs(interaction: discord.Interaction) -> None:
if not await is_authorized(interaction):
await interaction.response.send_message(
"You are not authorized to run this command.", ephemeral=True)
return
available = cog_names()
loaded = {ext.split(".")[-1] for ext in bot.extensions}
embed = discord.Embed(title="Cogs", colour=0x5865F2)
for cog in available:
embed.add_field(name=cog, value="Loaded" if cog in loaded else "Not loaded", inline=False)
await interaction.response.send_message(embed=embed, ephemeral=True)
if __name__ == "__main__":
try:
bot.run(TOKEN, log_handler=None)
except discord.LoginFailure:
bot_logger.error("Invalid DISCORD_TOKEN")
except Exception:
bot_logger.exception("Bot crashed")