Skip to content

Make job queue API similar to the dispatcher, add new functionality #307

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

Merged
merged 22 commits into from
Jun 29, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
6b90ac9
make job queue API similar to the dispatcher, add new functionality
jh0ker May 25, 2016
3aedd78
make job queue API similar to the dispatcher, add new functionality
jh0ker May 25, 2016
8278779
Merge branch 'jobqueue-rework' of github.com:python-telegram-bot/pyth…
jh0ker May 25, 2016
b3142d2
yapf
jh0ker May 25, 2016
7862163
Add context parameter in Job class #281
jh0ker May 26, 2016
41daccc
minor comments and formatting
jh0ker May 26, 2016
20067ff
add test for context parameter
jh0ker May 26, 2016
bb165b6
add pass_job_queue parameter to all handler classes
jh0ker May 26, 2016
e7f4a07
update timerbot example with pass_job_queue
jh0ker May 26, 2016
2534e0d
allow jobs to be ran outside of jobqueue
jh0ker May 28, 2016
406303d
refactor: running -> _running, next_peek -> _next_peek
jh0ker May 28, 2016
783f9c3
move job_queue kwarg to end
jh0ker May 28, 2016
d40f0a8
update update_queue and job_queue docstrings on all handlers
jh0ker May 28, 2016
de2d732
Merge branch 'master' into jobqueue-rework
jh0ker May 31, 2016
b08d41d
formatting
jh0ker May 31, 2016
738e321
Merge branch 'master' into jobqueue-rework
jh0ker Jun 19, 2016
c4a8ee5
Merge branch 'master' into jobqueue-rework
jh0ker Jun 20, 2016
02af1ea
jobqueue: cosmetic fixes
tsnoam Jun 21, 2016
f65b691
JobQueue: use class name for the logger name
tsnoam Jun 21, 2016
35872d7
test_jobqueue: fix test_jobs_tuple()
tsnoam Jun 21, 2016
1e0ebe8
JobQueue: minimize the amount of places changing self.__tick state
tsnoam Jun 21, 2016
3107310
yapf
jh0ker Jun 24, 2016
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
42 changes: 27 additions & 15 deletions examples/timerbot.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,15 @@
bot.
"""

from telegram.ext import Updater, CommandHandler
from telegram.ext import Updater, CommandHandler, Job
import logging

# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
level=logging.DEBUG)

logger = logging.getLogger(__name__)
job_queue = None
timers = dict()


# Define a few command handlers. These usually take the two arguments bot and
Expand All @@ -34,46 +34,58 @@ def start(bot, update):
bot.sendMessage(update.message.chat_id, text='Hi! Use /set <seconds> to ' 'set a timer')


def set(bot, update, args):
""" Adds a job to the queue """
def set(bot, update, args, job_queue):
"""Adds a job to the queue"""
chat_id = update.message.chat_id
try:
# args[0] should contain the time for the timer in seconds
due = int(args[0])
if due < 0:
bot.sendMessage(chat_id, text='Sorry we can not go back to future!')

def alarm(bot):
""" Inner function to send the alarm message """
def alarm(bot, job):
"""Inner function to send the alarm message"""
bot.sendMessage(chat_id, text='Beep!')

# Add job to queue
job_queue.put(alarm, due, repeat=False)
job = Job(alarm, due, repeat=False)
timers[chat_id] = job
job_queue.put(job)

bot.sendMessage(chat_id, text='Timer successfully set!')

except IndexError:
bot.sendMessage(chat_id, text='Usage: /set <seconds>')
except ValueError:
except (IndexError, ValueError):
bot.sendMessage(chat_id, text='Usage: /set <seconds>')


def unset(bot, update):
"""Removes the job if the user changed their mind"""
chat_id = update.message.chat_id

if chat_id not in timers:
bot.sendMessage(chat_id, text='You have no active timer')
return

job = timers[chat_id]
job.schedule_removal()
bot.sendMessage(chat_id, text='Timer successfully unset!')


def error(bot, update, error):
logger.warn('Update "%s" caused error "%s"' % (update, error))


def main():
global job_queue

updater = Updater("TOKEN")
job_queue = updater.job_queue

# Get the dispatcher to register handlers
dp = updater.dispatcher

# on different commands - answer in Telegram
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", start))
dp.add_handler(CommandHandler("set", set, pass_args=True))
dp.add_handler(CommandHandler("set", set, pass_args=True, pass_job_queue=True))
dp.add_handler(CommandHandler("unset", unset))

# log all errors
dp.add_error_handler(error)
Expand Down
4 changes: 2 additions & 2 deletions telegram/ext/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
"""Extensions over the Telegram Bot API to facilitate bot making"""

from .dispatcher import Dispatcher
from .jobqueue import JobQueue
from .jobqueue import JobQueue, Job
from .updater import Updater
from .callbackqueryhandler import CallbackQueryHandler
from .choseninlineresulthandler import ChosenInlineResultHandler
Expand All @@ -32,7 +32,7 @@
from .stringregexhandler import StringRegexHandler
from .typehandler import TypeHandler

__all__ = ('Dispatcher', 'JobQueue', 'Updater', 'CallbackQueryHandler',
__all__ = ('Dispatcher', 'JobQueue', 'Job', 'Updater', 'CallbackQueryHandler',
'ChosenInlineResultHandler', 'CommandHandler', 'Handler', 'InlineQueryHandler',
'MessageHandler', 'Filters', 'RegexHandler', 'StringCommandHandler',
'StringRegexHandler', 'TypeHandler')
17 changes: 12 additions & 5 deletions telegram/ext/callbackqueryhandler.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,20 @@ class CallbackQueryHandler(Handler):
callback (function): A function that takes ``bot, update`` as
positional arguments. It will be called when the ``check_update``
has determined that an update should be processed by this handler.
pass_update_queue (optional[bool]): If the handler should be passed the
update queue as a keyword argument called ``update_queue``. It can
be used to insert updates. Default is ``False``
pass_update_queue (optional[bool]): 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 ``Updater`` and ``Dispatcher`` that contains new updates which can
be used to insert updates. Default is ``False``.
pass_job_queue (optional[bool]): If set to ``True``, a keyword argument called
``job_queue`` will be passed to the callback function. It will be a ``JobQueue``
instance created by the ``Updater`` which can be used to schedule new jobs.
Default is ``False``.
"""
Copy link
Member

