Co-authored-by: Poolitzer <25934244+Poolitzer@users.noreply.github.com>
Co-authored-by: Bas ten Berge <bas+github@tenberge-ict.nl>
Co-authored-by: Harshil <ilovebhagwan@gmail.com>
This commit is contained in:
Bibo-Joshi 2021-06-06 12:16:23 +02:00 committed by GitHub
parent 8531a7a40c
commit cf4d3cae01
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
32 changed files with 144 additions and 146 deletions

View file

@ -3,6 +3,6 @@ contact_links:
- name: Telegram Group
url: https://telegram.me/pythontelegrambotgroup
about: Questions asked on the group usually get answered faster.
- name: IRC Channel
url: https://webchat.freenode.net/?channels=##python-telegram-bot
about: In case you are unable to join our group due to Telegram restrictions, you can use our IRC channel
- name: GitHub Discussions
url: https://github.com/python-telegram-bot/python-telegram-bot/discussions
about: For getting answers to usage on GitHub, Discussions is even better than this bug tracker :)

View file

@ -12,7 +12,7 @@ Hey there, you have a question? We are happy to answer. Please make sure no simi
To make it easier for us to help you, please read this article https://git.io/JURJO and try to follow the template below as closely as possible.
Please mind that there is also a users' Telegram group at https://t.me/pythontelegrambotgroup for questions about the library. Questions asked there might be answered quicker than here. In case you are unable to join our group due to Telegram restrictions, you can use our IRC channel at https://webchat.freenode.net/?channels=##python-telegram-bot to participate in the group.
Please mind that there is also a users' Telegram group at https://t.me/pythontelegrambotgroup for questions about the library. Questions asked there might be answered quicker than here. Moreover, GitHub Discussions at https://git.io/JG3rk offer a slightly better format to discuss usage questions.
-->
### Issue I am facing

View file

@ -63,10 +63,6 @@ We have a vibrant community of developers helping each other in our `Telegram gr
:target: https://telegram.me/pythontelegrambotgroup
:alt: Telegram Group
.. image:: https://img.shields.io/badge/IRC-Channel-blue.svg
:target: https://webchat.freenode.net/?channels=##python-telegram-bot
:alt: IRC Bridge
=================
Table of contents
=================
@ -97,7 +93,7 @@ Introduction
This library provides a pure Python interface for the
`Telegram Bot API <https://core.telegram.org/bots/api>`_.
It's compatible with Python versions 3.6+. PTB might also work on `PyPy <http://pypy.org/>`_, though there have been a lot of issues before. Hence, PyPy is not officially supported.
It's compatible with Python versions 3.6.2+. PTB might also work on `PyPy <http://pypy.org/>`_, though there have been a lot of issues before. Hence, PyPy is not officially supported.
In addition to the pure API implementation, this library features a number of high-level classes to
make the development of bots easy and straightforward. These classes are contained in the
@ -219,13 +215,11 @@ You can get help in several ways:
1. We have a vibrant community of developers helping each other in our `Telegram group <https://telegram.me/pythontelegrambotgroup>`_. Join us!
2. In case you are unable to join our group due to Telegram restrictions, you can use our `IRC channel <https://webchat.freenode.net/?channels=##python-telegram-bot>`_.
2. Report bugs, request new features or ask questions by `creating an issue <https://github.com/python-telegram-bot/python-telegram-bot/issues/new/choose>`_ or `a discussion <https://github.com/python-telegram-bot/python-telegram-bot/discussions/new>`_.
3. Report bugs, request new features or ask questions by `creating an issue <https://github.com/python-telegram-bot/python-telegram-bot/issues/new/choose>`_ or `a discussion <https://github.com/python-telegram-bot/python-telegram-bot/discussions/new>`_.
3. Our `Wiki pages <https://github.com/python-telegram-bot/python-telegram-bot/wiki/>`_ offer a growing amount of resources.
4. Our `Wiki pages <https://github.com/python-telegram-bot/python-telegram-bot/wiki/>`_ offer a growing amount of resources.
5. You can even ask for help on Stack Overflow using the `python-telegram-bot tag <https://stackoverflow.com/questions/tagged/python-telegram-bot>`_.
4. You can even ask for help on Stack Overflow using the `python-telegram-bot tag <https://stackoverflow.com/questions/tagged/python-telegram-bot>`_.
============

View file

