Skip to content

Commit

Permalink
Generalize modules, some minor improvements
Browse files Browse the repository at this point in the history
Create `BaseModule` and `BaseHandler` classes
Remove `MessageNotModified` warning
Accept varargs instead of list when registering a command
Register all shortcuts via decorators
Allow hooks to return a value
Resolve hooks and shortcuts dependencies
Rename `ShortcutTransformersModule` to `ShortcutsModule`
Add `MiddlewareManager.__contains__`
Rename `__is_prod__` to `is_prod`
Bump version to 0.5
  • Loading branch information
evgfilim1 committed Nov 1, 2022
1 parent c201351 commit 2d862d1
Show file tree
Hide file tree
Showing 18 changed files with 892 additions and 518 deletions.
79 changes: 33 additions & 46 deletions locales/evgfilim1-userbot.pot
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: evgfilim1/userbot 0.4.x\n"
"Project-Id-Version: evgfilim1/userbot 0.5.x\n"
"Report-Msgid-Bugs-To: https://github.com/evgfilim1/userbot/issues\n"
"POT-Creation-Date: 2022-10-28 23:38+0500\n"
"POT-Creation-Date: 2022-11-02 02:36+0500\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <[email protected]>\n"
Expand Down Expand Up @@ -152,7 +152,7 @@ msgstr ""
msgid "{icon} The file has been downloaded to <code>{output}</code>"
msgstr ""

#: userbot/commands/download.py:77
#: userbot/commands/download.py:78
msgid "<i>Downloading file(s)...</i>"
msgstr ""

Expand Down Expand Up @@ -234,34 +234,34 @@ msgstr ""
msgid "{icon} Message with key={key!r} not found"
msgstr ""

#: userbot/commands/notes.py:52
#: userbot/commands/notes.py:53
#, python-brace-format
msgid ""
"{icon} <b>File reference expired, please save the note again.</b>\n"
"<i>Note key:</i> <code>{key}</code>"
msgstr ""

#: userbot/commands/notes.py:77 userbot/commands/notes.py:112
#: userbot/commands/notes.py:78 userbot/commands/notes.py:113
#, python-brace-format
msgid ""
"{icon} Please specify note key\n"
"\n"
"Possible fix: <code>{message_text} key</code>"
msgstr ""

#: userbot/commands/notes.py:87
#: userbot/commands/notes.py:88
#, python-brace-format
msgid "{icon} Note <code>{key}</code> saved"
msgstr ""

#: userbot/commands/notes.py:98
#: userbot/commands/notes.py:99
#, python-brace-format
msgid ""
"{icon} <b>Saved notes:</b>\n"
"{t}"
msgstr ""

#: userbot/commands/notes.py:116
#: userbot/commands/notes.py:117
#, python-brace-format
msgid "{icon} Note <code>{key}</code> deleted"
msgstr ""
Expand Down Expand Up @@ -331,7 +331,25 @@ msgstr ""
msgid "{icon} <b>Stopping userbot...</b>"
msgstr ""

#: userbot/modules/commands.py:118
#: userbot/modules/base.py:103
msgid "<i>Userbot is processing the message...</i>"
msgstr ""

#: userbot/modules/base.py:122
#, python-brace-format
msgid ""
"{icon} <b>Timed out after {timeout} while processing the message.</b>\n"
"<i>More info can be found in logs.</i>"
msgstr ""

#: userbot/modules/base.py:127
#, python-brace-format
msgid "{timeout} second"
msgid_plural "{timeout} seconds"
msgstr[0] ""
msgstr[1] ""

#: userbot/modules/commands.py:206
#, python-brace-format
msgid ""
"{icon} <b>An error occurred during executing command.</b>\n"
Expand All @@ -343,7 +361,7 @@ msgid ""
"<i>More info can be found in logs.</i>"
msgstr ""

#: userbot/modules/commands.py:136
#: userbot/modules/commands.py:222
#, python-brace-format
msgid ""
"{icon} <b>Successfully executed.</b>\n"
Expand All @@ -353,63 +371,32 @@ msgid ""
"<b>Result:</b>"
msgstr ""

#: userbot/modules/commands.py:145
#: userbot/modules/commands.py:233
#, python-brace-format
msgid "{text} <i>See reply.</i>"
msgstr ""

#: userbot/modules/commands.py:234
#, python-brace-format
msgid ""
"{icon} <b>Command timed out after {timeout}.</b>\n"
"\n"
"<b>Command:</b> <code>{message_text}</code>\n"
"\n"
"<i>More info can be found in logs.</i>"
msgstr ""

#: userbot/modules/commands.py:240
#, python-brace-format
msgid "{timeout} second"
msgid_plural "{timeout} seconds"
msgstr[0] ""
msgstr[1] ""

#: userbot/modules/commands.py:259
#, python-brace-format
msgid "<i>Executing</i> <code>{command}</code>..."
msgstr ""