@tsnoam tsnoam May 26, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jh0ker
I find the whole docstring very confusing. Maybe this need rewrite as well?
example:
When set to true, the callback (what callback? the function just called? soemthing else?) will be passed to the job queue as a keyword argument called ``job_queue``. It can be used to schedule new jobs.

I think similar changes for other arguments are in order

Copy link
Member Author

@jh0ker jh0ker May 27, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

callback is the first argument to __init__, also you added a to there. It's actually the other way: job_queue is passed to the callback function.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jh0ker
just shows you how much I got confused 😉
another thought:
always pass job_queue and update_queue as keyword args
then no documentation is needed here

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll change the wording ;)
Always passing it means that all callback functions have to at least accept **kwargs, which they currently don't have to (and I'd like to keep it that way)


def __init__(self, callback, pass_update_queue=False):
super(CallbackQueryHandler, self).__init__(callback, pass_update_queue)
def __init__(self, callback, pass_update_queue=False, pass_job_queue=False):
super(CallbackQueryHandler, self).__init__(callback,
pass_update_queue=pass_update_queue,
pass_job_queue=pass_job_queue)

def check_update(self, update):
return isinstance(update, Update) and update.callback_query
Expand Down
17 changes: 12 additions & 5 deletions telegram/ext/choseninlineresulthandler.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,20 @@ class ChosenInlineResultHandler(Handler):
callback (function): A function that takes ``bot, update`` as
positional arguments. It will be called when the ``check_update``
has determined that an update should be processed by this handler.
pass_update_queue (optional[bool]): If the handler should be passed the
update queue as a keyword argument called ``update_queue``. It can
be used to insert updates. Default is ``False``
pass_update_queue (optional[bool]): 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 ``Updater`` and ``Dispatcher`` that contains new updates which can
be used to insert updates. Default is ``False``.
pass_job_queue (optional[bool]): If set to ``True``, a keyword argument called
``job_queue`` will be passed to the callback function. It will be a ``JobQueue``
instance created by the ``Updater`` which can be used to schedule new jobs.
Default is ``False``.
"""
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same comment as for callbackqueryhandler.py


def __init__(self, callback, pass_update_queue=False):
super(ChosenInlineResultHandler, self).__init__(callback, pass_update_queue)
def __init__(self, callback, pass_update_queue=False, pass_job_queue=False):
super(ChosenInlineResultHandler, self).__init__(callback,
pass_update_queue=pass_update_queue,
pass_job_queue=pass_job_queue)

def check_update(self, update):
return isinstance(update, Update) and update.chosen_inline_result
Expand Down
18 changes: 13 additions & 5 deletions telegram/ext/commandhandler.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,18 +40,26 @@ class CommandHandler(Handler):
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 spaces. Default is ``False``
pass_update_queue (optional[bool]): If the handler should be passed the
update queue as a keyword argument called ``update_queue``. It can
be used to insert updates. Default is ``False``
pass_update_queue (optional[bool]): 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 ``Updater`` and ``Dispatcher`` that contains new updates which can
be used to insert updates. Default is ``False``.
pass_job_queue (optional[bool]): If set to ``True``, a keyword argument called
``job_queue`` will be passed to the callback function. It will be a ``JobQueue``
instance created by the ``Updater`` which can be used to schedule new jobs.
Default is ``False``.
"""
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same comment as above