@ -63,10 +63,6 @@ We have a vibrant community of developers helping each other in our `Telegram gr
:target: https://telegram.me/pythontelegrambotgroup
:alt: Telegram Group
.. image:: https://img.shields.io/badge/IRC-Channel-blue.svg
:target: https://webchat.freenode.net/?channels=##python-telegram-bot
:alt: IRC Bridge
=================
Table of contents
=================
@ -95,7 +91,7 @@ Introduction
This library provides a pure Python, lightweight interface for the
`Telegram Bot API <https://core.telegram.org/bots/api>`_.
It's compatible with Python versions 3.6+. PTB-Raw might also work on `PyPy <http://pypy.org/>`_, though there have been a lot of issues before. Hence, PyPy is not officially supported.
It's compatible with Python versions 3.6.2+. PTB-Raw might also work on `PyPy <http://pypy.org/>`_, though there have been a lot of issues before. Hence, PyPy is not officially supported.
``python-telegram-bot-raw`` is part of the `python-telegram-bot <https://python-telegram-bot.org>`_ ecosystem and provides the pure API functionality extracted from PTB. It therefore does *not* have independent release schedules, changelogs or documentation. Please consult the PTB resources.
@ -202,13 +198,11 @@ You can get help in several ways:
1. We have a vibrant community of developers helping each other in our `Telegram group <https://telegram.me/pythontelegrambotgroup>`_. Join us!
2. In case you are unable to join our group due to Telegram restrictions, you can use our `IRC channel <https://webchat.freenode.net/?channels=##python-telegram-bot>`_.
2. Report bugs, request new features or ask questions by `creating an issue <https://github.com/python-telegram-bot/python-telegram-bot/issues/new/choose>`_ or `a discussion <https://github.com/python-telegram-bot/python-telegram-bot/discussions/new>`_.
3. Report bugs, request new features or ask questions by `creating an issue <https://github.com/python-telegram-bot/python-telegram-bot/issues/new/choose>`_ or `a discussion <https://github.com/python-telegram-bot/python-telegram-bot/discussions/new>`_.
3. Our `Wiki pages <https://github.com/python-telegram-bot/python-telegram-bot/wiki/>`_ offer a growing amount of resources.
4. Our `Wiki pages <https://github.com/python-telegram-bot/python-telegram-bot/wiki/>`_ offer a growing amount of resources.
5. You can even ask for help on Stack Overflow using the `python-telegram-bot tag <https://stackoverflow.com/questions/tagged/python-telegram-bot>`_.
4. You can even ask for help on Stack Overflow using the `python-telegram-bot tag <https://stackoverflow.com/questions/tagged/python-telegram-bot>`_.
============
Contributing

View file

@ -4,6 +4,8 @@ In this folder are small examples to show what a bot written with `python-telegr
All examples are licensed under the [CC0 License](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/LICENSE.txt) and are therefore fully dedicated to the public domain. You can use them as the base for your own bots without worrying about copyrights.
Do note that we ignore one pythonic convention. Best practice would dictate, in many handler callbacks function signatures, to replace the argument `context` with an underscore, since `context` is an unused local variable in those callbacks. However, since these are examples and not having a name for that argument confuses beginners, we decided to have it present.
### [`echobot.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/echobot.py)
This is probably the base for most of the bots made with `python-telegram-bot`. It simply replies to each text message with a message that contains the same text.

View file

@ -1,5 +1,5 @@
#!/usr/bin/env python
# pylint: disable=C0116
# pylint: disable=C0116,W0613
# This program is dedicated to the public domain under the CC0 license.
"""
@ -114,7 +114,7 @@ def show_chats(update: Update, context: CallbackContext) -> None:
update.effective_message.reply_text(text)
def greet_chat_members(update: Update, _: CallbackContext) -> None:
def greet_chat_members(update: Update, context: CallbackContext) -> None:
"""Greets new users in chats and announces when someone leaves"""
result = extract_status_change(update.chat_member)
if result is None:
@ -152,11 +152,9 @@ def main() -> None:
dispatcher.add_handler(ChatMemberHandler(greet_chat_members, ChatMemberHandler.CHAT_MEMBER))
# Start the Bot
# We pass 'allowed_updates' to *only* handle updates with '(my_)chat_member' or 'message'
# If you want to handle *all* updates, pass Update.ALL_TYPES
updater.start_polling(
allowed_updates=[Update.MESSAGE, Update.CHAT_MEMBER, Update.MY_CHAT_MEMBER]
)
# We pass 'allowed_updates' handle *all* updates including `chat_member` updates
# To reset this, simply pass `allowed_updates=[]`
updater.start_polling(allowed_updates=Update.ALL_TYPES)
# Run the bot until you press Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT. This should be used most of the time, since

View file

@ -1,5 +1,5 @@
#!/usr/bin/env python
# pylint: disable=C0116
# pylint: disable=C0116,W0613
# This program is dedicated to the public domain under the CC0 license.
"""
@ -36,7 +36,7 @@ logger = logging.getLogger(__name__)
GENDER, PHOTO, LOCATION, BIO = range(4)
def start(update: Update, _: CallbackContext) -> int:
def start(update: Update, context: CallbackContext) -> int:
"""Starts the conversation and asks the user about their gender."""
reply_keyboard = [['Boy', 'Girl', 'Other']]
@ -50,7 +50,7 @@ def start(update: Update, _: CallbackContext) -> int:
return GENDER
def gender(update: Update, _: CallbackContext) -> int:
def gender(update: Update, context: CallbackContext) -> int:
"""Stores the selected gender and asks for a photo."""
user = update.message.from_user
logger.info("Gender of %s: %s", user.first_name, update.message.text)
@ -63,7 +63,7 @@ def gender(update: Update, _: CallbackContext) -> int:
return PHOTO
def photo(update: Update, _: CallbackContext) -> int:
def photo(update: Update, context: CallbackContext) -> int:
"""Stores the photo and asks for a location."""
user = update.message.from_user
photo_file = update.message.photo[-1].get_file()
@ -76,7 +76,7 @@ def photo(update: Update, _: CallbackContext) -> int:
return LOCATION
def skip_photo(update: Update, _: CallbackContext) -> int:
def skip_photo(update: Update, context: CallbackContext) -> int:
"""Skips the photo and asks for a location."""
user = update.message.from_user
logger.info("User %s did not send a photo.", user.first_name)
@ -87,7 +87,7 @@ def skip_photo(update: Update, _: CallbackContext) -> int:
return LOCATION
def location(update: Update, _: CallbackContext) -> int:
def location(update: Update, context: CallbackContext) -> int:
"""Stores the location and asks for some info about the user."""
user = update.message.from_user
user_location = update.message.location
@ -101,7 +101,7 @@ def location(update: Update, _: CallbackContext) -> int:
return BIO
def skip_location(update: Update, _: CallbackContext) -> int:
def skip_location(update: Update, context: CallbackContext) -> int:
"""Skips the location and asks for info about the user."""
user = update.message.from_user
logger.info("User %s did not send a location.", user.first_name)
@ -112,7 +112,7 @@ def skip_location(update: Update, _: CallbackContext) -> int:
return BIO
def bio(update: Update, _: CallbackContext) -> int:
def bio(update: Update, context: CallbackContext) -> int:
"""Stores the info about the user and ends the conversation."""
user = update.message.from_user
logger.info("Bio of %s: %s", user.first_name, update.message.text)
@ -121,7 +121,7 @@ def bio(update: Update, _: CallbackContext) -> int:
return ConversationHandler.END
def cancel(update: Update, _: CallbackContext) -> int:
def cancel(update: Update, context: CallbackContext) -> int:
"""Cancels and ends the conversation."""
user = update.message.from_user
logger.info("User %s canceled the conversation.", user.first_name)