#: userbot/modules/commands.py:301
#, python-brace-format
msgid ""
"{result}\n"
"\n"
"{icon} <i><b>MessageNotModified</b> was raised, check that there's only one instance of userbot "
"is running.</i>"
msgstr ""

#: userbot/modules/commands.py:460
#: userbot/modules/commands.py:400
#, python-brace-format
msgid ""
"<b>Help for {args}:</b>\n"
"{usage}"
msgstr ""

#: userbot/modules/commands.py:466
#: userbot/modules/commands.py:406
msgid ""
"<b>List of userbot commands available:</b>\n"
"\n"
msgstr ""

#: userbot/modules/hooks.py:27
#: userbot/modules/hooks.py:34
#, python-brace-format
msgid ""
"Hooks in this chat:\n"
"{hooks}"
msgstr ""

#: userbot/modules/hooks.py:128
#: userbot/modules/hooks.py:213
#, python-brace-format
msgid ""
"Available hooks:\n"
Expand Down
6 changes: 3 additions & 3 deletions userbot/__init__.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
__all__ = [
"__is_prod__",
"is_prod",
"__version__",
]

from os import environ
from typing import Final

__is_prod__: Final[bool] = bool(environ.get("GITHUB_SHA", ""))
__version__: Final[str] = "0.4.x" + ("-dev" if not __is_prod__ else "")
is_prod: Final[bool] = bool(environ.get("GITHUB_SHA", ""))
__version__: Final[str] = "0.5.x" + ("-dev" if not is_prod else "")
42 changes: 25 additions & 17 deletions userbot/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,21 +9,21 @@
from pyrogram.handlers import RawUpdateHandler
from pyrogram.methods.utilities.idle import idle

from userbot import __is_prod__, __version__
from userbot import __version__, is_prod
from userbot.commands import commands
from userbot.commands.chat_admin import react2ban_raw_reaction_handler
from userbot.config import Config, RedisConfig
from userbot.constants import GH_PATTERN
from userbot.hooks import hooks
from userbot.job_manager import AsyncJobManager
from userbot.middlewares import KwargsMiddleware, icon_middleware, translate_middleware
from userbot.shortcuts import get_note, github, shortcuts
from userbot.modules import HooksModule
from userbot.shortcuts import shortcuts
from userbot.storage import RedisStorage, Storage
from userbot.utils import GitHubClient, fetch_stickers

logging.basicConfig(level=logging.WARNING)
_log = logging.getLogger(__name__)
_log.setLevel(logging.INFO if __is_prod__ else logging.DEBUG)
_log.setLevel(logging.INFO if is_prod else logging.DEBUG)


async def _main(
Expand Down Expand Up @@ -69,27 +69,35 @@ def main() -> None:
github_client = GitHubClient(AsyncClient(http2=True))

_log.debug("Registering handlers...")
shortcuts.add_handler(partial(github, github_client=github_client), GH_PATTERN)
shortcuts.add_handler(partial(get_note, storage=storage), r"n://(.+?)/")
client.add_handler(
RawUpdateHandler(partial(react2ban_raw_reaction_handler, storage=storage)),
group=1,
)
commands.add_middleware(
KwargsMiddleware(
{
"storage": storage,
"data_dir": config.data_location,
"notes_chat": config.media_notes_chat,
}
)

root_hooks = HooksModule(commands=commands, storage=storage)
root_hooks.add_submodule(hooks)

kwargs_middleware = KwargsMiddleware(
{
"storage": storage,
"data_dir": config.data_location,
"notes_chat": config.media_notes_chat,
"github_client": github_client,
}
)
commands.add_middleware(icon_middleware)
commands.add_middleware(kwargs_middleware)
commands.add_middleware(translate_middleware)
commands.add_middleware(icon_middleware)
root_hooks.add_middleware(kwargs_middleware)
root_hooks.add_middleware(translate_middleware)
root_hooks.add_middleware(icon_middleware)
shortcuts.add_middleware(kwargs_middleware)
shortcuts.add_middleware(translate_middleware)
shortcuts.add_middleware(icon_middleware)

# `HooksModule` must be registered before `CommandsModule` because it adds some commands
hooks.register(client, storage, commands)
commands.register(client, with_help=True)
root_hooks.register(client)
commands.register(client)
shortcuts.register(client)

job_manager = AsyncJobManager()
Expand Down
2 changes: 1 addition & 1 deletion userbot/commands/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
except ImportError:
test_commands = None

commands = CommandsModule()
commands = CommandsModule(root=True)

for submodule in (
about_commands,
Expand Down
4 changes: 2 additions & 2 deletions userbot/commands/about.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

from pyrogram import Client

from .. import __is_prod__
from .. import is_prod
from ..constants import Icons, PremiumIcons
from ..modules import CommandsModule
from ..translation import Translation
Expand All @@ -33,7 +33,7 @@ async def about(client: Client, icons: Type[Icons], tr: Translation) -> str:
f"{github_icon} <a href='{base_url}'>evgfilim1/userbot</a>\n"
f"{commit_icon} <code>{commit}</code>"
)
if __is_prod__:
if is_prod:
t += _(" (<a href='{base_url}/deployments'>deployments</a>)").format(
base_url=base_url,
)
Expand Down
2 changes: 1 addition & 1 deletion userbot/commands/chat_admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ async def react2ban(
return _(_REACT2BAN_TEXT)


@commands.add(["no_react2ban", "noreact2ban"], usage="<reply>")
@commands.add("no_react2ban", "noreact2ban", usage="<reply>")
async def no_react2ban(
message: Message,
storage: Storage,
Expand Down
2 changes: 1 addition & 1 deletion userbot/commands/dice.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def _str_die(self, node):
return ", ".join(the_rolls)


@commands.add(["roll", "dice"], usage="<dice-spec>")
@commands.add("roll", "dice", usage="<dice-spec>")
async def dice(command: CommandObject) -> str:
"""Rolls dice according to d20.roll syntax
Expand Down
3 changes: 2 additions & 1 deletion userbot/commands/download.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,8 @@ async def _downloader(


@commands.add(
["download", "dl"],
"download",
"dl",
usage="[reply] [filename]",
waiting_message=_("<i>Downloading file(s)...</i>"),
)
Expand Down
4 changes: 2 additions & 2 deletions userbot/commands/messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
commands = CommandsModule("Messages")


@commands.add(["delete", "delet", "del"], usage="<reply>")
@commands.add("delete", "delet", "del", usage="<reply>")
async def delete_this(message: Message) -> None:
"""Deletes replied message for everyone"""
try:
Expand Down Expand Up @@ -128,7 +128,7 @@ async def user_first_message(
await message.delete()


@commands.add(["copyhere", "cphere", "cph"], usage="<reply>")
@commands.add("copyhere", "cphere", "cph", usage="<reply>")
async def copy_here(message: Message) -> None:
"""Copies replied message to current chat"""
await message.reply_to_message.copy(message.chat.id)
Expand Down
8 changes: 4 additions & 4 deletions userbot/commands/notes.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
commands = CommandsModule("Notes")


@commands.add(["get", "note", "n"], usage="<name>")
@commands.add("get", "note", "n", usage="<name>")
async def get_note(
client: Client,
message: Message,
Expand Down Expand Up @@ -63,7 +63,7 @@ async def get_note(
await message.delete()


@commands.add(["save", "note_add", "nadd"], usage="<reply> <name>")
@commands.add("save", "note_add", "nadd", usage="<reply> <name>")
async def save_note(
message: Message,
command: CommandObject,
Expand All @@ -88,7 +88,7 @@ async def save_note(
return _("{icon} Note <code>{key}</code> saved").format(icon=icons.BOOKMARK, key=key)


@commands.add(["notes", "ns"])
@commands.add("notes", "ns")
async def saved_notes(storage: Storage, icons: Type[Icons], tr: Translation) -> str:
"""Shows all saved notes"""
_ = tr.gettext
Expand All @@ -99,7 +99,7 @@ async def saved_notes(storage: Storage, icons: Type[Icons], tr: Translation) ->
return _("{icon} <b>Saved notes:</b>\n{t}").format(icon=icons.BOOKMARK, t=t)


@commands.add(["note_del", "ndel"], usage="<name>")
@commands.add("note_del", "ndel", usage="<name>")
async def delete_note(
message: Message,
command: CommandObject,
Expand Down
10 changes: 5 additions & 5 deletions userbot/hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,19 +23,19 @@


@hooks.add("emojis", filters.regex(r"\b((?:дак\b|кря(?:к.?|\b))|блин)", flags=re.I))
async def on_emojis(_: Client, message: Message) -> None:
async def on_emojis(message: Message) -> str:
t = ""
for match in message.matches:
m = match[1].lower()
if m == "дак" or m.startswith("кря"):
t += "🦆"
elif m == "блин":
t += "🥞"
await message.reply(t)
return t


@hooks.add("tap", (filters.regex(r"\b(?:тык|nsr)\b", flags=re.I) | sticker(TAP_FLT)))
async def on_tap(_: Client, message: Message) -> None:
async def on_tap(message: Message) -> None:
await message.reply_sticker(TAP_STICKER)


Expand All @@ -47,10 +47,10 @@ async def mibib(client: Client, message: Message) -> None:


@hooks.add("bra", filters.regex(r"\b(?:бра|bra)\b", flags=re.I))
async def on_bra(_: Client, message: Message) -> None:
async def on_bra(message: Message) -> None:
await message.reply_photo(BRA_MEME_PICTURE)


@hooks.add("uwu", filters.regex(r"\b(?:uwu|owo|уву|ово)\b", flags=re.I))
async def on_uwu(_: Client, message: Message) -> None:
async def on_uwu(message: Message) -> None:
await message.reply_photo(UWU_MEME_PICTURE)
Loading

0 comments on commit 2d862d1

Please sign in to comment.