1"""Shared logic for channels the bot keeps in step with backend data (``#addons``, ``#roles``, ...).
2
3Each read-only mirror channel is created once, below a fixed anchor channel with the anchor's own visibility, then
4holds one message per rendered section: plain ``content`` for an intro, or a single embed per section.
5:func:`sync_messages` edits, posts or deletes the channel's own messages so they match the wanted list, touching
6nothing else and never reposting unchanged content.
7
8:func:`sync_pinned_post` keeps one pinned embed (a guide, a panel) in a channel others also post in, found again by
9its title.
10"""
11
12import logging
13from typing import TYPE_CHECKING, Any
14
15import discord
16
17if TYPE_CHECKING:
18 from collections.abc import Sequence
19
20logger = logging.getLogger(__name__)
21
22
[docs]
23def find_text_channel(guild: discord.Guild, name: str) -> discord.TextChannel | None:
24 """The one text channel called ``name`` anywhere in ``guild``, or ``None``."""
25 for channel in guild.channels:
26 if isinstance(channel, discord.TextChannel) and channel.name.casefold() == name.casefold():
27 return channel
28 return None
29
30
[docs]
31async def ensure_channel_below(
32 guild: discord.Guild, *, name: str, anchor_name: str, topic: str, reason: str
33) -> discord.TextChannel | None:
34 """The existing channel called ``name``, or a new one placed right below ``anchor_name`` with its overwrites.
35
36 ``None`` if neither ``name`` nor ``anchor_name`` exists yet.
37 """
38 existing = find_text_channel(guild, name)
39 if existing is not None:
40 return existing
41 anchor = find_text_channel(guild, anchor_name)
42 if anchor is None:
43 return None
44 channel = await guild.create_text_channel(name, overwrites=dict(anchor.overwrites), topic=topic, reason=reason)
45 await channel.move(after=anchor)
46 return channel
47
48
[docs]
49class RenderedPost:
50 """One message to sync: either plain ``content`` (an intro) or a single section ``embed``, never both."""
51
52 __slots__ = ("content", "embed")
53
54 def __init__(self, *, content: str | None = None, embed: discord.Embed | None = None) -> None:
55 self.content = content
56 self.embed = embed
57
58
59def _embed_key(embed: discord.Embed) -> tuple[str | None, str | None, int | None]:
60 """What a plugin sets on an embed, compared field by field: Discord may add keys of its own to a sent one."""
61 return embed.title, embed.description, embed.colour.value if embed.colour is not None else None
62
63
64def _post_matches(message: discord.Message, post: RenderedPost) -> bool:
65 """Whether ``message`` already shows ``post``'s content and embed, so editing it would be a no-op."""
66 content_matches = (message.content or "") == (post.content or "")
67 desired_embeds = [_embed_key(post.embed)] if post.embed is not None else []
68 return content_matches and [_embed_key(embed) for embed in message.embeds] == desired_embeds
69
70
[docs]
71async def sync_messages(
72 channel: discord.TextChannel, bot_user_id: int, posts: Sequence[RenderedPost], *, history_limit: int = 50
73) -> None:
74 """Edit, post or delete ``channel``'s own messages so they match ``posts``, touching nothing else."""
75 existing = [
76 message
77 async for message in channel.history(limit=history_limit, oldest_first=True)
78 if message.author.id == bot_user_id
79 ]
80 for index, post in enumerate(posts):
81 if index < len(existing):
82 if not _post_matches(existing[index], post):
83 await existing[index].edit(
84 content=post.content, embed=post.embed, allowed_mentions=discord.AllowedMentions.none()
85 )
86 else:
87 send_kwargs: dict[str, Any] = {"allowed_mentions": discord.AllowedMentions.none()}
88 if post.content is not None:
89 send_kwargs["content"] = post.content
90 if post.embed is not None:
91 send_kwargs["embed"] = post.embed
92 await channel.send(**send_kwargs)
93 for surplus in existing[len(posts) :]:
94 await surplus.delete()
95
96
97def _embed_text(embed: discord.Embed) -> tuple[str | None, str | None, list[tuple[str | None, str | None]]]:
98 """What a plugin sets on a pinned post's embed, compared piece by piece: Discord may add keys of its own."""
99 return embed.title, embed.description, [(field.name, field.value) for field in embed.fields]
100
101
102def _is_post(message: discord.Message, bot_user_id: int, title: str | None) -> bool:
103 return message.author.id == bot_user_id and bool(message.embeds) and message.embeds[0].title == title
104
105
[docs]
106async def find_pinned_post(
107 channel: discord.TextChannel, bot_user_id: int, title: str | None, *, history_limit: int = 100
108) -> discord.Message | None:
109 """The bot's post whose embed is titled ``title``: among the pins, or else in recent history."""
110 async for message in channel.pins():
111 if _is_post(message, bot_user_id, title):
112 return message
113 async for message in channel.history(limit=history_limit):
114 if _is_post(message, bot_user_id, title):
115 return message
116 return None
117
118
[docs]
119async def sync_pinned_post(
120 channel: discord.TextChannel,
121 bot_user_id: int,
122 embed: discord.Embed,
123 *,
124 view: discord.ui.View | None = None,
125 pin_reason: str,
126 history_limit: int = 100,
127) -> None:
128 """Edit the bot's post titled like ``embed`` if its text changed, or post and pin it if it's missing.
129
130 Only the embed's text is compared, so ``view`` should be fixed for a given embed. A failed pin is left for the
131 next call to find in history rather than raised; any other Discord error is.
132 """
133 existing = await find_pinned_post(channel, bot_user_id, embed.title, history_limit=history_limit)
134 if existing is not None:
135 if _embed_text(existing.embeds[0]) != _embed_text(embed):
136 kwargs: dict[str, Any] = {"embed": embed, "allowed_mentions": discord.AllowedMentions.none()}
137 if view is not None:
138 kwargs["view"] = view
139 await existing.edit(**kwargs)
140 return
141 send_kwargs: dict[str, Any] = {"embed": embed, "allowed_mentions": discord.AllowedMentions.none()}
142 if view is not None:
143 send_kwargs["view"] = view
144 message = await channel.send(**send_kwargs)
145 try:
146 await message.pin(reason=pin_reason)
147 except discord.HTTPException:
148 logger.warning("Couldn't pin %r in channel %s", embed.title, channel.id, exc_info=True)