View file

@ -1,5 +1,5 @@
#!/usr/bin/env python
# pylint: disable=C0116
# pylint: disable=C0116,W0613
# This program is dedicated to the public domain under the CC0 license.
"""
@ -50,7 +50,7 @@ def facts_to_str(user_data: Dict[str, str]) -> str:
return "\n".join(facts).join(['\n', '\n'])
def start(update: Update, _: CallbackContext) -> int:
def start(update: Update, context: CallbackContext) -> int:
"""Start the conversation and ask user for input."""
update.message.reply_text(
"Hi! My name is Doctor Botter. I will hold a more complex conversation with you. "
@ -70,7 +70,7 @@ def regular_choice(update: Update, context: CallbackContext) -> int:
return TYPING_REPLY
def custom_choice(update: Update, _: CallbackContext) -> int:
def custom_choice(update: Update, context: CallbackContext) -> int:
"""Ask the user for a description of a custom category."""
update.message.reply_text(
'Alright, please send me the category first, for example "Most impressive skill"'

View file

@ -1,5 +1,5 @@
#!/usr/bin/env python
# pylint: disable=C0116
# pylint: disable=C0116,W0613
# This program is dedicated to the public domain under the CC0 license.
"""Bot that explains Telegram's "Deep Linking Parameters" functionality.
@ -78,7 +78,7 @@ def deep_linked_level_2(update: Update, context: CallbackContext) -> None:
update.message.reply_text(text, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True)
def deep_linked_level_3(update: Update, _: CallbackContext) -> None:
def deep_linked_level_3(update: Update, context: CallbackContext) -> None:
"""Reached through the USING_ENTITIES payload"""
update.message.reply_text(
"It is also possible to make deep-linking using InlineKeyboardButtons.",

View file

@ -1,5 +1,5 @@
#!/usr/bin/env python
# pylint: disable=C0116
# pylint: disable=C0116,W0613
# This program is dedicated to the public domain under the CC0 license.
"""
@ -30,7 +30,7 @@ logger = logging.getLogger(__name__)
# Define a few command handlers. These usually take the two arguments update and
# context.
def start(update: Update, _: CallbackContext) -> None:
def start(update: Update, context: CallbackContext) -> None:
"""Send a message when the command /start is issued."""
user = update.effective_user
update.message.reply_markdown_v2(
@ -39,12 +39,12 @@ def start(update: Update, _: CallbackContext) -> None:
)
def help_command(update: Update, _: CallbackContext) -> None:
def help_command(update: Update, context: CallbackContext) -> None:
"""Send a message when the command /help is issued."""
update.message.reply_text('Help!')
def echo(update: Update, _: CallbackContext) -> None:
def echo(update: Update, context: CallbackContext) -> None:
"""Echo the user message."""
update.message.reply_text(update.message.text)

View file

@ -1,5 +1,5 @@
#!/usr/bin/env python
# pylint: disable=C0116
# pylint: disable=C0116,W0613
# This program is dedicated to the public domain under the CC0 license.
"""This is a very simple example on how one could implement a custom error handler."""
@ -51,12 +51,12 @@ def error_handler(update: object, context: CallbackContext) -> None:
context.bot.send_message(chat_id=DEVELOPER_CHAT_ID, text=message, parse_mode=ParseMode.HTML)
def bad_command(_: Update, context: CallbackContext) -> None:
def bad_command(update: Update, context: CallbackContext) -> None:
"""Raise an error to trigger the error handler."""
context.bot.wrong_method_name() # type: ignore[attr-defined]
def start(update: Update, _: CallbackContext) -> None:
def start(update: Update, context: CallbackContext) -> None:
"""Displays info on how to trigger an error."""
update.effective_message.reply_html(
'Use /bad_command to cause an error.\n'

View file

@ -1,5 +1,5 @@
#!/usr/bin/env python
# pylint: disable=C0116
# pylint: disable=C0116,W0613
# This program is dedicated to the public domain under the CC0 license.
"""
@ -29,17 +29,17 @@ logger = logging.getLogger(__name__)
# Define a few command handlers. These usually take the two arguments update and
# context. Error handlers also receive the raised TelegramError object in error.
def start(update: Update, _: CallbackContext) -> None:
def start(update: Update, context: CallbackContext) -> None:
"""Send a message when the command /start is issued."""
update.message.reply_text('Hi!')
def help_command(update: Update, _: CallbackContext) -> None:
def help_command(update: Update, context: CallbackContext) -> None:
"""Send a message when the command /help is issued."""
update.message.reply_text('Help!')
def inlinequery(update: Update, _: CallbackContext) -> None:
def inlinequery(update: Update, context: CallbackContext) -> None:
"""Handle the inline query."""
query = update.inline_query.query

View file

@ -1,5 +1,5 @@
#!/usr/bin/env python
# pylint: disable=C0116
# pylint: disable=C0116,W0613
# This program is dedicated to the public domain under the CC0 license.
"""
@ -17,7 +17,7 @@ logging.basicConfig(
logger = logging.getLogger(__name__)
def start(update: Update, _: CallbackContext) -> None:
def start(update: Update, context: CallbackContext) -> None:
"""Sends a message with three inline buttons attached."""
keyboard = [
[
@ -32,7 +32,7 @@ def start(update: Update, _: CallbackContext) -> None:
update.message.reply_text('Please choose:', reply_markup=reply_markup)
def button(update: Update, _: CallbackContext) -> None:
def button(update: Update, context: CallbackContext) -> None:
"""Parses the CallbackQuery and updates the message text."""
query = update.callback_query
@ -43,7 +43,7 @@ def button(update: Update, _: CallbackContext) -> None:
query.edit_message_text(text=f"Selected option: {query.data}")
def help_command(update: Update, _: CallbackContext) -> None:
def help_command(update: Update, context: CallbackContext) -> None:
"""Displays info on how to use the bot."""
update.message.reply_text("Use /start to test this bot.")

View file

@ -1,5 +1,5 @@
#!/usr/bin/env python
# pylint: disable=C0116
# pylint: disable=C0116,W0613
# This program is dedicated to the public domain under the CC0 license.
"""Simple inline keyboard bot with multiple CallbackQueryHandlers.
@ -37,7 +37,7 @@ FIRST, SECOND = range(2)
ONE, TWO, THREE, FOUR = range(4)
def start(update: Update, _: CallbackContext) -> int:
def start(update: Update, context: CallbackContext) -> int:
"""Send message on `/start`."""
# Get user that sent /start and log his name
user = update.message.from_user
@ -59,7 +59,7 @@ def start(update: Update, _: CallbackContext) -> int:
return FIRST
def start_over(update: Update, _: CallbackContext) -> int:
def start_over(update: Update, context: CallbackContext) -> int:
"""Prompt same text & keyboard as `start` does but not as new message"""
# Get CallbackQuery from Update
query = update.callback_query
@ -80,7 +80,7 @@ def start_over(update: Update, _: CallbackContext) -> int:
return FIRST
def one(update: Update, _: CallbackContext) -> int:
def one(update: Update, context: CallbackContext) -> int:
"""Show new choice of buttons"""
query = update.callback_query
query.answer()
@ -97,7 +97,7 @@ def one(update: Update, _: CallbackContext) -> int:
return FIRST
def two(update: Update, _: CallbackContext) -> int:
def two(update: Update, context: CallbackContext) -> int:
"""Show new choice of buttons"""
query = update.callback_query
query.answer()
@ -114,7 +114,7 @@ def two(update: Update, _: CallbackContext) -> int:
return FIRST
def three(update: Update, _: CallbackContext) -> int:
def three(update: Update, context: CallbackContext) -> int:
"""Show new choice of buttons"""
query = update.callback_query
query.answer()
@ -132,7 +132,7 @@ def three(update: Update, _: CallbackContext) -> int:
return SECOND
def four(update: Update, _: CallbackContext) -> int:
def four(update: Update, context: CallbackContext) -> int:
"""Show new choice of buttons"""
query = update.callback_query
query.answer()
@ -149,7 +149,7 @@ def four(update: Update, _: CallbackContext) -> int:
return FIRST
def end(update: Update, _: CallbackContext) -> int:
def end(update: Update, context: CallbackContext) -> int:
"""Returns `ConversationHandler.END`, which tells the
ConversationHandler that the conversation is over.
"""

View file

@ -1,5 +1,5 @@
#!/usr/bin/env python
# pylint: disable=C0116
# pylint: disable=C0116,W0613
# This program is dedicated to the public domain under the CC0 license.
"""
@ -152,14 +152,14 @@ def show_data(update: Update, context: CallbackContext) -> str:
return SHOWING
def stop(update: Update, _: CallbackContext) -> int:
def stop(update: Update, context: CallbackContext) -> int:
"""End Conversation by command."""
update.message.reply_text('Okay, bye.')
return END
def end(update: Update, _: CallbackContext) -> int:
def end(update: Update, context: CallbackContext) -> int:
"""End conversation from InlineKeyboardButton."""
update.callback_query.answer()
@ -170,7 +170,7 @@ def end(update: Update, _: CallbackContext) -> int:
# Second level conversation callbacks
def select_level(update: Update, _: CallbackContext) -> str:
def select_level(update: Update, context: CallbackContext) -> str:
"""Choose to add a parent or a child."""
text = 'You may add a parent or a child. Also you can show the gathered data or go back.'
buttons = [
@ -293,7 +293,7 @@ def end_describing(update: Update, context: CallbackContext) -> int:
return END
def stop_nested(update: Update, _: CallbackContext) -> str:
def stop_nested(update: Update, context: CallbackContext) -> str:
"""Completely end conversation from within nested conversation."""
update.message.reply_text('Okay, bye.')

View file

@ -1,5 +1,5 @@
#!/usr/bin/env python
# pylint: disable=C0116
# pylint: disable=C0116,W0613
# This program is dedicated to the public domain under the CC0 license.
"""
@ -23,7 +23,7 @@ logging.basicConfig(
logger = logging.getLogger(__name__)
def msg(update: Update, _: CallbackContext) -> None:
def msg(update: Update, context: CallbackContext) -> None:
"""Downloads and prints the received passport data."""
# Retrieve passport data
passport_data = update.message.passport_data

View file

@ -1,5 +1,5 @@
#!/usr/bin/env python
# pylint: disable=C0116
# pylint: disable=C0116,W0613
# This program is dedicated to the public domain under the CC0 license.
"""Basic example for a bot that can receive payment from user."""
@ -25,7 +25,7 @@ logging.basicConfig(
logger = logging.getLogger(__name__)
def start_callback(update: Update, _: CallbackContext) -> None:
def start_callback(update: Update, context: CallbackContext) -> None:
"""Displays info on how to use the bot."""
msg = (
"Use /shipping to get an invoice for shipping-payment, or /noshipping for an "
@ -91,7 +91,7 @@ def start_without_shipping_callback(update: Update, context: CallbackContext) ->
)
def shipping_callback(update: Update, _: CallbackContext) -> None:
def shipping_callback(update: Update, context: CallbackContext) -> None:
"""Answers the ShippingQuery with ShippingOptions"""
query = update.shipping_query
# check the payload, is this from your bot?
@ -109,7 +109,7 @@ def shipping_callback(update: Update, _: CallbackContext) -> None:
# after (optional) shipping, it's the pre-checkout
def precheckout_callback(update: Update, _: CallbackContext) -> None:
def precheckout_callback(update: Update, context: CallbackContext) -> None:
"""Answers the PreQecheckoutQuery"""
query = update.pre_checkout_query
# check the payload, is this from your bot?
@ -121,7 +121,7 @@ def precheckout_callback(update: Update, _: CallbackContext) -> None:
# finally, after contacting the payment provider...
def successful_payment_callback(update: Update, _: CallbackContext) -> None:
def successful_payment_callback(update: Update, context: CallbackContext) -> None:
"""Confirms the successful payment."""
# do something after successfully receiving payment?
update.message.reply_text("Thank you for your payment!")

View file

@ -1,5 +1,5 @@
#!/usr/bin/env python
# pylint: disable=C0116
# pylint: disable=C0116,W0613
# This program is dedicated to the public domain under the CC0 license.
"""
@ -84,7 +84,7 @@ def regular_choice(update: Update, context: CallbackContext) -> int:
return TYPING_REPLY
def custom_choice(update: Update, _: CallbackContext) -> int:
def custom_choice(update: Update, context: CallbackContext) -> int:
"""Ask the user for a description of a custom category."""
update.message.reply_text(
'Alright, please send me the category first, for example "Most impressive skill"'

View file

@ -1,5 +1,5 @@
#!/usr/bin/env python
# pylint: disable=C0116
# pylint: disable=C0116,W0613
# This program is dedicated to the public domain under the CC0 license.
"""
@ -34,7 +34,7 @@ logging.basicConfig(
logger = logging.getLogger(__name__)
def start(update: Update, _: CallbackContext) -> None:
def start(update: Update, context: CallbackContext) -> None:
"""Inform user about what this bot can do"""
update.message.reply_text(
'Please select /poll to get a Poll, /quiz to get a Quiz or /preview'
@ -120,7 +120,7 @@ def receive_quiz_answer(update: Update, context: CallbackContext) -> None:
context.bot.stop_poll(quiz_data["chat_id"], quiz_data["message_id"])
def preview(update: Update, _: CallbackContext) -> None:
def preview(update: Update, context: CallbackContext) -> None:
"""Ask user to create a poll and display a preview of it"""
# using this without a type lets the user chooses what he wants (quiz or poll)
button = [[KeyboardButton("Press me!", request_poll=KeyboardButtonPollType())]]
@ -131,7 +131,7 @@ def preview(update: Update, _: CallbackContext) -> None:
)
def receive_poll(update: Update, _: CallbackContext) -> None:
def receive_poll(update: Update, context: CallbackContext) -> None:
"""On receiving polls, reply to it by a closed poll copying the received poll"""
actual_poll = update.effective_message.poll
# Only need to set the question and options, since all other parameters don't matter for
@ -145,7 +145,7 @@ def receive_poll(update: Update, _: CallbackContext) -> None:
)
def help_handler(update: Update, _: CallbackContext) -> None:
def help_handler(update: Update, context: CallbackContext) -> None:
"""Display a help message"""
update.message.reply_text("Use /quiz, /poll or /preview to test this bot.")

View file

@ -1,5 +1,5 @@
#!/usr/bin/env python
# pylint: disable=C0116
# pylint: disable=C0116,W0613
# This program is dedicated to the public domain under the CC0 license.
"""
@ -33,7 +33,11 @@ logger = logging.getLogger(__name__)
# Define a few command handlers. These usually take the two arguments update and
# context. Error handlers also receive the raised TelegramError object in error.
def start(update: Update, _: CallbackContext) -> None:
# Best practice would be to replace context with an underscore,
# since context is an unused local variable.
# This being an example and not having context present confusing beginners,
# we decided to have it present as context.
def start(update: Update, context: CallbackContext) -> None:
"""Sends explanation on how to use the bot."""
update.message.reply_text('Hi! Use /set <seconds> to set a timer')

View file

@ -3283,6 +3283,11 @@ class Bot(TelegramObject):
Use this method to get data for high score tables. Will return the score of the specified
user and several of their neighbors in a game.
Note:
This method will currently return scores for the target user, plus two of their
closest neighbors on each side. Will also return the top three users if the user and
his neighbors are not among them. Please note that this behavior is subject to change.
Args:
user_id (:obj:`int`): Target user id.
chat_id (:obj:`int` | :obj:`str`, optional): Required if inline_message_id is not
@ -3924,7 +3929,7 @@ class Bot(TelegramObject):
chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
of the target channel (in the format ``@channelusername``).
expire_date (:obj:`int` | :obj:`datetime.datetime`, optional): Date when the link will
expire.
expire. Integer input will be interpreted as Unix timestamp.
For timezone naive :obj:`datetime.datetime` objects, the default timezone of the
bot will be used.
member_limit (:obj:`int`, optional): Maximum number of users that can be members of

View file

@ -193,7 +193,7 @@ class CallbackQuery(TelegramObject):
*args, **kwargs)
For the documentation of the arguments, please see
:meth:`telegram.Bot.edit_message_text`.
:meth:`telegram.Bot.edit_message_text` and :meth:`telegram.Message.edit_text`.
Returns:
:class:`telegram.Message`: On success, if edited message is sent by the bot, the
@ -243,7 +243,7 @@ class CallbackQuery(TelegramObject):
*args, **kwargs)
For the documentation of the arguments, please see
:meth:`telegram.Bot.edit_message_caption`.
:meth:`telegram.Bot.edit_message_caption` and :meth:`telegram.Message.edit_caption`.
Returns:
:class:`telegram.Message`: On success, if edited message is sent by the bot, the
@ -295,7 +295,8 @@ class CallbackQuery(TelegramObject):
)
For the documentation of the arguments, please see
:meth:`telegram.Bot.edit_message_reply_markup`.
:meth:`telegram.Bot.edit_message_reply_markup` and
:meth:`telegram.Message.edit_reply_markup`.
Returns:
:class:`telegram.Message`: On success, if edited message is sent by the bot, the
@ -334,7 +335,7 @@ class CallbackQuery(TelegramObject):
*args, **kwargs)
For the documentation of the arguments, please see
:meth:`telegram.Bot.edit_message_media`.
:meth:`telegram.Bot.edit_message_media` and :meth:`telegram.Message.edit_media`.
Returns:
:class:`telegram.Message`: On success, if edited message is sent by the bot, the
@ -382,7 +383,8 @@ class CallbackQuery(TelegramObject):
)
For the documentation of the arguments, please see
:meth:`telegram.Bot.edit_message_live_location`.
:meth:`telegram.Bot.edit_message_live_location` and
:meth:`telegram.Message.edit_live_location`.
Returns:
:class:`telegram.Message`: On success, if edited message is sent by the bot, the
@ -434,7 +436,8 @@ class CallbackQuery(TelegramObject):
)
For the documentation of the arguments, please see
:meth:`telegram.Bot.stop_message_live_location`.
:meth:`telegram.Bot.stop_message_live_location` and
:meth:`telegram.Message.stop_live_location`.
Returns:
:class:`telegram.Message`: On success, if edited message is sent by the bot, the
@ -475,7 +478,7 @@ class CallbackQuery(TelegramObject):
*args, **kwargs)
For the documentation of the arguments, please see
:meth:`telegram.Bot.set_game_score`.
:meth:`telegram.Bot.set_game_score` and :meth:`telegram.Message.set_game_score`.
Returns:
:class:`telegram.Message`: On success, if edited message is sent by the bot, the
@ -519,7 +522,7 @@ class CallbackQuery(TelegramObject):
*args, **kwargs)
For the documentation of the arguments, please see
:meth:`telegram.Bot.get_game_high_scores`.
:meth:`telegram.Bot.get_game_high_scores` and :meth:`telegram.Message.get_game_high_score`.
Returns:
List[:class:`telegram.GameHighScore`]
@ -550,7 +553,7 @@ class CallbackQuery(TelegramObject):
update.callback_query.message.delete(*args, **kwargs)
For the documentation of the arguments, please see
:meth:`telegram.Bot.delete_message`.
:meth:`telegram.Message.delete`.
Returns:
:obj:`bool`: On success, :obj:`True` is returned.
@ -569,13 +572,10 @@ class CallbackQuery(TelegramObject):
) -> bool:
"""Shortcut for::
bot.pin_chat_message(chat_id=message.chat_id,
message_id=message.message_id,
*args,
**kwargs)
update.callback_query.message.pin(*args, **kwargs)
For the documentation of the arguments, please see
:meth:`telegram.Bot.pin_chat_message`.
:meth:`telegram.Message.pin`.
Returns:
:obj:`bool`: On success, :obj:`True` is returned.
@ -594,13 +594,10 @@ class CallbackQuery(TelegramObject):
) -> bool:
"""Shortcut for::
bot.unpin_chat_message(chat_id=message.chat_id,
message_id=message.message_id,
*args,
**kwargs)
update.callback_query.message.unpin(*args, **kwargs)
For the documentation of the arguments, please see
:meth:`telegram.Bot.unpin_chat_message`.
:meth:`telegram.Message.unpin`.
Returns:
:obj:`bool`: On success, :obj:`True` is returned.
@ -634,7 +631,7 @@ class CallbackQuery(TelegramObject):
**kwargs)
For the documentation of the arguments, please see
:meth:`telegram.Bot.copy_message`.
:meth:`telegram.Message.copy`.
Returns:
:class:`telegram.MessageId`: On success, returns the MessageId of the sent message.

View file

@ -33,8 +33,7 @@ class ChatAction:
""":const:`telegram.constants.CHATACTION_RECORD_AUDIO`
.. deprecated:: 13.5
Deprecated by Telegram. Use :attr:`RECORD_VOICE` instead, as backwards
compatibility is not guaranteed by Telegram.
Deprecated by Telegram. Use :attr:`RECORD_VOICE` instead.
"""
RECORD_VOICE: ClassVar[str] = constants.CHATACTION_RECORD_VOICE
""":const:`telegram.constants.CHATACTION_RECORD_VOICE`
@ -51,8 +50,7 @@ class ChatAction:
""":const:`telegram.constants.CHATACTION_UPLOAD_AUDIO`
.. deprecated:: 13.5
Deprecated by Telegram. Use :attr:`UPLOAD_VOICE` instead, as backwards
compatibility is not guaranteed by Telegram.
Deprecated by Telegram. Use :attr:`UPLOAD_VOICE` instead.
"""
UPLOAD_VOICE: ClassVar[str] = constants.CHATACTION_UPLOAD_VOICE
""":const:`telegram.constants.CHATACTION_UPLOAD_VOICE`

View file

@ -211,7 +211,7 @@ class BasePersistence(Generic[UD, CD, BD], ABC):
Replaces all instances of :class:`telegram.Bot` that occur within the passed object with
:attr:`REPLACED_BOT`. Currently, this handles objects of type ``list``, ``tuple``, ``set``,
``frozenset``, ``dict``, ``defaultdict`` and objects that have a ``__dict__`` or
``__slot__`` attribute, excluding classes and objects that can't be copied with
``__slots__`` attribute, excluding classes and objects that can't be copied with
``copy.copy``.
Args:
@ -298,7 +298,7 @@ class BasePersistence(Generic[UD, CD, BD], ABC):
Replaces all instances of :attr:`REPLACED_BOT` that occur within the passed object with
:attr:`bot`. Currently, this handles objects of type ``list``, ``tuple``, ``set``,
``frozenset``, ``dict``, ``defaultdict`` and objects that have a ``__dict__`` or
``__slot__`` attribute, excluding classes and objects that can't be copied with
``__slots__`` attribute, excluding classes and objects that can't be copied with
``copy.copy``.
Args:

View file

@ -42,6 +42,9 @@ class Defaults:
timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as the
read timeout from the server (instead of the one specified during creation of the
connection pool).
Note:
Will *not* be used for :meth:`telegram.Bot.get_updates`!
quote (:obj:`bool`, optional): If set to :obj:`True`, the reply is sent as an actual reply
to the message. If ``reply_to_message_id`` is passed in ``kwargs``, this parameter will
be ignored. Default: :obj:`True` in group chats and :obj:`False` in private chats.
@ -49,9 +52,6 @@ class Defaults:
appearing throughout PTB, i.e. if a timezone naive date(time) object is passed
somewhere, it will be assumed to be in ``tzinfo``. Must be a timezone provided by the
``pytz`` module. Defaults to UTC.
Note:
Will *not* be used for :meth:`telegram.Bot.get_updates`!
run_async (:obj:`bool`, optional): Default setting for the ``run_async`` parameter of
handlers and error handlers registered through :meth:`Dispatcher.add_handler` and
:meth:`Dispatcher.add_error_handler`. Defaults to :obj:`False`.

View file

@ -56,7 +56,7 @@ class DictPersistence(BasePersistence):
Args:
store_user_data (:obj:`bool`, optional): Whether user_data should be saved by this
persistence class. Default is :obj:`True`.
store_chat_data (:obj:`bool`, optional): Whether user_data should be saved by this
store_chat_data (:obj:`bool`, optional): Whether chat_data should be saved by this
persistence class. Default is :obj:`True`.
store_bot_data (:obj:`bool`, optional): Whether bot_data should be saved by this
persistence class. Default is :obj:`True`.
@ -64,17 +64,17 @@ class DictPersistence(BasePersistence):
persistence class. Default is :obj:`False`.
.. versionadded:: 13.6
user_data_json (:obj:`str`, optional): Json string that will be used to reconstruct
user_data_json (:obj:`str`, optional): JSON string that will be used to reconstruct
user_data on creating this persistence. Default is ``""``.
chat_data_json (:obj:`str`, optional): Json string that will be used to reconstruct
chat_data_json (:obj:`str`, optional): JSON string that will be used to reconstruct
chat_data on creating this persistence. Default is ``""``.
bot_data_json (:obj:`str`, optional): Json string that will be used to reconstruct
bot_data_json (:obj:`str`, optional): JSON string that will be used to reconstruct
bot_data on creating this persistence. Default is ``""``.
callback_data_json (:obj:`str`, optional): Json string that will be used to reconstruct
callback_data on creating this persistence. Default is ``""``.
.. versionadded:: 13.6
conversations_json (:obj:`str`, optional): Json string that will be used to reconstruct
conversations_json (:obj:`str`, optional): JSON string that will be used to reconstruct
conversation on creating this persistence. Default is ``""``.
Attributes:

View file

@ -657,7 +657,7 @@ class Dispatcher(Generic[CCT, UD, CD, BD]):
Args:
update (:class:`telegram.Update`, optional): The update to process. If passed, only the
corresponding ``user_data`` and ``chat_data`` will be updated.
corresponding ``user_data`` and ``chat_data`` will be updated.
"""
with self._update_persistence_lock:
self.__update_persistence(update)

View file

@ -2145,10 +2145,15 @@ officedocument.wordprocessingml.document")``.
Examples:
To allow any dice message, simply use
``MessageHandler(Filters.dice, callback_method)``.
To allow only dice with value 6, use
``MessageHandler(Filters.dice(6), callback_method)``.
To allow only dice with value 5 `or` 6, use
``MessageHandler(Filters.dice([5, 6]), callback_method)``.
To allow only dice messages with the emoji 🎲, but any value, use
``MessageHandler(Filters.dice.dice, callback_method)``.
To allow only dice messages with the emoji 🎯 and with value 6, use
``MessageHandler(Filters.dice.darts(6), callback_method)``.
To allow only dice messages with the emoji and with value 5 `or` 6, use
``MessageHandler(Filters.dice.football([5, 6]), callback_method)``.
Note:
Dice messages don't have text. If you want to filter either text or dice messages, use

View file

@ -218,6 +218,12 @@ class JobQueue:
) -> 'Job':
"""Creates a new ``Job`` that runs at specified intervals and adds it to the queue.
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
Args:
callback (:obj:`callable`): The callback function that should be executed by the new
job. Callback signature for context based API:
@ -268,11 +274,6 @@ class JobQueue:
:class:`telegram.ext.Job`: The new ``Job`` instance that has been added to the job
queue.
Note:
`interval` is always respected "as-is". That means that if DST changes during that
interval, the job might not run at the time one would expect. It is always recommended
to pin servers to UTC time, then time related behaviour can always be expected.
"""
if not job_kwargs:
job_kwargs = {}
@ -399,6 +400,12 @@ class JobQueue:
) -> 'Job':
"""Creates a new ``Job`` that runs on a daily basis and adds it to the queue.
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
Args:
callback (:obj:`callable`): The callback function that should be executed by the new
job. Callback signature for context based API:
@ -422,12 +429,6 @@ class JobQueue:
:class:`telegram.ext.Job`: The new ``Job`` instance that has been added to the job
queue.
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
"""
if not job_kwargs:
job_kwargs = {}

View file

@ -35,7 +35,7 @@ from .contexttypes import ContextTypes
class PicklePersistence(BasePersistence[UD, CD, BD]):
"""Using python's builtin pickle for making you bot persistent.
"""Using python's builtin pickle for making your bot persistent.
Warning:
:class:`PicklePersistence` will try to replace :class:`telegram.Bot` instances by
@ -51,7 +51,7 @@ class PicklePersistence(BasePersistence[UD, CD, BD]):
is :obj:`False` this will be used as a prefix.
store_user_data (:obj:`bool`, optional): Whether user_data should be saved by this
persistence class. Default is :obj:`True`.
store_chat_data (:obj:`bool`, optional): Whether user_data should be saved by this
store_chat_data (:obj:`bool`, optional): Whether chat_data should be saved by this
persistence class. Default is :obj:`True`.
store_bot_data (:obj:`bool`, optional): Whether bot_data should be saved by this
persistence class. Default is :obj:`True`.
@ -78,7 +78,7 @@ class PicklePersistence(BasePersistence[UD, CD, BD]):
is :obj:`False` this will be used as a prefix.
store_user_data (:obj:`bool`): Optional. Whether user_data should be saved by this
persistence class.
store_chat_data (:obj:`bool`): Optional. Whether user_data should be saved by this
store_chat_data (:obj:`bool`): Optional. Whether chat_data should be saved by this
persistence class.
store_bot_data (:obj:`bool`): Optional. Whether bot_data should be saved by this
persistence class.
@ -298,7 +298,7 @@ class PicklePersistence(BasePersistence[UD, CD, BD]):
return self.callback_data[0], self.callback_data[1].copy()
def get_conversations(self, name: str) -> ConversationDict:
"""Returns the conversations from the pickle file if it exsists or an empty dict.
"""Returns the conversations from the pickle file if it exists or an empty dict.
Args:
name (:obj:`str`): The handlers name.

View file

@ -45,7 +45,7 @@ class Game(TelegramObject):
game message. Can be automatically edited to include current high scores for the game
when the bot calls :meth:`telegram.Bot.set_game_score`, or manually edited
using :meth:`telegram.Bot.edit_message_text`.
1-4096 characters. Also found as ``telegram.constants.MAX_MESSAGE_LENGTH``.
0-4096 characters. Also found as ``telegram.constants.MAX_MESSAGE_LENGTH``.
text_entities (List[:class:`telegram.MessageEntity`], optional): Special entities that
appear in text, such as usernames, URLs, bot commands, etc.
animation (:class:`telegram.Animation`, optional): Animation that will be displayed in the

View file

@ -54,7 +54,7 @@ class InlineKeyboardButton(TelegramObject):
Args:
text (:obj:`str`): Label text on the button.
url (:obj:`str`): HTTP or tg:// url to be opened when button is pressed.
url (:obj:`str`, optional): HTTP or tg:// url to be opened when button is pressed.
login_url (:class:`telegram.LoginUrl`, optional): An HTTP URL used to automatically
authorize the user. Can be used as a replacement for the Telegram Login Widget.
callback_data (:obj:`str` | :obj:`Any`, optional): Data to be sent in a callback query to