Skip to content

add after processing #162

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions botogram/before_after.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# Copyright (c) 2015-2019 The Botogram Authors (see AUTHORS)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.


def process_before(bot, chains, update):
"""before process"""
for hook in chains["before_processors"]:
bot.logger.debug("Processing update #%s with the hook %s..." %
(update.update_id, hook.name))
result = hook.call(bot, update)
if result is True:
bot.logger.debug("Update #%s was just processed by the %s hook." %
(update.update_id, hook.name))
return True
return False


def process_after(bot, chains, update):
"""after process"""
for hook in chains["after_processors"]:
bot.logger.debug("Processing update #%s with the hook %s..." %
(update.update_id, hook.name))
result = hook.call(bot, update)
if result is True:
bot.logger.debug("Update #%s was just processed by the %s hook." %
(update.update_id, hook.name))
return True
return False
5 changes: 5 additions & 0 deletions botogram/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,11 @@ def before_processing(self, func):
self._main_component.add_before_processing_hook(func)
return func

def after_processing(self, func):
"""Register a after processing hook"""
self._main_component.add_after_processing_hook(func)
return func

def process_message(self, func):
"""Add a message processor hook"""
self._main_component.add_process_message_hook(func)
Expand Down
12 changes: 9 additions & 3 deletions botogram/callbacks.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@

from . import crypto
from .context import ctx
from .before_after import process_before, process_after


DIGEST = hashlib.md5
Expand Down Expand Up @@ -172,7 +173,7 @@ def process(bot, chains, update):
chat = update.callback_query.message.chat

raw = update.callback_query._data

result = False
try:
name, data = parse_callback_data(bot, chat, raw)
except crypto.TamperedMessageError:
Expand All @@ -181,7 +182,8 @@ def process(bot, chains, update):
% update.update_id
)
return

if process_before(bot, chains, update):
return
for hook in chains["callbacks"]:
bot.logger.debug("Processing update #%s with the hook %s" %
(update.update_id, hook.name))
Expand All @@ -190,7 +192,11 @@ def process(bot, chains, update):
if result is True:
bot.logger.debug("Update #%s was just processed by the %s hook" %
(update.update_id, hook.name))
return
break
if process_after(bot, chains, update):
return
if result:
return

bot.logger.debug("No hook actually processed the #%s update." %
update.update_id)
12 changes: 11 additions & 1 deletion botogram/components.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ def __new__(cls, *args, **kwargs):
self.__processors = []
self.__no_commands = []
self.__before_processors = []
self.__after_processors = []
self.__memory_preparers = []
self.__timers = []
self.__chat_unavailable_hooks = []
Expand Down Expand Up @@ -75,6 +76,14 @@ def add_before_processing_hook(self, func):
hook = hooks.BeforeProcessingHook(func, self)
self.__before_processors.append(hook)

def add_after_processing_hook(self, func):
"""Register a before processing hook"""
if not callable(func):
raise ValueError("A after processing hook must be callable")

hook = hooks.AfterProcessingHook(func, self)
self.__after_processors.append(hook)

