desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Check if the request is a file request.
Args:
data (Dict[:obj:`str`, :obj:`str`]): A dict of (str, str) key/value pairs.
Returns:
:obj:`bool`'
| @staticmethod
def is_inputfile(data):
| if data:
file_type = [i for i in iter(data) if (i in FILE_TYPES)]
if file_type:
file_content = data[file_type[0]]
return hasattr(file_content, 'read')
return False
|
':obj:`str`: The users :attr:`username` if available, if not it returns the first name and
if present :attr:`first_name` and :attr:`last_name`.'
| @property
def name(self):
| if self.username:
return ('@%s' % self.username)
if self.last_name:
return ('%s %s' % (self.first_name, self.last_name))
return self.first_name
|
'Shortcut for::
bot.get_user_profile_photos(update.message.from_user.id, *args, **kwargs)'
| def get_profile_photos(self, *args, **kwargs):
| return self.bot.get_user_profile_photos(self.id, *args, **kwargs)
|
'Shortcut for::
bot.answer_callback_query(update.callback_query.id, *args, **kwargs)
Returns:
:obj:`bool`: On success, ``True`` is returned.'
| def answer(self, *args, **kwargs):
| return self.bot.answerCallbackQuery(self.id, *args, **kwargs)
|
'Shortcut for either::
bot.edit_message_text(chat_id=update.callback_query.message.chat_id,
message_id=update.callback_query.message.message_id,
*args, **kwargs)
or::
bot.edit_message_text(inline_message_id=update.callback_query.inline_message_id,
*args, **kwargs)
Returns:
:class:`telegram.Message`: On success, if edit... | def edit_message_text(self, *args, **kwargs):
| if self.inline_message_id:
return self.bot.edit_message_text(inline_message_id=self.inline_message_id, *args, **kwargs)
else:
return self.bot.edit_message_text(chat_id=self.message.chat_id, message_id=self.message.message_id, *args, **kwargs)
|
'Shortcut for either::
bot.edit_message_caption(chat_id=update.callback_query.message.chat_id,
message_id=update.callback_query.message.message_id,
*args, **kwargs)
or::
bot.edit_message_caption(inline_message_id=update.callback_query.inline_message_id,
*args, **kwargs)
Returns:
:class:`telegram.Message`: On success, i... | def edit_message_caption(self, *args, **kwargs):
| if self.inline_message_id:
return self.bot.edit_message_caption(inline_message_id=self.inline_message_id, *args, **kwargs)
else:
return self.bot.edit_message_caption(chat_id=self.message.chat_id, message_id=self.message.message_id, *args, **kwargs)
|
'Shortcut for either::
bot.edit_message_replyMarkup(chat_id=update.callback_query.message.chat_id,
message_id=update.callback_query.message.message_id,
*args, **kwargs)
or::
bot.edit_message_reply_markup(inline_message_id=update.callback_query.inline_message_id,
*args, **kwargs)
Returns:
:class:`telegram.Message`: On s... | def edit_message_reply_markup(self, *args, **kwargs):
| if self.inline_message_id:
return self.bot.edit_message_reply_markup(inline_message_id=self.inline_message_id, *args, **kwargs)
else:
return self.bot.edit_message_reply_markup(chat_id=self.message.chat_id, message_id=self.message.message_id, *args, **kwargs)
|
'Get the singleton instance of this class.
Returns:
:class:`telegram.ext.Dispatcher`
Raises:
RuntimeError'
| @classmethod
def get_instance(cls):
| if (cls.__singleton is not None):
return cls.__singleton()
else:
raise RuntimeError('{} not initialized or multiple instances exist'.format(cls.__name__))
|
'Queue a function (with given args/kwargs) to be run asynchronously.
Args:
func (:obj:`callable`): The function to run in the thread.
*args (:obj:`tuple`, optional): Arguments to `func`.
**kwargs (:obj:`dict`, optional): Keyword arguments to `func`.
Returns:
Promise'
| def run_async(self, func, *args, **kwargs):
| promise = Promise(func, args, kwargs)
self.__async_queue.put(promise)
return promise
|
'Thread target of thread \'dispatcher\'. Runs in background and processes
the update queue.'
| def start(self):
| if self.running:
self.logger.warning('already running')
return
if self.__exception_event.is_set():
msg = 'reusing dispatcher after exception event is forbidden'
self.logger.error(msg)
raise TelegramError(msg)
self._init_async_threads(uuid4(), self... |
'Stops the thread.'
| def stop(self):
| if self.running:
self.__stop_event.set()
while self.running:
sleep(0.1)
self.__stop_event.clear()
threads = list(self.__async_threads)
total = len(threads)
for i in range(total):
self.__async_queue.put(None)
for (i, thr) in enumerate(threads):
self... |
'Processes a single update.
Args:
update (:obj:`str` | :class:`telegram.Update` | :class:`telegram.TelegramError`):
The update to process.'
| def process_update(self, update):
| if isinstance(update, TelegramError):
self.dispatch_error(None, update)
return
for group in self.groups:
try:
for handler in self.handlers[group]:
try:
if handler.check_update(update):
try:
... |
'Register a handler.
TL;DR: Order and priority counts. 0 or 1 handlers per group will be
used.
A handler must be an instance of a subclass of :class:`telegram.ext.Handler`. All handlers
are organized in groups with a numeric value. The default group is 0. All groups will be
evaluated for handling an update, but only 0 ... | def add_handler(self, handler, group=DEFAULT_GROUP):
| if (not isinstance(handler, Handler)):
raise TypeError('handler is not an instance of {0}'.format(Handler.__name__))
if (not isinstance(group, int)):
raise TypeError('group is not int')
if (group not in self.handlers):
self.handlers[group] = list()
... |
'Remove a handler from the specified group
Args:
handler (:class:`telegram.ext.Handler`): A Handler instance.
group (:obj:`object`, optional): The group identifier. Default is 0.'
| def remove_handler(self, handler, group=DEFAULT_GROUP):
| if (handler in self.handlers[group]):
self.handlers[group].remove(handler)
if (not self.handlers[group]):
del self.handlers[group]
self.groups.remove(group)
|
'Registers an error handler in the Dispatcher.
Args:
callback (:obj:`callable`): A function that takes ``Bot, Update, TelegramError`` as
arguments.'
| def add_error_handler(self, callback):
| self.error_handlers.append(callback)
|
'Removes an error handler.
Args:
callback (:obj:`callable`): The error handler to remove.'
| def remove_error_handler(self, callback):
| if (callback in self.error_handlers):
self.error_handlers.remove(callback)
|
'Dispatches an error.
Args:
update (:obj:`str` | :class:`telegram.Update` | None): The update that caused the error
error (:class:`telegram.TelegramError`): The Telegram error that was raised.'
| def dispatch_error(self, update, error):
| for callback in self.error_handlers:
callback(self.bot, update, error)
|
'Determines whether an update should be passed to this handlers :attr:`callback`.
Args:
update (:obj:`str`): An incomming command.
Returns:
:obj:`bool`'
| def check_update(self, update):
| return (isinstance(update, string_types) and bool(re.match(self.pattern, update)))
|
'Send the update to the :attr:`callback`.
Args:
update (:obj:`str`): An incomming command.
dispatcher (:class:`telegram.ext.Dispatcher`): Dispatcher that originated the command.'
| def handle_update(self, update, dispatcher):
| optional_args = self.collect_optional_args(dispatcher)
match = re.match(self.pattern, update)
if self.pass_groups:
optional_args['groups'] = match.groups()
if self.pass_groupdict:
optional_args['groupdict'] = match.groupdict()
return self.callback(dispatcher.bot, update, **optional_a... |
'Starts polling updates from Telegram.
Args:
poll_interval (:obj:`float`, optional): Time to wait between polling updates from
Telegram in seconds. Default is 0.0.
timeout (:obj:`float`, optional): Passed to :attr:`telegram.Bot.get_updates`.
clean (:obj:`bool`, optional): Whether to clean any pending updates on Telegra... | def start_polling(self, poll_interval=0.0, timeout=10, network_delay=None, clean=False, bootstrap_retries=0, read_latency=2.0, allowed_updates=None):
| if (network_delay is not None):
warnings.warn('network_delay is deprecated, use read_latency instead')
read_latency = network_delay
with self.__lock:
if (not self.running):
self.running = True
self.job_queue.start()
self._init_thread(sel... |
'Starts a small http server to listen for updates via webhook. If cert
and key are not provided, the webhook will be started directly on
http://listen:port/url_path, so SSL can be handled by another
application. Else, the webhook will be started on
https://listen:port/url_path
Args:
listen (:obj:`str`, optional): IP-Ad... | def start_webhook(self, listen='127.0.0.1', port=80, url_path='', cert=None, key=None, clean=False, bootstrap_retries=0, webhook_url=None, allowed_updates=None):
| with self.__lock:
if (not self.running):
self.running = True
self.job_queue.start()
(self._init_thread(self.dispatcher.start, 'dispatcher'),)
self._init_thread(self._start_webhook, 'updater', listen, port, url_path, cert, key, bootstrap_retries, clean, webhook... |
'Stops the polling/webhook thread, the dispatcher and the job queue.'
| def stop(self):
| self.job_queue.stop()
with self.__lock:
if (self.running or self.dispatcher.has_running_threads):
self.logger.debug('Stopping Updater and Dispatcher...')
self.running = False
self._stop_httpd()
self._stop_dispatcher()
self._join_thread... |
'Blocks until one of the signals are received and stops the updater.
Args:
stop_signals (:obj:`iterable`): Iterable containing signals from the signal module that
should be subscribed to. Updater.stop() will be called on receiving one of those
signals. Defaults to (``SIGINT``, ``SIGTERM``, ``SIGABRT``).'
| def idle(self, stop_signals=(SIGINT, SIGTERM, SIGABRT)):
| for sig in stop_signals:
signal(sig, self.signal_handler)
self.is_idle = True
while self.is_idle:
sleep(1)
|
'Determines whether an update should be passed to this handlers :attr:`callback`.
Args:
update (:class:`telegram.Update`): Incoming telegram update.
Returns:
:obj:`bool`'
| def check_update(self, update):
| if (isinstance(update, Update) and update.inline_query):
if self.pattern:
if update.inline_query.query:
match = re.match(self.pattern, update.inline_query.query)
return bool(match)
else:
return True
|
'Send the update to the :attr:`callback`.
Args:
update (:class:`telegram.Update`): Incoming telegram update.
dispatcher (:class:`telegram.ext.Dispatcher`): Dispatcher that originated the Update.'
| def handle_update(self, update, dispatcher):
| optional_args = self.collect_optional_args(dispatcher, update)
if self.pattern:
match = re.match(self.pattern, update.inline_query.query)
if self.pass_groups:
optional_args['groups'] = match.groups()
if self.pass_groupdict:
optional_args['groupdict'] = match.group... |
'Determines whether an update should be passed to this handlers :attr:`callback`.
Args:
update (:class:`telegram.Update`): Incoming telegram update.
Returns:
:obj:`bool`'
| def check_update(self, update):
| return (isinstance(update, Update) and update.shipping_query)
|
'Send the update to the :attr:`callback`.
Args:
update (:class:`telegram.Update`): Incoming telegram update.
dispatcher (:class:`telegram.ext.Dispatcher`): Dispatcher that originated the Update.'
| def handle_update(self, update, dispatcher):
| optional_args = self.collect_optional_args(dispatcher, update)
return self.callback(dispatcher.bot, update, **optional_args)
|
'Determines whether an update should be passed to this handlers :attr:`callback`.
Args:
update (:class:`telegram.Update`): Incoming telegram update.
Returns:
:obj:`bool`'
| def check_update(self, update):
| if (isinstance(update, Update) and update.callback_query):
if self.pattern:
if update.callback_query.data:
match = re.match(self.pattern, update.callback_query.data)
return bool(match)
else:
return True
|
'Send the update to the :attr:`callback`.
Args:
update (:class:`telegram.Update`): Incoming telegram update.
dispatcher (:class:`telegram.ext.Dispatcher`): Dispatcher that originated the Update.'
| def handle_update(self, update, dispatcher):
| optional_args = self.collect_optional_args(dispatcher, update)
if self.pattern:
match = re.match(self.pattern, update.callback_query.data)
if self.pass_groups:
optional_args['groups'] = match.groups()
if self.pass_groupdict:
optional_args['groupdict'] = match.grou... |
'Queue a new job.
Note:
This method is deprecated. Please use: :attr:`run_once`, :attr:`run_daily`
or :attr:`run_repeating` instead.
Args:
job (:class:`telegram.ext.Job`): The ``Job`` instance representing the new job.
next_t (:obj:`int` | :obj:`float` | :obj:`datetime.timedelta` | :obj:`datetime.datetime` | :obj:`date... | def put(self, job, next_t=None):
| warnings.warn("'JobQueue.put' is being deprecated, use 'JobQueue.run_once', 'JobQueue.run_daily' or 'JobQueue.run_repeating' instead")
if (job.job_queue is None):
job.job_queue = self
self._put(job, next_t=next_t)
|
'Creates a new ``Job`` that runs once and adds it to the queue.
Args:
callback (:obj:`callable`): The callback function that should be executed by the new
job. It should take ``bot, job`` as parameters, where ``job`` is the
:class:`telegram.ext.Job` instance. It can be used to access it\'s
``job.context`` or change it ... | def run_once(self, callback, when, context=None, name=None):
| job = Job(callback, repeat=False, context=context, name=name, job_queue=self)
self._put(job, next_t=when)
return job
|
'Creates a new ``Job`` that runs once and adds it to the queue.
Args:
callback (:obj:`callable`): The callback function that should be executed by the new
job. It should take ``bot, job`` as parameters, where ``job`` is the
:class:`telegram.ext.Job` instance. It can be used to access it\'s
``Job.context`` or change it ... | def run_repeating(self, callback, interval, first=None, context=None, name=None):
| job = Job(callback, interval=interval, repeat=True, context=context, name=name, job_queue=self)
self._put(job, next_t=first)
return job
|
'Creates a new ``Job`` that runs once and adds it to the queue.
Args:
callback (:obj:`callable`): The callback function that should be executed by the new
job. It should take ``bot, job`` as parameters, where ``job`` is the
:class:`telegram.ext.Job` instance. It can be used to access it\'s ``Job.context``
or change it ... | def run_daily(self, callback, time, days=Days.EVERY_DAY, context=None, name=None):
| job = Job(callback, interval=datetime.timedelta(days=1), repeat=True, days=days, context=context, name=name, job_queue=self)
self._put(job, next_t=time)
return job
|
'Run all jobs that are due and re-enqueue them with their interval.'
| def tick(self):
| now = time.time()
self.logger.debug('Ticking jobs with t=%f', now)
while True:
try:
(t, job) = self.queue.get(False)
except Empty:
break
self.logger.debug('Peeked at %s with t=%f', job.name, t)
if (t > now):
self.logger... |
'Starts the job_queue thread.'
| def start(self):
| self.__start_lock.acquire()
if (not self._running):
self._running = True
self.__start_lock.release()
self.__thread = Thread(target=self._main_loop, name='job_queue')
self.__thread.start()
self.logger.debug('%s thread started', self.__class__.__name__)
else:
... |
'Thread target of thread ``job_queue``. Runs in background and performs ticks on the job
queue.'
| def _main_loop(self):
| while self._running:
with self.__next_peek_lock:
tmout = ((self._next_peek - time.time()) if self._next_peek else None)
self._next_peek = None
self.__tick.clear()
self.__tick.wait(tmout)
if (not self._running):
break
self.tick()
sel... |
'Stops the thread.'
| def stop(self):
| with self.__start_lock:
self._running = False
self.__tick.set()
if (self.__thread is not None):
self.__thread.join()
|
'Returns a tuple of all jobs that are currently in the ``JobQueue``'
| def jobs(self):
| return tuple((job[1] for job in self.queue.queue if job))
|
'Executes the callback function.'
| def run(self, bot):
| self.callback(bot, self)
|
'Schedules this job for removal from the ``JobQueue``. It will be removed without executing
its callback function again.'
| def schedule_removal(self):
| self._remove.set()
|
':obj:`bool`: Whether this job is due to be removed.'
| @property
def removed(self):
| return self._remove.is_set()
|
':obj:`bool`: Whether this job is enabled.'
| @property
def enabled(self):
| return self._enabled.is_set()
|
':obj:`int` | :obj:`float` | :obj:`datetime.timedelta`: Optional. The interval in which the
job will run.'
| @property
def interval(self):
| return self._interval
|
':obj:`int`: The interval for this job in seconds.'
| @property
def interval_seconds(self):
| if isinstance(self.interval, datetime.timedelta):
return self.interval.total_seconds()
else:
return self.interval
|
':obj:`bool`: Optional. If this job should be periodically execute its callback function.'
| @property
def repeat(self):
| return self._repeat
|
'Tuple[:obj:`int`]: Optional. Defines on which days of the week the job should run.'
| @property
def days(self):
| return self._days
|
':class:`telegram.ext.JobQueue`: Optional. The ``JobQueue`` this job belongs to.'
| @property
def job_queue(self):
| return self._job_queue
|
'This method must be overwritten.
Args:
message (:class:`telegram.Message`): The message that is tested.
Returns:
:obj:`bool`'
| def filter(self, message):
| raise NotImplementedError
|
'Determines whether an update should be passed to this handlers :attr:`callback`.
Args:
update (:obj:`str`): An incomming command.
Returns:
:obj:`bool`'
| def check_update(self, update):
| return (isinstance(update, string_types) and update.startswith('/') and (update[1:].split(' ')[0] == self.command))
|
'Send the update to the :attr:`callback`.
Args:
update (:obj:`str`): An incomming command.
dispatcher (:class:`telegram.ext.Dispatcher`): Dispatcher that originated the command.'
| def handle_update(self, update, dispatcher):
| optional_args = self.collect_optional_args(dispatcher)
if self.pass_args:
optional_args['args'] = update.split()[1:]
return self.callback(dispatcher.bot, update, **optional_args)
|
'Determines whether an update should be passed to this handlers :attr:`callback`.
Args:
update (:class:`telegram.Update`): Incoming telegram update.
Returns:
:obj:`bool`'
| def check_update(self, update):
| if (isinstance(update, Update) and self._is_allowed_update(update)):
if (not self.filters):
res = True
else:
message = update.effective_message
if isinstance(self.filters, list):
res = any((func(message) for func in self.filters))
else:... |
'Send the update to the :attr:`callback`.
Args:
update (:class:`telegram.Update`): Incoming telegram update.
dispatcher (:class:`telegram.ext.Dispatcher`): Dispatcher that originated the Update.'
| def handle_update(self, update, dispatcher):
| optional_args = self.collect_optional_args(dispatcher, update)
return self.callback(dispatcher.bot, update, **optional_args)
|
'Determines whether an update should be handled by this conversationhandler, and if so in
which state the conversation currently is.
Args:
update (:class:`telegram.Update`): Incoming telegram update.
Returns:
:obj:`bool`'
| def check_update(self, update):
| if ((not isinstance(update, Update)) or update.channel_post or (self.per_chat and (update.inline_query or update.chosen_inline_result)) or (self.per_message and (not update.callback_query)) or (update.callback_query and self.per_chat and (not update.callback_query.message))):
return False
key = self._ge... |
'Send the update to the callback for the current state and Handler
Args:
update (:class:`telegram.Update`): Incoming telegram update.
dispatcher (:class:`telegram.ext.Dispatcher`): Dispatcher that originated the Update.'
| def handle_update(self, update, dispatcher):
| new_state = self.current_handler.handle_update(update, dispatcher)
self.update_state(new_state, self.current_conversation)
|
'Determines whether an update should be passed to this handlers :attr:`callback`.
Args:
update (:class:`telegram.Update`): Incoming telegram update.
Returns:
:obj:`bool`'
| def check_update(self, update):
| if (not self.strict):
return isinstance(update, self.type)
else:
return (type(update) is self.type)
|
'Send the update to the :attr:`callback`.
Args:
update (:class:`telegram.Update`): Incoming telegram update.
dispatcher (:class:`telegram.ext.Dispatcher`): Dispatcher that originated the Update.'
| def handle_update(self, update, dispatcher):
| optional_args = self.collect_optional_args(dispatcher)
return self.callback(dispatcher.bot, update, **optional_args)
|
'Determines whether an update should be passed to this handlers :attr:`callback`.
Args:
update (:class:`telegram.Update`): Incoming telegram update.
Returns:
:obj:`bool`'
| def check_update(self, update):
| if (isinstance(update, Update) and (update.message or (update.edited_message and self.allow_edited))):
message = (update.message or update.edited_message)
if message.text:
command = message.text[1:].split(' ')[0].split('@')
command.append(message.bot.username)
... |
'Send the update to the :attr:`callback`.
Args:
update (:class:`telegram.Update`): Incoming telegram update.
dispatcher (:class:`telegram.ext.Dispatcher`): Dispatcher that originated the Update.'
| def handle_update(self, update, dispatcher):
| optional_args = self.collect_optional_args(dispatcher, update)
message = (update.message or update.edited_message)
if self.pass_args:
optional_args['args'] = message.text.split()[1:]
return self.callback(dispatcher.bot, update, **optional_args)
|
'Do not use the method except for unthreaded testing purposes, the method normally is
automatically called by autostart argument .'
| def run(self):
| times = []
while True:
item = self._queue.get()
if self.__exit_req:
return
now = curtime()
t_delta = (now - self.time_limit)
if (times and (t_delta > times[(-1)])):
times = [now]
else:
times = [t for t in times if (t >= t_delta)... |
'Used to gently stop processor and shutdown its thread.
Args:
timeout (:obj:`float`): Indicates maximum time to wait for processor to stop and its
thread to exit. If timeout exceeds and processor has not stopped, method silently
returns. :attr:`is_alive` could be used afterwards to check the actual status.
``timeout`` ... | def stop(self, timeout=None):
| self.__exit_req = True
self._queue.put(None)
super(DelayQueue, self).join(timeout=timeout)
|
'Dummy exception handler which re-raises exception in thread. Could be possibly overwritten
by subclasses.'
| @staticmethod
def _default_exception_handler(exc):
| raise exc
|
'Used to process callbacks in throughput-limiting thread through queue.
Args:
func (:obj:`callable`): The actual function (or any callable) that is processed through
queue.
*args (:obj:`list`): Variable-length `func` arguments.
**kwargs (:obj:`dict`): Arbitrary keyword-arguments to `func`.'
| def __call__(self, func, *args, **kwargs):
| if ((not self.is_alive()) or self.__exit_req):
raise DelayQueueError('Could not process callback in stopped thread')
self._queue.put((func, args, kwargs))
|
'Method is used to manually start the ``MessageQueue`` processing.'
| def start(self):
| self._all_delayq.start()
self._group_delayq.start()
|
'Processes callables in troughput-limiting queues to avoid hitting limits (specified with
:attr:`burst_limit` and :attr:`time_limit`.
Args:
promise (:obj:`callable`): Mainly the ``telegram.utils.promise.Promise`` (see Notes for
other callables), that is processed in delay queues.
is_group_msg (:obj:`bool`, optional): D... | def __call__(self, promise, is_group_msg=False):
| if (not is_group_msg):
self._all_delayq(promise)
else:
self._group_delayq(self._all_delayq, promise)
return promise
|
'Determines whether an update should be passed to this handlers :attr:`callback`.
Args:
update (:class:`telegram.Update`): Incoming telegram update.
Returns:
:obj:`bool`'
| def check_update(self, update):
| return (isinstance(update, Update) and update.chosen_inline_result)
|
'Send the update to the :attr:`callback`.
Args:
update (:class:`telegram.Update`): Incoming telegram update.
dispatcher (:class:`telegram.ext.Dispatcher`): Dispatcher that originated the Update.'
| def handle_update(self, update, dispatcher):
| optional_args = self.collect_optional_args(dispatcher, update)
return self.callback(dispatcher.bot, update, **optional_args)
|
'Determines whether an update should be passed to this handlers :attr:`callback`.
Args:
update (:class:`telegram.Update`): Incoming telegram update.
Returns:
:obj:`bool`'
| def check_update(self, update):
| return (isinstance(update, Update) and update.pre_checkout_query)
|
'Send the update to the :attr:`callback`.
Args:
update (:class:`telegram.Update`): Incoming telegram update.
dispatcher (:class:`telegram.ext.Dispatcher`): Dispatcher that originated the Update.'
| def handle_update(self, update, dispatcher):
| optional_args = self.collect_optional_args(dispatcher, update)
return self.callback(dispatcher.bot, update, **optional_args)
|
'Determines whether an update should be passed to this handlers :attr:`callback`.
Args:
update (:class:`telegram.Update`): Incoming telegram update.
Returns:
:obj:`bool`'
| def check_update(self, update):
| if ((not isinstance(update, Update)) and (not update.effective_message)):
return False
if (any([(self.message_updates and update.message), (self.edited_updates and update.edited_message), (self.channel_post_updates and update.channel_post)]) and update.effective_message.text):
match = re.match(s... |
'Send the update to the :attr:`callback`.
Args:
update (:class:`telegram.Update`): Incoming telegram update.
dispatcher (:class:`telegram.ext.Dispatcher`): Dispatcher that originated the Update.'
| def handle_update(self, update, dispatcher):
| optional_args = self.collect_optional_args(dispatcher, update)
match = re.match(self.pattern, update.effective_message.text)
if self.pass_groups:
optional_args['groups'] = match.groups()
if self.pass_groupdict:
optional_args['groupdict'] = match.groupdict()
return self.callback(dispa... |
'This method is called to determine if an update should be handled by
this handler instance. It should always be overridden.
Args:
update (:obj:`str` | :class:`telegram.Update`): The update to be tested.
Returns:
:obj:`bool`'
| def check_update(self, update):
| raise NotImplementedError
|
'This method is called if it was determined that an update should indeed
be handled by this instance. It should also be overridden, but in most
cases call ``self.callback(dispatcher.bot, update)``, possibly along with
optional arguments. To work with the ``ConversationHandler``, this method should return the
value retu... | def handle_update(self, update, dispatcher):
| raise NotImplementedError
|
'Prepares the optional arguments that are the same for all types of
handlers.
Args:
dispatcher (:class:`telegram.ext.Dispatcher`): The dispatcher.'
| def collect_optional_args(self, dispatcher, update=None):
| 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
if (self.pass_user_data or self.pass_chat_data):
chat = update.effective_chat
user = update.... |
'Shortcut for::
bot.answer_shipping_query(update.shipping_query.id, *args, **kwargs)
Args:
ok (:obj:`bool`): Specify True if delivery to the specified address is possible and
False if there are any problems (for example, if delivery to the specified address
is not possible).
shipping_options (List[:class:`telegram.Ship... | def answer(self, *args, **kwargs):
| return self.bot.answer_shipping_query(self.id, *args, **kwargs)
|
'Shortcut for::
bot.answer_pre_checkout_query(update.pre_checkout_query.id, *args, **kwargs)
Args:
ok (:obj:`bool`): Specify True if everything is alright (goods are available, etc.) and
the bot is ready to proceed with the order. Use False if there are any problems.
error_message (:obj:`str`, optional): Required if ok... | def answer(self, *args, **kwargs):
| return self.bot.answer_pre_checkout_query(self.id, *args, **kwargs)
|
'Shortcut for::
bot.answer_inline_query(update.inline_query.id, *args, **kwargs)
Args:
results (List[:class:`telegram.InlineQueryResult`]): A list of results for the inline
query.
cache_time (:obj:`int`, optional): The maximum amount of time in seconds that the
result of the inline query may be cached on the server. De... | def answer(self, *args, **kwargs):
| return self.bot.answer_inline_query(self.id, *args, **kwargs)
|
'Returns the text from a given :class:`telegram.MessageEntity`.
Note:
This method is present because Telegram calculates the offset and length in
UTF-16 codepoint pairs, which some versions of Python don\'t handle automatically.
(That is, you can\'t just slice ``Message.text`` with the offset and length.)
Args:
entity ... | def parse_text_entity(self, entity):
| if (sys.maxunicode == 65535):
return self.text[entity.offset:(entity.offset + entity.length)]
else:
entity_text = self.text.encode('utf-16-le')
entity_text = entity_text[(entity.offset * 2):((entity.offset + entity.length) * 2)]
return entity_text.decode('utf-16-le')
|
'Returns a :obj:`dict` that maps :class:`telegram.MessageEntity` to :obj:`str`.
It contains entities from this message filtered by their ``type`` attribute as the key, and
the text that each entity belongs to as the value of the :obj:`dict`.
Note:
This method should always be used instead of the :attr:`text_entities` a... | def parse_text_entities(self, types=None):
| if (types is None):
types = MessageEntity.ALL_TYPES
return {entity: self.parse_text_entity(entity) for entity in self.text_entities if (entity.type in types)}
|
':obj:`int`: Shortcut for :attr:`telegram.Chat.id` for :attr:`chat`.'
| @property
def chat_id(self):
| return self.chat.id
|
':class:`telegram.Audio`
or :class:`telegram.Contact`
or :class:`telegram.Document`
or :class:`telegram.Game`
or :class:`telegram.Invoice`
or :class:`telegram.Location`
or List[:class:`telegram.PhotoSize`]
or :class:`telegram.Sticker`
or :class:`telegram.SuccessfulPayment`
or :class:`telegram.Venue`
or :class:`telegram... | @property
def effective_attachment(self):
| if (self._effective_attachment is not _UNDEFINED):
return self._effective_attachment
for i in (self.audio, self.game, self.document, self.photo, self.sticker, self.video, self.voice, self.video_note, self.contact, self.location, self.venue, self.invoice, self.successful_payment):
if (i is not No... |
'Modify kwargs for replying with or without quoting'
| def _quote(self, kwargs):
| if ('reply_to_message_id' in kwargs):
if ('quote' in kwargs):
del kwargs['quote']
elif ('quote' in kwargs):
if kwargs['quote']:
kwargs['reply_to_message_id'] = self.message_id
del kwargs['quote']
elif (self.chat.type != Chat.PRIVATE):
kwargs['reply_to_... |
'Shortcut for::
bot.send_message(update.message.chat_id, *args, **kwargs)
Keyword Args:
quote (:obj:`bool`, optional): If set to ``True``, the message is sent as an actual
reply to this message. If ``reply_to_message_id`` is passed in ``kwargs``, this
parameter will be ignored. Default: ``True`` in group chats and ``Fa... | def reply_text(self, *args, **kwargs):
| self._quote(kwargs)
return self.bot.send_message(self.chat_id, *args, **kwargs)
|
'Shortcut for::
bot.send_photo(update.message.chat_id, *args, **kwargs)
Keyword Args:
quote (:obj:`bool`, optional): If set to ``True``, the photo is sent as an actual reply
to this message. If ``reply_to_message_id`` is passed in ``kwargs``, this parameter
will be ignored. Default: ``True`` in group chats and ``False`... | def reply_photo(self, *args, **kwargs):
| self._quote(kwargs)
return self.bot.send_photo(self.chat_id, *args, **kwargs)
|
'Shortcut for::
bot.send_audio(update.message.chat_id, *args, **kwargs)
Keyword Args:
quote (:obj:`bool`, optional): If set to ``True``, the photo is sent as an actual reply
to this message. If ``reply_to_message_id`` is passed in ``kwargs``, this parameter
will be ignored. Default: ``True`` in group chats and ``False`... | def reply_audio(self, *args, **kwargs):
| self._quote(kwargs)
return self.bot.send_audio(self.chat_id, *args, **kwargs)
|
'Shortcut for::
bot.send_document(update.message.chat_id, *args, **kwargs)
Keyword Args:
quote (:obj:`bool`, optional): If set to ``True``, the photo is sent as an actual reply
to this message. If ``reply_to_message_id`` is passed in ``kwargs``, this parameter
will be ignored. Default: ``True`` in group chats and ``Fal... | def reply_document(self, *args, **kwargs):
| self._quote(kwargs)
return self.bot.send_document(self.chat_id, *args, **kwargs)
|
'Shortcut for::
bot.send_sticker(update.message.chat_id, *args, **kwargs)
Keyword Args:
quote (:obj:`bool`, optional): If set to ``True``, the photo is sent as an actual reply
to this message. If ``reply_to_message_id`` is passed in ``kwargs``, this parameter
will be ignored. Default: ``True`` in group chats and ``Fals... | def reply_sticker(self, *args, **kwargs):
| self._quote(kwargs)
return self.bot.send_sticker(self.chat_id, *args, **kwargs)
|
'Shortcut for::
bot.send_video(update.message.chat_id, *args, **kwargs)
Keyword Args:
quote (:obj:`bool`, optional): If set to ``True``, the photo is sent as an actual reply
to this message. If ``reply_to_message_id`` is passed in ``kwargs``, this parameter
will be ignored. Default: ``True`` in group chats and ``False`... | def reply_video(self, *args, **kwargs):
| self._quote(kwargs)
return self.bot.send_video(self.chat_id, *args, **kwargs)
|
'Shortcut for::
bot.send_video_note(update.message.chat_id, *args, **kwargs)
Keyword Args:
quote (:obj:`bool`, optional): If set to ``True``, the photo is sent as an actual reply
to this message. If ``reply_to_message_id`` is passed in ``kwargs``, this parameter
will be ignored. Default: ``True`` in group chats and ``F... | def reply_video_note(self, *args, **kwargs):
| self._quote(kwargs)
return self.bot.send_video_note(self.chat_id, *args, **kwargs)
|
'Shortcut for::
bot.send_voice(update.message.chat_id, *args, **kwargs)
Keyword Args:
quote (:obj:`bool`, optional): If set to ``True``, the photo is sent as an actual reply
to this message. If ``reply_to_message_id`` is passed in ``kwargs``, this parameter
will be ignored. Default: ``True`` in group chats and ``False`... | def reply_voice(self, *args, **kwargs):
| self._quote(kwargs)
return self.bot.send_voice(self.chat_id, *args, **kwargs)
|
'Shortcut for::
bot.send_location(update.message.chat_id, *args, **kwargs)
Keyword Args:
quote (:obj:`bool`, optional): If set to ``True``, the photo is sent as an actual reply
to this message. If ``reply_to_message_id`` is passed in ``kwargs``, this parameter
will be ignored. Default: ``True`` in group chats and ``Fal... | def reply_location(self, *args, **kwargs):
| self._quote(kwargs)
return self.bot.send_location(self.chat_id, *args, **kwargs)
|
'Shortcut for::
bot.send_venue(update.message.chat_id, *args, **kwargs)
Keyword Args:
quote (:obj:`bool`, optional): If set to ``True``, the photo is sent as an actual reply
to this message. If ``reply_to_message_id`` is passed in ``kwargs``, this parameter
will be ignored. Default: ``True`` in group chats and ``False`... | def reply_venue(self, *args, **kwargs):
| self._quote(kwargs)
return self.bot.send_venue(self.chat_id, *args, **kwargs)
|
'Shortcut for::
bot.send_contact(update.message.chat_id, *args, **kwargs)
Keyword Args:
quote (:obj:`bool`, optional): If set to ``True``, the photo is sent as an actual reply
to this message. If ``reply_to_message_id`` is passed in ``kwargs``, this parameter
will be ignored. Default: ``True`` in group chats and ``Fals... | def reply_contact(self, *args, **kwargs):
| self._quote(kwargs)
return self.bot.send_contact(self.chat_id, *args, **kwargs)
|
'Shortcut for::
bot.forward_message(chat_id=chat_id,
from_chat_id=update.message.chat_id,
disable_notification=disable_notification,
message_id=update.message.message_id)
Returns:
:class:`telegram.Message`: On success, instance representing the message forwarded.'
| def forward(self, chat_id, disable_notification=False):
| return self.bot.forward_message(chat_id=chat_id, from_chat_id=self.chat_id, disable_notification=disable_notification, message_id=self.message_id)
|
'Shortcut for::
bot.edit_message_text(chat_id=message.chat_id,
message_id=message.message_id,
*args,
**kwargs)
Note:
You can only edit messages that the bot sent itself,
therefore this method can only be used on the
return value of the ``bot.send_*`` family of methods..
Returns:
:class:`telegram.Message`: On success, i... | def edit_text(self, *args, **kwargs):
| return self.bot.edit_message_text(chat_id=self.chat_id, message_id=self.message_id, *args, **kwargs)
|
'Shortcut for::
bot.edit_message_caption(chat_id=message.chat_id,
message_id=message.message_id,
*args,
**kwargs)
Note:
You can only edit messages that the bot sent itself,
therefore this method can only be used on the
return value of the ``bot.send_*`` family of methods.
Returns:
:class:`telegram.Message`: On success,... | def edit_caption(self, *args, **kwargs):
| return self.bot.edit_message_caption(chat_id=self.chat_id, message_id=self.message_id, *args, **kwargs)
|
'Shortcut for::
bot.edit_message_reply_markup(chat_id=message.chat_id,
message_id=message.message_id,
*args,
**kwargs)
Note:
You can only edit messages that the bot sent itself,
therefore this method can only be used on the
return value of the ``bot.send_*`` family of methods.
Returns:
:class:`telegram.Message`: On suc... | def edit_reply_markup(self, *args, **kwargs):
| return self.bot.edit_message_reply_markup(chat_id=self.chat_id, message_id=self.message_id, *args, **kwargs)
|
'Shortcut for::
bot.delete_message(chat_id=message.chat_id,
message_id=message.message_id,
*args,
**kwargs)
Returns:
:obj:`bool`: On success, ``True`` is returned.'
| def delete(self, *args, **kwargs):
| return self.bot.delete_message(chat_id=self.chat_id, message_id=self.message_id, *args, **kwargs)
|
'Returns the text from a given :class:`telegram.MessageEntity`.
Note:
This method is present because Telegram calculates the offset and length in
UTF-16 codepoint pairs, which some versions of Python don\'t handle automatically.
(That is, you can\'t just slice ``Message.text`` with the offset and length.)
Args:
entity ... | def parse_entity(self, entity):
| if (sys.maxunicode == 65535):
return self.text[entity.offset:(entity.offset + entity.length)]
else:
entity_text = self.text.encode('utf-16-le')
entity_text = entity_text[(entity.offset * 2):((entity.offset + entity.length) * 2)]
return entity_text.decode('utf-16-le')
|
'Returns a :obj:`dict` that maps :class:`telegram.MessageEntity` to :obj:`str`.
It contains entities from this message filtered by their
:attr:`telegram.MessageEntity.type` attribute as the key, and the text that each entity
belongs to as the value of the :obj:`dict`.
Note:
This method should always be used instead of ... | def parse_entities(self, types=None):
| if (types is None):
types = MessageEntity.ALL_TYPES
return {entity: self.parse_entity(entity) for entity in self.entities if (entity.type in types)}
|
'Creates an HTML-formatted string from the markup entities found in the message.
Use this if you want to retrieve the message text with the entities formatted as HTML in
the same way the original message was formatted.
Returns:
:obj:`str`: Message text with entities formatted as HTML.'
| @property
def text_html(self):
| return self._text_html(urled=False)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.