2015-12-31 14:55:15 +01:00
|
|
|
#!/usr/bin/env python
|
|
|
|
#
|
|
|
|
# A library that provides a Python interface to the Telegram Bot API
|
2024-02-19 20:06:25 +01:00
|
|
|
# Copyright (C) 2015-2024
|
2016-01-05 14:12:03 +01:00
|
|
|
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
2015-12-31 14:55:15 +01:00
|
|
|
#
|
|
|
|
# This program is free software: you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU Lesser Public License as published by
|
|
|
|
# the Free Software Foundation, either version 3 of the License, or
|
|
|
|
# (at your option) any later version.
|
|
|
|
#
|
|
|
|
# This program is distributed in the hope that it will be useful,
|
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
# GNU Lesser Public License for more details.
|
|
|
|
#
|
|
|
|
# You should have received a copy of the GNU Lesser Public License
|
|
|
|
# along with this program. If not, see [http://www.gnu.org/licenses/].
|
2016-05-26 14:01:59 +02:00
|
|
|
"""This module contains the classes JobQueue and Job."""
|
2022-04-24 12:38:09 +02:00
|
|
|
import asyncio
|
2018-09-21 08:57:01 +02:00
|
|
|
import datetime
|
2021-10-09 13:56:50 +02:00
|
|
|
import weakref
|
2024-10-24 20:48:49 +02:00
|
|
|
from typing import TYPE_CHECKING, Any, Generic, Optional, Union, cast, overload
|
2020-07-10 13:11:28 +02:00
|
|
|
|
2022-10-31 10:12:18 +01:00
|
|
|
try:
|
|
|
|
import pytz
|
|
|
|
from apscheduler.executors.asyncio import AsyncIOExecutor
|
|
|
|
from apscheduler.schedulers.asyncio import AsyncIOScheduler
|
|
|
|
|
|
|
|
APS_AVAILABLE = True
|
|
|
|
except ImportError:
|
|
|
|
APS_AVAILABLE = False
|
2018-09-21 08:57:01 +02:00
|
|
|
|
2024-05-20 15:25:56 +02:00
|
|
|
from telegram._utils.logging import get_logger
|
2023-09-15 21:35:45 +02:00
|
|
|
from telegram._utils.repr import build_repr_with_selected_attrs
|
2021-10-10 15:10:21 +02:00
|
|
|
from telegram._utils.types import JSONDict
|
|
|
|
from telegram.ext._extbot import ExtBot
|
2023-02-02 18:55:07 +01:00
|
|
|
from telegram.ext._utils.types import CCT, JobCallback
|
2020-10-09 17:22:07 +02:00
|
|
|
|
2020-10-06 19:28:40 +02:00
|
|
|
if TYPE_CHECKING:
|
2023-06-29 11:38:09 +02:00
|
|
|
if APS_AVAILABLE:
|
|
|
|
from apscheduler.job import Job as APSJob
|
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
from telegram.ext import Application
|
2020-10-06 19:28:40 +02:00
|
|
|
|
2015-12-31 14:55:15 +01:00
|
|
|
|
2023-03-25 19:18:04 +01:00
|
|
|
_ALL_DAYS = tuple(range(7))
|
2024-05-20 15:25:56 +02:00
|
|
|
_LOGGER = get_logger(__name__, class_name="JobQueue")
|
2023-03-25 19:18:04 +01:00
|
|
|
|
|
|
|
|
2023-02-02 18:55:07 +01:00
|
|
|
class JobQueue(Generic[CCT]):
|
2020-07-10 13:11:28 +02:00
|
|
|
"""This class allows you to periodically perform tasks with the bot. It is a convenience
|
|
|
|
wrapper for the APScheduler library.
|
2015-12-31 14:55:15 +01:00
|
|
|
|
2023-02-02 18:55:07 +01:00
|
|
|
This class is a :class:`~typing.Generic` class and accepts one type variable that specifies
|
|
|
|
the type of the argument ``context`` of the job callbacks (:paramref:`~run_once.callback`) of
|
|
|
|
:meth:`run_once` and the other scheduling methods.
|
|
|
|
|
2022-10-31 10:12:18 +01:00
|
|
|
Important:
|
|
|
|
If you want to use this class, you must install PTB with the optional requirement
|
|
|
|
``job-queue``, i.e.
|
|
|
|
|
|
|
|
.. code-block:: bash
|
|
|
|
|
2023-06-29 07:46:00 +02:00
|
|
|
pip install "python-telegram-bot[job-queue]"
|
2022-10-31 10:12:18 +01:00
|
|
|
|
Documentation Improvements (#3214, #3217, #3218, #3271, #3289, #3292, #3303, #3312, #3306, #3319, #3326, #3314)
Co-authored-by: Harshil <37377066+harshil21@users.noreply.github.com>
Co-authored-by: Simon Fong <44134941+simonfongnt@users.noreply.github.com>
Co-authored-by: Piotr Rogulski <rivinek@gmail.com>
Co-authored-by: poolitzer <25934244+Poolitzer@users.noreply.github.com>
Co-authored-by: Or Bin <or@raftt.io>
Co-authored-by: Sandro <j32g7f67hb@liamekaens.com>
Co-authored-by: Hatim Zahid <63000127+HatimZ@users.noreply.github.com>
Co-authored-by: Robi <53259730+RobiMez@users.noreply.github.com>
Co-authored-by: Dmitry Kolomatskiy <58207913+lemontree210@users.noreply.github.com>
2022-11-15 09:06:23 +01:00
|
|
|
Examples:
|
|
|
|
:any:`Timer Bot <examples.timerbot>`
|
|
|
|
|
2023-02-05 18:09:55 +01:00
|
|
|
.. seealso:: :wiki:`Architecture Overview <Architecture>`,
|
2023-07-09 11:22:08 +02:00
|
|
|
:wiki:`Job Queue <Extensions---JobQueue>`
|
2022-10-31 10:12:18 +01:00
|
|
|
|
|
|
|
.. versionchanged:: 20.0
|
|
|
|
To use this class, PTB must be installed via
|
2023-06-29 07:46:00 +02:00
|
|
|
``pip install "python-telegram-bot[job-queue]"``.
|
2022-10-31 10:12:18 +01:00
|
|
|
|
2015-12-31 14:55:15 +01:00
|
|
|
Attributes:
|
2022-04-24 12:38:09 +02:00
|
|
|
scheduler (:class:`apscheduler.schedulers.asyncio.AsyncIOScheduler`): The scheduler.
|
|
|
|
|
2023-10-16 20:25:25 +02:00
|
|
|
Warning:
|
|
|
|
This scheduler is configured by :meth:`set_application`. Additional configuration
|
|
|
|
settings can be made by users. However, calling
|
|
|
|
:meth:`~apscheduler.schedulers.base.BaseScheduler.configure` will delete any
|
|
|
|
previous configuration settings. Therefore, please make sure to pass the values
|
|
|
|
returned by :attr:`scheduler_configuration` to the method call in addition to your
|
|
|
|
custom values.
|
|
|
|
Alternatively, you can also use methods like
|
|
|
|
:meth:`~apscheduler.schedulers.base.BaseScheduler.add_jobstore` to avoid using
|
|
|
|
:meth:`~apscheduler.schedulers.base.BaseScheduler.configure` altogether.
|
|
|
|
|
2022-05-06 17:15:23 +02:00
|
|
|
.. versionchanged:: 20.0
|
2022-06-09 17:08:54 +02:00
|
|
|
Uses :class:`~apscheduler.schedulers.asyncio.AsyncIOScheduler` instead of
|
2022-04-24 12:38:09 +02:00
|
|
|
:class:`~apscheduler.schedulers.background.BackgroundScheduler`
|
|
|
|
|
2015-12-31 14:55:15 +01:00
|
|
|
"""
|
|
|
|
|
2024-02-05 19:24:00 +01:00
|
|
|
__slots__ = ("_application", "_executor", "scheduler")
|
2022-05-25 10:02:00 +02:00
|
|
|
_CRON_MAPPING = ("sun", "mon", "tue", "wed", "thu", "fri", "sat")
|
2021-05-29 16:18:16 +02:00
|
|
|
|
2020-10-06 19:28:40 +02:00
|
|
|
def __init__(self) -> None:
|
2022-10-31 10:12:18 +01:00
|
|
|
if not APS_AVAILABLE:
|
|
|
|
raise RuntimeError(
|
|
|
|
"To use `JobQueue`, PTB must be installed via `pip install "
|
2023-06-29 07:46:00 +02:00
|
|
|
'"python-telegram-bot[job-queue]"`.'
|
2022-10-31 10:12:18 +01:00
|
|
|
)
|
|
|
|
|
2023-08-02 11:51:17 +02:00
|
|
|
self._application: Optional[weakref.ReferenceType[Application]] = None
|
2022-04-24 12:38:09 +02:00
|
|
|
self._executor = AsyncIOExecutor()
|
2024-06-30 18:22:12 +02:00
|
|
|
self.scheduler: "AsyncIOScheduler" = AsyncIOScheduler( # noqa: UP037
|
|
|
|
**self.scheduler_configuration
|
|
|
|
)
|
2020-07-10 13:11:28 +02:00
|
|
|
|
2023-09-15 21:35:45 +02:00
|
|
|
def __repr__(self) -> str:
|
|
|
|
"""Give a string representation of the JobQueue in the form ``JobQueue[application=...]``.
|
|
|
|
|
|
|
|
As this class doesn't implement :meth:`object.__str__`, the default implementation
|
|
|
|
will be used, which is equivalent to :meth:`__repr__`.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
:obj:`str`
|
|
|
|
"""
|
|
|
|
return build_repr_with_selected_attrs(self, application=self.application)
|
|
|
|
|
2023-09-15 22:19:45 +02:00
|
|
|
@property
|
|
|
|
def application(self) -> "Application[Any, CCT, Any, Any, Any, JobQueue[CCT]]":
|
|
|
|
"""The application this JobQueue is associated with."""
|
|
|
|
if self._application is None:
|
|
|
|
raise RuntimeError("No application was set for this JobQueue.")
|
|
|
|
application = self._application()
|
|
|
|
if application is not None:
|
|
|
|
return application
|
|
|
|
raise RuntimeError("The application instance is no longer alive.")
|
|
|
|
|
2023-10-16 20:25:25 +02:00
|
|
|
@property
|
|
|
|
def scheduler_configuration(self) -> JSONDict:
|
|
|
|
"""Provides configuration values that are used by :class:`JobQueue` for :attr:`scheduler`.
|
|
|
|
|
|
|
|
Tip:
|
|
|
|
Since calling
|
|
|
|
:meth:`scheduler.configure() <apscheduler.schedulers.base.BaseScheduler.configure>`
|
|
|
|
deletes any previous setting, please make sure to pass these values to the method call
|
|
|
|
in addition to your custom values:
|
|
|
|
|
|
|
|
.. code-block:: python
|
|
|
|
|
|
|
|
scheduler.configure(..., **job_queue.scheduler_configuration)
|
|
|
|
|
|
|
|
Alternatively, you can also use methods like
|
|
|
|
:meth:`~apscheduler.schedulers.base.BaseScheduler.add_jobstore` to avoid using
|
|
|
|
:meth:`~apscheduler.schedulers.base.BaseScheduler.configure` altogether.
|
|
|
|
|
2023-11-27 19:01:57 +01:00
|
|
|
.. versionadded:: 20.7
|
2023-10-16 20:25:25 +02:00
|
|
|
|
|
|
|
Returns:
|
2024-10-24 20:48:49 +02:00
|
|
|
dict[:obj:`str`, :obj:`object`]: The configuration values as dictionary.
|
2023-10-16 20:25:25 +02:00
|
|
|
|
|
|
|
"""
|
|
|
|
timezone: object = pytz.utc
|
|
|
|
if (
|
|
|
|
self._application
|
|
|
|
and isinstance(self.application.bot, ExtBot)
|
|
|
|
and self.application.bot.defaults
|
|
|
|
):
|
|
|
|
timezone = self.application.bot.defaults.tzinfo or pytz.utc
|
|
|
|
|
|
|
|
return {
|
|
|
|
"timezone": timezone,
|
|
|
|
"executors": {"default": self._executor},
|
|
|
|
}
|
|
|
|
|
2020-10-06 19:28:40 +02:00
|
|
|
def _tz_now(self) -> datetime.datetime:
|
2020-07-10 13:11:28 +02:00
|
|
|
return datetime.datetime.now(self.scheduler.timezone)
|
|
|
|
|
2020-10-06 19:28:40 +02:00
|
|
|
@overload
|
2024-02-05 19:24:00 +01:00
|
|
|
def _parse_time_input(self, time: None, shift_day: bool = False) -> None: ...
|
2020-10-06 19:28:40 +02:00
|
|
|
|
|
|
|
@overload
|
|
|
|
def _parse_time_input(
|
|
|
|
self,
|
2023-09-09 23:12:30 +02:00
|
|
|
time: Union[float, datetime.timedelta, datetime.datetime, datetime.time],
|
2020-10-06 19:28:40 +02:00
|
|
|
shift_day: bool = False,
|
2024-02-05 19:24:00 +01:00
|
|
|
) -> datetime.datetime: ...
|
2020-10-06 19:28:40 +02:00
|
|
|
|
|
|
|
def _parse_time_input(
|
|
|
|
self,
|
2023-09-09 23:12:30 +02:00
|
|
|
time: Union[float, datetime.timedelta, datetime.datetime, datetime.time, None],
|
2020-10-06 19:28:40 +02:00
|
|
|
shift_day: bool = False,
|
|
|
|
) -> Optional[datetime.datetime]:
|
2020-07-10 13:11:28 +02:00
|
|
|
if time is None:
|
|
|
|
return None
|
|
|
|
if isinstance(time, (int, float)):
|
|
|
|
return self._tz_now() + datetime.timedelta(seconds=time)
|
|
|
|
if isinstance(time, datetime.timedelta):
|
|
|
|
return self._tz_now() + time
|
|
|
|
if isinstance(time, datetime.time):
|
2020-10-31 16:33:34 +01:00
|
|
|
date_time = datetime.datetime.combine(
|
2020-09-27 12:59:48 +02:00
|
|
|
datetime.datetime.now(tz=time.tzinfo or self.scheduler.timezone).date(), time
|
|
|
|
)
|
2020-10-31 16:33:34 +01:00
|
|
|
if date_time.tzinfo is None:
|
|
|
|
date_time = self.scheduler.timezone.localize(date_time)
|
|
|
|
if shift_day and date_time <= datetime.datetime.now(pytz.utc):
|
|
|
|
date_time += datetime.timedelta(days=1)
|
|
|
|
return date_time
|
2020-07-10 13:11:28 +02:00
|
|
|
return time
|
2015-12-31 14:55:15 +01:00
|
|
|
|
2023-02-02 18:55:07 +01:00
|
|
|
def set_application(
|
|
|
|
self, application: "Application[Any, CCT, Any, Any, Any, JobQueue[CCT]]"
|
|
|
|
) -> None:
|
2022-04-24 12:38:09 +02:00
|
|
|
"""Set the application to be used by this JobQueue.
|
2019-10-27 00:04:48 +02:00
|
|
|
|
|
|
|
Args:
|
2022-04-24 12:38:09 +02:00
|
|
|
application (:class:`telegram.ext.Application`): The application.
|
2019-10-27 00:04:48 +02:00
|
|
|
|
|
|
|
"""
|
2022-04-24 12:38:09 +02:00
|
|
|
self._application = weakref.ref(application)
|
2023-10-16 20:25:25 +02:00
|
|
|
self.scheduler.configure(**self.scheduler_configuration)
|
2018-09-21 08:57:01 +02:00
|
|
|
|
2023-06-02 22:17:46 +02:00
|
|
|
@staticmethod
|
|
|
|
async def job_callback(job_queue: "JobQueue[CCT]", job: "Job[CCT]") -> None:
|
|
|
|
"""This method is used as a callback for the APScheduler jobs.
|
|
|
|
|
|
|
|
More precisely, the ``func`` argument of :class:`apscheduler.job.Job` is set to this method
|
|
|
|
and the ``arg`` argument (representing positional arguments to ``func``) is set to a tuple
|
|
|
|
containing the :class:`JobQueue` itself and the :class:`~telegram.ext.Job` instance.
|
|
|
|
|
|
|
|
Tip:
|
|
|
|
This method is a static method rather than a bound method. This makes the arguments
|
|
|
|
more transparent and allows for easier handling of PTBs integration of APScheduler
|
|
|
|
when utilizing advanced features of APScheduler.
|
|
|
|
|
|
|
|
Hint:
|
|
|
|
This method is effectively a wrapper for :meth:`telegram.ext.Job.run`.
|
|
|
|
|
2023-07-09 12:18:32 +02:00
|
|
|
.. versionadded:: 20.4
|
2023-06-02 22:17:46 +02:00
|
|
|
|
|
|
|
Args:
|
|
|
|
job_queue (:class:`JobQueue`): The job queue that created the job.
|
|
|
|
job (:class:`~telegram.ext.Job`): The job to run.
|
|
|
|
"""
|
|
|
|
await job.run(job_queue.application)
|
|
|
|
|
2020-10-06 19:28:40 +02:00
|
|
|
def run_once(
|
|
|
|
self,
|
2023-02-02 18:55:07 +01:00
|
|
|
callback: JobCallback[CCT],
|
2020-10-06 19:28:40 +02:00
|
|
|
when: Union[float, datetime.timedelta, datetime.datetime, datetime.time],
|
2023-05-18 07:57:59 +02:00
|
|
|
data: Optional[object] = None,
|
|
|
|
name: Optional[str] = None,
|
|
|
|
chat_id: Optional[int] = None,
|
|
|
|
user_id: Optional[int] = None,
|
|
|
|
job_kwargs: Optional[JSONDict] = None,
|
2023-02-02 18:55:07 +01:00
|
|
|
) -> "Job[CCT]":
|
2021-12-13 18:21:38 +01:00
|
|
|
"""Creates a new :class:`Job` instance that runs once and adds it to the queue.
|
2016-12-14 16:27:45 +01:00
|
|
|
|
|
|
|
Args:
|
2022-04-24 12:38:09 +02:00
|
|
|
callback (:term:`coroutine function`): The callback function that should be executed by
|
|
|
|
the new job. Callback signature::
|
|
|
|
|
|
|
|
async def callback(context: CallbackContext)
|
|
|
|
|
2018-02-19 09:36:40 +01:00
|
|
|
when (:obj:`int` | :obj:`float` | :obj:`datetime.timedelta` | \
|
|
|
|
:obj:`datetime.datetime` | :obj:`datetime.time`):
|
2016-12-14 16:27:45 +01:00
|
|
|
Time in or at which the job should run. This parameter will be interpreted
|
|
|
|
depending on its type.
|
2016-12-14 23:08:03 +01:00
|
|
|
|
2017-07-23 22:33:08 +02:00
|
|
|
* :obj:`int` or :obj:`float` will be interpreted as "seconds from now" in which the
|
|
|
|
job should run.
|
|
|
|
* :obj:`datetime.timedelta` will be interpreted as "time from now" in which the
|
|
|
|
job should run.
|
|
|
|
* :obj:`datetime.datetime` will be interpreted as a specific date and time at
|
2021-12-13 18:21:38 +01:00
|
|
|
which the job should run. If the timezone (:attr:`datetime.datetime.tzinfo`) is
|
2022-06-27 18:58:51 +02:00
|
|
|
:obj:`None`, the default timezone of the bot will be used, which is UTC unless
|
|
|
|
:attr:`telegram.ext.Defaults.tzinfo` is used.
|
2017-07-23 22:33:08 +02:00
|
|
|
* :obj:`datetime.time` will be interpreted as a specific time of day at which the
|
|
|
|
job should run. This could be either today or, if the time has already passed,
|
2021-12-13 18:21:38 +01:00
|
|
|
tomorrow. If the timezone (:attr:`datetime.time.tzinfo`) is :obj:`None`, the
|
2022-06-27 18:58:51 +02:00
|
|
|
default timezone of the bot will be used, which is UTC unless
|
|
|
|
:attr:`telegram.ext.Defaults.tzinfo` is used.
|
2020-04-18 15:08:16 +02:00
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
chat_id (:obj:`int`, optional): Chat id of the chat associated with this job. If
|
|
|
|
passed, the corresponding :attr:`~telegram.ext.CallbackContext.chat_data` will
|
|
|
|
be available in the callback.
|
|
|
|
|
2022-05-06 17:15:23 +02:00
|
|
|
.. versionadded:: 20.0
|
2022-04-24 12:38:09 +02:00
|
|
|
|
|
|
|
user_id (:obj:`int`, optional): User id of the user associated with this job. If
|
|
|
|
passed, the corresponding :attr:`~telegram.ext.CallbackContext.user_data` will
|
|
|
|
be available in the callback.
|
|
|
|
|
2022-05-06 17:15:23 +02:00
|
|
|
.. versionadded:: 20.0
|
2022-05-12 19:26:03 +02:00
|
|
|
data (:obj:`object`, optional): Additional data needed for the callback function.
|
|
|
|
Can be accessed through :attr:`Job.data` in the callback. Defaults to
|
2021-12-13 18:21:38 +01:00
|
|
|
:obj:`None`.
|
2022-05-12 19:26:03 +02:00
|
|
|
|
|
|
|
.. versionchanged:: 20.0
|
|
|
|
Renamed the parameter ``context`` to :paramref:`data`.
|
2017-07-23 22:33:08 +02:00
|
|
|
name (:obj:`str`, optional): The name of the new job. Defaults to
|
2022-04-24 12:38:09 +02:00
|
|
|
:external:attr:`callback.__name__ <definition.__name__>`.
|
2020-07-10 13:11:28 +02:00
|
|
|
job_kwargs (:obj:`dict`, optional): Arbitrary keyword arguments to pass to the
|
2021-12-13 18:21:38 +01:00
|
|
|
:meth:`apscheduler.schedulers.base.BaseScheduler.add_job()`.
|
2016-12-14 16:27:45 +01:00
|
|
|
|
|
|
|
Returns:
|
2021-12-13 18:21:38 +01:00
|
|
|
:class:`telegram.ext.Job`: The new :class:`Job` instance that has been added to the job
|
2017-07-23 22:33:08 +02:00
|
|
|
queue.
|
|
|
|
|
2017-09-01 08:43:08 +02:00
|
|
|
"""
|
2020-07-10 13:11:28 +02:00
|
|
|
if not job_kwargs:
|
|
|
|
job_kwargs = {}
|
|
|
|
|
|
|
|
name = name or callback.__name__
|
2022-05-12 19:26:03 +02:00
|
|
|
job = Job(callback=callback, data=data, name=name, chat_id=chat_id, user_id=user_id)
|
2020-10-31 16:33:34 +01:00
|
|
|
date_time = self._parse_time_input(when, shift_day=True)
|
2020-07-10 13:11:28 +02:00
|
|
|
|
|
|
|
j = self.scheduler.add_job(
|
2023-06-02 22:17:46 +02:00
|
|
|
self.job_callback,
|
2020-07-10 13:11:28 +02:00
|
|
|
name=name,
|
|
|
|
trigger="date",
|
2020-10-31 16:33:34 +01:00
|
|
|
run_date=date_time,
|
2023-06-02 22:17:46 +02:00
|
|
|
args=(self, job),
|
2020-10-31 16:33:34 +01:00
|
|
|
timezone=date_time.tzinfo or self.scheduler.timezone,
|
2020-07-10 13:11:28 +02:00
|
|
|
**job_kwargs,
|
|
|
|
)
|
|
|
|
|
2022-09-28 21:33:15 +02:00
|
|
|
job._job = j # pylint: disable=protected-access
|
2016-12-14 16:27:45 +01:00
|
|
|
return job
|
|
|
|
|
2020-10-06 19:28:40 +02:00
|
|
|
def run_repeating(
|
|
|
|
self,
|
2023-02-02 18:55:07 +01:00
|
|
|
callback: JobCallback[CCT],
|
2020-10-06 19:28:40 +02:00
|
|
|
interval: Union[float, datetime.timedelta],
|
2023-05-18 07:57:59 +02:00
|
|
|
first: Optional[Union[float, datetime.timedelta, datetime.datetime, datetime.time]] = None,
|
|
|
|
last: Optional[Union[float, datetime.timedelta, datetime.datetime, datetime.time]] = None,
|
|
|
|
data: Optional[object] = None,
|
|
|
|
name: Optional[str] = None,
|
|
|
|
chat_id: Optional[int] = None,
|
|
|
|
user_id: Optional[int] = None,
|
|
|
|
job_kwargs: Optional[JSONDict] = None,
|
2023-02-02 18:55:07 +01:00
|
|
|
) -> "Job[CCT]":
|
2021-12-13 18:21:38 +01:00
|
|
|
"""Creates a new :class:`Job` instance that runs at specified intervals and adds it to the
|
2022-02-09 17:30:16 +01:00
|
|
|
queue.
|
2016-12-14 16:27:45 +01:00
|
|
|
|
2021-06-06 12:16:23 +02:00
|
|
|
Note:
|
|
|
|
For a note about DST, please see the documentation of `APScheduler`_.
|
|
|
|
|
|
|
|
.. _`APScheduler`: https://apscheduler.readthedocs.io/en/stable/modules/triggers/cron.html
|
|
|
|
#daylight-saving-time-behavior
|
|
|
|
|
2016-12-14 16:27:45 +01:00
|
|
|
Args:
|
2022-04-24 12:38:09 +02:00
|
|
|
callback (:term:`coroutine function`): The callback function that should be executed by
|
|
|
|
the new job. Callback signature::
|
|
|
|
|
|
|
|
async def callback(context: CallbackContext)
|
|
|
|
|
2017-07-23 22:33:08 +02:00
|
|
|
interval (:obj:`int` | :obj:`float` | :obj:`datetime.timedelta`): The interval in which
|
|
|
|
the job will run. If it is an :obj:`int` or a :obj:`float`, it will be interpreted
|
|
|
|
as seconds.
|
2018-02-19 09:36:40 +01:00
|
|
|
first (:obj:`int` | :obj:`float` | :obj:`datetime.timedelta` | \
|
|
|
|
:obj:`datetime.datetime` | :obj:`datetime.time`, optional):
|
2017-07-23 22:33:08 +02:00
|
|
|
Time in or at which the job should run. This parameter will be interpreted
|
|
|
|
depending on its type.
|
|
|
|
|
|
|
|
* :obj:`int` or :obj:`float` will be interpreted as "seconds from now" in which the
|
|
|
|
job should run.
|
|
|
|
* :obj:`datetime.timedelta` will be interpreted as "time from now" in which the
|
|
|
|
job should run.
|
|
|
|
* :obj:`datetime.datetime` will be interpreted as a specific date and time at
|
2021-12-13 18:21:38 +01:00
|
|
|
which the job should run. If the timezone (:attr:`datetime.datetime.tzinfo`) is
|
|
|
|
:obj:`None`, the default timezone of the bot will be used.
|
2017-07-23 22:33:08 +02:00
|
|
|
* :obj:`datetime.time` will be interpreted as a specific time of day at which the
|
|
|
|
job should run. This could be either today or, if the time has already passed,
|
2021-12-13 18:21:38 +01:00
|
|
|
tomorrow. If the timezone (:attr:`datetime.time.tzinfo`) is :obj:`None`, the
|
2022-06-27 18:58:51 +02:00
|
|
|
default timezone of the bot will be used, which is UTC unless
|
|
|
|
:attr:`telegram.ext.Defaults.tzinfo` is used.
|
2020-04-18 15:08:16 +02:00
|
|
|
|
2022-06-09 17:08:54 +02:00
|
|
|
Defaults to :paramref:`interval`
|
2023-05-07 14:51:22 +02:00
|
|
|
|
|
|
|
Note:
|
|
|
|
Setting :paramref:`first` to ``0``, ``datetime.datetime.now()`` or another
|
|
|
|
value that indicates that the job should run immediately will not work due
|
|
|
|
to how the APScheduler library works. If you want to run a job immediately,
|
|
|
|
we recommend to use an approach along the lines of::
|
|
|
|
|
|
|
|
job = context.job_queue.run_repeating(callback, interval=5)
|
|
|
|
await job.run(context.application)
|
|
|
|
|
|
|
|
.. seealso:: :meth:`telegram.ext.Job.run`
|
|
|
|
|
2020-07-10 13:11:28 +02:00
|
|
|
last (:obj:`int` | :obj:`float` | :obj:`datetime.timedelta` | \
|
|
|
|
:obj:`datetime.datetime` | :obj:`datetime.time`, optional):
|
|
|
|
Latest possible time for the job to run. This parameter will be interpreted
|
2022-06-09 17:08:54 +02:00
|
|
|
depending on its type. See :paramref:`first` for details.
|
2020-07-10 13:11:28 +02:00
|
|
|
|
2022-06-09 17:08:54 +02:00
|
|
|
If :paramref:`last` is :obj:`datetime.datetime` or :obj:`datetime.time` type
|
2020-09-27 12:59:48 +02:00
|
|
|
and ``last.tzinfo`` is :obj:`None`, the default timezone of the bot will be
|
2022-06-27 18:58:51 +02:00
|
|
|
assumed, which is UTC unless :attr:`telegram.ext.Defaults.tzinfo` is used.
|
2020-07-10 13:11:28 +02:00
|
|
|
|
|
|
|
Defaults to :obj:`None`.
|
2022-05-12 19:26:03 +02:00
|
|
|
data (:obj:`object`, optional): Additional data needed for the callback function.
|
|
|
|
Can be accessed through :attr:`Job.data` in the callback. Defaults to
|
2021-12-13 18:21:38 +01:00
|
|
|
:obj:`None`.
|
2022-05-12 19:26:03 +02:00
|
|
|
|
|
|
|
.. versionchanged:: 20.0
|
|
|
|
Renamed the parameter ``context`` to :paramref:`data`.
|
2017-07-23 22:33:08 +02:00
|
|
|
name (:obj:`str`, optional): The name of the new job. Defaults to
|
2022-04-24 12:38:09 +02:00
|
|
|
:external:attr:`callback.__name__ <definition.__name__>`.
|
|
|
|
chat_id (:obj:`int`, optional): Chat id of the chat associated with this job. If
|
|
|
|
passed, the corresponding :attr:`~telegram.ext.CallbackContext.chat_data` will
|
|
|
|
be available in the callback.
|
|
|
|
|
2022-05-06 17:15:23 +02:00
|
|
|
.. versionadded:: 20.0
|
2022-04-24 12:38:09 +02:00
|
|
|
|
|
|
|
user_id (:obj:`int`, optional): User id of the user associated with this job. If
|
|
|
|
passed, the corresponding :attr:`~telegram.ext.CallbackContext.user_data` will
|
|
|
|
be available in the callback.
|
|
|
|
|
2022-05-06 17:15:23 +02:00
|
|
|
.. versionadded:: 20.0
|
2020-07-10 13:11:28 +02:00
|
|
|
job_kwargs (:obj:`dict`, optional): Arbitrary keyword arguments to pass to the
|
2021-12-13 18:21:38 +01:00
|
|
|
:meth:`apscheduler.schedulers.base.BaseScheduler.add_job()`.
|
2016-12-14 16:27:45 +01:00
|
|
|
|
|
|
|
Returns:
|
2021-12-13 18:21:38 +01:00
|
|
|
:class:`telegram.ext.Job`: The new :class:`Job` instance that has been added to the job
|
2017-07-23 22:33:08 +02:00
|
|
|
queue.
|
2017-09-01 08:43:08 +02:00
|
|
|
|
2016-12-14 16:27:45 +01:00
|
|
|
"""
|
2020-07-10 13:11:28 +02:00
|
|
|
if not job_kwargs:
|
|
|
|
job_kwargs = {}
|
|
|
|
|
|
|
|
name = name or callback.__name__
|
2022-05-12 19:26:03 +02:00
|
|
|
job = Job(callback=callback, data=data, name=name, chat_id=chat_id, user_id=user_id)
|
2020-07-10 13:11:28 +02:00
|
|
|
|
|
|
|
dt_first = self._parse_time_input(first)
|
|
|
|
dt_last = self._parse_time_input(last)
|
|
|
|
|
|
|
|
if dt_last and dt_first and dt_last < dt_first:
|
|
|
|
raise ValueError("'last' must not be before 'first'!")
|
|
|
|
|
|
|
|
if isinstance(interval, datetime.timedelta):
|
|
|
|
interval = interval.total_seconds()
|
|
|
|
|
|
|
|
j = self.scheduler.add_job(
|
2023-06-02 22:17:46 +02:00
|
|
|
self.job_callback,
|
2020-07-10 13:11:28 +02:00
|
|
|
trigger="interval",
|
2023-06-02 22:17:46 +02:00
|
|
|
args=(self, job),
|
2020-07-10 13:11:28 +02:00
|
|
|
start_date=dt_first,
|
|
|
|
end_date=dt_last,
|
|
|
|
seconds=interval,
|
|
|
|
name=name,
|
|
|
|
**job_kwargs,
|
|
|
|
)
|
|
|
|
|
2022-09-28 21:33:15 +02:00
|
|
|
job._job = j # pylint: disable=protected-access
|
2016-12-14 16:27:45 +01:00
|
|
|
return job
|
|
|
|
|
2020-10-06 19:28:40 +02:00
|
|
|
def run_monthly(
|
|
|
|
self,
|
2023-02-02 18:55:07 +01:00
|
|
|
callback: JobCallback[CCT],
|
2020-10-06 19:28:40 +02:00
|
|
|
when: datetime.time,
|
|
|
|
day: int,
|
2023-05-18 07:57:59 +02:00
|
|
|
data: Optional[object] = None,
|
|
|
|
name: Optional[str] = None,
|
|
|
|
chat_id: Optional[int] = None,
|
|
|
|
user_id: Optional[int] = None,
|
|
|
|
job_kwargs: Optional[JSONDict] = None,
|
2023-02-02 18:55:07 +01:00
|
|
|
) -> "Job[CCT]":
|
2021-12-13 18:21:38 +01:00
|
|
|
"""Creates a new :class:`Job` that runs on a monthly basis and adds it to the queue.
|
|
|
|
|
2022-05-06 17:15:23 +02:00
|
|
|
.. versionchanged:: 20.0
|
2022-06-09 17:08:54 +02:00
|
|
|
The ``day_is_strict`` argument was removed. Instead one can now pass ``-1`` to the
|
|
|
|
:paramref:`day` parameter to have the job run on the last day of the month.
|
2021-08-26 20:59:23 +02:00
|
|
|
|
2020-05-02 08:59:50 +02:00
|
|
|
Args:
|
2022-04-24 12:38:09 +02:00
|
|
|
callback (:term:`coroutine function`): The callback function that should be executed by
|
|
|
|
the new job. Callback signature::
|
|
|
|
|
|
|
|
async def callback(context: CallbackContext)
|
|
|
|
|
2020-05-02 08:59:50 +02:00
|
|
|
when (:obj:`datetime.time`): Time of day at which the job should run. If the timezone
|
2022-06-27 18:58:51 +02:00
|
|
|
(``when.tzinfo``) is :obj:`None`, the default timezone of the bot will be used,
|
|
|
|
which is UTC unless :attr:`telegram.ext.Defaults.tzinfo` is used.
|
2020-05-02 08:59:50 +02:00
|
|
|
day (:obj:`int`): Defines the day of the month whereby the job would run. It should
|
2022-06-09 17:08:54 +02:00
|
|
|
be within the range of ``1`` and ``31``, inclusive. If a month has fewer days than
|
|
|
|
this number, the job will not run in this month. Passing ``-1`` leads to the job
|
|
|
|
running on the last day of the month.
|
2022-05-12 19:26:03 +02:00
|
|
|
data (:obj:`object`, optional): Additional data needed for the callback function.
|
|
|
|
Can be accessed through :attr:`Job.data` in the callback. Defaults to
|
2021-12-13 18:21:38 +01:00
|
|
|
:obj:`None`.
|
2022-05-12 19:26:03 +02:00
|
|
|
|
|
|
|
.. versionchanged:: 20.0
|
|
|
|
Renamed the parameter ``context`` to :paramref:`data`.
|
2020-05-02 08:59:50 +02:00
|
|
|
name (:obj:`str`, optional): The name of the new job. Defaults to
|
2022-04-24 12:38:09 +02:00
|
|
|
:external:attr:`callback.__name__ <definition.__name__>`.
|
|
|
|
chat_id (:obj:`int`, optional): Chat id of the chat associated with this job. If
|
|
|
|
passed, the corresponding :attr:`~telegram.ext.CallbackContext.chat_data` will
|
|
|
|
be available in the callback.
|
|
|
|
|
2022-05-06 17:15:23 +02:00
|
|
|
.. versionadded:: 20.0
|
2022-04-24 12:38:09 +02:00
|
|
|
|
|
|
|
user_id (:obj:`int`, optional): User id of the user associated with this job. If
|
|
|
|
passed, the corresponding :attr:`~telegram.ext.CallbackContext.user_data` will
|
|
|
|
be available in the callback.
|
|
|
|
|
2022-05-06 17:15:23 +02:00
|
|
|
.. versionadded:: 20.0
|
2020-07-10 13:11:28 +02:00
|
|
|
job_kwargs (:obj:`dict`, optional): Arbitrary keyword arguments to pass to the
|
2021-12-13 18:21:38 +01:00
|
|
|
:meth:`apscheduler.schedulers.base.BaseScheduler.add_job()`.
|
2020-05-02 08:59:50 +02:00
|
|
|
|
|
|
|
Returns:
|
2021-12-13 18:21:38 +01:00
|
|
|
:class:`telegram.ext.Job`: The new :class:`Job` instance that has been added to the job
|
2020-05-02 08:59:50 +02:00
|
|
|
queue.
|
|
|
|
|
|
|
|
"""
|
2020-07-10 13:11:28 +02:00
|
|
|
if not job_kwargs:
|
|
|
|
job_kwargs = {}
|
|
|
|
|
|
|
|
name = name or callback.__name__
|
2022-05-12 19:26:03 +02:00
|
|
|
job = Job(callback=callback, data=data, name=name, chat_id=chat_id, user_id=user_id)
|
2020-07-10 13:11:28 +02:00
|
|
|
|
2021-08-26 20:59:23 +02:00
|
|
|
j = self.scheduler.add_job(
|
2023-06-02 22:17:46 +02:00
|
|
|
self.job_callback,
|
2021-08-26 20:59:23 +02:00
|
|
|
trigger="cron",
|
2023-06-02 22:17:46 +02:00
|
|
|
args=(self, job),
|
2021-08-26 20:59:23 +02:00
|
|
|
name=name,
|
|
|
|
day="last" if day == -1 else day,
|
|
|
|
hour=when.hour,
|
|
|
|
minute=when.minute,
|
|
|
|
second=when.second,
|
|
|
|
timezone=when.tzinfo or self.scheduler.timezone,
|
|
|
|
**job_kwargs,
|
|
|
|
)
|
2022-09-28 21:33:15 +02:00
|
|
|
job._job = j # pylint: disable=protected-access
|
2020-07-10 13:11:28 +02:00
|
|
|
return job
|
2020-05-02 08:59:50 +02:00
|
|
|
|
2020-10-06 19:28:40 +02:00
|
|
|
def run_daily(
|
|
|
|
self,
|
2023-02-02 18:55:07 +01:00
|
|
|
callback: JobCallback[CCT],
|
2020-10-06 19:28:40 +02:00
|
|
|
time: datetime.time,
|
2024-10-24 20:48:49 +02:00
|
|
|
days: tuple[int, ...] = _ALL_DAYS,
|
2023-05-18 07:57:59 +02:00
|
|
|
data: Optional[object] = None,
|
|
|
|
name: Optional[str] = None,
|
|
|
|
chat_id: Optional[int] = None,
|
|
|
|
user_id: Optional[int] = None,
|
|
|
|
job_kwargs: Optional[JSONDict] = None,
|
2023-02-02 18:55:07 +01:00
|
|
|
) -> "Job[CCT]":
|
2021-12-13 18:21:38 +01:00
|
|
|
"""Creates a new :class:`Job` that runs on a daily basis and adds it to the queue.
|
2016-12-14 16:27:45 +01:00
|
|
|
|
2021-06-06 12:16:23 +02:00
|
|
|
Note:
|
|
|
|
For a note about DST, please see the documentation of `APScheduler`_.
|
|
|
|
|
|
|
|
.. _`APScheduler`: https://apscheduler.readthedocs.io/en/stable/modules/triggers/cron.html
|
|
|
|
#daylight-saving-time-behavior
|
|
|
|
|
2016-12-14 16:27:45 +01:00
|
|
|
Args:
|
2022-04-24 12:38:09 +02:00
|
|
|
callback (:term:`coroutine function`): The callback function that should be executed by
|
|
|
|
the new job. Callback signature::
|
|
|
|
|
|
|
|
async def callback(context: CallbackContext)
|
|
|
|
|
2019-11-15 21:51:22 +01:00
|
|
|
time (:obj:`datetime.time`): Time of day at which the job should run. If the timezone
|
2022-02-09 17:30:16 +01:00
|
|
|
(:obj:`datetime.time.tzinfo`) is :obj:`None`, the default timezone of the bot will
|
2022-06-27 18:58:51 +02:00
|
|
|
be used, which is UTC unless :attr:`telegram.ext.Defaults.tzinfo` is used.
|
2024-10-24 20:48:49 +02:00
|
|
|
days (tuple[:obj:`int`], optional): Defines on which days of the week the job should
|
2022-05-25 10:02:00 +02:00
|
|
|
run (where ``0-6`` correspond to sunday - saturday). By default, the job will run
|
|
|
|
every day.
|
|
|
|
|
|
|
|
.. versionchanged:: 20.0
|
|
|
|
Changed day of the week mapping of 0-6 from monday-sunday to sunday-saturday.
|
2023-01-14 18:57:08 +01:00
|
|
|
|
2022-05-12 19:26:03 +02:00
|
|
|
data (:obj:`object`, optional): Additional data needed for the callback function.
|
|
|
|
Can be accessed through :attr:`Job.data` in the callback. Defaults to
|
2021-12-13 18:21:38 +01:00
|
|
|
:obj:`None`.
|
2022-05-12 19:26:03 +02:00
|
|
|
|
|
|
|
.. versionchanged:: 20.0
|
|
|
|
Renamed the parameter ``context`` to :paramref:`data`.
|
2017-07-23 22:33:08 +02:00
|
|
|
name (:obj:`str`, optional): The name of the new job. Defaults to
|
2022-04-24 12:38:09 +02:00
|
|
|
:external:attr:`callback.__name__ <definition.__name__>`.
|
|
|
|
chat_id (:obj:`int`, optional): Chat id of the chat associated with this job. If
|
|
|
|
passed, the corresponding :attr:`~telegram.ext.CallbackContext.chat_data` will
|
|
|
|
be available in the callback.
|
|
|
|
|
2022-05-06 17:15:23 +02:00
|
|
|
.. versionadded:: 20.0
|
2022-04-24 12:38:09 +02:00
|
|
|
|
|
|
|
user_id (:obj:`int`, optional): User id of the user associated with this job. If
|
|
|
|
passed, the corresponding :attr:`~telegram.ext.CallbackContext.user_data` will
|
|
|
|
be available in the callback.
|
|
|
|
|
2022-05-06 17:15:23 +02:00
|
|
|
.. versionadded:: 20.0
|
2020-07-10 13:11:28 +02:00
|
|
|
job_kwargs (:obj:`dict`, optional): Arbitrary keyword arguments to pass to the
|
2021-12-13 18:21:38 +01:00
|
|
|
:meth:`apscheduler.schedulers.base.BaseScheduler.add_job()`.
|
2016-12-14 16:27:45 +01:00
|
|
|
|
|
|
|
Returns:
|
2021-12-13 18:21:38 +01:00
|
|
|
:class:`telegram.ext.Job`: The new :class:`Job` instance that has been added to the job
|
2017-07-23 22:33:08 +02:00
|
|
|
queue.
|
2017-09-01 08:43:08 +02:00
|
|
|
|
2016-12-14 16:27:45 +01:00
|
|
|
"""
|
2020-07-10 13:11:28 +02:00
|
|
|
if not job_kwargs:
|
|
|
|
job_kwargs = {}
|
|
|
|
|
|
|
|
name = name or callback.__name__
|
2022-05-12 19:26:03 +02:00
|
|
|
job = Job(callback=callback, data=data, name=name, chat_id=chat_id, user_id=user_id)
|
2020-07-10 13:11:28 +02:00
|
|
|
|
|
|
|
j = self.scheduler.add_job(
|
2023-06-02 22:17:46 +02:00
|
|
|
self.job_callback,
|
2020-07-10 13:11:28 +02:00
|
|
|
name=name,
|
2023-06-02 22:17:46 +02:00
|
|
|
args=(self, job),
|
2020-07-10 13:11:28 +02:00
|
|
|
trigger="cron",
|
2022-05-25 10:02:00 +02:00
|
|
|
day_of_week=",".join([self._CRON_MAPPING[d] for d in days]),
|
2020-07-10 13:11:28 +02:00
|
|
|
hour=time.hour,
|
|
|
|
minute=time.minute,
|
|
|
|
second=time.second,
|
|
|
|
timezone=time.tzinfo or self.scheduler.timezone,
|
|
|
|
**job_kwargs,
|
|
|
|
)
|
|
|
|
|
2022-09-28 21:33:15 +02:00
|
|
|
job._job = j # pylint: disable=protected-access
|
2016-12-14 16:27:45 +01:00
|
|
|
return job
|
|
|
|
|
2020-10-06 19:28:40 +02:00
|
|
|
def run_custom(
|
|
|
|
self,
|
2023-02-02 18:55:07 +01:00
|
|
|
callback: JobCallback[CCT],
|
2020-10-06 19:28:40 +02:00
|
|
|
job_kwargs: JSONDict,
|
2023-05-18 07:57:59 +02:00
|
|
|
data: Optional[object] = None,
|
|
|
|
name: Optional[str] = None,
|
|
|
|
chat_id: Optional[int] = None,
|
|
|
|
user_id: Optional[int] = None,
|
2023-02-02 18:55:07 +01:00
|
|
|
) -> "Job[CCT]":
|
2021-12-13 18:21:38 +01:00
|
|
|
"""Creates a new custom defined :class:`Job`.
|
2016-01-05 13:32:19 +01:00
|
|
|
|
2020-07-10 13:11:28 +02:00
|
|
|
Args:
|
2022-04-24 12:38:09 +02:00
|
|
|
callback (:term:`coroutine function`): The callback function that should be executed by
|
|
|
|
the new job. Callback signature::
|
|
|
|
|
|
|
|
async def callback(context: CallbackContext)
|
|
|
|
|
2020-07-10 13:11:28 +02:00
|
|
|
job_kwargs (:obj:`dict`): Arbitrary keyword arguments. Used as arguments for
|
2021-12-13 18:21:38 +01:00
|
|
|
:meth:`apscheduler.schedulers.base.BaseScheduler.add_job`.
|
2022-05-12 19:26:03 +02:00
|
|
|
data (:obj:`object`, optional): Additional data needed for the callback function.
|
|
|
|
Can be accessed through :attr:`Job.data` in the callback. Defaults to
|
2021-12-13 18:21:38 +01:00
|
|
|
:obj:`None`.
|
2022-05-12 19:26:03 +02:00
|
|
|
|
|
|
|
.. versionchanged:: 20.0
|
|
|
|
Renamed the parameter ``context`` to :paramref:`data`.
|
2020-07-10 13:11:28 +02:00
|
|
|
name (:obj:`str`, optional): The name of the new job. Defaults to
|
2022-04-24 12:38:09 +02:00
|
|
|
:external:attr:`callback.__name__ <definition.__name__>`.
|
|
|
|
chat_id (:obj:`int`, optional): Chat id of the chat associated with this job. If
|
|
|
|
passed, the corresponding :attr:`~telegram.ext.CallbackContext.chat_data` will
|
|
|
|
be available in the callback.
|
|
|
|
|
2022-05-06 17:15:23 +02:00
|
|
|
.. versionadded:: 20.0
|
2022-04-24 12:38:09 +02:00
|
|
|
|
|
|
|
user_id (:obj:`int`, optional): User id of the user associated with this job. If
|
|
|
|
passed, the corresponding :attr:`~telegram.ext.CallbackContext.user_data` will
|
|
|
|
be available in the callback.
|
|
|
|
|
2022-05-06 17:15:23 +02:00
|
|
|
.. versionadded:: 20.0
|
2015-12-31 14:55:15 +01:00
|
|
|
|
2020-07-10 13:11:28 +02:00
|
|
|
Returns:
|
2021-12-13 18:21:38 +01:00
|
|
|
:class:`telegram.ext.Job`: The new :class:`Job` instance that has been added to the job
|
2020-07-10 13:11:28 +02:00
|
|
|
queue.
|
2017-07-23 22:33:08 +02:00
|
|
|
|
2017-09-01 08:43:08 +02:00
|
|
|
"""
|
2020-07-10 13:11:28 +02:00
|
|
|
name = name or callback.__name__
|
2022-05-12 19:26:03 +02:00
|
|
|
job = Job(callback=callback, data=data, name=name, chat_id=chat_id, user_id=user_id)
|
2016-06-22 00:24:59 +02:00
|
|
|
|
2023-06-02 22:17:46 +02:00
|
|
|
j = self.scheduler.add_job(self.job_callback, args=(self, job), name=name, **job_kwargs)
|
2016-05-25 22:51:13 +02:00
|
|
|
|
2022-09-28 21:33:15 +02:00
|
|
|
job._job = j # pylint: disable=protected-access
|
2020-07-10 13:11:28 +02:00
|
|
|
return job
|
2016-01-04 00:01:00 +01:00
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
async def start(self) -> None:
|
|
|
|
# this method async just in case future versions need that
|
2022-06-09 17:08:54 +02:00
|
|
|
"""Starts the :class:`~telegram.ext.JobQueue`."""
|
2020-07-10 13:11:28 +02:00
|
|
|
if not self.scheduler.running:
|
|
|
|
self.scheduler.start()
|
2016-01-04 01:56:22 +01:00
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
async def stop(self, wait: bool = True) -> None:
|
|
|
|
"""Shuts down the :class:`~telegram.ext.JobQueue`.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
wait (:obj:`bool`, optional): Whether to wait until all currently running jobs
|
|
|
|
have finished. Defaults to :obj:`True`.
|
|
|
|
|
|
|
|
"""
|
|
|
|
# the interface methods of AsyncIOExecutor are currently not really asyncio-compatible
|
|
|
|
# so we apply some small tweaks here to try and smoothen the integration into PTB
|
|
|
|
# TODO: When APS 4.0 hits, we should be able to remove the tweaks
|
|
|
|
if wait:
|
|
|
|
# Unfortunately AsyncIOExecutor just cancels them all ...
|
|
|
|
await asyncio.gather(
|
|
|
|
*self._executor._pending_futures, # pylint: disable=protected-access
|
|
|
|
return_exceptions=True,
|
|
|
|
)
|
2020-07-10 13:11:28 +02:00
|
|
|
if self.scheduler.running:
|
2022-04-24 12:38:09 +02:00
|
|
|
self.scheduler.shutdown(wait=wait)
|
|
|
|
# scheduler.shutdown schedules a task in the event loop but immediately returns
|
|
|
|
# so give it a tiny bit of time to actually shut down.
|
|
|
|
await asyncio.sleep(0.01)
|
2016-05-25 22:51:13 +02:00
|
|
|
|
2024-10-24 20:48:49 +02:00
|
|
|
def jobs(self) -> tuple["Job[CCT]", ...]:
|
2022-08-27 11:46:51 +02:00
|
|
|
"""Returns a tuple of all *scheduled* jobs that are currently in the :class:`JobQueue`.
|
|
|
|
|
|
|
|
Returns:
|
2024-10-24 20:48:49 +02:00
|
|
|
tuple[:class:`Job`]: Tuple of all *scheduled* jobs.
|
2022-08-27 11:46:51 +02:00
|
|
|
"""
|
2023-06-02 22:17:46 +02:00
|
|
|
return tuple(Job.from_aps_job(job) for job in self.scheduler.get_jobs())
|
2016-05-25 22:51:13 +02:00
|
|
|
|
2024-10-24 20:48:49 +02:00
|
|
|
def get_jobs_by_name(self, name: str) -> tuple["Job[CCT]", ...]:
|
2020-11-29 16:25:47 +01:00
|
|
|
"""Returns a tuple of all *pending/scheduled* jobs with the given name that are currently
|
2021-12-13 18:21:38 +01:00
|
|
|
in the :class:`JobQueue`.
|
2022-08-27 11:46:51 +02:00
|
|
|
|
|
|
|
Returns:
|
2024-10-24 20:48:49 +02:00
|
|
|
tuple[:class:`Job`]: Tuple of all *pending* or *scheduled* jobs matching the name.
|
2021-05-27 09:38:17 +02:00
|
|
|
"""
|
2020-07-10 13:11:28 +02:00
|
|
|
return tuple(job for job in self.jobs() if job.name == name)
|
2018-02-19 09:36:40 +01:00
|
|
|
|
2016-05-25 22:51:13 +02:00
|
|
|
|
2023-02-02 18:55:07 +01:00
|
|
|
class Job(Generic[CCT]):
|
2020-07-10 13:11:28 +02:00
|
|
|
"""This class is a convenience wrapper for the jobs held in a :class:`telegram.ext.JobQueue`.
|
|
|
|
With the current backend APScheduler, :attr:`job` holds a :class:`apscheduler.job.Job`
|
|
|
|
instance.
|
|
|
|
|
2021-07-01 17:34:23 +02:00
|
|
|
Objects of this class are comparable in terms of equality. Two objects of this class are
|
2022-02-09 17:30:16 +01:00
|
|
|
considered equal, if their :class:`id <apscheduler.job.Job>` is equal.
|
2021-07-01 17:34:23 +02:00
|
|
|
|
2023-02-02 18:55:07 +01:00
|
|
|
This class is a :class:`~typing.Generic` class and accepts one type variable that specifies
|
|
|
|
the type of the argument ``context`` of :paramref:`callback`.
|
|
|
|
|
2022-10-31 10:12:18 +01:00
|
|
|
Important:
|
|
|
|
If you want to use this class, you must install PTB with the optional requirement
|
|
|
|
``job-queue``, i.e.
|
|
|
|
|
|
|
|
.. code-block:: bash
|
|
|
|
|
2023-06-29 07:46:00 +02:00
|
|
|
pip install "python-telegram-bot[job-queue]"
|
2022-10-31 10:12:18 +01:00
|
|
|
|
2020-07-10 13:11:28 +02:00
|
|
|
Note:
|
2022-09-28 21:33:15 +02:00
|
|
|
All attributes and instance methods of :attr:`job` are also directly available as
|
|
|
|
attributes/methods of the corresponding :class:`telegram.ext.Job` object.
|
|
|
|
|
|
|
|
Warning:
|
|
|
|
This class should not be instantiated manually.
|
|
|
|
Use the methods of :class:`telegram.ext.JobQueue` to schedule jobs.
|
2016-05-25 22:51:13 +02:00
|
|
|
|
2023-07-09 11:22:08 +02:00
|
|
|
.. seealso:: :wiki:`Job Queue <Extensions---JobQueue>`
|
Documentation Improvements (#3214, #3217, #3218, #3271, #3289, #3292, #3303, #3312, #3306, #3319, #3326, #3314)
Co-authored-by: Harshil <37377066+harshil21@users.noreply.github.com>
Co-authored-by: Simon Fong <44134941+simonfongnt@users.noreply.github.com>
Co-authored-by: Piotr Rogulski <rivinek@gmail.com>
Co-authored-by: poolitzer <25934244+Poolitzer@users.noreply.github.com>
Co-authored-by: Or Bin <or@raftt.io>
Co-authored-by: Sandro <j32g7f67hb@liamekaens.com>
Co-authored-by: Hatim Zahid <63000127+HatimZ@users.noreply.github.com>
Co-authored-by: Robi <53259730+RobiMez@users.noreply.github.com>
Co-authored-by: Dmitry Kolomatskiy <58207913+lemontree210@users.noreply.github.com>
2022-11-15 09:06:23 +01:00
|
|
|
|
2022-05-06 17:15:23 +02:00
|
|
|
.. versionchanged:: 20.0
|
2022-06-27 18:58:51 +02:00
|
|
|
|
2022-05-12 19:26:03 +02:00
|
|
|
* Removed argument and attribute ``job_queue``.
|
|
|
|
* Renamed ``Job.context`` to :attr:`Job.data`.
|
2022-09-28 21:33:15 +02:00
|
|
|
* Removed argument ``job``
|
2022-10-31 10:12:18 +01:00
|
|
|
* To use this class, PTB must be installed via
|
2023-06-29 07:46:00 +02:00
|
|
|
``pip install "python-telegram-bot[job-queue]"``.
|
2021-08-30 16:31:19 +02:00
|
|
|
|
2016-05-25 22:51:13 +02:00
|
|
|
Args:
|
2022-04-24 12:38:09 +02:00
|
|
|
callback (:term:`coroutine function`): The callback function that should be executed by the
|
|
|
|
new job. Callback signature::
|
|
|
|
|
|
|
|
async def callback(context: CallbackContext)
|
|
|
|
|
2023-02-05 18:09:55 +01:00
|
|
|
data (:obj:`object`, optional): Additional data needed for the :paramref:`callback`
|
|
|
|
function. Can be accessed through :attr:`Job.data` in the callback. Defaults to
|
|
|
|
:obj:`None`.
|
2022-04-24 12:38:09 +02:00
|
|
|
name (:obj:`str`, optional): The name of the new job. Defaults to
|
|
|
|
:external:obj:`callback.__name__ <definition.__name__>`.
|
|
|
|
chat_id (:obj:`int`, optional): Chat id of the chat that this job is associated with.
|
|
|
|
|
2022-05-06 17:15:23 +02:00
|
|
|
.. versionadded:: 20.0
|
2022-04-24 12:38:09 +02:00
|
|
|
user_id (:obj:`int`, optional): User id of the user that this job is associated with.
|
|
|
|
|
2022-05-06 17:15:23 +02:00
|
|
|
.. versionadded:: 20.0
|
2020-12-30 15:59:50 +01:00
|
|
|
Attributes:
|
2022-04-24 12:38:09 +02:00
|
|
|
callback (:term:`coroutine function`): The callback function that should be executed by the
|
|
|
|
new job.
|
2023-02-05 18:09:55 +01:00
|
|
|
data (:obj:`object`): Optional. Additional data needed for the :attr:`callback` function.
|
2020-12-30 15:59:50 +01:00
|
|
|
name (:obj:`str`): Optional. The name of the new job.
|
2022-04-24 12:38:09 +02:00
|
|
|
chat_id (:obj:`int`): Optional. Chat id of the chat that this job is associated with.
|
|
|
|
|
2022-05-06 17:15:23 +02:00
|
|
|
.. versionadded:: 20.0
|
2022-04-24 12:38:09 +02:00
|
|
|
user_id (:obj:`int`): Optional. User id of the user that this job is associated with.
|
|
|
|
|
2022-05-06 17:15:23 +02:00
|
|
|
.. versionadded:: 20.0
|
2016-05-25 22:51:13 +02:00
|
|
|
"""
|
|
|
|
|
2021-05-29 16:18:16 +02:00
|
|
|
__slots__ = (
|
|
|
|
"_enabled",
|
2022-09-28 21:33:15 +02:00
|
|
|
"_job",
|
2024-02-05 19:24:00 +01:00
|
|
|
"_removed",
|
|
|
|
"callback",
|
2022-04-24 12:38:09 +02:00
|
|
|
"chat_id",
|
2024-02-05 19:24:00 +01:00
|
|
|
"data",
|
|
|
|
"name",
|
2022-04-24 12:38:09 +02:00
|
|
|
"user_id",
|
2021-05-29 16:18:16 +02:00
|
|
|
)
|
|
|
|
|
2016-12-14 16:27:45 +01:00
|
|
|
def __init__(
|
|
|
|
self,
|
2023-02-02 18:55:07 +01:00
|
|
|
callback: JobCallback[CCT],
|
2023-05-18 07:57:59 +02:00
|
|
|
data: Optional[object] = None,
|
|
|
|
name: Optional[str] = None,
|
|
|
|
chat_id: Optional[int] = None,
|
|
|
|
user_id: Optional[int] = None,
|
2020-10-06 19:28:40 +02:00
|
|
|
):
|
2022-10-31 10:12:18 +01:00
|
|
|
if not APS_AVAILABLE:
|
|
|
|
raise RuntimeError(
|
|
|
|
"To use `Job`, PTB must be installed via `pip install "
|
2023-06-29 07:46:00 +02:00
|
|
|
'"python-telegram-bot[job-queue]"`.'
|
2022-10-31 10:12:18 +01:00
|
|
|
)
|
2016-12-14 16:27:45 +01:00
|
|
|
|
2023-02-02 18:55:07 +01:00
|
|
|
self.callback: JobCallback[CCT] = callback
|
|
|
|
self.data: Optional[object] = data
|
|
|
|
self.name: Optional[str] = name or callback.__name__
|
|
|
|
self.chat_id: Optional[int] = chat_id
|
|
|
|
self.user_id: Optional[int] = user_id
|
2016-05-25 22:51:13 +02:00
|
|
|
|
2020-07-10 13:11:28 +02:00
|
|
|
self._removed = False
|
|
|
|
self._enabled = False
|
2016-12-13 23:38:13 +01:00
|
|
|
|
2024-02-07 20:45:57 +01:00
|
|
|
self._job = cast("APSJob", None)
|
2022-09-28 21:33:15 +02:00
|
|
|
|
2023-09-15 22:19:45 +02:00
|
|
|
def __getattr__(self, item: str) -> object:
|
2023-12-10 20:17:11 +01:00
|
|
|
"""Overrides :py:meth:`object.__getattr__` to get specific attribute of the
|
|
|
|
:class:`telegram.ext.Job` object or of its attribute :class:`apscheduler.job.Job`,
|
|
|
|
if exists.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
item (:obj:`str`): The name of the attribute.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
:object: The value of the attribute.
|
|
|
|
|
|
|
|
Raises:
|
|
|
|
:exc:`AttributeError`: If the attribute does not exist in both
|
|
|
|
:class:`telegram.ext.Job` and :class:`apscheduler.job.Job` objects.
|
|
|
|
"""
|
2023-09-15 22:19:45 +02:00
|
|
|
try:
|
|
|
|
return getattr(self.job, item)
|
|
|
|
except AttributeError as exc:
|
|
|
|
raise AttributeError(
|
|
|
|
f"Neither 'telegram.ext.Job' nor 'apscheduler.job.Job' has attribute '{item}'"
|
|
|
|
) from exc
|
|
|
|
|
|
|
|
def __eq__(self, other: object) -> bool:
|
2023-12-10 20:17:11 +01:00
|
|
|
"""Defines equality condition for the :class:`telegram.ext.Job` object.
|
|
|
|
Two objects of this class are considered to be equal if their
|
|
|
|
:class:`id <apscheduler.job.Job>` are equal.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
:obj:`True` if both objects have :paramref:`id` parameters identical.
|
|
|
|
:obj:`False` otherwise.
|
|
|
|
"""
|
2023-09-15 22:19:45 +02:00
|
|
|
if isinstance(other, self.__class__):
|
|
|
|
return self.id == other.id
|
|
|
|
return False
|
|
|
|
|
|
|
|
def __hash__(self) -> int:
|
2023-12-10 20:17:11 +01:00
|
|
|
"""Builds a hash value for this object such that the hash of two objects is
|
|
|
|
equal if and only if the objects are equal in terms of :meth:`__eq__`.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
:obj:`int`: The hash value of the object.
|
|
|
|
"""
|
2023-09-15 22:19:45 +02:00
|
|
|
return hash(self.id)
|
|
|
|
|
2023-09-15 21:35:45 +02:00
|
|
|
def __repr__(self) -> str:
|
|
|
|
"""Give a string representation of the job in the form
|
|
|
|
``Job[id=..., name=..., callback=..., trigger=...]``.
|
|
|
|
|
|
|
|
As this class doesn't implement :meth:`object.__str__`, the default implementation
|
|
|
|
will be used, which is equivalent to :meth:`__repr__`.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
:obj:`str`
|
|
|
|
"""
|
|
|
|
return build_repr_with_selected_attrs(
|
|
|
|
self,
|
|
|
|
id=self.job.id,
|
|
|
|
name=self.name,
|
|
|
|
callback=self.callback.__name__,
|
|
|
|
trigger=self.job.trigger,
|
|
|
|
)
|
|
|
|
|
2022-09-28 21:33:15 +02:00
|
|
|
@property
|
2022-10-31 10:12:18 +01:00
|
|
|
def job(self) -> "APSJob":
|
2022-09-28 21:33:15 +02:00
|
|
|
""":class:`apscheduler.job.Job`: The APS Job this job is a wrapper for.
|
|
|
|
|
|
|
|
.. versionchanged:: 20.0
|
|
|
|
This property is now read-only.
|
|
|
|
"""
|
|
|
|
return self._job
|
2016-05-25 22:51:13 +02:00
|
|
|
|
2016-12-19 23:14:03 +01:00
|
|
|
@property
|
2020-10-06 19:28:40 +02:00
|
|
|
def removed(self) -> bool:
|
2017-09-01 08:43:08 +02:00
|
|
|
""":obj:`bool`: Whether this job is due to be removed."""
|
2020-07-10 13:11:28 +02:00
|
|
|
return self._removed
|
2016-12-14 23:08:03 +01:00
|
|
|
|
2016-12-14 16:27:45 +01:00
|
|
|
@property
|
2020-10-06 19:28:40 +02:00
|
|
|
def enabled(self) -> bool:
|
2017-09-01 08:43:08 +02:00
|
|
|
""":obj:`bool`: Whether this job is enabled."""
|
2020-07-10 13:11:28 +02:00
|
|
|
return self._enabled
|
2016-05-25 22:51:13 +02:00
|
|
|
|
2016-12-14 16:27:45 +01:00
|
|
|
@enabled.setter
|
2020-10-06 19:28:40 +02:00
|
|
|
def enabled(self, status: bool) -> None:
|
2016-05-25 22:51:13 +02:00
|
|
|
if status:
|
2020-07-10 13:11:28 +02:00
|
|
|
self.job.resume()
|
2016-12-14 16:27:45 +01:00
|
|
|
else:
|
2020-07-10 13:11:28 +02:00
|
|
|
self.job.pause()
|
|
|
|
self._enabled = status
|
2016-12-14 16:27:45 +01:00
|
|
|
|
2020-04-18 15:08:16 +02:00
|
|
|
@property
|
2020-10-06 19:28:40 +02:00
|
|
|
def next_t(self) -> Optional[datetime.datetime]:
|
2020-04-18 15:08:16 +02:00
|
|
|
"""
|
2022-01-03 09:07:18 +01:00
|
|
|
:class:`datetime.datetime`: Datetime for the next job execution.
|
|
|
|
Datetime is localized according to :attr:`datetime.datetime.tzinfo`.
|
|
|
|
If job is removed or already ran it equals to :obj:`None`.
|
|
|
|
|
|
|
|
Warning:
|
|
|
|
This attribute is only available, if the :class:`telegram.ext.JobQueue` this job
|
|
|
|
belongs to is already started. Otherwise APScheduler raises an :exc:`AttributeError`.
|
2020-04-18 15:08:16 +02:00
|
|
|
"""
|
2020-07-10 13:11:28 +02:00
|
|
|
return self.job.next_run_time
|
2016-12-14 16:27:45 +01:00
|
|
|
|
2020-07-10 13:11:28 +02:00
|
|
|
@classmethod
|
2023-06-02 22:17:46 +02:00
|
|
|
def from_aps_job(cls, aps_job: "APSJob") -> "Job[CCT]":
|
|
|
|
"""Provides the :class:`telegram.ext.Job` that is associated with the given APScheduler
|
|
|
|
job.
|
|
|
|
|
|
|
|
Tip:
|
|
|
|
This method can be useful when using advanced APScheduler features along with
|
|
|
|
:class:`telegram.ext.JobQueue`.
|
|
|
|
|
2023-07-09 12:18:32 +02:00
|
|
|
.. versionadded:: 20.4
|
2023-06-02 22:17:46 +02:00
|
|
|
|
|
|
|
Args:
|
|
|
|
aps_job (:class:`apscheduler.job.Job`): The APScheduler job
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
:class:`telegram.ext.Job`
|
|
|
|
"""
|
|
|
|
ext_job = aps_job.args[1]
|
|
|
|
ext_job._job = aps_job # pylint: disable=protected-access
|
|
|
|
return ext_job
|
2020-07-10 13:11:28 +02:00
|
|
|
|
2023-09-15 22:19:45 +02:00
|
|
|
async def run(
|
|
|
|
self, application: "Application[Any, CCT, Any, Any, Any, JobQueue[CCT]]"
|
|
|
|
) -> None:
|
|
|
|
"""Executes the callback function independently of the jobs schedule. Also calls
|
|
|
|
:meth:`telegram.ext.Application.update_persistence`.
|
2015-12-31 14:55:15 +01:00
|
|
|
|
2023-09-15 22:19:45 +02:00
|
|
|
.. versionchanged:: 20.0
|
|
|
|
Calls :meth:`telegram.ext.Application.update_persistence`.
|
2022-09-28 21:33:15 +02:00
|
|
|
|
2023-09-15 22:19:45 +02:00
|
|
|
Args:
|
|
|
|
application (:class:`telegram.ext.Application`): The application this job is associated
|
|
|
|
with.
|
|
|
|
"""
|
|
|
|
# We shield the task such that the job isn't cancelled mid-run
|
|
|
|
await asyncio.shield(self._run(application))
|
|
|
|
|
|
|
|
async def _run(
|
|
|
|
self, application: "Application[Any, CCT, Any, Any, Any, JobQueue[CCT]]"
|
|
|
|
) -> None:
|
|
|
|
try:
|
2024-05-20 15:25:56 +02:00
|
|
|
try:
|
|
|
|
context = application.context_types.context.from_job(self, application)
|
|
|
|
except Exception as exc:
|
|
|
|
_LOGGER.critical(
|
|
|
|
"Error while building CallbackContext for job %s. Job will not be run.",
|
|
|
|
self._job,
|
|
|
|
exc_info=exc,
|
|
|
|
)
|
|
|
|
return
|
|
|
|
|
2023-09-15 22:19:45 +02:00
|
|
|
await context.refresh_data()
|
|
|
|
await self.callback(context)
|
|
|
|
except Exception as exc:
|
|
|
|
await application.create_task(
|
|
|
|
application.process_error(None, exc, job=self),
|
|
|
|
name=f"Job:{self.id}:run:process_error",
|
|
|
|
)
|
|
|
|
finally:
|
|
|
|
# This is internal logic of application - let's keep it private for now
|
|
|
|
application._mark_for_persistence_update(job=self) # pylint: disable=protected-access
|
|
|
|
|
|
|
|
def schedule_removal(self) -> None:
|
|
|
|
"""
|
|
|
|
Schedules this job for removal from the :class:`JobQueue`. It will be removed without
|
|
|
|
executing its callback function again.
|
|
|
|
"""
|
|
|
|
self.job.remove()
|
|
|
|
self._removed = True
|