Skip to content

Roles #1789

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

Closed
wants to merge 22 commits into from
Closed

Roles #1789

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
6 changes: 6 additions & 0 deletions docs/source/telegram.ext.chatadminsrole.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
telegram.ext.ChatAdminsRole
===========================

.. autoclass:: telegram.ext.ChatAdminsRole
:members:
:show-inheritance:
6 changes: 6 additions & 0 deletions docs/source/telegram.ext.chatcreatorrole.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
telegram.ext.ChatCreatorRole
============================

.. autoclass:: telegram.ext.ChatCreatorRole
:members:
:show-inheritance:
6 changes: 6 additions & 0 deletions docs/source/telegram.ext.role.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
telegram.ext.Role
=================

.. autoclass:: telegram.ext.Role
:members:
:show-inheritance:
6 changes: 6 additions & 0 deletions docs/source/telegram.ext.roles.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
telegram.ext.Roles
==================

.. autoclass:: telegram.ext.Roles
:members:
:show-inheritance:
14 changes: 13 additions & 1 deletion docs/source/telegram.ext.rst
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ telegram.ext package
telegram.ext.delayqueue
telegram.ext.callbackcontext
telegram.ext.defaults
telegram.ext.role
telegram.ext.roles

Handlers
--------
Expand Down Expand Up @@ -43,4 +45,14 @@ Persistence

telegram.ext.basepersistence
telegram.ext.picklepersistence
telegram.ext.dictpersistence
telegram.ext.dictpersistence

Authentication
--------------

.. toctree::

telegram.ext.role
telegram.ext.roles
telegram.ext.chatadminsrole
telegram.ext.chatcreatorrole
3 changes: 2 additions & 1 deletion telegram/ext/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
from .pollanswerhandler import PollAnswerHandler
from .pollhandler import PollHandler
from .defaults import Defaults
from .roles import Role, Roles, ChatAdminsRole, ChatCreatorRole

__all__ = ('Dispatcher', 'JobQueue', 'Job', 'Updater', 'CallbackQueryHandler',
'ChosenInlineResultHandler', 'CommandHandler', 'Handler', 'InlineQueryHandler',
Expand All @@ -52,4 +53,4 @@
'PreCheckoutQueryHandler', 'ShippingQueryHandler', 'MessageQueue', 'DelayQueue',
'DispatcherHandlerStop', 'run_async', 'CallbackContext', 'BasePersistence',
'PicklePersistence', 'DictPersistence', 'PrefixHandler', 'PollAnswerHandler',
'PollHandler', 'Defaults')
'PollHandler', 'Defaults', 'Role', 'Roles', 'ChatAdminsRole', 'ChatCreatorRole')
32 changes: 31 additions & 1 deletion telegram/ext/basepersistence.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ class BasePersistence(object):
:meth:`update_chat_data`.
* If :attr:`store_user_data` is ``True`` you must overwrite :meth:`get_user_data` and
:meth:`update_user_data`.
* If :attr:`store_roles` is ``True`` you must overwrite :meth:`get_roles` and
:meth:`update_roles`.
* If you want to store conversation data with :class:`telegram.ext.ConversationHandler`, you
must overwrite :meth:`get_conversations` and :meth:`update_conversation`.
* :meth:`flush` will be called when the bot is shutdown.
Expand All @@ -42,6 +44,8 @@ class BasePersistence(object):
persistence class.
store_bot_data (:obj:`bool`): Optional. Whether bot_data should be saved by this
persistence class.
store_roles (:obj:`bool`): Optional. Whether roles should be saved by this persistence
class.

Args:
store_user_data (:obj:`bool`, optional): Whether user_data should be saved by this
Expand All @@ -50,12 +54,16 @@ class BasePersistence(object):
persistence class. Default is ``True`` .
store_bot_data (:obj:`bool`, optional): Whether bot_data should be saved by this
persistence class. Default is ``True`` .
store_roles (:obj:`bool`, optional): Whether roles should be saved by this persistence
class. Default is ``True``.
"""

def __init__(self, store_user_data=True, store_chat_data=True, store_bot_data=True):
def __init__(self, store_user_data=True, store_chat_data=True, store_bot_data=True,
store_roles=True):
self.store_user_data = store_user_data
self.store_chat_data = store_chat_data
self.store_bot_data = store_bot_data
self.store_roles = store_roles

def get_user_data(self):
""""Will be called by :class:`telegram.ext.Dispatcher` upon creation with a
Expand Down Expand Up @@ -87,6 +95,19 @@ def get_bot_data(self):
"""
raise NotImplementedError

def get_roles(self):
""""Will be called by :class:`telegram.ext.Dispatcher` upon creation with a
persistence object.

Warning:
The produced roles instance usually will have no bot assigned. Use
:attr:`telegram.ext.Roles.set_bot` to set it.

