Skip to content
This repository has been archived by the owner on Jul 4, 2024. It is now read-only.

Commit

Permalink
Updated to Pyrogram 1.0.2, but removed the dependency
Browse files Browse the repository at this point in the history
  • Loading branch information
Joscha Götzer authored and Joscha Götzer committed Aug 26, 2020
1 parent 55b9780 commit 830912b
Show file tree
Hide file tree
Showing 75 changed files with 613 additions and 703 deletions.
10 changes: 4 additions & 6 deletions botkit/botkit_modules/module_manager/__init__.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
from haps import Inject
from pyrogram import Filters, Message
from pyrogram.filters import command

from botkit.core.moduleloader import ModuleLoader
from botkit.core.modules import Module
from .paged_module_view import PagedModuleView
from .view_models import ModuleInfo, ModuleInfosCollectionModel
from botkit.routing.route_builder.builder import RouteBuilder
from botkit.services.companionbotservice import CompanionBotService
from botkit.views.renderer_client_mixin import PyroRendererClientMixin
from .paged_module_view import PagedModuleView
from .view_models import ModuleInfo, ModuleInfosCollectionModel
from ...types.client import IClient
from ...views.botkit_context import BotkitContext


class ModuleManagerModule(Module):
Expand All @@ -23,7 +21,7 @@ def __init__(self, user_client: IClient, bot_client: IClient):
def register(self, routes: RouteBuilder):
with routes.using(self.user_client):
(
routes.on(Filters.command("modules", prefixes=["#", "/"]))
routes.on(command("modules", prefixes=["#", "/"]))
.gather(self.get_modules)
.then_send(PagedModuleView, via=self.bot_client)
)
Expand Down
3 changes: 2 additions & 1 deletion botkit/botkit_modules/system/status_pings.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@
from datetime import datetime, timedelta
from pydantic import BaseModel
from pyrogram import Client
from pyrogram import Message
from typing import Literal
from typing import Optional, Union, List
from typing import cast

from pyrogram.types import Message
from typing_extensions import AsyncGenerator

from botkit.botkit_modules.system.sytem_management_module import ToggleSystemStateCommand
Expand Down
9 changes: 4 additions & 5 deletions botkit/botkit_modules/system/system_tests.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
from typing import Any, List, Optional
from typing import List
from unittest.mock import Mock

from haps import Inject
from pyrogram import Chat, Message, User
from pyrogram.types import Chat, Message, User

from botkit.core.moduleloader import ModuleLoader
from botkit.core.modules import Module, module
from botkit.routing.pipelines.callbacks import HandlerSignature
from botkit.core.modules import Module
from botkit.routing.route import RouteDefinition, RouteHandler
from botkit.routing.route_builder.builder import RouteBuilder
from botkit.routing.route_builder.route_collection import RouteCollection
from botkit.routing.update_types.updatetype import UpdateType
from botkit.types.client import IClient

Expand Down Expand Up @@ -44,6 +42,7 @@ async def test_module_routes(self, routes: List[RouteDefinition]):

async def fire_request(self, update_type: UpdateType, route: RouteHandler):
try:
# noinspection PyUnresolvedReferences
should_not_test = route.callback.notests
return
except AttributeError:
Expand Down
18 changes: 10 additions & 8 deletions botkit/botkit_modules/system/sytem_management_module.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@
import asyncio
from buslane.commands import Command, CommandHandler
from haps import Inject, Container
from pyrogram import Filters, Message, User, Client
from pyrogram import filters
from pyrogram.types import Message, User
from typing import Optional, List, Any, Literal