def __init__(self,
command,
callback,
allow_edited=False,
pass_args=False,
pass_update_queue=False):
super(CommandHandler, self).__init__(callback, pass_update_queue)
pass_update_queue=False,
pass_job_queue=False):
super(CommandHandler, self).__init__(callback,
pass_update_queue=pass_update_queue,
pass_job_queue=pass_job_queue)
self.command = command
self.allow_edited = allow_edited
self.pass_args = pass_args
Expand Down
7 changes: 6 additions & 1 deletion telegram/ext/dispatcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,11 +94,16 @@ class Dispatcher(object):
handlers
update_queue (Queue): The synchronized queue that will contain the
updates.
job_queue (Optional[telegram.ext.JobQueue]): The ``JobQueue`` instance to pass onto handler
callbacks
workers (Optional[int]): Number of maximum concurrent worker threads for the ``@run_async``
decorator
"""

def __init__(self, bot, update_queue, workers=4, exception_event=None):
def __init__(self, bot, update_queue, workers=4, exception_event=None, job_queue=None):
self.bot = bot
self.update_queue = update_queue
self.job_queue = job_queue

self.handlers = {}
""":type: dict[int, list[Handler]"""
Expand Down
16 changes: 12 additions & 4 deletions telegram/ext/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,20 @@ class Handler(object):
callback (function): A function that takes ``bot, update`` as
positional arguments. It will be called when the ``check_update``
has determined that an update should be processed by this handler.
pass_update_queue (optional[bool]): If the callback should be passed
the update queue as a keyword argument called ``update_queue``. It
can be used to insert updates. Default is ``False``
pass_update_queue (optional[bool]): 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 ``Updater`` and ``Dispatcher`` that contains new updates which can
be used to insert updates. Default is ``False``.
pass_job_queue (optional[bool]): If set to ``True``, a keyword argument called
``job_queue`` will be passed to the callback function. It will be a ``JobQueue``
instance created by the ``Updater`` which can be used to schedule new jobs.
Default is ``False``.
"""
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same comment as for callbackqueryhandler.py


def __init__(self, callback, pass_update_queue=False):
def __init__(self, callback, pass_update_queue=False, pass_job_queue=False):
self.callback = callback
self.pass_update_queue = pass_update_queue
self.pass_job_queue = pass_job_queue

def check_update(self, update):
"""
Expand Down Expand Up @@ -77,6 +83,8 @@ def collect_optional_args(self, dispatcher):
optional_args = dict()
if self.pass_update_queue:
optional_args['update_queue'] = dispatcher.update_queue
if self.pass_job_queue:
optional_args['job_queue'] = dispatcher.job_queue

return optional_args

Expand Down
17 changes: 12 additions & 5 deletions telegram/ext/inlinequeryhandler.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,20 @@ class InlineQueryHandler(Handler):
callback (function): A function that takes ``bot, update`` as
positional arguments. It will be called when the ``check_update``
has determined that an update should be processed by this handler.
pass_update_queue (optional[bool]): If the handler should be passed the
update queue as a keyword argument called ``update_queue``. It can
be used to insert updates. Default is ``False``
pass_update_queue (optional[bool]): 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 ``Updater`` and ``Dispatcher`` that contains new updates which can
be used to insert updates. Default is ``False``.
pass_job_queue (optional[bool]): If set to ``True``, a keyword argument called
``job_queue`` will be passed to the callback function. It will be a ``JobQueue``
instance created by the ``Updater`` which can be used to schedule new jobs.
Default is ``False``.
"""
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same comment as for callbackqueryhandler.py


def __init__(self, callback, pass_update_queue=False):
super(InlineQueryHandler, self).__init__(callback, pass_update_queue)
def __init__(self, callback, pass_update_queue=False, pass_job_queue=False):
super(InlineQueryHandler, self).__init__(callback,
pass_update_queue=pass_update_queue,
pass_job_queue=pass_job_queue)

def check_update(self, update):
return isinstance(update, Update) and update.inline_query
Expand Down
Loading
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy