Skip to content

Commit

Permalink
autoconv: fix codeblock autoconv
Browse files Browse the repository at this point in the history
  • Loading branch information
Paul Przybyszewski committed Jul 16, 2022
1 parent 4c97b79 commit a698fb9
Show file tree
Hide file tree
Showing 6 changed files with 24 additions and 22 deletions.
10 changes: 6 additions & 4 deletions cogs/backend/handle/events/event_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from lib.utils import regex
from cogs.github.other.snippets.snippet_tools import handle_url, gen_carbon_inmemory
from typing import Optional
from lib.typehints import AutomaticConversion
from lib.typehints import AutomaticConversionSettings
from lib.structs import GitBotEmbed
from lib.structs.discord.context import GitBotContext

Expand All @@ -22,11 +22,12 @@ def set_handler_ctx_attributes(ctx: GitBotContext) -> commands.Context:
@commands.max_concurrency(6, wait=True)
async def silent_snippet_command(ctx: GitBotContext) -> Optional[discord.Message]:
codeblock: Optional[str] = None
config: AutomaticConversion = await Mgr.get_autoconv_config(ctx)
config: AutomaticConversionSettings = await Mgr.get_autoconv_config(ctx)
match_ = None # put the match_ name in the namespace
if (attachment_url := Mgr.carbon_attachment_cache.get(ctx.message.content)) and config['gh_lines'] == 2:
Mgr.debug('Responding with cached asset URL')
return await ctx.reply(attachment_url, mention_author=False)
elif (result := Mgr.extract_content_from_codeblock(ctx.message.content)) and config['codeblock']:
elif (result := Mgr.extract_content_from_codeblock(ctx.message.content)) and config.get('codeblock', False):
Mgr.debug(f'Converting codeblock in MID {ctx.message.id} into carbon snippet...')
codeblock: str = result
elif match_ := (regex.GITHUB_LINES_URL_RE.search(ctx.message.content)
Expand All @@ -44,10 +45,11 @@ async def silent_snippet_command(ctx: GitBotContext) -> Optional[discord.Message
if codeblock:
Mgr.debug(f'Converting MID {ctx.message.id} into codeblock...')
return await ctx.reply(codeblock, mention_author=False)
_1st_lineno: int = 1 if not match_ else match_.group('first_line_number')
if codeblock and len(codeblock.splitlines()) < Mgr.env.carbon_len_threshold:
start: float = time.time()
reply: discord.Message = await ctx.reply(file=discord.File(filename='snippet.png',
fp=await gen_carbon_inmemory(codeblock, match_.group('first_line_number'))), # noqa
fp=await gen_carbon_inmemory(codeblock, _1st_lineno)),
mention_author=False)
Mgr.debug(f'Carbon asset generation elapsed: {time.time() - start}s')
Mgr.carbon_attachment_cache[ctx.message.content] = reply.attachments[0].url
Expand Down
12 changes: 6 additions & 6 deletions cogs/ecosystem/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from lib.typehints import (GitHubRepository, GitHubOrganization,
GitHubUser, GitBotGuild,
ReleaseFeedItem, ReleaseFeed,
ReleaseFeedRepo, AutomaticConversion,
ReleaseFeedRepo, AutomaticConversionSettings,
GitBotUser)
from typing import Optional, Literal
from lib.structs import GitBotEmbed, GitBotCommandState
Expand Down Expand Up @@ -37,7 +37,7 @@ def construct_release_feed_list(ctx: GitBotContext, rf: ReleaseFeed) -> str:
async def toggle_autoconv_item(ctx: GitBotContext,
item: Literal['gh_url', 'codeblock']) -> bool:
guild: GitBotGuild = await Mgr.db.guilds.find_one({'_id': ctx.guild.id}) or {}
config: AutomaticConversion = guild.get('autoconv', Mgr.env.autoconv_default)
config: AutomaticConversionSettings = guild.get('autoconv', Mgr.env.autoconv_default)
config[item] = (state := not (config.get(item, Mgr.env.autoconv_default[item]))) # noqa cause PyCharm is high
if guild:
await Mgr.db.guilds.update_one({'_id': guild['_id']}, {'$set': {f'autoconv.{item}': state}})
Expand Down Expand Up @@ -87,9 +87,9 @@ async def config_show_command_group(self, ctx: GitBotContext) -> None:
f' `{ctx.l.config.show.base.item_not_configured}`'
ctx.fmt.set_prefix('+guild list autoconv')
if not guild:
ac: AutomaticConversion = Mgr.env.autoconv_default
ac: AutomaticConversionSettings = Mgr.env.autoconv_default
else:
ac: AutomaticConversion = {k: (v if k not in (_ac := guild.get('autoconv', {}))
ac: AutomaticConversionSettings = {k: (v if k not in (_ac := guild.get('autoconv', {}))
else _ac[k]) for k, v in Mgr.env.autoconv_default.items()}
codeblock: str = ctx.fmt('codeblock',
f'`{ctx.l.enum.generic.switch[str(ac["codeblock"])]}`')
Expand Down Expand Up @@ -471,11 +471,11 @@ async def _callback(_, res: discord.Message):
actual_state = skip_state
if (_str := str(actual_state)) in ctx.lp.results.keys():
if guild:
config: AutomaticConversion = guild.get('autoconv', Mgr.env.autoconv_default)
config: AutomaticConversionSettings = guild.get('autoconv', Mgr.env.autoconv_default)
config['gh_lines'] = actual_state
await Mgr.db.guilds.update_one({'_id': guild['_id']}, {'$set': {'autoconv.gh_lines': actual_state}})
else:
config: AutomaticConversion = Mgr.env.autoconv_default
config: AutomaticConversionSettings = Mgr.env.autoconv_default
config['gh_lines'] = actual_state
await Mgr.db.guilds.insert_one({'_id': ctx.guild.id, 'autoconv': config})
Mgr.autoconv_cache[ctx.guild.id] = config
Expand Down
12 changes: 6 additions & 6 deletions lib/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@
from typing import Optional, Callable, Any, Reversible, Iterable, Type, TYPE_CHECKING, Generator
if TYPE_CHECKING:
from lib.structs.discord.context import GitBotContext
from lib.typehints import DictSequence, AnyDict, Identity, GitBotGuild, AutomaticConversion, LocaleName, ReleaseFeedItemMention
from lib.typehints import DictSequence, AnyDict, Identity, GitBotGuild, AutomaticConversionSettings, LocaleName, ReleaseFeedItemMention


class Manager:
Expand Down Expand Up @@ -880,8 +880,8 @@ def readdir(self, path: str, ext: Optional[str | list | tuple] = None, **kwargs)
@normalize_identity(context_resource='guild')
async def get_autoconv_config(self,
_id: Identity,
did_exist: bool = False) -> Type[AutomaticConversion] | tuple[AutomaticConversion,
bool]:
did_exist: bool = False) -> Type[AutomaticConversionSettings] | tuple[AutomaticConversionSettings,
bool]:
"""
Get the configured permission for automatic conversion from messages (links, snippets, etc.)
Expand All @@ -894,15 +894,15 @@ async def get_autoconv_config(self,

if cached := self.autoconv_cache.get(_id):
_did_exist: bool = True
permission: AutomaticConversion = cached
permission: AutomaticConversionSettings = cached
self.debug(f'Returning cached value for identity "{_id}"')
else:
stored: Optional[GitBotGuild] = await self.db.guilds.find_one({'_id': _id})
if stored:
permission: AutomaticConversion = stored.get('autoconv', self.env.autoconv_default)
permission: AutomaticConversionSettings = stored.get('autoconv', self.env.autoconv_default)
_did_exist: bool = True
else:
permission: AutomaticConversion = self.env.autoconv_default
permission: AutomaticConversionSettings = self.env.autoconv_default
self.autoconv_cache[_id] = permission
return permission if not did_exist else (permission, _did_exist)

Expand Down
4 changes: 2 additions & 2 deletions lib/typehints/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from lib.typehints.db.user import GitBotUser
from lib.typehints.db.guild.guild import GitBotGuild
from lib.structs import DictProxy, DirProxy, CaseInsensitiveDict, MaxAgeDict, FixedSizeOrderedDict
from lib.typehints.db.guild.autoconv import AutomaticConversion
from lib.typehints.db.guild.autoconv import AutomaticConversionSettings
from lib.typehints.generic import *
from lib.typehints.locale.help import *
from lib.typehints.db.guild.release_feed import *
Expand All @@ -23,7 +23,7 @@
'GitHubUser',
'GitHubOrganization',
'PyPIProject',
'AutomaticConversion',
'AutomaticConversionSettings',
'Hash',
'MessageAttachmentURL',
'EmbedLike',
Expand Down
4 changes: 2 additions & 2 deletions lib/typehints/db/guild/autoconv.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
from typing import TypedDict, Literal

__all__: tuple = ('AutomaticConversion',)
__all__: tuple = ('AutomaticConversionSettings',)


class AutomaticConversion(TypedDict):
class AutomaticConversionSettings(TypedDict):
codeblock: bool
gh_url: bool
gh_lines: Literal[0, 1, 2]
4 changes: 2 additions & 2 deletions lib/typehints/db/guild/guild.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from typing import TypedDict
from lib.typehints.generic import GuildID
from lib.typehints.db.guild.release_feed import ReleaseFeed
from .autoconv import AutomaticConversion
from .autoconv import AutomaticConversionSettings

__all__: tuple = ('GitBotGuild',)

Expand All @@ -18,4 +18,4 @@ class GitBotGuild(TypedDict, total=False):

_id: GuildID
feed: ReleaseFeed
autoconv: AutomaticConversion
autoconv: AutomaticConversionSettings

0 comments on commit a698fb9

Please sign in to comment.