from botkit.botkit_modules.system.system_tests import notests
from botkit.libraries.annotations import IClient
from botkit.persistence.callback_manager import (
RedisCallbackManager,
ICallbackManager,
Expand All @@ -19,7 +21,7 @@

@dataclass
class _LoadCtx:
user_client_me: User
user_client_id: int


@dataclass
Expand All @@ -32,25 +34,25 @@ class ToggleSystemStateCommand(Command):
class SystemManagementModule(Module):
module_loader: ModuleLoader = Inject()

def __init__(self, user_client: Client) -> None:
def __init__(self, user_client: IClient) -> None:
self.user_client = user_client

self.system_paused: bool = False
self.paused_modules: Optional[List[Module]] = None

async def load(self) -> _LoadCtx:
return _LoadCtx(user_client_me=await self.user_client.get_me())
return _LoadCtx(user_client_id=(await self.user_client.get_me()).id)

def register(self, routes: RouteBuilder):
routes.use(self.user_client)

restart_command = Filters.command("r", prefixes=[".", "#"]) | Filters.command("restart")
only_owner = Filters.user(routes.context.load_result.user_client_me.id)
restart_command = filters.command("r", prefixes=[".", "#"]) | filters.command("restart")
only_owner = filters.user(routes.context.load_result.user_client_id)

routes.on(restart_command & only_owner).call(self.restart_system)

routes.on(Filters.command(["off", "pause"]) & only_owner).call(self.handle_pause_command)
routes.on(Filters.command(["on", "unpause"]) & only_owner).call(
routes.on(filters.command(["off", "pause"]) & only_owner).call(self.handle_pause_command)
routes.on(filters.command(["on", "unpause"]) & only_owner).call(
self.handle_unpause_command
)

Expand Down
37 changes: 18 additions & 19 deletions botkit/botkit_services/lookupservice.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,13 @@
from haps import *
from telethon.tl.custom import Message, Dialog

from commons.core.routing import Event
from commons.core.clients.userclient import IUserClient
from commons.core.descriptors.base import EntityDescriptor
from commons.core.util import string_similarity
from telethon.tl import TLObject
from telethon.utils import get_display_name as telethon_get_display_name

T = TypeVar('P')
T = TypeVar("P")


class EntityNotFoundError(Exception):
Expand All @@ -22,26 +21,32 @@ class EntityNotFoundError(Exception):
def get_display_name(entity: Any):
if isinstance(entity, Dialog):
return entity.name
if hasattr(entity, 'title'):
if hasattr(entity, "title"):
return entity.title
return telethon_get_display_name(entity)


@base
class ILookupService(ABC):
@abstractmethod
async def resolve_peer(self, descriptor: EntityDescriptor, raise_=True): pass
async def resolve_peer(self, descriptor: EntityDescriptor, raise_=True):
pass

@abstractmethod
async def resolve_full_peer(self, descriptor: EntityDescriptor): pass
async def resolve_full_peer(self, descriptor: EntityDescriptor):
pass

@abstractmethod
async def get_message_by_id(self, chat: Any, message_id: int) -> Message: pass
async def get_message_by_id(self, chat: Any, message_id: int) -> Message:
pass

@abstractmethod
async def get_previous_messages(self, event: Event, n: int = 1) -> List[Message]: pass
async def get_previous_messages(self, event: Event, n: int = 1) -> List[Message]:
pass

@abstractmethod
async def get_last_message_in_chat(self, input_chat: Any) -> Message: pass
async def get_last_message_in_chat(self, input_chat: Any) -> Message:
pass


@egg
Expand All @@ -63,11 +68,7 @@ async def resolve_full_peer(self, descriptor: EntityDescriptor):
return self.client.session.get_input_entity(descriptor)

async def _resolve_chat_by_title(
self,
title: str,
confidence=0.9,
aggressive=False,
raise_=True
self, title: str, confidence=0.9, aggressive=False, raise_=True
) -> TLObject:
results = await self.client.get_dialogs(limit=200)

Expand All @@ -87,11 +88,7 @@ def matches_query(found_name):
return None

async def _resolve_user_by_title(
self,
title: str,
confidence=0.9,
aggressive=False,
raise_=True
self, title: str, confidence=0.9, aggressive=False, raise_=True
) -> TLObject:
results = await self.client.get_dialogs(limit=40)

Expand All @@ -104,7 +101,9 @@ def matches_query(found_name):
# Search failed.
for d in results:
try:
participants = self.client.iter_participants(d.input_entity, 200, search='', aggressive=aggressive)
participants = self.client.iter_participants(
d.input_entity, 200, search="", aggressive=aggressive
)
async for p in participants:
if matches_query(get_display_name(p)):
return p.entity
Expand Down
2 changes: 1 addition & 1 deletion botkit/builders/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from .htmlbuilder import HtmlBuilder
from .inlinemenubuilder import InlineMenuBuilder
from .metabuilder import MetaBuilder
from ..views.base import RenderedMessage, RenderedTextMessage
from ..views.rendered_messages import RenderedMessage, RenderedTextMessage


class ViewBuilder:
Expand Down
3 changes: 2 additions & 1 deletion botkit/builders/inlinemenubuilder.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from cached_property import cached_property
from haps import Container
from haps.exceptions import NotConfigured
from pyrogram import InlineKeyboardButton
from pyrogram.types import InlineKeyboardButton

from botkit import buttons
from botkit.persistence.callback_manager import (
Expand All @@ -16,6 +16,7 @@
from botkit.utils.sentinel import NotSet, Sentinel


# noinspection PyIncorrectDocstring
class InlineMenuRowBuilder:
def __init__(self, state: Optional[Any], override_buttons: List[Any] = None):
if override_buttons:
Expand Down
4 changes: 2 additions & 2 deletions botkit/buttons.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from pyrogram import InlineKeyboardButton
from pyrogram.types import InlineKeyboardButton

from botkit.inlinequeries.contexts import IInlineModeContext, DefaultInlineModeContext

Expand All @@ -14,5 +14,5 @@ def switch_inline_button(
"switch_inline_query" + "_current_chat"
if current_chat
else "": in_context.format_query()
}
},
)
29 changes: 2 additions & 27 deletions botkit/clients/configured_client.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
from abc import abstractmethod

from decouple import config
from pyrogram import Client, User
from tgintegration import InteractionClient
from pyrogram import Client
from pyrogram.types import User

from botkit.clients.client_config import ClientConfig

Expand Down Expand Up @@ -42,28 +42,3 @@ async def get_me(self) -> User:
return self._me
self._me = await super().get_me()
return self._me


class ConfiguredInteractionClient(InteractionClient):
def __init__(self, **kwargs) -> None:
merged_args = dict(
session_name=self.config.session_name,
api_id=config("API_ID"),
api_hash=config("API_HASH"),
bot_token=self.config.bot_token,
phone_number=self.config.phone_number,
)
merged_args.update(kwargs)
super().__init__(**merged_args)
self._me = None

@property
@abstractmethod
def config(self) -> ClientConfig:
...

async def get_me(self) -> User:
if self._me is not None:
return self._me
self._me = await super().get_me()
return self._me
26 changes: 13 additions & 13 deletions botkit/commands/TODO.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ Commands from all modules get registered in a central place.
A singleton (compound, all types) internal handler goes through all registered commands and builds a list
`quick_action_matches: List[CommandDefinition]`.
Then it replies with reply keyboard buttons. `botkit.use_quick_actions()` ??

modulemanager

```
routes.register_command()
```
Expand All @@ -30,23 +30,23 @@ routes.register_command()

## Quick Action Registry (Ideas)

### Filters.text
### filters.text
(Most common. Needs a good hierarchical menu)
- **Use in inline query** -> "Which bot @?" - @letmebot -> Share button
- **Remind me**
-> `ChoiceView("Who to remind?", ["Just me", "Someone else", "Me and others"])`
-> `ChoiceView("Who to remind?", ["Just me", "Someone else", "Me and others"])`
-> `DateTimePickerView("When?")`
- **Edit** -> `send_as_user(...)` (so that user can edit)
- **Share** -> `ShareView(...)`

### Filters.text (multiple)
### filters.text (multiple)
"Does this message belong to the others?" yes/no
- **Merge** ->
- **Delete** (if forwarded and user admin)
- **Merge** ->
- **Delete** (if forwarded and user admin)
-> "This will delete messages 1-3, 7, and 8 from {origin_chat_title}" (yes/no)
- **Open in VSCode**

### Filters.link
### filters.link
- **Open in browser** -> `ChoiceView(links) if len(links) > 1 else links[0]`
- **Add to Pocket** -> `ChoiceView(links, multiple=True) if len(links) > 1 else links[0]`

Expand All @@ -57,17 +57,17 @@ routes.register_command()
- Notion
- Add to project -> `ChoiceView(...)`

### Filters.sticker
### filters.sticker
- Add to pack
- Optimize

### Filters.sticker (multiple)
### filters.sticker (multiple)
- Merge

### Filters.command
### filters.command
- Choose bot

### Filters.contains_emoji
### filters.contains_emoji
- Explain emojis

# Editor
Expand All @@ -89,4 +89,4 @@ The `EditorView` consists of a message with quick actions above and the content

## Prototype of hierarchical settings module

Click on setting -> opens group of related settings (and back button)
Click on setting -> opens group of related settings (and back button)
Loading

0 comments on commit 830912b

Please sign in to comment.