Add cache to fetch_users (closes #171)
All checks were successful
divent / lint (push) Successful in 2m30s
divent / docker (push) Successful in 2m19s
divent / pypi (push) Has been skipped

This commit is contained in:
Michel Roux 2023-11-07 10:52:38 +01:00
parent 96ac519fde
commit 842896642e

View File

@ -3,9 +3,9 @@ import logging
from datetime import datetime, timedelta
from functools import wraps
from os import getenv, path
from typing import Dict, Optional
from typing import Dict, Optional, Union
from disnake import Asset, Client, Guild
from disnake import Asset, Client, Guild, Intents, Member, User
from disnake.guild_scheduled_event import GuildScheduledEvent
from dotenv import load_dotenv
from ics import Calendar, ContentLine, Event
@ -36,13 +36,47 @@ API_BASE_URL = getenv("API_BASE_URL", "https://discordapp.com/api")
AUTHORIZATION_BASE_URL = f"{API_BASE_URL}/oauth2/authorize"
TOKEN_URL = f"{API_BASE_URL}/oauth2/token"
CATALOG_CACHE = {}
EVENTS_CACHE = {}
class Discord(Client):
async def on_ready(self):
print(f"Logged on as {self.user}!", flush=True)
for guild in self.guilds:
for scheduled_event in guild.scheduled_events:
EVENTS_CACHE[scheduled_event.id] = [
member.id
for member in await scheduled_event.fetch_users().flatten()
]
print("Events synchronised!", flush=True)
async def on_guild_scheduled_event_subscribe(
self, event: GuildScheduledEvent, user: Union[Member, User]
):
EVENTS_CACHE[event.id].append(user.id)
async def on_guild_scheduled_event_unsubscribe(
self, event: GuildScheduledEvent, user: Union[Member, User]
):
EVENTS_CACHE[event.id].remove(user.id)
async def on_guild_scheduled_event_create(self, event: GuildScheduledEvent):
EVENTS_CACHE[event.id] = [
member.id for member in await event.fetch_users().flatten()
]
async def on_guild_scheduled_event_delete(self, event: GuildScheduledEvent):
EVENTS_CACHE.pop(event.id)
intents = Intents.default()
intents.guild_scheduled_events = True
intents.members = True
client = Discord(intents=intents)
client = Discord()
app = Quart(__name__)
app.config["SECRET_KEY"] = OAUTH2_CLIENT_SECRET
app.config["EXPLAIN_TEMPLATE_LOADING"] = QUART_DEBUG
@ -57,9 +91,6 @@ def get_guild_by_id(guild_id: str) -> Optional[Guild]:
return None
CATALOG_CACHE = {}
@app.errorhandler(500)
async def errorhandler(error: Exception):
print(f"\33[31m{error}\33[m", flush=True)
@ -301,12 +332,8 @@ async def ical(entity_id: str):
)
for guild in client.guilds:
if await guild.get_or_fetch_member(int(entity_id)):
for scheduled_event in guild.scheduled_events:
if any(
user.id == member.id
for member in await scheduled_event.fetch_users().flatten()
):
if user.id in EVENTS_CACHE[scheduled_event.id]:
event = make_event(scheduled_event)
calendar.events.append(event)