Add custom data to context

#264
This commit is contained in:
MarkusRost 2024-09-26 04:57:45 +02:00
parent f80c671964
commit 481f368a4d
7 changed files with 21 additions and 7 deletions

View file

@ -117,11 +117,14 @@ Context can consist of the following fields:
- `event` - string - action called, should be the same as formatter event action
- `categories` - {"new": set(), "removed": set()} - each set containing strings of added or removed categories for given page
- `parsedcomment` - string - contains escaped and Markdown parsed summary (parsed_comment) of a log/edit action
- `changed_content` - dict/None - contains edit diff api response when show_edit_changes is enabled and the embed edit formatter was used
- `image_data` - dict/None - contains image data api response when the embed upload formatter was used
- `comment_page` - dict - containing `fullUrl` and `article` with strings both to full article url and its name
- `_` gettext.gettext - function for singular translations
- `ngettext` gettext.ngettext function for plural translations
- `pgettext` gettext.pgettext function for translations differentiated by the context
- `npgettext` gettext.npgettext function for plural translations differentiated by the context
- `custom_data` dict empty dict for hooks or formatters to store information, use at own risk
### Util
**Path**: `src.api.util`

View file

@ -80,6 +80,7 @@ def embed_edit(ctx: Context, change: dict) -> DiscordMessage:
except (ServerError, MediaWikiError):
changed_content = None
if changed_content:
ctx.changed_content = changed_content
parse_mediawiki_changes(ctx, changed_content, embed)
else:
logger.warning("Unable to download data on the edit content!")
@ -159,6 +160,7 @@ def embed_upload_upload(ctx: Context, change: dict) -> DiscordMessage:
# Make a request for file revisions so we can get direct URL to the image for embed
if request_for_image_data is not None:
try:
ctx.image_data = image_data
urls = image_data["imageinfo"]
for num, revision in enumerate(urls):
if revision["timestamp"] == change["logparams"][

View file

@ -62,9 +62,15 @@ def buttons_hook(message: DiscordMessage, metadata: DiscordMessageMetadata, cont
if "delete" in action_buttons and context.event in ("new", "upload/upload"):
add_button(message, BUTTON_PREFIX + " delete " + str(change["pageid"]),
action_buttons["delete"], 4, {"id": None, "name": "🗑️"})
# if "filerevert" in action_buttons and context.event in ("upload/overwrite", "upload/revert"):
# add_button(message, BUTTON_PREFIX + " file " + str(change["pageid"]) + " " + revision["archivename"].split("!")[0],
# action_buttons["filerevert"], 2, {"id": None, "name": "🔂"})
if "filerevert" in action_buttons and context.event in ("upload/overwrite", "upload/revert") and context.image_data:
found_cur = False
for revision in context.image_data.get("imageinfo", []):
if found_cur:
add_button(message, BUTTON_PREFIX + " file " + str(change["pageid"]) + " " + revision["archivename"].split("!")[0],
action_buttons["filerevert"], 2, {"id": None, "name": "🔂"})
break
if revision["timestamp"] == change["logparams"]["img_timestamp"]: # find the correct revision corresponding for this log entry
found_cur = True
if "move" in action_buttons and context.event in ("move/move", "move/move_redir"):
add_button(message, BUTTON_PREFIX + " move " + str(change["pageid"]) + " " + change["title"],
action_buttons["move"], 2, {"id": None, "name": "🔂"})

View file

@ -15,7 +15,7 @@
from __future__ import annotations
from datetime import datetime
from datetime import datetime, timezone
import src.misc
import sched
from typing import Union, Callable, Any
@ -63,7 +63,7 @@ class Client:
"""Converts UTC time to amount of seconds from now, if amount of seconds given returns seconds as a float"""
if isinstance(given_time, float) or isinstance(given_time, int):
return float(given_time)
now = datetime.utcnow()
now = datetime.now(timezone.utc)
then = datetime(now.year, now.month, now.day, *(map(int, given_time.split(':'))), 0, 0)
return float((then - now).seconds)
def wrap_reschedule(function, period: float, *args, **kwargs):

View file

@ -31,6 +31,8 @@ class Context:
self.feed_type = feed_type
self.categories = None
self.parsedcomment = None
self.changed_content = None
self.image_data = None
self.event = None
self.comment_page = None
self._ = language.gettext # Singular translations (ex. ctx._("Large goat"))
@ -39,6 +41,7 @@ class Context:
self.pgettext = language.pgettext # Translation with context (ex. ctx.pgettext("From mediawiki module", "Blocked {} user"))
self.npgettext = language.npgettext # Plural translation with context (ex. ctx.npgettext("From mediawiki module", "Edited {} time", "Edited {} times", edit_amoint)
self.settings = settings
self.custom_data = {}
def set_categories(self, cats):
self.categories = cats

View file

@ -83,7 +83,7 @@ formatter_hooks["no_formatter"] = no_formatter
def day_overview_request() -> list:
"""Make requests for changes in last 24h"""
logger.info("Fetching daily overview... This may take up to 30 seconds!")
timestamp = (datetime.datetime.utcnow() - datetime.timedelta(hours=24)).isoformat(timespec='milliseconds')
timestamp = (datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(hours=24)).isoformat(timespec='milliseconds')
result = []
passes = 0
continuearg: Optional[str] = None