Returns:
:class:`telegram.ext.Roles`: The restored roles.
"""
raise NotImplementedError

def get_conversations(self, name):
""""Will be called by :class:`telegram.ext.Dispatcher` when a
:class:`telegram.ext.ConversationHandler` is added if
Expand Down Expand Up @@ -141,6 +162,15 @@ def update_bot_data(self, data):
"""
raise NotImplementedError

def update_roles(self, data):
"""Will be called by the :class:`telegram.ext.Dispatcher` after a handler has
handled an update.

Args:
data (:class:`telegram.ext.Roles`): The :attr:`telegram.ext.dispatcher.roles` .
"""
raise NotImplementedError

def flush(self):
"""Will be called by :class:`telegram.ext.Updater` upon receiving a stop signal. Gives the
persistence a chance to finish up saving or close a database connection gracefully. If this
Expand Down
9 changes: 9 additions & 0 deletions telegram/ext/callbackcontext.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ def __init__(self, dispatcher):
raise ValueError('CallbackContext should not be used with a non context aware '
'dispatcher!')
self._dispatcher = dispatcher
self._roles = dispatcher.roles
self._bot_data = dispatcher.bot_data
self._chat_data = None
self._user_data = None
Expand All @@ -95,6 +96,14 @@ def dispatcher(self):
""":class:`telegram.ext.Dispatcher`: The dispatcher associated with this context."""
return self._dispatcher

@property
def roles(self):
return self._roles

@roles.setter
def roles(self, value):
raise AttributeError("You can not assign a new value to roles.")

@property
def bot_data(self):
return self._bot_data
Expand Down
11 changes: 9 additions & 2 deletions telegram/ext/callbackqueryhandler.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ class CallbackQueryHandler(Handler):

Attributes:
callback (:obj:`callable`): The callback function for this handler.
roles (:obj:`telegram.ext.Role`): Optional. A user role used to restrict access to the
handler.
pass_update_queue (:obj:`bool`): Determines whether ``update_queue`` will be
passed to the callback function.
pass_job_queue (:obj:`bool`): Determines whether ``job_queue`` will be passed to
Expand Down Expand Up @@ -66,6 +68,9 @@ class CallbackQueryHandler(Handler):

The return value of the callback is usually ignored except for the special case of
:class:`telegram.ext.ConversationHandler`.
roles (:obj:`telegram.ext.Role`, optional): A user role used to restrict access to the
handler. Roles can be combined using bitwise operators (& for and, | for or, ~ for
not).
pass_update_queue (:obj:`bool`, optional): If set to ``True``, a keyword argument called
``update_queue`` will be passed to the callback function. It will be the ``Queue``
instance used by the :class:`telegram.ext.Updater` and :class:`telegram.ext.Dispatcher`
Expand Down Expand Up @@ -104,13 +109,15 @@ def __init__(self,
pass_groups=False,
pass_groupdict=False,
pass_user_data=False,
pass_chat_data=False):
pass_chat_data=False,
roles=None):
super(CallbackQueryHandler, self).__init__(
callback,
pass_update_queue=pass_update_queue,
pass_job_queue=pass_job_queue,
pass_user_data=pass_user_data,
pass_chat_data=pass_chat_data)
pass_chat_data=pass_chat_data,
roles=roles)

if isinstance(pattern, string_types):
pattern = re.compile(pattern)
Expand Down
5 changes: 5 additions & 0 deletions telegram/ext/choseninlineresulthandler.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ class ChosenInlineResultHandler(Handler):

Attributes:
callback (:obj:`callable`): The callback function for this handler.
roles (:obj:`telegram.ext.Role`): Optional. A user role used to restrict access to the
handler.
pass_update_queue (:obj:`bool`): Determines whether ``update_queue`` will be
passed to the callback function.
pass_job_queue (:obj:`bool`): Determines whether ``job_queue`` will be passed to
Expand Down Expand Up @@ -54,6 +56,9 @@ class ChosenInlineResultHandler(Handler):

