Skip to content

Commit

Permalink
change logs
Browse files Browse the repository at this point in the history
  • Loading branch information
Sidnev Nikolaj committed Aug 13, 2019
1 parent 35ee8b0 commit 3c91e92
Show file tree
Hide file tree
Showing 7 changed files with 61 additions and 11 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@

# Introduction

`pybotx` is a toolkit for building bots for Express providing a mechanism for simple integration with your favourite web frameworks.
`pybotx` is a framework for building bots for Express providing a mechanism for simple integration with your favourite web frameworks.

Main features:

Expand Down
27 changes: 25 additions & 2 deletions botx/clients.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import abc
import json
from typing import Any, Awaitable, Callable, Dict, Optional
from uuid import UUID

from httpx import AsyncClient
from httpx.models import BaseResponse
from httpx.status_codes import StatusCode

from botx.models.botx_api import BotXPayloadOptions
from loguru import logger

from .core import BotXAPI, BotXException
from .helpers import get_data_for_api_error
Expand All @@ -19,6 +19,9 @@
SendingCredentials,
SendingPayload,
)
from .models.botx_api import BotXPayloadOptions

logger_ctx = logger.bind(botx_client=True)


def get_headers(token: str) -> Dict[str, str]:
Expand Down Expand Up @@ -69,6 +72,11 @@ async def send_file(
assert payload.file, "payload should include File object"

async with AsyncClient(app=self.asgi_app) as client:
logger_ctx.bind(
credentials=json.loads(credentials.json(exclude={"token", "chat_ids"})),
payload={"filename": payload.file.file_name},
).debug("send file")

resp = await client.post(
self._file_url.format(host=credentials.host),
data=BotXFilePayload.from_orm(credentials).dict(),
Expand All @@ -82,6 +90,11 @@ async def send_file(

async def obtain_token(self, host: str, bot_id: UUID, signature: str) -> Any:
async with AsyncClient(app=self.asgi_app) as client:
logger_ctx.bind(
credentials={"host": host, "bot_id": str(bot_id)},
payload={"signature": signature},
).debug("obtain token")

resp = await client.get(
self._token_url.format(host=host, bot_id=bot_id),
params=BotXTokenRequestParams(signature=signature).dict(),
Expand Down Expand Up @@ -115,6 +128,11 @@ async def send_command_result(
)

async with AsyncClient(app=self.asgi_app) as client:
logger_ctx.bind(
credentials=json.loads(credentials.json(exclude={"token", "chat_ids"})),
payload=json.loads(command_result.json()),
).debug("send command result")

resp = await client.post(
self._command_url.format(host=credentials.host),
json=command_result.dict(),
Expand Down Expand Up @@ -145,6 +163,11 @@ async def send_notification(
opts=BotXPayloadOptions(notification_opts=payload.options.notifications),
)
async with AsyncClient(app=self.asgi_app) as client:
logger.bind(
credentials=json.loads(credentials.json(exclude={"token", "sync_id"})),
payload=json.loads(notification.json()),
).debug("send notification")

resp = await client.post(
self._notification_url.format(host=credentials.host),
json=notification.dict(),
Expand Down
23 changes: 19 additions & 4 deletions botx/dispatchers.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
from .helpers import create_message
from .models import CommandCallback, CommandHandler, Message, Status, StatusResult

logger_ctx = logger.bind(botx_dispatcher=True)


class BaseDispatcher(abc.ABC):
_handlers: Dict[Pattern, CommandHandler]
Expand Down Expand Up @@ -61,7 +63,7 @@ def add_handler(self, handler: CommandHandler) -> None:

self._default_handler = handler
else:
logger.debug(f"registered handler for {handler.command.pattern !r}")
logger.debug(f"registered handler => {handler.command.pattern !r}")

self._handlers[handler.command] = handler

Expand All @@ -77,11 +79,17 @@ def register_exception_catcher(
raise BotXException(f"catcher for {exc} was already registered")

self._exceptions_map[exc] = callback
logger_ctx.bind(exc_type=exc).debug("registered new exception catcher")

def _add_next_step_handler(
self, message: Message, callback: CommandCallback
) -> None:
key = (message.host, message.bot_id, message.group_chat_id, message.user_huid)
logger_ctx.bind(message=message).debug(
"registered next step handler => "
"host: {0}; bot_id: {1}, group_chat_id: {2}, user_huid: {3}",
*key,
)
if key in self._next_step_handlers:
self._next_step_handlers[key].append(callback)
else:
Expand All @@ -90,13 +98,20 @@ def _add_next_step_handler(
def _get_callback_for_message(self, message: Message) -> CommandCallback:
try:
callback = self._get_next_step_handler_from_message(message)
logger.info(
f"next step handler for {message.group_chat_id} {message.user_huid}"
logger.bind(message=message).info(
"next step handler => "
"host: {0}; bot_id: {1}, group_chat_id: {2}, user_huid: {3}",
message.host,
message.bot_id,
message.group_chat_id,
message.user_huid,
)
except (IndexError, KeyError):
handler = self._get_command_handler_from_message(message)
callback = handler.callback
logger.info(f"handler for {handler.command.pattern !r}")
logger.bind(message=message).info(
f"handler => {handler.command.pattern !r}"
)

return callback

Expand Down
2 changes: 1 addition & 1 deletion docs/api-reference/bots.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ for displaying notifications, users who will receive messages and mentions.
* `**kwargs: Any` - additional key arguments to be passed to the handler.

### Errors Handlers Registrations
* `exception_catcher(exceptions, force_replace)` - decorator to register a handler that will be used when an exception occurs during
* `.exception_catcher(exceptions, force_replace)` - decorator to register a handler that will be used when an exception occurs during
the execution of a handler for a command.
* `exceptions: List[Type[Exception]]` - list of exception types that will be handled by exception handler
* `force_replace: bool = False` - replace the existing handler for exception with a new one if the new one,
Expand Down
13 changes: 13 additions & 0 deletions docs/api-reference/botx-types.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,14 @@ All these classes are `pydantic` models except `BotXException` and enums.
* `.callback: Callable`
* `.args: Tuple[Any, ...] = ()`
* `.kwargs: Dict[str, Any] = {}`
* `.background_dependencies: List[Dependency] = []`

### Dependencies

* `Dependency`
* `.call: Callable`

* `Depends(dependency: Callable) -> Any`

### Status

Expand Down Expand Up @@ -116,7 +124,9 @@ All these classes are `pydantic` models except `BotXException` and enums.
* `.opts: NotificationOpts = NotificationOpts()`
* `.file: Optional[File] = None`
---

* `.chat_id: UUID readonly`

---
* `.add_file(file)`
* `.mention_user(user_huid, name)`
Expand Down Expand Up @@ -282,3 +292,6 @@ All these classes are `pydantic` models except `BotXException` and enums.
* `BotXException(message, data)`
* `.message: str = ""`
* `.data: Optional[Dict[str, Any]] = None`


* `BotXDependencyFailure`
3 changes: 1 addition & 2 deletions docs/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,12 @@ such as creating a new chat with a bot.
* Added logging via `loguru`.
* Dropped `aiojobs`.
* Replaced `requests` and `aiohttp` with `httpx`.
* Renamed `chat_id` argument in `send_file` to `sync_id`.
* `Bot` can now accept both coroutines and normal functions.
* Dropped support for BotX API V1, V2 and V3.
* Moved synchronous `Bot` to `botx.sync` module. The current `Bot` is an alias to the `AsyncBot`.
* `Bot.status` again became a coroutine to add the ability to receive different commands for different users
depending on different conditions defined in the handlers (to be added to future releases, when BotX API support comes up).
* Added mechanism for catching exceptions.
* Add ability to use sync and async functions to send data from `Bot`.
* <b>Changed methods signatures</b>. See [api-reference](/api-reference/bots/) for details.
* Fixed `opts` shape.
* Added dependency injection system
Expand Down
2 changes: 1 addition & 1 deletion docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@

# Introduction

`pybotx` is a toolkit for building bots for Express providing a mechanism for simple integration with your favourite web frameworks.
`pybotx` is a framework for building bots for Express providing a mechanism for simple integration with your favourite web frameworks.

Main features:

Expand Down

0 comments on commit 3c91e92

Please sign in to comment.