def add_process_message_hook(self, func):
"""Add a message processor hook"""
if not callable(func):
Expand Down Expand Up @@ -255,13 +264,14 @@ def _add_no_commands_hook(self, func):
def _get_chains(self):
"""Get the full hooks chain for this component"""
messages = [
self.__before_processors[:],
[self.__commands[name]._hook
for name in sorted(self.__commands.keys())],
self.__no_commands[:],
self.__processors[:],
]
return {
"before_processors": [self.__before_processors[:]],
"after_processors": [self.__after_processors[:]],
"messages": messages,
"poll_updates": [self.__poll_update_hooks],
"memory_preparers": [self.__memory_preparers],
Expand Down
4 changes: 4 additions & 0 deletions botogram/frozenbot.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,10 @@ def before_processing(self, func):
"""Register a before processing hook"""
raise FrozenBotError("Can't add hooks to a bot at runtime")

def after_processing(self, func):
"""Register a after processing hook"""
raise FrozenBotError("Can't add hooks to a bot at runtime")

def process_message(self, func):
"""Register a message processor hook"""
raise FrozenBotError("Can't add hooks to a bot at runtime")
Expand Down
34 changes: 33 additions & 1 deletion botogram/hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,39 @@ def rebuild(cls, func, component, args):


class BeforeProcessingHook(Hook):
"""Underlying hook for @bot.process_message"""
"""before processing hook for all update"""

def _call(self, bot, update):
"""*Actually* call the hook"""
# add message and chat for backward compatibility
kwargs = {"update": update, "message": None, "chat": None,
"user": None}
if update.message is not None:
kwargs.update({"message": update.message,
"chat": update.message.chat,
"user": update.message.sender})
elif update.edited_message is not None:
kwargs.update({"message": update.edited_message,
"chat": update.edited_message.chat,
"user": update.edited_message.sender})
elif update.channel_post is not None:
kwargs.update({"message": update.channel_post,
"chat": update.channel_post.chat,
"user": update.channel_post.sender})
elif update.edited_channel_post is not None:
kwargs.update({"message": update.edited_channel_post,
"chat": update.edited_channel_post.chat,
"user": update.edited_channel_post.sender})
elif update.callback_query is not None:
kwargs.update({"message": update.callback_query.message,
"chat": update.callback_query.message.chat,
"user": update.callback_query.sender})

return bot._call(self.func, self.component_id, **kwargs)


class AfterProcessingHook(BeforeProcessingHook):
"""after processing hook for all update"""
pass


Expand Down
49 changes: 41 additions & 8 deletions botogram/messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,14 @@
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
from .before_after import process_before, process_after


def process_message(bot, chains, update):
"""Process a message sent to the bot"""
result = False
if process_before(bot, chains, update):
return
for hook in chains["messages"]:
bot.logger.debug("Processing update #%s with the hook %s..." %
(update.update_id, hook.name))
Expand All @@ -29,14 +33,20 @@ def process_message(bot, chains, update):
if result is True:
bot.logger.debug("Update #%s was just processed by the %s hook." %
(update.update_id, hook.name))
return

break
if process_after(bot, chains, update):
return
if result:
return
bot.logger.debug("No hook actually processed the #%s update." %
update.update_id)


def process_edited_message(bot, chains, update):
"""Process an edited message"""
result = False
if process_before(bot, chains, update):
return
for hook in chains["messages_edited"]:
bot.logger.debug("Processing edited message in update #%s with the "
"hook %s..." % (update.update_id, hook.name))
Expand All @@ -45,14 +55,20 @@ def process_edited_message(bot, chains, update):
if result is True:
bot.logger.debug("Update %s was just processed by the %s hook." %
(update.update_id, hook.name))
return

break
if process_after(bot, chains, update):
return
if result:
return
bot.logger.debug("No hook actually processed the #%s update." %
update.update_id)


def process_channel_post(bot, chains, update):
"""Process a channel post"""
result = False
if process_before(bot, chains, update):
return
for hook in chains["channel_post"]:
bot.logger.debug("Processing channel post in update #%s with the "
"hook %s..." % (update.update_id, hook.name))
Expand All @@ -61,14 +77,20 @@ def process_channel_post(bot, chains, update):
if result is True:
bot.logger.debug("Update %s was just processed by the %s hook." %
(update.update_id, hook.name))
return

break
if process_after(bot, chains, update):
return
if result:
return
bot.logger.debug("No hook actually processed the #%s update." %
update.update_id)


def process_channel_post_edited(bot, chains, update):
"""Process an edited channel post"""
result = False
if process_before(bot, chains, update):
return
for hook in chains["channel_post_edited"]:
bot.logger.debug("Processing edited channel post in update #%s with"
"the hook %s..." % (update.update_id, hook.name))
Expand All @@ -77,14 +99,21 @@ def process_channel_post_edited(bot, chains, update):
if result is True:
bot.logger.debug("Update %s was just processed by the %s hook." %
(update.update_id, hook.name))
return
break
if process_after(bot, chains, update):
return
if result:
return

bot.logger.debug("No hook actually processed the #%s update." %
update.update_id)


def process_poll_update(bot, chains, update):
"""Process a poll update"""
result = False
if process_before(bot, chains, update):
return
for hook in chains["poll_updates"]:
bot.logger.debug("Processing poll update in update #%s with"
"the hook %s..." % (update.update_id, hook.name))
Expand All @@ -93,7 +122,11 @@ def process_poll_update(bot, chains, update):
if result is True:
bot.logger.debug("Update %s was just processed by the %s hook." %
(update.update_id, hook.name))
return
break
if process_after(bot, chains, update):
return
if result:
return

bot.logger.debug("No hook actually processed the #%s update." %
update.update_id)
34 changes: 31 additions & 3 deletions docs/api/bot.rst
Original file line number Diff line number Diff line change
Expand Up @@ -98,17 +98,45 @@ components.

Functions decorated with this decorator will be called before an update
is processed. This allows you, for example, to set up a filter on who can
send messages to the bot. Decorated functions will be called with two
send messages to the bot. Decorated functions will be called with four
parameters:

* A ``update`` parameter with the representation
of the update (an istance of :py:class:`botogram.Update`)
* A ``chat`` parameter with the representation of the chat in which the
message was sent (an instance of :py:class:`botogram.Chat`)
message was sent (an instance of :py:class:`botogram.Chat`) if provided by update
* A ``message`` parameter with the representation of the received
message (an instance of :py:class:`botogram.Message`)
message (an instance of :py:class:`botogram.Message`) if provided by update
* A ``user`` parameter with the representation of the user send
update (an instance of :py:class:`botogram.User`) if provided by update

.. versionchanged:: 0.7

Added update and user parameter

If the function returns ``True``, then the message processing is stopped,
and no more functions will be called for this update.

.. py:decoratormethod:: after_processing

Functions decorated with this decorator will be called after an update
is processed. This allows you, for example, to send log.
Decorated functions will be called with four parameters:

* A ``update`` parameter with the representation
of the update (an istance of :py:class:`botogram.Update`)
* A ``chat`` parameter with the representation of the chat in which the
message was sent (an instance of :py:class:`botogram.Chat`) if provided by update
* A ``message`` parameter with the representation of the received
message (an instance of :py:class:`botogram.Message`) if provided by update
* A ``user`` parameter with the representation of the user send
update (an instance of :py:class:`botogram.User`) if provided by update

If the function returns ``True``, then the message processing is stopped,
and no more functions will be called for this update.

.. versionadded:: 0.7

.. py:decoratormethod:: process_message

Functions decorated with this decorator will be called while processing
Expand Down
Loading