The return value of the callback is usually ignored except for the special case of
:class:`telegram.ext.ConversationHandler`.
roles (:obj:`telegram.ext.Role`, optional): A user role used to restrict access to the
handler. Roles can be combined using bitwise operators (& for and, | for or, ~ for
not).
pass_update_queue (:obj:`bool`, optional): If set to ``True``, a keyword argument called
``update_queue`` will be passed to the callback function. It will be the ``Queue``
instance used by the :class:`telegram.ext.Updater` and :class:`telegram.ext.Dispatcher`
Expand Down
22 changes: 18 additions & 4 deletions telegram/ext/commandhandler.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ class CommandHandler(Handler):
callback (:obj:`callable`): The callback function for this handler.
filters (:class:`telegram.ext.BaseFilter`): Optional. Only allow updates with these
Filters.
roles (:obj:`telegram.ext.Role`): Optional. A user role used to restrict access to the
handler.
allow_edited (:obj:`bool`): Determines Whether the handler should also accept
edited messages.
pass_args (:obj:`bool`): Determines whether the handler should be passed
Expand Down Expand Up @@ -85,6 +87,9 @@ class CommandHandler(Handler):
:class:`telegram.ext.filters.BaseFilter`. Standard filters can be found in
:class:`telegram.ext.filters.Filters`. Filters can be combined using bitwise
operators (& for and, | for or, ~ for not).
roles (:obj:`telegram.ext.Role`, optional): A user role used to restrict access to the
handler. Roles can be combined using bitwise operators (& for and, | for or, ~ for
not).
allow_edited (:obj:`bool`, optional): Determines whether the handler should also accept
edited messages. Default is ``False``.
DEPRECATED: Edited is allowed by default. To change this behavior use
Expand Down Expand Up @@ -124,13 +129,15 @@ def __init__(self,
pass_update_queue=False,
pass_job_queue=False,
pass_user_data=False,
pass_chat_data=False):
pass_chat_data=False,
roles=None):
super(CommandHandler, self).__init__(
callback,
pass_update_queue=pass_update_queue,
pass_job_queue=pass_job_queue,
pass_user_data=pass_user_data,
pass_chat_data=pass_chat_data)
pass_chat_data=pass_chat_data,
roles=roles)

if isinstance(command, string_types):
self.command = [command.lower()]
Expand Down Expand Up @@ -231,6 +238,8 @@ class PrefixHandler(CommandHandler):
callback (:obj:`callable`): The callback function for this handler.
filters (:class:`telegram.ext.BaseFilter`): Optional. Only allow updates with these
Filters.
roles (:obj:`telegram.ext.Role`): Optional. A user role used to restrict access to the
handler.
pass_args (:obj:`bool`): Determines whether the handler should be passed
``args``.
pass_update_queue (:obj:`bool`): Determines whether ``update_queue`` will be
Expand Down Expand Up @@ -267,6 +276,9 @@ class PrefixHandler(CommandHandler):
:class:`telegram.ext.filters.BaseFilter`. Standard filters can be found in
:class:`telegram.ext.filters.Filters`. Filters can be combined using bitwise
operators (& for and, | for or, ~ for not).
roles (:obj:`telegram.ext.Role`, optional): A user role used to restrict access to the
handler. Roles can be combined using bitwise operators (& for and, | for or, ~ for
not).
pass_args (:obj:`bool`, optional): Determines whether the handler should be passed the
arguments passed to the command as a keyword argument called ``args``. It will contain
a list of strings, which is the text following the command split on single or
Expand Down Expand Up @@ -300,7 +312,8 @@ def __init__(self,
pass_update_queue=False,
pass_job_queue=False,
pass_user_data=False,
pass_chat_data=False):
pass_chat_data=False,
roles=None):

self._prefix = list()
self._command = list()
Expand All @@ -311,7 +324,8 @@ def __init__(self,
pass_update_queue=pass_update_queue,
pass_job_queue=pass_job_queue,
pass_user_data=pass_user_data,
pass_chat_data=pass_chat_data)
pass_chat_data=pass_chat_data,
roles=roles)

self.prefix = prefix
self.command = command
Expand Down
9 changes: 8 additions & 1 deletion telegram/ext/conversationhandler.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,8 @@ class ConversationHandler(Handler):
map_to_parent (Dict[:obj:`object`, :obj:`object`]): Optional. A :obj:`dict` that can be
used to instruct a nested conversationhandler to transition into a mapped state on
its parent conversationhandler in place of a specified nested state.
roles (:obj:`telegram.ext.Role`): Optional. A user role used to restrict access to the
handler.

Args:
entry_points (List[:class:`telegram.ext.Handler`]): A list of ``Handler`` objects that can
Expand Down Expand Up @@ -142,6 +144,9 @@ class ConversationHandler(Handler):
map_to_parent (Dict[:obj:`object`, :obj:`object`], optional): A :obj:`dict` that can be
used to instruct a nested conversationhandler to transition into a mapped state on
its parent conversationhandler in place of a specified nested state.
roles (:obj:`telegram.ext.Role`, optional): A user role used to restrict access to the
handler. Roles can be combined using bitwise operators (& for and, | for or, ~ for
not).

Raises:
ValueError
Expand All @@ -166,7 +171,8 @@ def __init__(self,
conversation_timeout=None,
name=None,
persistent=False,
map_to_parent=None):
map_to_parent=None,
roles=None):

self._entry_points = entry_points
self._states = states
Expand All @@ -185,6 +191,7 @@ def __init__(self,
""":obj:`telegram.ext.BasePersistance`: The persistence used to store conversations.
Set by dispatcher"""
self._map_to_parent = map_to_parent
self.roles = roles

self.timeout_jobs = dict()
self._timeout_jobs_lock = Lock()
Expand Down
Loading