Improve Code Quality (#2131)

* Make pre-commit more strict

* Get pylint to read setup.cfg

* Make pylint & mypy happy aka ignore all the things

* use LogRecord.getMessage() in tests

* Make noam happy

* Update both pylint & mypy while we're at it

* Bring reqs-dev and makefile up to speed

* try making pre-commit happy

* fix jobqueue tests on the fly
This commit is contained in:
Bibo-Joshi 2020-10-31 16:33:34 +01:00 committed by GitHub
parent 237e73bfb4
commit 92b9370c23
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
140 changed files with 1279 additions and 1081 deletions

View file

@ -1,3 +1,6 @@
# Make sure that
# * the revs specified here match requirements-dev.txt
# * the makefile checks the same files as pre-commit
repos: repos:
- repo: https://github.com/psf/black - repo: https://github.com/psf/black
rev: 20.8b1 rev: 20.8b1
@ -7,19 +10,18 @@ repos:
- --diff - --diff
- --check - --check
- repo: https://gitlab.com/pycqa/flake8 - repo: https://gitlab.com/pycqa/flake8
rev: 3.8.1 rev: 3.8.4
hooks: hooks:
- id: flake8 - id: flake8
- repo: git://github.com/pre-commit/mirrors-pylint - repo: https://github.com/PyCQA/pylint
rev: v2.5.3 rev: pylint-2.6.0
hooks: hooks:
- id: pylint - id: pylint
files: ^telegram/.*\.py$ files: ^(telegram|examples)/.*\.py$
args: args:
- --errors-only - --rcfile=setup.cfg
- --disable=import-error
- repo: https://github.com/pre-commit/mirrors-mypy - repo: https://github.com/pre-commit/mirrors-mypy
rev: 'v0.770' rev: v0.790
hooks: hooks:
- id: mypy - id: mypy
files: ^telegram/.*\.py$ files: ^(telegram|examples)/.*\.py$

View file

@ -1,11 +1,10 @@
.DEFAULT_GOAL := help .DEFAULT_GOAL := help
.PHONY: clean pep257 pep8 yapf lint test install .PHONY: clean pep8 black lint test install
PYLINT := pylint PYLINT := pylint
PYTEST := pytest PYTEST := pytest
PEP257 := pep257
PEP8 := flake8 PEP8 := flake8
YAPF := yapf BLACK := black
MYPY := mypy MYPY := mypy
PIP := pip PIP := pip
@ -15,22 +14,20 @@ clean:
find . -name '*.pyc' -exec rm -f {} \; find . -name '*.pyc' -exec rm -f {} \;
find . -name '*.pyo' -exec rm -f {} \; find . -name '*.pyo' -exec rm -f {} \;
find . -name '*~' -exec rm -f {} \; find . -name '*~' -exec rm -f {} \;
find . -regex "./telegram.\(mp3\|mp4\|ogg\|png\|webp\)" -exec rm {} \; find . -regex "./telegram[0-9]*.\(jpg\|mp3\|mp4\|ogg\|png\|webp\)" -exec rm {} \;
pep257:
$(PEP257) telegram
pep8: pep8:
$(PEP8) telegram $(PEP8) telegram tests examples
yapf: black:
$(YAPF) -r telegram $(BLACK) .
lint: lint:
$(PYLINT) -E telegram --disable=no-name-in-module,import-error $(PYLINT) --rcfile=setup.cfg telegram examples
mypy: mypy:
$(MYPY) -p telegram $(MYPY) -p telegram
$(MYPY) examples
test: test:
$(PYTEST) -v $(PYTEST) -v
@ -41,18 +38,16 @@ install:
help: help:
@echo "Available targets:" @echo "Available targets:"
@echo "- clean Clean up the source directory" @echo "- clean Clean up the source directory"
@echo "- pep257 Check docstring style with pep257"
@echo "- pep8 Check style with flake8" @echo "- pep8 Check style with flake8"
@echo "- lint Check style with pylint" @echo "- lint Check style with pylint"
@echo "- yapf Check style with yapf" @echo "- black Check style with black"
@echo "- mypy Check type hinting with mypy" @echo "- mypy Check type hinting with mypy"
@echo "- test Run tests using pytest" @echo "- test Run tests using pytest"
@echo @echo
@echo "Available variables:" @echo "Available variables:"
@echo "- PYLINT default: $(PYLINT)" @echo "- PYLINT default: $(PYLINT)"
@echo "- PYTEST default: $(PYTEST)" @echo "- PYTEST default: $(PYTEST)"
@echo "- PEP257 default: $(PEP257)"
@echo "- PEP8 default: $(PEP8)" @echo "- PEP8 default: $(PEP8)"
@echo "- YAPF default: $(YAPF)" @echo "- BLACK default: $(BLACK)"
@echo "- MYPY default: $(MYPY)" @echo "- MYPY default: $(MYPY)"
@echo "- PIP default: $(PIP)" @echo "- PIP default: $(PIP)"

View file

@ -1,5 +1,7 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# pylint: disable=W0613, C0116
# type: ignore[union-attr]
# This program is dedicated to the public domain under the CC0 license. # This program is dedicated to the public domain under the CC0 license.
""" """
@ -16,8 +18,15 @@ bot.
import logging import logging
from telegram import ReplyKeyboardMarkup, ReplyKeyboardRemove from telegram import ReplyKeyboardMarkup, ReplyKeyboardRemove, Update
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, ConversationHandler from telegram.ext import (
Updater,
CommandHandler,
MessageHandler,
Filters,
ConversationHandler,
CallbackContext,
)
# Enable logging # Enable logging
logging.basicConfig( logging.basicConfig(
@ -29,7 +38,7 @@ logger = logging.getLogger(__name__)
GENDER, PHOTO, LOCATION, BIO = range(4) GENDER, PHOTO, LOCATION, BIO = range(4)
def start(update, context): def start(update: Update, context: CallbackContext) -> int:
reply_keyboard = [['Boy', 'Girl', 'Other']] reply_keyboard = [['Boy', 'Girl', 'Other']]
update.message.reply_text( update.message.reply_text(
@ -42,7 +51,7 @@ def start(update, context):
return GENDER return GENDER
def gender(update, context): def gender(update: Update, context: CallbackContext) -> int:
user = update.message.from_user user = update.message.from_user
logger.info("Gender of %s: %s", user.first_name, update.message.text) logger.info("Gender of %s: %s", user.first_name, update.message.text)
update.message.reply_text( update.message.reply_text(
@ -54,7 +63,7 @@ def gender(update, context):
return PHOTO return PHOTO
def photo(update, context): def photo(update: Update, context: CallbackContext) -> int:
user = update.message.from_user user = update.message.from_user
photo_file = update.message.photo[-1].get_file() photo_file = update.message.photo[-1].get_file()
photo_file.download('user_photo.jpg') photo_file.download('user_photo.jpg')
@ -66,7 +75,7 @@ def photo(update, context):
return LOCATION return LOCATION
def skip_photo(update, context): def skip_photo(update: Update, context: CallbackContext) -> int:
user = update.message.from_user user = update.message.from_user
logger.info("User %s did not send a photo.", user.first_name) logger.info("User %s did not send a photo.", user.first_name)
update.message.reply_text( update.message.reply_text(
@ -76,7 +85,7 @@ def skip_photo(update, context):
return LOCATION return LOCATION
def location(update, context): def location(update: Update, context: CallbackContext) -> int:
user = update.message.from_user user = update.message.from_user
user_location = update.message.location user_location = update.message.location
logger.info( logger.info(
@ -89,7 +98,7 @@ def location(update, context):
return BIO return BIO
def skip_location(update, context): def skip_location(update: Update, context: CallbackContext) -> int:
user = update.message.from_user user = update.message.from_user
logger.info("User %s did not send a location.", user.first_name) logger.info("User %s did not send a location.", user.first_name)
update.message.reply_text( update.message.reply_text(
@ -99,7 +108,7 @@ def skip_location(update, context):
return BIO return BIO
def bio(update, context): def bio(update: Update, context: CallbackContext) -> int:
user = update.message.from_user user = update.message.from_user
logger.info("Bio of %s: %s", user.first_name, update.message.text) logger.info("Bio of %s: %s", user.first_name, update.message.text)
update.message.reply_text('Thank you! I hope we can talk again some day.') update.message.reply_text('Thank you! I hope we can talk again some day.')
@ -107,7 +116,7 @@ def bio(update, context):
return ConversationHandler.END return ConversationHandler.END
def cancel(update, context): def cancel(update: Update, context: CallbackContext) -> int:
user = update.message.from_user user = update.message.from_user
logger.info("User %s canceled the conversation.", user.first_name) logger.info("User %s canceled the conversation.", user.first_name)
update.message.reply_text( update.message.reply_text(
@ -117,14 +126,14 @@ def cancel(update, context):
return ConversationHandler.END return ConversationHandler.END
def main(): def main() -> None:
# Create the Updater and pass it your bot's token. # Create the Updater and pass it your bot's token.
# Make sure to set use_context=True to use the new context based callbacks # Make sure to set use_context=True to use the new context based callbacks
# Post version 12 this will no longer be necessary # Post version 12 this will no longer be necessary
updater = Updater("TOKEN", use_context=True) updater = Updater("TOKEN", use_context=True)
# Get the dispatcher to register handlers # Get the dispatcher to register handlers
dp = updater.dispatcher dispatcher = updater.dispatcher
# Add conversation handler with the states GENDER, PHOTO, LOCATION and BIO # Add conversation handler with the states GENDER, PHOTO, LOCATION and BIO
conv_handler = ConversationHandler( conv_handler = ConversationHandler(
@ -141,7 +150,7 @@ def main():
fallbacks=[CommandHandler('cancel', cancel)], fallbacks=[CommandHandler('cancel', cancel)],
) )
dp.add_handler(conv_handler) dispatcher.add_handler(conv_handler)
# Start the Bot # Start the Bot
updater.start_polling() updater.start_polling()

View file

@ -1,5 +1,7 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# pylint: disable=W0613, C0116
# type: ignore[union-attr]
# This program is dedicated to the public domain under the CC0 license. # This program is dedicated to the public domain under the CC0 license.
""" """
@ -15,9 +17,17 @@ bot.
""" """
import logging import logging
from typing import Dict
from telegram import ReplyKeyboardMarkup from telegram import ReplyKeyboardMarkup, Update
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, ConversationHandler from telegram.ext import (
Updater,
CommandHandler,
MessageHandler,
Filters,
ConversationHandler,
CallbackContext,
)
# Enable logging # Enable logging
logging.basicConfig( logging.basicConfig(
@ -36,7 +46,7 @@ reply_keyboard = [
markup = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True) markup = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True)
def facts_to_str(user_data): def facts_to_str(user_data: Dict[str, str]) -> str:
facts = list() facts = list()
for key, value in user_data.items(): for key, value in user_data.items():
@ -45,7 +55,7 @@ def facts_to_str(user_data):
return "\n".join(facts).join(['\n', '\n']) return "\n".join(facts).join(['\n', '\n'])
def start(update, context): def start(update: Update, context: CallbackContext) -> int:
update.message.reply_text( update.message.reply_text(
"Hi! My name is Doctor Botter. I will hold a more complex conversation with you. " "Hi! My name is Doctor Botter. I will hold a more complex conversation with you. "
"Why don't you tell me something about yourself?", "Why don't you tell me something about yourself?",
@ -55,7 +65,7 @@ def start(update, context):
return CHOOSING return CHOOSING
def regular_choice(update, context): def regular_choice(update: Update, context: CallbackContext) -> int:
text = update.message.text text = update.message.text
context.user_data['choice'] = text context.user_data['choice'] = text
update.message.reply_text( update.message.reply_text(
@ -65,7 +75,7 @@ def regular_choice(update, context):
return TYPING_REPLY return TYPING_REPLY
def custom_choice(update, context): def custom_choice(update: Update, context: CallbackContext) -> int:
update.message.reply_text( update.message.reply_text(
'Alright, please send me the category first, ' 'for example "Most impressive skill"' 'Alright, please send me the category first, ' 'for example "Most impressive skill"'
) )
@ -73,7 +83,7 @@ def custom_choice(update, context):
return TYPING_CHOICE return TYPING_CHOICE
def received_information(update, context): def received_information(update: Update, context: CallbackContext) -> int:
user_data = context.user_data user_data = context.user_data
text = update.message.text text = update.message.text
category = user_data['choice'] category = user_data['choice']
@ -90,7 +100,7 @@ def received_information(update, context):
return CHOOSING return CHOOSING
def done(update, context): def done(update: Update, context: CallbackContext) -> int:
user_data = context.user_data user_data = context.user_data
if 'choice' in user_data: if 'choice' in user_data:
del user_data['choice'] del user_data['choice']
@ -103,14 +113,14 @@ def done(update, context):
return ConversationHandler.END return ConversationHandler.END
def main(): def main() -> None:
# Create the Updater and pass it your bot's token. # Create the Updater and pass it your bot's token.
# Make sure to set use_context=True to use the new context based callbacks # Make sure to set use_context=True to use the new context based callbacks
# Post version 12 this will no longer be necessary # Post version 12 this will no longer be necessary
updater = Updater("TOKEN", use_context=True) updater = Updater("TOKEN", use_context=True)
# Get the dispatcher to register handlers # Get the dispatcher to register handlers
dp = updater.dispatcher dispatcher = updater.dispatcher
# Add conversation handler with the states CHOOSING, TYPING_CHOICE and TYPING_REPLY # Add conversation handler with the states CHOOSING, TYPING_CHOICE and TYPING_REPLY
conv_handler = ConversationHandler( conv_handler = ConversationHandler(
@ -137,7 +147,7 @@ def main():
fallbacks=[MessageHandler(Filters.regex('^Done$'), done)], fallbacks=[MessageHandler(Filters.regex('^Done$'), done)],
) )
dp.add_handler(conv_handler) dispatcher.add_handler(conv_handler)
# Start the Bot # Start the Bot
updater.start_polling() updater.start_polling()

View file

@ -1,5 +1,8 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# pylint: disable=W0613, C0116
# type: ignore[union-attr]
# This program is dedicated to the public domain under the CC0 license.
"""Bot that explains Telegram's "Deep Linking Parameters" functionality. """Bot that explains Telegram's "Deep Linking Parameters" functionality.
@ -19,8 +22,8 @@ bot.
import logging import logging
from telegram import ParseMode, InlineKeyboardMarkup, InlineKeyboardButton from telegram import ParseMode, InlineKeyboardMarkup, InlineKeyboardButton, Update
from telegram.ext import Updater, CommandHandler, Filters from telegram.ext import Updater, CommandHandler, Filters, CallbackContext
# Enable logging # Enable logging
from telegram.utils import helpers from telegram.utils import helpers
@ -37,7 +40,7 @@ USING_ENTITIES = 'using-entities-here'
SO_COOL = 'so-cool' SO_COOL = 'so-cool'
def start(update, context): def start(update: Update, context: CallbackContext) -> None:
"""Send a deep-linked URL when the command /start is issued.""" """Send a deep-linked URL when the command /start is issued."""
bot = context.bot bot = context.bot
url = helpers.create_deep_linked_url(bot.get_me().username, CHECK_THIS_OUT, group=True) url = helpers.create_deep_linked_url(bot.get_me().username, CHECK_THIS_OUT, group=True)
@ -45,7 +48,7 @@ def start(update, context):
update.message.reply_text(text) update.message.reply_text(text)
def deep_linked_level_1(update, context): def deep_linked_level_1(update: Update, context: CallbackContext) -> None:
"""Reached through the CHECK_THIS_OUT payload""" """Reached through the CHECK_THIS_OUT payload"""
bot = context.bot bot = context.bot
url = helpers.create_deep_linked_url(bot.get_me().username, SO_COOL) url = helpers.create_deep_linked_url(bot.get_me().username, SO_COOL)
@ -59,7 +62,7 @@ def deep_linked_level_1(update, context):
update.message.reply_text(text, reply_markup=keyboard) update.message.reply_text(text, reply_markup=keyboard)
def deep_linked_level_2(update, context): def deep_linked_level_2(update: Update, context: CallbackContext) -> None:
"""Reached through the SO_COOL payload""" """Reached through the SO_COOL payload"""
bot = context.bot bot = context.bot
url = helpers.create_deep_linked_url(bot.get_me().username, USING_ENTITIES) url = helpers.create_deep_linked_url(bot.get_me().username, USING_ENTITIES)
@ -67,7 +70,7 @@ def deep_linked_level_2(update, context):
update.message.reply_text(text, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True) update.message.reply_text(text, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True)
def deep_linked_level_3(update, context): def deep_linked_level_3(update: Update, context: CallbackContext) -> None:
"""Reached through the USING_ENTITIES payload""" """Reached through the USING_ENTITIES payload"""
payload = context.args payload = context.args
update.message.reply_text( update.message.reply_text(
@ -81,24 +84,26 @@ def main():
updater = Updater("TOKEN", use_context=True) updater = Updater("TOKEN", use_context=True)
# Get the dispatcher to register handlers # Get the dispatcher to register handlers
dp = updater.dispatcher dispatcher = updater.dispatcher
# More info on what deep linking actually is (read this first if it's unclear to you): # More info on what deep linking actually is (read this first if it's unclear to you):
# https://core.telegram.org/bots#deep-linking # https://core.telegram.org/bots#deep-linking
# Register a deep-linking handler # Register a deep-linking handler
dp.add_handler(CommandHandler("start", deep_linked_level_1, Filters.regex(CHECK_THIS_OUT))) dispatcher.add_handler(
CommandHandler("start", deep_linked_level_1, Filters.regex(CHECK_THIS_OUT))
)
# This one works with a textual link instead of an URL # This one works with a textual link instead of an URL
dp.add_handler(CommandHandler("start", deep_linked_level_2, Filters.regex(SO_COOL))) dispatcher.add_handler(CommandHandler("start", deep_linked_level_2, Filters.regex(SO_COOL)))
# We can also pass on the deep-linking payload # We can also pass on the deep-linking payload
dp.add_handler( dispatcher.add_handler(
CommandHandler("start", deep_linked_level_3, Filters.regex(USING_ENTITIES), pass_args=True) CommandHandler("start", deep_linked_level_3, Filters.regex(USING_ENTITIES), pass_args=True)
) )
# Make sure the deep-linking handlers occur *before* the normal /start handler. # Make sure the deep-linking handlers occur *before* the normal /start handler.
dp.add_handler(CommandHandler("start", start)) dispatcher.add_handler(CommandHandler("start", start))
# Start the Bot # Start the Bot
updater.start_polling() updater.start_polling()

View file

@ -1,5 +1,7 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# pylint: disable=W0613, C0116
# type: ignore[union-attr]
# This program is dedicated to the public domain under the CC0 license. # This program is dedicated to the public domain under the CC0 license.
""" """
@ -17,7 +19,8 @@ bot.
import logging import logging
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters from telegram import Update
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext
# Enable logging # Enable logging
logging.basicConfig( logging.basicConfig(
@ -29,17 +32,17 @@ logger = logging.getLogger(__name__)
# Define a few command handlers. These usually take the two arguments update and # Define a few command handlers. These usually take the two arguments update and
# context. Error handlers also receive the raised TelegramError object in error. # context. Error handlers also receive the raised TelegramError object in error.
def start(update, context): def start(update: Update, context: CallbackContext) -> None:
"""Send a message when the command /start is issued.""" """Send a message when the command /start is issued."""
update.message.reply_text('Hi!') update.message.reply_text('Hi!')
def help_command(update, context): def help_command(update: Update, context: CallbackContext) -> None:
"""Send a message when the command /help is issued.""" """Send a message when the command /help is issued."""
update.message.reply_text('Help!') update.message.reply_text('Help!')
def echo(update, context): def echo(update: Update, context: CallbackContext) -> None:
"""Echo the user message.""" """Echo the user message."""
update.message.reply_text(update.message.text) update.message.reply_text(update.message.text)
@ -52,14 +55,14 @@ def main():
updater = Updater("TOKEN", use_context=True) updater = Updater("TOKEN", use_context=True)
# Get the dispatcher to register handlers # Get the dispatcher to register handlers
dp = updater.dispatcher dispatcher = updater.dispatcher
# on different commands - answer in Telegram # on different commands - answer in Telegram
dp.add_handler(CommandHandler("start", start)) dispatcher.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", help_command)) dispatcher.add_handler(CommandHandler("help", help_command))
# on noncommand i.e message - echo the message on Telegram # on noncommand i.e message - echo the message on Telegram
dp.add_handler(MessageHandler(Filters.text & ~Filters.command, echo)) dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, echo))
# Start the Bot # Start the Bot
updater.start_polling() updater.start_polling()

View file

@ -1,5 +1,7 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# pylint: disable=W0613, C0116
# type: ignore[union-attr]
# This program is dedicated to the public domain under the CC0 license. # This program is dedicated to the public domain under the CC0 license.
""" """
@ -27,7 +29,7 @@ BOT_TOKEN = "TOKEN"
DEVELOPER_CHAT_ID = 123456789 DEVELOPER_CHAT_ID = 123456789
def error_handler(update: Update, context: CallbackContext): def error_handler(update: Update, context: CallbackContext) -> None:
"""Log the error and send a telegram message to notify the developer.""" """Log the error and send a telegram message to notify the developer."""
# Log the error before we do anything else, so we can see it even if something breaks. # Log the error before we do anything else, so we can see it even if something breaks.
logger.error(msg="Exception while handling an update:", exc_info=context.error) logger.error(msg="Exception while handling an update:", exc_info=context.error)
@ -35,7 +37,7 @@ def error_handler(update: Update, context: CallbackContext):
# traceback.format_exception returns the usual python message about an exception, but as a # traceback.format_exception returns the usual python message about an exception, but as a
# list of strings rather than a single string, so we have to join them together. # list of strings rather than a single string, so we have to join them together.
tb_list = traceback.format_exception(None, context.error, context.error.__traceback__) tb_list = traceback.format_exception(None, context.error, context.error.__traceback__)
tb = ''.join(tb_list) tb_string = ''.join(tb_list)
# Build the message with some markup and additional information about what happened. # Build the message with some markup and additional information about what happened.
# You might need to add some logic to deal with messages longer than the 4096 character limit. # You might need to add some logic to deal with messages longer than the 4096 character limit.
@ -49,19 +51,19 @@ def error_handler(update: Update, context: CallbackContext):
html.escape(json.dumps(update.to_dict(), indent=2, ensure_ascii=False)), html.escape(json.dumps(update.to_dict(), indent=2, ensure_ascii=False)),
html.escape(str(context.chat_data)), html.escape(str(context.chat_data)),
html.escape(str(context.user_data)), html.escape(str(context.user_data)),
html.escape(tb), html.escape(tb_string),
) )
# Finally, send the message # Finally, send the message
context.bot.send_message(chat_id=DEVELOPER_CHAT_ID, text=message, parse_mode=ParseMode.HTML) context.bot.send_message(chat_id=DEVELOPER_CHAT_ID, text=message, parse_mode=ParseMode.HTML)
def bad_command(update: Update, context: CallbackContext): def bad_command(update: Update, context: CallbackContext) -> None:
"""Raise an error to trigger the error handler.""" """Raise an error to trigger the error handler."""
context.bot.wrong_method_name() context.bot.wrong_method_name()
def start(update: Update, context: CallbackContext): def start(update: Update, context: CallbackContext) -> None:
update.effective_message.reply_html( update.effective_message.reply_html(
'Use /bad_command to cause an error.\n' 'Use /bad_command to cause an error.\n'
'Your chat id is <code>{}</code>.'.format(update.effective_chat.id) 'Your chat id is <code>{}</code>.'.format(update.effective_chat.id)
@ -75,14 +77,14 @@ def main():
updater = Updater(BOT_TOKEN, use_context=True) updater = Updater(BOT_TOKEN, use_context=True)
# Get the dispatcher to register handlers # Get the dispatcher to register handlers
dp = updater.dispatcher dispatcher = updater.dispatcher
# Register the commands... # Register the commands...
dp.add_handler(CommandHandler('start', start)) dispatcher.add_handler(CommandHandler('start', start))
dp.add_handler(CommandHandler('bad_command', bad_command)) dispatcher.add_handler(CommandHandler('bad_command', bad_command))
# ...and the error handler # ...and the error handler
dp.add_error_handler(error_handler) dispatcher.add_error_handler(error_handler)
# Start the Bot # Start the Bot
updater.start_polling() updater.start_polling()

View file

@ -1,5 +1,7 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# pylint: disable=W0613, C0116
# type: ignore[union-attr]
# This program is dedicated to the public domain under the CC0 license. # This program is dedicated to the public domain under the CC0 license.
""" """
@ -15,8 +17,8 @@ bot.
import logging import logging
from uuid import uuid4 from uuid import uuid4
from telegram import InlineQueryResultArticle, ParseMode, InputTextMessageContent from telegram import InlineQueryResultArticle, ParseMode, InputTextMessageContent, Update
from telegram.ext import Updater, InlineQueryHandler, CommandHandler from telegram.ext import Updater, InlineQueryHandler, CommandHandler, CallbackContext
from telegram.utils.helpers import escape_markdown from telegram.utils.helpers import escape_markdown
# Enable logging # Enable logging
@ -29,17 +31,17 @@ logger = logging.getLogger(__name__)
# Define a few command handlers. These usually take the two arguments update and # Define a few command handlers. These usually take the two arguments update and
# context. Error handlers also receive the raised TelegramError object in error. # context. Error handlers also receive the raised TelegramError object in error.
def start(update, context): def start(update: Update, context: CallbackContext) -> None:
"""Send a message when the command /start is issued.""" """Send a message when the command /start is issued."""
update.message.reply_text('Hi!') update.message.reply_text('Hi!')
def help_command(update, context): def help_command(update: Update, context: CallbackContext) -> None:
"""Send a message when the command /help is issued.""" """Send a message when the command /help is issued."""
update.message.reply_text('Help!') update.message.reply_text('Help!')
def inlinequery(update, context): def inlinequery(update: Update, context: CallbackContext) -> None:
"""Handle the inline query.""" """Handle the inline query."""
query = update.inline_query.query query = update.inline_query.query
results = [ results = [
@ -65,21 +67,21 @@ def inlinequery(update, context):
update.inline_query.answer(results) update.inline_query.answer(results)
def main(): def main() -> None:
# Create the Updater and pass it your bot's token. # Create the Updater and pass it your bot's token.
# Make sure to set use_context=True to use the new context based callbacks # Make sure to set use_context=True to use the new context based callbacks
# Post version 12 this will no longer be necessary # Post version 12 this will no longer be necessary
updater = Updater("TOKEN", use_context=True) updater = Updater("TOKEN", use_context=True)
# Get the dispatcher to register handlers # Get the dispatcher to register handlers
dp = updater.dispatcher dispatcher = updater.dispatcher
# on different commands - answer in Telegram # on different commands - answer in Telegram
dp.add_handler(CommandHandler("start", start)) dispatcher.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", help_command)) dispatcher.add_handler(CommandHandler("help", help_command))
# on noncommand i.e message - echo the message on Telegram # on noncommand i.e message - echo the message on Telegram
dp.add_handler(InlineQueryHandler(inlinequery)) dispatcher.add_handler(InlineQueryHandler(inlinequery))
# Start the Bot # Start the Bot
updater.start_polling() updater.start_polling()

View file

@ -1,5 +1,7 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# pylint: disable=W0613, C0116
# type: ignore[union-attr]
# This program is dedicated to the public domain under the CC0 license. # This program is dedicated to the public domain under the CC0 license.
""" """
@ -7,8 +9,8 @@ Basic example for a bot that uses inline keyboards.
""" """
import logging import logging
from telegram import InlineKeyboardButton, InlineKeyboardMarkup from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update
from telegram.ext import Updater, CommandHandler, CallbackQueryHandler from telegram.ext import Updater, CommandHandler, CallbackQueryHandler, CallbackContext
logging.basicConfig( logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO
@ -16,7 +18,7 @@ logging.basicConfig(
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
def start(update, context): def start(update: Update, context: CallbackContext) -> None:
keyboard = [ keyboard = [
[ [
InlineKeyboardButton("Option 1", callback_data='1'), InlineKeyboardButton("Option 1", callback_data='1'),
@ -30,7 +32,7 @@ def start(update, context):
update.message.reply_text('Please choose:', reply_markup=reply_markup) update.message.reply_text('Please choose:', reply_markup=reply_markup)
def button(update, context): def button(update: Update, context: CallbackContext) -> None:
query = update.callback_query query = update.callback_query
# CallbackQueries need to be answered, even if no notification to the user is needed # CallbackQueries need to be answered, even if no notification to the user is needed
@ -40,7 +42,7 @@ def button(update, context):
query.edit_message_text(text="Selected option: {}".format(query.data)) query.edit_message_text(text="Selected option: {}".format(query.data))
def help_command(update, context): def help_command(update: Update, context: CallbackContext) -> None:
update.message.reply_text("Use /start to test this bot.") update.message.reply_text("Use /start to test this bot.")

View file

@ -1,5 +1,9 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# pylint: disable=W0613, C0116
# type: ignore[union-attr]
# This program is dedicated to the public domain under the CC0 license.
"""Simple inline keyboard bot with multiple CallbackQueryHandlers. """Simple inline keyboard bot with multiple CallbackQueryHandlers.
This Bot uses the Updater class to handle the bot. This Bot uses the Updater class to handle the bot.
@ -12,9 +16,15 @@ ConversationHandler.
Send /start to initiate the conversation. Send /start to initiate the conversation.
Press Ctrl-C on the command line to stop the bot. Press Ctrl-C on the command line to stop the bot.
""" """
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Updater, CommandHandler, CallbackQueryHandler, ConversationHandler
import logging import logging
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update
from telegram.ext import (
Updater,
CommandHandler,
CallbackQueryHandler,
ConversationHandler,
CallbackContext,
)
# Enable logging # Enable logging
logging.basicConfig( logging.basicConfig(
@ -29,7 +39,7 @@ FIRST, SECOND = range(2)
ONE, TWO, THREE, FOUR = range(4) ONE, TWO, THREE, FOUR = range(4)
def start(update, context): def start(update: Update, context: CallbackContext) -> None:
"""Send message on `/start`.""" """Send message on `/start`."""
# Get user that sent /start and log his name # Get user that sent /start and log his name
user = update.message.from_user user = update.message.from_user
@ -51,7 +61,7 @@ def start(update, context):
return FIRST return FIRST
def start_over(update, context): def start_over(update: Update, context: CallbackContext) -> None:
"""Prompt same text & keyboard as `start` does but not as new message""" """Prompt same text & keyboard as `start` does but not as new message"""
# Get CallbackQuery from Update # Get CallbackQuery from Update
query = update.callback_query query = update.callback_query
@ -72,7 +82,7 @@ def start_over(update, context):
return FIRST return FIRST
def one(update, context): def one(update: Update, context: CallbackContext) -> None:
"""Show new choice of buttons""" """Show new choice of buttons"""
query = update.callback_query query = update.callback_query
query.answer() query.answer()
@ -89,7 +99,7 @@ def one(update, context):
return FIRST return FIRST
def two(update, context): def two(update: Update, context: CallbackContext) -> None:
"""Show new choice of buttons""" """Show new choice of buttons"""
query = update.callback_query query = update.callback_query
query.answer() query.answer()
@ -106,7 +116,7 @@ def two(update, context):
return FIRST return FIRST
def three(update, context): def three(update: Update, context: CallbackContext) -> None:
"""Show new choice of buttons""" """Show new choice of buttons"""
query = update.callback_query query = update.callback_query
query.answer() query.answer()
@ -124,7 +134,7 @@ def three(update, context):
return SECOND return SECOND
def four(update, context): def four(update: Update, context: CallbackContext) -> None:
"""Show new choice of buttons""" """Show new choice of buttons"""
query = update.callback_query query = update.callback_query
query.answer() query.answer()
@ -141,7 +151,7 @@ def four(update, context):
return FIRST return FIRST
def end(update, context): def end(update: Update, context: CallbackContext) -> None:
"""Returns `ConversationHandler.END`, which tells the """Returns `ConversationHandler.END`, which tells the
ConversationHandler that the conversation is over""" ConversationHandler that the conversation is over"""
query = update.callback_query query = update.callback_query
@ -155,7 +165,7 @@ def main():
updater = Updater("TOKEN", use_context=True) updater = Updater("TOKEN", use_context=True)
# Get the dispatcher to register handlers # Get the dispatcher to register handlers
dp = updater.dispatcher dispatcher = updater.dispatcher
# Setup conversation handler with the states FIRST and SECOND # Setup conversation handler with the states FIRST and SECOND
# Use the pattern parameter to pass CallbackQueries with specific # Use the pattern parameter to pass CallbackQueries with specific
@ -182,7 +192,7 @@ def main():
# Add ConversationHandler to dispatcher that will be used for handling # Add ConversationHandler to dispatcher that will be used for handling
# updates # updates
dp.add_handler(conv_handler) dispatcher.add_handler(conv_handler)
# Start the Bot # Start the Bot
updater.start_polling() updater.start_polling()

View file

@ -1,5 +1,7 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# pylint: disable=W0613, C0116
# type: ignore[union-attr]
# This program is dedicated to the public domain under the CC0 license. # This program is dedicated to the public domain under the CC0 license.
""" """
@ -16,7 +18,7 @@ bot.
import logging import logging
from telegram import InlineKeyboardMarkup, InlineKeyboardButton from telegram import InlineKeyboardMarkup, InlineKeyboardButton, Update
from telegram.ext import ( from telegram.ext import (
Updater, Updater,
CommandHandler, CommandHandler,
@ -24,6 +26,7 @@ from telegram.ext import (
Filters, Filters,
ConversationHandler, ConversationHandler,
CallbackQueryHandler, CallbackQueryHandler,
CallbackContext,
) )
# Enable logging # Enable logging
@ -64,13 +67,12 @@ END = ConversationHandler.END
# Helper # Helper
def _name_switcher(level): def _name_switcher(level):
if level == PARENTS: if level == PARENTS:
return ('Father', 'Mother') return 'Father', 'Mother'
elif level == CHILDREN: return 'Brother', 'Sister'
return ('Brother', 'Sister')
# Top level conversation callbacks # Top level conversation callbacks
def start(update, context): def start(update: Update, context: CallbackContext) -> None:
"""Select an action: Adding parent/child or show data.""" """Select an action: Adding parent/child or show data."""
text = ( text = (
'You may add a familiy member, yourself show the gathered data or end the ' 'You may add a familiy member, yourself show the gathered data or end the '
@ -102,7 +104,7 @@ def start(update, context):
return SELECTING_ACTION return SELECTING_ACTION
def adding_self(update, context): def adding_self(update: Update, context: CallbackContext) -> None:
"""Add information about youself.""" """Add information about youself."""
context.user_data[CURRENT_LEVEL] = SELF context.user_data[CURRENT_LEVEL] = SELF
text = 'Okay, please tell me about yourself.' text = 'Okay, please tell me about yourself.'
@ -115,7 +117,7 @@ def adding_self(update, context):
return DESCRIBING_SELF return DESCRIBING_SELF
def show_data(update, context): def show_data(update: Update, context: CallbackContext) -> None:
"""Pretty print gathered data.""" """Pretty print gathered data."""
def prettyprint(user_data, level): def prettyprint(user_data, level):
@ -137,29 +139,29 @@ def show_data(update, context):
) )
return text return text
ud = context.user_data user_data = context.user_data
text = 'Yourself:' + prettyprint(ud, SELF) text = 'Yourself:' + prettyprint(user_data, SELF)
text += '\n\nParents:' + prettyprint(ud, PARENTS) text += '\n\nParents:' + prettyprint(user_data, PARENTS)
text += '\n\nChildren:' + prettyprint(ud, CHILDREN) text += '\n\nChildren:' + prettyprint(user_data, CHILDREN)
buttons = [[InlineKeyboardButton(text='Back', callback_data=str(END))]] buttons = [[InlineKeyboardButton(text='Back', callback_data=str(END))]]
keyboard = InlineKeyboardMarkup(buttons) keyboard = InlineKeyboardMarkup(buttons)
update.callback_query.answer() update.callback_query.answer()
update.callback_query.edit_message_text(text=text, reply_markup=keyboard) update.callback_query.edit_message_text(text=text, reply_markup=keyboard)
ud[START_OVER] = True user_data[START_OVER] = True
return SHOWING return SHOWING
def stop(update, context): def stop(update: Update, context: CallbackContext) -> None:
"""End Conversation by command.""" """End Conversation by command."""
update.message.reply_text('Okay, bye.') update.message.reply_text('Okay, bye.')
return END return END
def end(update, context): def end(update: Update, context: CallbackContext) -> None:
"""End conversation from InlineKeyboardButton.""" """End conversation from InlineKeyboardButton."""
update.callback_query.answer() update.callback_query.answer()
@ -170,7 +172,7 @@ def end(update, context):
# Second level conversation callbacks # Second level conversation callbacks
def select_level(update, context): def select_level(update: Update, context: CallbackContext) -> None:
"""Choose to add a parent or a child.""" """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.' text = 'You may add a parent or a child. Also you can show the gathered data or go back.'
buttons = [ buttons = [
@ -191,7 +193,7 @@ def select_level(update, context):
return SELECTING_LEVEL return SELECTING_LEVEL
def select_gender(update, context): def select_gender(update: Update, context: CallbackContext) -> None:
"""Choose to add mother or father.""" """Choose to add mother or father."""
level = update.callback_query.data level = update.callback_query.data
context.user_data[CURRENT_LEVEL] = level context.user_data[CURRENT_LEVEL] = level
@ -218,7 +220,7 @@ def select_gender(update, context):
return SELECTING_GENDER return SELECTING_GENDER
def end_second_level(update, context): def end_second_level(update: Update, context: CallbackContext) -> None:
"""Return to top level conversation.""" """Return to top level conversation."""
context.user_data[START_OVER] = True context.user_data[START_OVER] = True
start(update, context) start(update, context)
@ -227,7 +229,7 @@ def end_second_level(update, context):
# Third level callbacks # Third level callbacks
def select_feature(update, context): def select_feature(update: Update, context: CallbackContext) -> None:
"""Select a feature to update for the person.""" """Select a feature to update for the person."""
buttons = [ buttons = [
[ [
@ -254,7 +256,7 @@ def select_feature(update, context):
return SELECTING_FEATURE return SELECTING_FEATURE
def ask_for_input(update, context): def ask_for_input(update: Update, context: CallbackContext) -> None:
"""Prompt user to input data for selected feature.""" """Prompt user to input data for selected feature."""
context.user_data[CURRENT_FEATURE] = update.callback_query.data context.user_data[CURRENT_FEATURE] = update.callback_query.data
text = 'Okay, tell me.' text = 'Okay, tell me.'
@ -265,27 +267,27 @@ def ask_for_input(update, context):
return TYPING return TYPING
def save_input(update, context): def save_input(update: Update, context: CallbackContext) -> None:
"""Save input for feature and return to feature selection.""" """Save input for feature and return to feature selection."""
ud = context.user_data user_data = context.user_data
ud[FEATURES][ud[CURRENT_FEATURE]] = update.message.text user_data[FEATURES][user_data[CURRENT_FEATURE]] = update.message.text
ud[START_OVER] = True user_data[START_OVER] = True
return select_feature(update, context) return select_feature(update, context)
def end_describing(update, context): def end_describing(update: Update, context: CallbackContext) -> None:
"""End gathering of features and return to parent conversation.""" """End gathering of features and return to parent conversation."""
ud = context.user_data user_data = context.user_data
level = ud[CURRENT_LEVEL] level = user_data[CURRENT_LEVEL]
if not ud.get(level): if not user_data.get(level):
ud[level] = [] user_data[level] = []
ud[level].append(ud[FEATURES]) user_data[level].append(user_data[FEATURES])
# Print upper level menu # Print upper level menu
if level == SELF: if level == SELF:
ud[START_OVER] = True user_data[START_OVER] = True
start(update, context) start(update, context)
else: else:
select_level(update, context) select_level(update, context)
@ -293,7 +295,7 @@ def end_describing(update, context):
return END return END
def stop_nested(update, context): def stop_nested(update: Update, context: CallbackContext) -> None:
"""Completely end conversation from within nested conversation.""" """Completely end conversation from within nested conversation."""
update.message.reply_text('Okay, bye.') update.message.reply_text('Okay, bye.')
@ -307,7 +309,7 @@ def main():
updater = Updater("TOKEN", use_context=True) updater = Updater("TOKEN", use_context=True)
# Get the dispatcher to register handlers # Get the dispatcher to register handlers
dp = updater.dispatcher dispatcher = updater.dispatcher
# Set up third level ConversationHandler (collecting features) # Set up third level ConversationHandler (collecting features)
description_conv = ConversationHandler( description_conv = ConversationHandler(
@ -381,7 +383,7 @@ def main():
fallbacks=[CommandHandler('stop', stop)], fallbacks=[CommandHandler('stop', stop)],
) )
dp.add_handler(conv_handler) dispatcher.add_handler(conv_handler)
# Start the Bot # Start the Bot
updater.start_polling() updater.start_polling()

View file

@ -1,5 +1,7 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# pylint: disable=W0613, C0116
# type: ignore[union-attr]
# This program is dedicated to the public domain under the CC0 license. # This program is dedicated to the public domain under the CC0 license.
""" """
@ -12,7 +14,8 @@ See https://git.io/fAvYd for how to use Telegram Passport properly with python-t
""" """
import logging import logging
from telegram.ext import Updater, MessageHandler, Filters from telegram import Update
from telegram.ext import Updater, MessageHandler, Filters, CallbackContext
# Enable logging # Enable logging
logging.basicConfig( logging.basicConfig(
@ -22,7 +25,7 @@ logging.basicConfig(
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
def msg(update, context): def msg(update: Update, context: CallbackContext) -> None:
# If we received any passport data # If we received any passport data
passport_data = update.message.passport_data passport_data = update.message.passport_data
if passport_data: if passport_data:
@ -100,10 +103,10 @@ def main():
updater = Updater("TOKEN", private_key=open('private.key', 'rb').read()) updater = Updater("TOKEN", private_key=open('private.key', 'rb').read())
# Get the dispatcher to register handlers # Get the dispatcher to register handlers
dp = updater.dispatcher dispatcher = updater.dispatcher
# On messages that include passport data call msg # On messages that include passport data call msg
dp.add_handler(MessageHandler(Filters.passport_data, msg)) dispatcher.add_handler(MessageHandler(Filters.passport_data, msg))
# Start the Bot # Start the Bot
updater.start_polling() updater.start_polling()

View file

@ -1,5 +1,7 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# pylint: disable=W0613, C0116
# type: ignore[union-attr]
# This program is dedicated to the public domain under the CC0 license. # This program is dedicated to the public domain under the CC0 license.
""" """
@ -8,7 +10,7 @@ Basic example for a bot that can receive payment from user.
import logging import logging
from telegram import LabeledPrice, ShippingOption from telegram import LabeledPrice, ShippingOption, Update
from telegram.ext import ( from telegram.ext import (
Updater, Updater,
CommandHandler, CommandHandler,
@ -16,6 +18,7 @@ from telegram.ext import (
Filters, Filters,
PreCheckoutQueryHandler, PreCheckoutQueryHandler,
ShippingQueryHandler, ShippingQueryHandler,
CallbackContext,
) )
# Enable logging # Enable logging
@ -26,13 +29,13 @@ logging.basicConfig(
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
def start_callback(update, context): def start_callback(update: Update, context: CallbackContext) -> None:
msg = "Use /shipping to get an invoice for shipping-payment, " msg = "Use /shipping to get an invoice for shipping-payment, "
msg += "or /noshipping for an invoice without shipping." msg += "or /noshipping for an invoice without shipping."
update.message.reply_text(msg) update.message.reply_text(msg)
def start_with_shipping_callback(update, context): def start_with_shipping_callback(update: Update, context: CallbackContext) -> None:
chat_id = update.message.chat_id chat_id = update.message.chat_id
title = "Payment Example" title = "Payment Example"
description = "Payment Example using python-telegram-bot" description = "Payment Example using python-telegram-bot"
@ -67,7 +70,7 @@ def start_with_shipping_callback(update, context):
) )
def start_without_shipping_callback(update, context): def start_without_shipping_callback(update: Update, context: CallbackContext) -> None:
chat_id = update.message.chat_id chat_id = update.message.chat_id
title = "Payment Example" title = "Payment Example"
description = "Payment Example using python-telegram-bot" description = "Payment Example using python-telegram-bot"
@ -89,14 +92,14 @@ def start_without_shipping_callback(update, context):
) )
def shipping_callback(update, context): def shipping_callback(update: Update, context: CallbackContext) -> None:
query = update.shipping_query query = update.shipping_query
# check the payload, is this from your bot? # check the payload, is this from your bot?
if query.invoice_payload != 'Custom-Payload': if query.invoice_payload != 'Custom-Payload':
# answer False pre_checkout_query # answer False pre_checkout_query
query.answer(ok=False, error_message="Something went wrong...") query.answer(ok=False, error_message="Something went wrong...")
return return
else:
options = list() options = list()
# a single LabeledPrice # a single LabeledPrice
options.append(ShippingOption('1', 'Shipping Option A', [LabeledPrice('A', 100)])) options.append(ShippingOption('1', 'Shipping Option A', [LabeledPrice('A', 100)]))
@ -107,7 +110,7 @@ def shipping_callback(update, context):
# after (optional) shipping, it's the pre-checkout # after (optional) shipping, it's the pre-checkout
def precheckout_callback(update, context): def precheckout_callback(update: Update, context: CallbackContext) -> None:
query = update.pre_checkout_query query = update.pre_checkout_query
# check the payload, is this from your bot? # check the payload, is this from your bot?
if query.invoice_payload != 'Custom-Payload': if query.invoice_payload != 'Custom-Payload':
@ -118,7 +121,7 @@ def precheckout_callback(update, context):
# finally, after contacting the payment provider... # finally, after contacting the payment provider...
def successful_payment_callback(update, context): def successful_payment_callback(update: Update, context: CallbackContext) -> None:
# do something after successfully receiving payment? # do something after successfully receiving payment?
update.message.reply_text("Thank you for your payment!") update.message.reply_text("Thank you for your payment!")
@ -130,23 +133,23 @@ def main():
updater = Updater("TOKEN", use_context=True) updater = Updater("TOKEN", use_context=True)
# Get the dispatcher to register handlers # Get the dispatcher to register handlers
dp = updater.dispatcher dispatcher = updater.dispatcher
# simple start function # simple start function
dp.add_handler(CommandHandler("start", start_callback)) dispatcher.add_handler(CommandHandler("start", start_callback))
# Add command handler to start the payment invoice # Add command handler to start the payment invoice
dp.add_handler(CommandHandler("shipping", start_with_shipping_callback)) dispatcher.add_handler(CommandHandler("shipping", start_with_shipping_callback))
dp.add_handler(CommandHandler("noshipping", start_without_shipping_callback)) dispatcher.add_handler(CommandHandler("noshipping", start_without_shipping_callback))
# Optional handler if your product requires shipping # Optional handler if your product requires shipping
dp.add_handler(ShippingQueryHandler(shipping_callback)) dispatcher.add_handler(ShippingQueryHandler(shipping_callback))
# Pre-checkout handler to final check # Pre-checkout handler to final check
dp.add_handler(PreCheckoutQueryHandler(precheckout_callback)) dispatcher.add_handler(PreCheckoutQueryHandler(precheckout_callback))
# Success! Notify your user! # Success! Notify your user!
dp.add_handler(MessageHandler(Filters.successful_payment, successful_payment_callback)) dispatcher.add_handler(MessageHandler(Filters.successful_payment, successful_payment_callback))
# Start the Bot # Start the Bot
updater.start_polling() updater.start_polling()

View file

@ -1,5 +1,7 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# pylint: disable=W0613, C0116, C0103
# type: ignore[union-attr]
# This program is dedicated to the public domain under the CC0 license. # This program is dedicated to the public domain under the CC0 license.
""" """
@ -14,7 +16,9 @@ Press Ctrl-C on the command line or send a signal to the process to stop the
bot. bot.
""" """
from telegram import ReplyKeyboardMarkup import logging
from telegram import ReplyKeyboardMarkup, Update
from telegram.ext import ( from telegram.ext import (
Updater, Updater,
CommandHandler, CommandHandler,
@ -22,9 +26,9 @@ from telegram.ext import (
Filters, Filters,
ConversationHandler, ConversationHandler,
PicklePersistence, PicklePersistence,
CallbackContext,
) )
import logging
# Enable logging # Enable logging
logging.basicConfig( logging.basicConfig(
@ -52,7 +56,7 @@ def facts_to_str(user_data):
return "\n".join(facts).join(['\n', '\n']) return "\n".join(facts).join(['\n', '\n'])
def start(update, context): def start(update: Update, context: CallbackContext) -> None:
reply_text = "Hi! My name is Doctor Botter." reply_text = "Hi! My name is Doctor Botter."
if context.user_data: if context.user_data:
reply_text += ( reply_text += (
@ -70,7 +74,7 @@ def start(update, context):
return CHOOSING return CHOOSING
def regular_choice(update, context): def regular_choice(update: Update, context: CallbackContext) -> None:
text = update.message.text.lower() text = update.message.text.lower()
context.user_data['choice'] = text context.user_data['choice'] = text
if context.user_data.get(text): if context.user_data.get(text):
@ -84,7 +88,7 @@ def regular_choice(update, context):
return TYPING_REPLY return TYPING_REPLY
def custom_choice(update, context): def custom_choice(update: Update, context: CallbackContext) -> None:
update.message.reply_text( update.message.reply_text(
'Alright, please send me the category first, ' 'for example "Most impressive skill"' 'Alright, please send me the category first, ' 'for example "Most impressive skill"'
) )
@ -92,7 +96,7 @@ def custom_choice(update, context):
return TYPING_CHOICE return TYPING_CHOICE
def received_information(update, context): def received_information(update: Update, context: CallbackContext) -> None:
text = update.message.text text = update.message.text
category = context.user_data['choice'] category = context.user_data['choice']
context.user_data[category] = text.lower() context.user_data[category] = text.lower()
@ -109,13 +113,13 @@ def received_information(update, context):
return CHOOSING return CHOOSING
def show_data(update, context): def show_data(update: Update, context: CallbackContext) -> None:
update.message.reply_text( update.message.reply_text(
"This is what you already told me:" "{}".format(facts_to_str(context.user_data)) "This is what you already told me:" "{}".format(facts_to_str(context.user_data))
) )
def done(update, context): def done(update: Update, context: CallbackContext) -> None:
if 'choice' in context.user_data: if 'choice' in context.user_data:
del context.user_data['choice'] del context.user_data['choice']

View file

@ -1,5 +1,7 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# pylint: disable=W0613, C0116
# type: ignore[union-attr]
# This program is dedicated to the public domain under the CC0 license. # This program is dedicated to the public domain under the CC0 license.
""" """
@ -16,6 +18,7 @@ from telegram import (
KeyboardButtonPollType, KeyboardButtonPollType,
ReplyKeyboardMarkup, ReplyKeyboardMarkup,
ReplyKeyboardRemove, ReplyKeyboardRemove,
Update,
) )
from telegram.ext import ( from telegram.ext import (
Updater, Updater,
@ -24,6 +27,7 @@ from telegram.ext import (
PollHandler, PollHandler,
MessageHandler, MessageHandler,
Filters, Filters,
CallbackContext,
) )
logging.basicConfig( logging.basicConfig(
@ -32,7 +36,7 @@ logging.basicConfig(
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
def start(update, context): def start(update: Update, context: CallbackContext) -> None:
"""Inform user about what this bot can do""" """Inform user about what this bot can do"""
update.message.reply_text( update.message.reply_text(
'Please select /poll to get a Poll, /quiz to get a Quiz or /preview' 'Please select /poll to get a Poll, /quiz to get a Quiz or /preview'
@ -40,7 +44,7 @@ def start(update, context):
) )
def poll(update, context): def poll(update: Update, context: CallbackContext) -> None:
"""Sends a predefined poll""" """Sends a predefined poll"""
questions = ["Good", "Really good", "Fantastic", "Great"] questions = ["Good", "Really good", "Fantastic", "Great"]
message = context.bot.send_poll( message = context.bot.send_poll(
@ -62,7 +66,7 @@ def poll(update, context):
context.bot_data.update(payload) context.bot_data.update(payload)
def receive_poll_answer(update, context): def receive_poll_answer(update: Update, context: CallbackContext) -> None:
"""Summarize a users poll vote""" """Summarize a users poll vote"""
answer = update.poll_answer answer = update.poll_answer
poll_id = answer.poll_id poll_id = answer.poll_id
@ -91,7 +95,7 @@ def receive_poll_answer(update, context):
) )
def quiz(update, context): def quiz(update: Update, context: CallbackContext) -> None:
"""Send a predefined poll""" """Send a predefined poll"""
questions = ["1", "2", "4", "20"] questions = ["1", "2", "4", "20"]
message = update.effective_message.reply_poll( message = update.effective_message.reply_poll(
@ -104,7 +108,7 @@ def quiz(update, context):
context.bot_data.update(payload) context.bot_data.update(payload)
def receive_quiz_answer(update, context): def receive_quiz_answer(update: Update, context: CallbackContext) -> None:
"""Close quiz after three participants took it""" """Close quiz after three participants took it"""
# the bot can receive closed poll updates we don't care about # the bot can receive closed poll updates we don't care about
if update.poll.is_closed: if update.poll.is_closed:
@ -118,7 +122,7 @@ def receive_quiz_answer(update, context):
context.bot.stop_poll(quiz_data["chat_id"], quiz_data["message_id"]) context.bot.stop_poll(quiz_data["chat_id"], quiz_data["message_id"])
def preview(update, context): def preview(update: Update, context: CallbackContext) -> None:
"""Ask user to create a poll and display a preview of it""" """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) # using this without a type lets the user chooses what he wants (quiz or poll)
button = [[KeyboardButton("Press me!", request_poll=KeyboardButtonPollType())]] button = [[KeyboardButton("Press me!", request_poll=KeyboardButtonPollType())]]
@ -129,7 +133,7 @@ def preview(update, context):
) )
def receive_poll(update, context): def receive_poll(update: Update, context: CallbackContext) -> None:
"""On receiving polls, reply to it by a closed poll copying the received poll""" """On receiving polls, reply to it by a closed poll copying the received poll"""
actual_poll = update.effective_message.poll actual_poll = update.effective_message.poll
# Only need to set the question and options, since all other parameters don't matter for # Only need to set the question and options, since all other parameters don't matter for
@ -143,25 +147,25 @@ def receive_poll(update, context):
) )
def help_handler(update, context): def help_handler(update: Update, context: CallbackContext) -> None:
"""Display a help message""" """Display a help message"""
update.message.reply_text("Use /quiz, /poll or /preview to test this " "bot.") update.message.reply_text("Use /quiz, /poll or /preview to test this " "bot.")
def main(): def main() -> None:
# Create the Updater and pass it your bot's token. # Create the Updater and pass it your bot's token.
# Make sure to set use_context=True to use the new context based callbacks # Make sure to set use_context=True to use the new context based callbacks
# Post version 12 this will no longer be necessary # Post version 12 this will no longer be necessary
updater = Updater("TOKEN", use_context=True) updater = Updater("TOKEN", use_context=True)
dp = updater.dispatcher dispatcher = updater.dispatcher
dp.add_handler(CommandHandler('start', start)) dispatcher.add_handler(CommandHandler('start', start))
dp.add_handler(CommandHandler('poll', poll)) dispatcher.add_handler(CommandHandler('poll', poll))
dp.add_handler(PollAnswerHandler(receive_poll_answer)) dispatcher.add_handler(PollAnswerHandler(receive_poll_answer))
dp.add_handler(CommandHandler('quiz', quiz)) dispatcher.add_handler(CommandHandler('quiz', quiz))
dp.add_handler(PollHandler(receive_quiz_answer)) dispatcher.add_handler(PollHandler(receive_quiz_answer))
dp.add_handler(CommandHandler('preview', preview)) dispatcher.add_handler(CommandHandler('preview', preview))
dp.add_handler(MessageHandler(Filters.poll, receive_poll)) dispatcher.add_handler(MessageHandler(Filters.poll, receive_poll))
dp.add_handler(CommandHandler('help', help_handler)) dispatcher.add_handler(CommandHandler('help', help_handler))
# Start the Bot # Start the Bot
updater.start_polling() updater.start_polling()

View file

@ -1,5 +1,6 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# pylint: disable=W0603
"""Simple Bot to reply to Telegram messages. """Simple Bot to reply to Telegram messages.
This is built on the API wrapper, see rawapibot.py to see the same example built This is built on the API wrapper, see rawapibot.py to see the same example built
@ -7,26 +8,28 @@ on the telegram.ext bot framework.
This program is dedicated to the public domain under the CC0 license. This program is dedicated to the public domain under the CC0 license.
""" """
import logging import logging
import telegram from typing import NoReturn
from telegram.error import NetworkError, Unauthorized
from time import sleep from time import sleep
import telegram
update_id = None from telegram.error import NetworkError, Unauthorized
def main(): UPDATE_ID = None
def main() -> NoReturn:
"""Run the bot.""" """Run the bot."""
global update_id global UPDATE_ID
# Telegram Bot Authorization Token # Telegram Bot Authorization Token
bot = telegram.Bot('TOKEN') bot = telegram.Bot('TOKEN')
# get the first pending update_id, this is so we can skip over it in case # get the first pending update_id, this is so we can skip over it in case
# we get an "Unauthorized" exception. # we get an "Unauthorized" exception.
try: try:
update_id = bot.get_updates()[0].update_id UPDATE_ID = bot.get_updates()[0].update_id
except IndexError: except IndexError:
update_id = None UPDATE_ID = None
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
@ -37,15 +40,15 @@ def main():
sleep(1) sleep(1)
except Unauthorized: except Unauthorized:
# The user has removed or blocked the bot. # The user has removed or blocked the bot.
update_id += 1 UPDATE_ID += 1 # type: ignore[operator]
def echo(bot): def echo(bot: telegram.Bot) -> None:
"""Echo the message the user sent.""" """Echo the message the user sent."""
global update_id global UPDATE_ID
# Request updates after the last update_id # Request updates after the last update_id
for update in bot.get_updates(offset=update_id, timeout=10): for update in bot.get_updates(offset=UPDATE_ID, timeout=10):
update_id = update.update_id + 1 UPDATE_ID = update.update_id + 1
if update.message: # your bot can receive updates without messages if update.message: # your bot can receive updates without messages
# Reply to the message # Reply to the message

View file

@ -1,5 +1,7 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# pylint: disable=W0613, C0116
# type: ignore[union-attr]
# This program is dedicated to the public domain under the CC0 license. # This program is dedicated to the public domain under the CC0 license.
""" """
@ -20,7 +22,8 @@ bot.
import logging import logging
from telegram.ext import Updater, CommandHandler from telegram import Update
from telegram.ext import Updater, CommandHandler, CallbackContext
# Enable logging # Enable logging
logging.basicConfig( logging.basicConfig(
@ -32,7 +35,7 @@ logger = logging.getLogger(__name__)
# Define a few command handlers. These usually take the two arguments update and # Define a few command handlers. These usually take the two arguments update and
# context. Error handlers also receive the raised TelegramError object in error. # context. Error handlers also receive the raised TelegramError object in error.
def start(update, context): def start(update: Update, context: CallbackContext) -> None:
update.message.reply_text('Hi! Use /set <seconds> to set a timer') update.message.reply_text('Hi! Use /set <seconds> to set a timer')
@ -52,7 +55,7 @@ def remove_job_if_exists(name, context):
return True return True
def set_timer(update, context): def set_timer(update: Update, context: CallbackContext) -> None:
"""Add a job to the queue.""" """Add a job to the queue."""
chat_id = update.message.chat_id chat_id = update.message.chat_id
try: try:
@ -74,7 +77,7 @@ def set_timer(update, context):
update.message.reply_text('Usage: /set <seconds>') update.message.reply_text('Usage: /set <seconds>')
def unset(update, context): def unset(update: Update, context: CallbackContext) -> None:
"""Remove the job if the user changed their mind.""" """Remove the job if the user changed their mind."""
chat_id = update.message.chat_id chat_id = update.message.chat_id
job_removed = remove_job_if_exists(str(chat_id), context) job_removed = remove_job_if_exists(str(chat_id), context)
@ -90,13 +93,13 @@ def main():
updater = Updater("TOKEN", use_context=True) updater = Updater("TOKEN", use_context=True)
# Get the dispatcher to register handlers # Get the dispatcher to register handlers
dp = updater.dispatcher dispatcher = updater.dispatcher
# on different commands - answer in Telegram # on different commands - answer in Telegram
dp.add_handler(CommandHandler("start", start)) dispatcher.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", start)) dispatcher.add_handler(CommandHandler("help", start))
dp.add_handler(CommandHandler("set", set_timer)) dispatcher.add_handler(CommandHandler("set", set_timer))
dp.add_handler(CommandHandler("unset", unset)) dispatcher.add_handler(CommandHandler("unset", unset))
# Start the Bot # Start the Bot
updater.start_polling() updater.start_polling()

View file

@ -1,12 +1,15 @@
flake8
pep257
pylint
flaky
yapf
mypy==0.770
pre-commit pre-commit
beautifulsoup4 # Make sure that the versions specified here match the pre-commit settings
black==20.8b1
flake8==3.8.4
pylint==2.6.0
mypy==0.790
pytest==4.2.0 pytest==4.2.0
# Need older attrs version for pytest 4.2.0
attrs==19.1.0
flaky
beautifulsoup4
pytest-timeout pytest-timeout
wheel wheel
attrs==19.1.0

View file

@ -13,7 +13,13 @@ upload-dir = docs/build/html
max-line-length = 99 max-line-length = 99
ignore = W503, W605 ignore = W503, W605
extend-ignore = E203 extend-ignore = E203
exclude = setup.py, docs/source/conf.py exclude = setup.py, docs/source/conf.py, telegram/vendor
[pylint]
ignore=vendor
[pylint.message-control]
disable = C0330,R0801,R0913,R0904,R0903,R0902,W0511,C0116,C0115,W0703,R0914,R0914,C0302,R0912,R0915,R0401
[tool:pytest] [tool:pytest]
testpaths = tests testpaths = tests
@ -52,3 +58,9 @@ ignore_errors = True
# We don't want to clutter the code with 'if self.bot is None: raise RuntimeError()' # We don't want to clutter the code with 'if self.bot is None: raise RuntimeError()'
[mypy-telegram.callbackquery,telegram.chat,telegram.message,telegram.user,telegram.files.*,telegram.inline.inlinequery,telegram.payment.precheckoutquery,telegram.payment.shippingquery,telegram.passport.passportdata,telegram.passport.credentials,telegram.passport.passportfile,telegram.ext.filters] [mypy-telegram.callbackquery,telegram.chat,telegram.message,telegram.user,telegram.files.*,telegram.inline.inlinequery,telegram.payment.precheckoutquery,telegram.payment.shippingquery,telegram.passport.passportdata,telegram.passport.credentials,telegram.passport.passportfile,telegram.ext.filters]
strict_optional = False strict_optional = False
[mypy-urllib3.*]
ignore_missing_imports = True
[mypy-apscheduler.*]
ignore_missing_imports = True

View file

@ -16,13 +16,13 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
import sys # pylint: disable=E0401, C0114
import subprocess import subprocess
import sys
from typing import Optional
import certifi import certifi
from typing import Optional
from . import __version__ as telegram_ver from . import __version__ as telegram_ver

View file

@ -23,9 +23,9 @@ except ImportError:
import json # type: ignore[no-redef] import json # type: ignore[no-redef]
import warnings import warnings
from typing import TYPE_CHECKING, Any, List, Optional, Tuple, Type, TypeVar
from telegram.utils.types import JSONDict from telegram.utils.types import JSONDict
from typing import Tuple, Any, Optional, Type, TypeVar, TYPE_CHECKING, List
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram import Bot from telegram import Bot
@ -36,7 +36,7 @@ TO = TypeVar('TO', bound='TelegramObject', covariant=True)
class TelegramObject: class TelegramObject:
"""Base class for most telegram objects.""" """Base class for most telegram objects."""
# def __init__(self, *args: Any, **kwargs: Any): # def __init__(self, *args: Any, **kwargs: Any): # pylint: disable=W0613
# pass # pass
_id_attrs: Tuple[Any, ...] = () _id_attrs: Tuple[Any, ...] = ()
@ -62,7 +62,6 @@ class TelegramObject:
if cls == TelegramObject: if cls == TelegramObject:
return cls() return cls()
else:
return cls(bot=bot, **data) # type: ignore[call-arg] return cls(bot=bot, **data) # type: ignore[call-arg]
@classmethod @classmethod

View file

@ -18,10 +18,27 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
# pylint: disable=E0401
"""This module contains an object that represents a Telegram Bot.""" """This module contains an object that represents a Telegram Bot."""
import functools import functools
import inspect import inspect
import logging
from datetime import datetime
from typing import (
IO,
TYPE_CHECKING,
Any,
Callable,
List,
Optional,
Tuple,
TypeVar,
Union,
cast,
no_type_check,
)
from decorator import decorate from decorator import decorate
@ -29,67 +46,51 @@ try:
import ujson as json import ujson as json
except ImportError: except ImportError:
import json # type: ignore[no-redef] # noqa: F723 import json # type: ignore[no-redef] # noqa: F723
import logging
from datetime import datetime
from cryptography.hazmat.backends import default_backend from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives import serialization
from telegram import ( from telegram import (
User, Animation,
Message, Audio,
Update, BotCommand,
Chat, Chat,
ChatMember, ChatMember,
UserProfilePhotos,
File,
ReplyMarkup,
TelegramObject,
WebhookInfo,
GameHighScore,
StickerSet,
PhotoSize,
Audio,
Document,
Sticker,
Video,
Animation,
Voice,
VideoNote,
Location,
Venue,
Contact,
InputFile,
Poll,
BotCommand,
InlineQueryResult,
InputMedia,
PassportElementError,
MaskPosition,
ChatPermissions, ChatPermissions,
ShippingOption,
LabeledPrice,
ChatPhoto, ChatPhoto,
Contact,
Document,
File,
GameHighScore,
InlineQueryResult,
InputFile,
InputMedia,
LabeledPrice,
Location,
MaskPosition,
Message,
PassportElementError,
PhotoSize,
Poll,
ReplyMarkup,
ShippingOption,
Sticker,
StickerSet,
TelegramObject,
Update,
User,
UserProfilePhotos,
Venue,
Video,
VideoNote,
Voice,
WebhookInfo,
) )
from telegram.constants import MAX_INLINE_QUERY_RESULTS from telegram.constants import MAX_INLINE_QUERY_RESULTS
from telegram.error import InvalidToken, TelegramError from telegram.error import InvalidToken, TelegramError
from telegram.utils.helpers import to_timestamp, DEFAULT_NONE, DefaultValue from telegram.utils.helpers import DEFAULT_NONE, DefaultValue, to_timestamp
from telegram.utils.request import Request from telegram.utils.request import Request
from telegram.utils.types import JSONDict, FileLike from telegram.utils.types import FileLike, JSONDict
from typing import (
Any,
Callable,
Optional,
TypeVar,
Union,
TYPE_CHECKING,
List,
Tuple,
no_type_check,
IO,
cast,
)
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram.ext import Defaults from telegram.ext import Defaults
@ -98,6 +99,7 @@ RT = TypeVar('RT')
def info(func: Callable[..., RT]) -> Callable[..., RT]: def info(func: Callable[..., RT]) -> Callable[..., RT]:
# pylint: disable=W0212
@functools.wraps(func) @functools.wraps(func)
def decorator(self: 'Bot', *args: Any, **kwargs: Any) -> RT: def decorator(self: 'Bot', *args: Any, **kwargs: Any) -> RT:
if not self.bot: if not self.bot:
@ -264,7 +266,7 @@ class Bot(TelegramObject):
result = self._post(endpoint, data, timeout=timeout, api_kwargs=api_kwargs) result = self._post(endpoint, data, timeout=timeout, api_kwargs=api_kwargs)
if result is True: if result is True:
return result # type: ignore return result
return Message.de_json(result, self) # type: ignore[arg-type] return Message.de_json(result, self) # type: ignore[arg-type]
@ -1346,7 +1348,7 @@ class Bot(TelegramObject):
"Either location or latitude and longitude must be passed as" "argument." "Either location or latitude and longitude must be passed as" "argument."
) )
if not ((latitude is not None or longitude is not None) ^ bool(location)): if not (latitude is not None or longitude is not None) ^ bool(location):
raise ValueError( raise ValueError(
"Either location or latitude and longitude must be passed as" "argument. Not both." "Either location or latitude and longitude must be passed as" "argument. Not both."
) )
@ -1417,7 +1419,7 @@ class Bot(TelegramObject):
raise ValueError( raise ValueError(
"Either location or latitude and longitude must be passed as" "argument." "Either location or latitude and longitude must be passed as" "argument."
) )
if not ((latitude is not None or longitude is not None) ^ bool(location)): if not (latitude is not None or longitude is not None) ^ bool(location):
raise ValueError( raise ValueError(
"Either location or latitude and longitude must be passed as" "argument. Not both." "Either location or latitude and longitude must be passed as" "argument. Not both."
) )
@ -1831,6 +1833,7 @@ class Bot(TelegramObject):
@no_type_check @no_type_check
def _set_defaults(res): def _set_defaults(res):
# pylint: disable=W0212
if res._has_parse_mode and res.parse_mode == DEFAULT_NONE: if res._has_parse_mode and res.parse_mode == DEFAULT_NONE:
if self.defaults: if self.defaults:
res.parse_mode = self.defaults.parse_mode res.parse_mode = self.defaults.parse_mode
@ -3207,7 +3210,7 @@ class Bot(TelegramObject):
""" """
ok = bool(ok) ok = bool(ok)
if not (ok ^ (error_message is not None)): if not (ok ^ (error_message is not None)): # pylint: disable=C0325
raise TelegramError( raise TelegramError(
'answerPreCheckoutQuery: If ok is True, there should ' 'answerPreCheckoutQuery: If ok is True, there should '
'not be error_message; if ok is False, error_message ' 'not be error_message; if ok is False, error_message '
@ -4079,7 +4082,7 @@ class Bot(TelegramObject):
question: str, question: str,
options: List[str], options: List[str],
is_anonymous: bool = True, is_anonymous: bool = True,
type: str = Poll.REGULAR, type: str = Poll.REGULAR, # pylint: disable=W0622
allows_multiple_answers: bool = False, allows_multiple_answers: bool = False,
correct_option_id: int = None, correct_option_id: int = None,
is_closed: bool = None, is_closed: bool = None,

View file

@ -18,9 +18,10 @@
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram Bot Command.""" """This module contains an object that represents a Telegram Bot Command."""
from telegram import TelegramObject
from typing import Any from typing import Any
from telegram import TelegramObject
class BotCommand(TelegramObject): class BotCommand(TelegramObject):
""" """
@ -39,7 +40,7 @@ class BotCommand(TelegramObject):
description (:obj:`str`): Description of the command, 3-256 characters. description (:obj:`str`): Description of the command, 3-256 characters.
""" """
def __init__(self, command: str, description: str, **kwargs: Any): def __init__(self, command: str, description: str, **kwargs: Any): # pylint: disable=W0613
self.command = command self.command = command
self.description = description self.description = description

View file

@ -16,14 +16,15 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
# pylint: disable=W0622
"""This module contains an object that represents a Telegram CallbackQuery""" """This module contains an object that represents a Telegram CallbackQuery"""
from telegram import TelegramObject, Message, User from typing import TYPE_CHECKING, Any, List, Optional, Union
from telegram import Message, TelegramObject, User
from telegram.utils.types import JSONDict from telegram.utils.types import JSONDict
from typing import Optional, Any, Union, TYPE_CHECKING, List
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram import Bot, InlineKeyboardMarkup, GameHighScore from telegram import Bot, GameHighScore, InlineKeyboardMarkup
class CallbackQuery(TelegramObject): class CallbackQuery(TelegramObject):
@ -79,8 +80,8 @@ class CallbackQuery(TelegramObject):
""" """
def __init__( def __init__(
self, self, # pylint: disable=W0613
id: str, id: str, # pylint: disable=W0622
from_user: User, from_user: User,
chat_instance: str, chat_instance: str,
message: Message = None, message: Message = None,
@ -91,7 +92,7 @@ class CallbackQuery(TelegramObject):
**kwargs: Any, **kwargs: Any,
): ):
# Required # Required
self.id = id self.id = id # pylint: disable=C0103
self.from_user = from_user self.from_user = from_user
self.chat_instance = chat_instance self.chat_instance = chat_instance
# Optionals # Optionals
@ -148,7 +149,6 @@ class CallbackQuery(TelegramObject):
return self.bot.edit_message_text( return self.bot.edit_message_text(
text, inline_message_id=self.inline_message_id, *args, **kwargs text, inline_message_id=self.inline_message_id, *args, **kwargs
) )
else:
return self.bot.edit_message_text( return self.bot.edit_message_text(
text, text,
chat_id=self.message.chat_id, chat_id=self.message.chat_id,
@ -182,7 +182,6 @@ class CallbackQuery(TelegramObject):
return self.bot.edit_message_caption( return self.bot.edit_message_caption(
caption=caption, inline_message_id=self.inline_message_id, *args, **kwargs caption=caption, inline_message_id=self.inline_message_id, *args, **kwargs
) )
else:
return self.bot.edit_message_caption( return self.bot.edit_message_caption(
caption=caption, caption=caption,
chat_id=self.message.chat_id, chat_id=self.message.chat_id,
@ -196,16 +195,21 @@ class CallbackQuery(TelegramObject):
) -> Union[Message, bool]: ) -> Union[Message, bool]:
"""Shortcut for either:: """Shortcut for either::
bot.edit_message_reply_markup(chat_id=update.callback_query.message.chat_id, bot.edit_message_reply_markup(
chat_id=update.callback_query.message.chat_id,
message_id=update.callback_query.message.message_id, message_id=update.callback_query.message.message_id,
reply_markup=reply_markup, reply_markup=reply_markup,
*args, **kwargs) *args, **kwargs
)
or:: or::
bot.edit_message_reply_markup(inline_message_id=update.callback_query.inline_message_id, bot.edit_message_reply_markup
inline_message_id=update.callback_query.inline_message_id,
reply_markup=reply_markup, reply_markup=reply_markup,
*args, **kwargs) *args,
**kwargs
)
Returns: Returns:
:class:`telegram.Message`: On success, if edited message is sent by the bot, the :class:`telegram.Message`: On success, if edited message is sent by the bot, the
@ -219,7 +223,6 @@ class CallbackQuery(TelegramObject):
*args, *args,
**kwargs, **kwargs,
) )
else:
return self.bot.edit_message_reply_markup( return self.bot.edit_message_reply_markup(
reply_markup=reply_markup, reply_markup=reply_markup,
chat_id=self.message.chat_id, chat_id=self.message.chat_id,
@ -251,7 +254,6 @@ class CallbackQuery(TelegramObject):
return self.bot.edit_message_media( return self.bot.edit_message_media(
inline_message_id=self.inline_message_id, *args, **kwargs inline_message_id=self.inline_message_id, *args, **kwargs
) )
else:
return self.bot.edit_message_media( return self.bot.edit_message_media(
chat_id=self.message.chat_id, message_id=self.message.message_id, *args, **kwargs chat_id=self.message.chat_id, message_id=self.message.message_id, *args, **kwargs
) )
@ -281,7 +283,6 @@ class CallbackQuery(TelegramObject):
return self.bot.edit_message_live_location( return self.bot.edit_message_live_location(
inline_message_id=self.inline_message_id, *args, **kwargs inline_message_id=self.inline_message_id, *args, **kwargs
) )
else:
return self.bot.edit_message_live_location( return self.bot.edit_message_live_location(
chat_id=self.message.chat_id, message_id=self.message.message_id, *args, **kwargs chat_id=self.message.chat_id, message_id=self.message.message_id, *args, **kwargs
) )
@ -311,7 +312,6 @@ class CallbackQuery(TelegramObject):
return self.bot.stop_message_live_location( return self.bot.stop_message_live_location(
inline_message_id=self.inline_message_id, *args, **kwargs inline_message_id=self.inline_message_id, *args, **kwargs
) )
else:
return self.bot.stop_message_live_location( return self.bot.stop_message_live_location(
chat_id=self.message.chat_id, message_id=self.message.message_id, *args, **kwargs chat_id=self.message.chat_id, message_id=self.message.message_id, *args, **kwargs
) )
@ -339,7 +339,6 @@ class CallbackQuery(TelegramObject):
return self.bot.set_game_score( return self.bot.set_game_score(
inline_message_id=self.inline_message_id, *args, **kwargs inline_message_id=self.inline_message_id, *args, **kwargs
) )
else:
return self.bot.set_game_score( return self.bot.set_game_score(
chat_id=self.message.chat_id, message_id=self.message.message_id, *args, **kwargs chat_id=self.message.chat_id, message_id=self.message.message_id, *args, **kwargs
) )
@ -366,7 +365,6 @@ class CallbackQuery(TelegramObject):
return self.bot.get_game_high_scores( return self.bot.get_game_high_scores(
inline_message_id=self.inline_message_id, *args, **kwargs inline_message_id=self.inline_message_id, *args, **kwargs
) )
else:
return self.bot.get_game_high_scores( return self.bot.get_game_high_scores(
chat_id=self.message.chat_id, message_id=self.message.message_id, *args, **kwargs chat_id=self.message.chat_id, message_id=self.message.message_id, *args, **kwargs
) )

View file

@ -19,14 +19,15 @@
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram Chat.""" """This module contains an object that represents a Telegram Chat."""
from telegram import TelegramObject, ChatPhoto, constants from typing import TYPE_CHECKING, Any, List, Optional, ClassVar
from telegram import ChatPhoto, TelegramObject, constants
from telegram.utils.types import JSONDict
from .chatpermissions import ChatPermissions from .chatpermissions import ChatPermissions
from telegram.utils.types import JSONDict
from typing import Any, Optional, List, TYPE_CHECKING, ClassVar
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram import Bot, Message, ChatMember from telegram import Bot, ChatMember, Message
class Chat(TelegramObject): class Chat(TelegramObject):
@ -102,7 +103,7 @@ class Chat(TelegramObject):
""":const:`telegram.constants.CHAT_CHANNEL`""" """:const:`telegram.constants.CHAT_CHANNEL`"""
def __init__( def __init__(
self, self, # pylint: disable=W0613
id: int, id: int,
type: str, type: str,
title: str = None, title: str = None,
@ -173,7 +174,7 @@ class Chat(TelegramObject):
return None return None
data['photo'] = ChatPhoto.de_json(data.get('photo'), bot) data['photo'] = ChatPhoto.de_json(data.get('photo'), bot)
from telegram import Message from telegram import Message # pylint: disable=C0415
data['pinned_message'] = Message.de_json(data.get('pinned_message'), bot) data['pinned_message'] = Message.de_json(data.get('pinned_message'), bot)
data['permissions'] = ChatPermissions.de_json(data.get('permissions'), bot) data['permissions'] = ChatPermissions.de_json(data.get('permissions'), bot)

View file

@ -18,12 +18,11 @@
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram ChatMember.""" """This module contains an object that represents a Telegram ChatMember."""
import datetime import datetime
from typing import TYPE_CHECKING, Any, Optional, ClassVar
from telegram import User, TelegramObject, constants from telegram import TelegramObject, User, constants
from telegram.utils.helpers import to_timestamp, from_timestamp from telegram.utils.helpers import from_timestamp, to_timestamp
from telegram.utils.types import JSONDict from telegram.utils.types import JSONDict
from typing import Any, Optional, TYPE_CHECKING, ClassVar
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram import Bot from telegram import Bot
@ -126,7 +125,7 @@ class ChatMember(TelegramObject):
""":const:`telegram.constants.CHATMEMBER_RESTRICTED`""" """:const:`telegram.constants.CHATMEMBER_RESTRICTED`"""
def __init__( def __init__(
self, self, # pylint: disable=W0613
user: User, user: User,
status: str, status: str,
until_date: datetime.datetime = None, until_date: datetime.datetime = None,

View file

@ -18,9 +18,10 @@
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram ChatPermission.""" """This module contains an object that represents a Telegram ChatPermission."""
from telegram import TelegramObject
from typing import Any from typing import Any
from telegram import TelegramObject
class ChatPermissions(TelegramObject): class ChatPermissions(TelegramObject):
"""Describes actions that a non-administrator user is allowed to take in a chat. """Describes actions that a non-administrator user is allowed to take in a chat.
@ -78,7 +79,7 @@ class ChatPermissions(TelegramObject):
""" """
def __init__( def __init__(
self, self, # pylint: disable=W0613
can_send_messages: bool = None, can_send_messages: bool = None,
can_send_media_messages: bool = None, can_send_media_messages: bool = None,
can_send_polls: bool = None, can_send_polls: bool = None,

View file

@ -1,5 +1,5 @@
#!/usr/bin/env python #!/usr/bin/env python
# pylint: disable=R0902,R0912,R0913 # pylint: disable=R0902,R0913
# #
# A library that provides a Python interface to the Telegram Bot API # A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2020 # Copyright (C) 2015-2020
@ -19,9 +19,10 @@
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram ChosenInlineResult.""" """This module contains an object that represents a Telegram ChosenInlineResult."""
from telegram import TelegramObject, User, Location from typing import TYPE_CHECKING, Any, Optional
from telegram import Location, TelegramObject, User
from telegram.utils.types import JSONDict from telegram.utils.types import JSONDict
from typing import Any, Optional, TYPE_CHECKING
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram import Bot from telegram import Bot
@ -63,7 +64,7 @@ class ChosenInlineResult(TelegramObject):
""" """
def __init__( def __init__(
self, self, # pylint: disable=W0613
result_id: str, result_id: str,
from_user: User, from_user: User,
query: str, query: str,

View file

@ -18,9 +18,10 @@
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram Dice.""" """This module contains an object that represents a Telegram Dice."""
from telegram import TelegramObject, constants
from typing import Any, List, ClassVar from typing import Any, List, ClassVar
from telegram import TelegramObject, constants
class Dice(TelegramObject): class Dice(TelegramObject):
""" """
@ -49,7 +50,7 @@ class Dice(TelegramObject):
emoji (:obj:`str`): Emoji on which the dice throw animation is based. emoji (:obj:`str`): Emoji on which the dice throw animation is based.
""" """
def __init__(self, value: int, emoji: str, **kwargs: Any): def __init__(self, value: int, emoji: str, **kwargs: Any): # pylint: disable=W0613
self.value = value self.value = value
self.emoji = emoji self.emoji = emoji

View file

@ -16,6 +16,7 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
# pylint: disable=C0115
"""This module contains an object that represents Telegram errors.""" """This module contains an object that represents Telegram errors."""
from typing import Tuple from typing import Tuple
@ -123,8 +124,5 @@ class Conflict(TelegramError):
""" """
def __init__(self, msg: str):
super().__init__(msg)
def __reduce__(self) -> Tuple[type, Tuple[str]]: def __reduce__(self) -> Tuple[type, Tuple[str]]:
return self.__class__, (self.message,) return self.__class__, (self.message,)

View file

@ -21,10 +21,10 @@
from abc import ABC, abstractmethod from abc import ABC, abstractmethod
from collections import defaultdict from collections import defaultdict
from copy import copy from copy import copy
from typing import Any, DefaultDict, Dict, Optional, Tuple, cast, ClassVar
from telegram import Bot from telegram import Bot
from typing import DefaultDict, Dict, Any, Tuple, Optional, cast, ClassVar
from telegram.utils.types import ConversationDict from telegram.utils.types import ConversationDict
@ -73,7 +73,7 @@ class BasePersistence(ABC):
persistence class. Default is :obj:`True` . persistence class. Default is :obj:`True` .
""" """
def __new__(cls, *args: Any, **kwargs: Any) -> 'BasePersistence': def __new__(cls, *args: Any, **kwargs: Any) -> 'BasePersistence': # pylint: disable=W0613
instance = super().__new__(cls) instance = super().__new__(cls)
get_user_data = instance.get_user_data get_user_data = instance.get_user_data
get_chat_data = instance.get_chat_data get_chat_data = instance.get_chat_data
@ -150,8 +150,8 @@ class BasePersistence(ABC):
if isinstance(obj, (dict, defaultdict)): if isinstance(obj, (dict, defaultdict)):
new_obj = cast(dict, new_obj) new_obj = cast(dict, new_obj)
new_obj.clear() new_obj.clear()
for k, v in obj.items(): for k, val in obj.items():
new_obj[cls.replace_bot(k)] = cls.replace_bot(v) new_obj[cls.replace_bot(k)] = cls.replace_bot(val)
return new_obj return new_obj
if hasattr(obj, '__dict__'): if hasattr(obj, '__dict__'):
for attr_name, attr in new_obj.__dict__.items(): for attr_name, attr in new_obj.__dict__.items():
@ -168,7 +168,7 @@ class BasePersistence(ABC):
return obj return obj
def insert_bot(self, obj: object) -> object: def insert_bot(self, obj: object) -> object: # pylint: disable=R0911
""" """
Replaces all instances of :attr:`REPLACED_BOT` that occur within the passed object with 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``, :attr:`bot`. Currently, this handles objects of type ``list``, ``tuple``, ``set``,
@ -192,8 +192,8 @@ class BasePersistence(ABC):
if isinstance(obj, (dict, defaultdict)): if isinstance(obj, (dict, defaultdict)):
new_obj = cast(dict, new_obj) new_obj = cast(dict, new_obj)
new_obj.clear() new_obj.clear()
for k, v in obj.items(): for k, val in obj.items():
new_obj[self.insert_bot(k)] = self.insert_bot(v) new_obj[self.insert_bot(k)] = self.insert_bot(val)
return new_obj return new_obj
if hasattr(obj, '__dict__'): if hasattr(obj, '__dict__'):
for attr_name, attr in new_obj.__dict__.items(): for attr_name, attr in new_obj.__dict__.items():
@ -300,7 +300,6 @@ class BasePersistence(ABC):
persistence a chance to finish up saving or close a database connection gracefully. If this persistence a chance to finish up saving or close a database connection gracefully. If this
is not of any importance just pass will be sufficient. is not of any importance just pass will be sufficient.
""" """
pass
REPLACED_BOT: ClassVar[str] = 'bot_instance_replaced_by_ptb_persistence' REPLACED_BOT: ClassVar[str] = 'bot_instance_replaced_by_ptb_persistence'
""":obj:`str`: Placeholder for :class:`telegram.Bot` instances replaced in saved data.""" """:obj:`str`: Placeholder for :class:`telegram.Bot` instances replaced in saved data."""

View file

@ -16,9 +16,10 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
# pylint: disable=R0201
"""This module contains the CallbackContext class.""" """This module contains the CallbackContext class."""
from queue import Queue from queue import Queue
from typing import Dict, Any, Tuple, TYPE_CHECKING, Optional, Match, List, NoReturn, Union from typing import TYPE_CHECKING, Any, Dict, List, Match, NoReturn, Optional, Tuple, Union
from telegram import Update from telegram import Update
@ -165,9 +166,9 @@ class CallbackContext:
user = update.effective_user user = update.effective_user
if chat: if chat:
self._chat_data = dispatcher.chat_data[chat.id] self._chat_data = dispatcher.chat_data[chat.id] # pylint: disable=W0212
if user: if user:
self._user_data = dispatcher.user_data[user.id] self._user_data = dispatcher.user_data[user.id] # pylint: disable=W0212
return self return self
@classmethod @classmethod

View file

@ -19,24 +19,24 @@
"""This module contains the CallbackQueryHandler class.""" """This module contains the CallbackQueryHandler class."""
import re import re
from telegram import Update
from .handler import Handler
from telegram.utils.types import HandlerArg
from typing import ( from typing import (
Callable,
TYPE_CHECKING, TYPE_CHECKING,
Any, Any,
Optional, Callable,
Union,
TypeVar,
Pattern,
Match,
Dict, Dict,
Match,
Optional,
Pattern,
TypeVar,
Union,
cast, cast,
) )
from telegram import Update
from telegram.utils.types import HandlerArg
from .handler import Handler
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram.ext import CallbackContext, Dispatcher from telegram.ext import CallbackContext, Dispatcher

View file

@ -18,11 +18,12 @@
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the ChosenInlineResultHandler class.""" """This module contains the ChosenInlineResultHandler class."""
from telegram import Update from typing import Optional, TypeVar, Union
from .handler import Handler
from telegram import Update
from telegram.utils.types import HandlerArg from telegram.utils.types import HandlerArg
from typing import Optional, Union, TypeVar
from .handler import Handler
RT = TypeVar('RT') RT = TypeVar('RT')

View file

@ -19,15 +19,14 @@
"""This module contains the CommandHandler and PrefixHandler classes.""" """This module contains the CommandHandler and PrefixHandler classes."""
import re import re
import warnings import warnings
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, TypeVar, Union
from telegram.ext import Filters, BaseFilter from telegram import MessageEntity, Update
from telegram.ext import BaseFilter, Filters
from telegram.utils.deprecate import TelegramDeprecationWarning from telegram.utils.deprecate import TelegramDeprecationWarning
from telegram import Update, MessageEntity
from .handler import Handler
from telegram.utils.types import HandlerArg from telegram.utils.types import HandlerArg
from typing import Callable, TYPE_CHECKING, Any, Optional, Union, TypeVar, Dict, List, Tuple
from .handler import Handler
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram.ext import CallbackContext, Dispatcher from telegram.ext import CallbackContext, Dispatcher
@ -212,7 +211,6 @@ class CommandHandler(Handler):
filter_result = self.filters(update) filter_result = self.filters(update)
if filter_result: if filter_result:
return args, filter_result return args, filter_result
else:
return False return False
return None return None
@ -270,9 +268,6 @@ class PrefixHandler(CommandHandler):
use ~``Filters.update.edited_message``. use ~``Filters.update.edited_message``.
Attributes: Attributes:
prefix (:obj:`str` | List[:obj:`str`]): The prefix(es) that will precede :attr:`command`.
command (:obj:`str` | List[:obj:`str`]): The command or list of commands this handler
should listen for.
callback (:obj:`callable`): The callback function for this handler. callback (:obj:`callable`): The callback function for this handler.
filters (:class:`telegram.ext.BaseFilter`): Optional. Only allow updates with these filters (:class:`telegram.ext.BaseFilter`): Optional. Only allow updates with these
Filters. Filters.
@ -380,6 +375,12 @@ class PrefixHandler(CommandHandler):
@property @property
def prefix(self) -> List[str]: def prefix(self) -> List[str]:
"""
The prefixes that will precede :attr:`command`.
Returns:
List[:obj:`str`]
"""
return self._prefix return self._prefix
@prefix.setter @prefix.setter
@ -392,6 +393,12 @@ class PrefixHandler(CommandHandler):
@property # type: ignore[override] @property # type: ignore[override]
def command(self) -> List[str]: # type: ignore[override] def command(self) -> List[str]: # type: ignore[override]
"""
The list of commands this handler should listen for.
Returns:
List[:obj:`str`]
"""
return self._command return self._command
@command.setter @command.setter
@ -427,7 +434,6 @@ class PrefixHandler(CommandHandler):
filter_result = self.filters(update) filter_result = self.filters(update)
if filter_result: if filter_result:
return text_list[1:], filter_result return text_list[1:], filter_result
else:
return False return False
return None return None

View file

@ -16,26 +16,26 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
# pylint: disable=R0201
"""This module contains the ConversationHandler.""" """This module contains the ConversationHandler."""
import logging import logging
import warnings import warnings
from threading import Lock from threading import Lock
from typing import TYPE_CHECKING, Any, Dict, List, NoReturn, Optional, Tuple, cast, ClassVar
from telegram import Update from telegram import Update
from telegram.ext import ( from telegram.ext import (
Handler,
CallbackQueryHandler,
InlineQueryHandler,
ChosenInlineResultHandler,
CallbackContext,
BasePersistence, BasePersistence,
CallbackContext,
CallbackQueryHandler,
ChosenInlineResultHandler,
DispatcherHandlerStop, DispatcherHandlerStop,
Handler,
InlineQueryHandler,
) )
from telegram.utils.promise import Promise from telegram.utils.promise import Promise
from telegram.utils.types import ConversationDict, HandlerArg from telegram.utils.types import ConversationDict, HandlerArg
from typing import Dict, Any, List, Optional, Tuple, TYPE_CHECKING, cast, NoReturn, ClassVar
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram.ext import Dispatcher, Job from telegram.ext import Dispatcher, Job
@ -176,7 +176,7 @@ class ConversationHandler(Handler):
WAITING: ClassVar[int] = -3 WAITING: ClassVar[int] = -3
""":obj:`int`: Used as a constant to handle state when a conversation is still waiting on the """:obj:`int`: Used as a constant to handle state when a conversation is still waiting on the
previous ``@run_sync`` decorated running handler to finish.""" previous ``@run_sync`` decorated running handler to finish."""
# pylint: disable=W0231
def __init__( def __init__(
self, self,
entry_points: List[Handler], entry_points: List[Handler],
@ -389,7 +389,7 @@ class ConversationHandler(Handler):
return tuple(key) return tuple(key)
def check_update(self, update: HandlerArg) -> CheckUpdateType: def check_update(self, update: HandlerArg) -> CheckUpdateType: # pylint: disable=R0911
""" """
Determines whether an update should be handled by this conversationhandler, and if so in Determines whether an update should be handled by this conversationhandler, and if so in
which state the conversation currently is. which state the conversation currently is.
@ -401,18 +401,16 @@ class ConversationHandler(Handler):
:obj:`bool` :obj:`bool`
""" """
if not isinstance(update, Update):
return None
# Ignore messages in channels # Ignore messages in channels
if ( if update.channel_post:
not isinstance(update, Update) return None
or update.channel_post if self.per_chat and not update.effective_chat:
or self.per_chat return None
and not update.effective_chat if self.per_message and not update.callback_query:
or self.per_message return None
and not update.callback_query if update.callback_query and self.per_chat and not update.callback_query.message:
or update.callback_query
and self.per_chat
and not update.callback_query.message
):
return None return None
key = self._get_key(update) key = self._get_key(update)
@ -430,7 +428,7 @@ class ConversationHandler(Handler):
res = res if res is not None else old_state res = res if res is not None else old_state
except Exception as exc: except Exception as exc:
self.logger.exception("Promise function raised exception") self.logger.exception("Promise function raised exception")
self.logger.exception("{}".format(exc)) self.logger.exception("%s", exc)
res = old_state res = old_state
finally: finally:
if res is None and old_state is None: if res is None and old_state is None:
@ -446,7 +444,7 @@ class ConversationHandler(Handler):
return key, hdlr, check return key, hdlr, check
return None return None
self.logger.debug('selecting conversation {} with state {}'.format(str(key), str(state))) self.logger.debug('selecting conversation %s with state %s', str(key), str(state))
handler = None handler = None
@ -515,8 +513,8 @@ class ConversationHandler(Handler):
timeout_job.schedule_removal() timeout_job.schedule_removal()
try: try:
new_state = handler.handle_update(update, dispatcher, check_result, context) new_state = handler.handle_update(update, dispatcher, check_result, context)
except DispatcherHandlerStop as e: except DispatcherHandlerStop as exception:
new_state = e.state new_state = exception.state
raise_dp_handler_stop = True raise_dp_handler_stop = True
with self._timeout_jobs_lock: with self._timeout_jobs_lock:
if self.conversation_timeout and new_state != self.END and dispatcher.job_queue: if self.conversation_timeout and new_state != self.END and dispatcher.job_queue:
@ -533,9 +531,8 @@ class ConversationHandler(Handler):
self.update_state(self.END, conversation_key) self.update_state(self.END, conversation_key)
if raise_dp_handler_stop: if raise_dp_handler_stop:
raise DispatcherHandlerStop(self.map_to_parent.get(new_state)) raise DispatcherHandlerStop(self.map_to_parent.get(new_state))
else:
return self.map_to_parent.get(new_state) return self.map_to_parent.get(new_state)
else:
self.update_state(new_state, conversation_key) self.update_state(new_state, conversation_key)
if raise_dp_handler_stop: if raise_dp_handler_stop:
# Don't pass the new state here. If we're in a nested conversation, the parent is # Don't pass the new state here. If we're in a nested conversation, the parent is

View file

@ -16,9 +16,11 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
# pylint: disable=R0201, E0401
"""This module contains the class Defaults, which allows to pass default values to Updater.""" """This module contains the class Defaults, which allows to pass default values to Updater."""
from typing import Any, NoReturn, Optional, Union
import pytz import pytz
from typing import Union, Optional, Any, NoReturn
from telegram.utils.helpers import DEFAULT_NONE, DefaultValue from telegram.utils.helpers import DEFAULT_NONE, DefaultValue

View file

@ -19,21 +19,21 @@
"""This module contains the DictPersistence class.""" """This module contains the DictPersistence class."""
from copy import deepcopy from copy import deepcopy
from typing import Any, DefaultDict, Dict, Optional, Tuple
from collections import defaultdict
from telegram.utils.helpers import ( from telegram.utils.helpers import (
decode_user_chat_data_from_json,
decode_conversations_from_json, decode_conversations_from_json,
decode_user_chat_data_from_json,
encode_conversations_to_json, encode_conversations_to_json,
) )
from telegram.ext import BasePersistence
from telegram.utils.types import ConversationDict
try: try:
import ujson as json import ujson as json
except ImportError: except ImportError:
import json # type: ignore[no-redef] import json # type: ignore[no-redef]
from collections import defaultdict
from telegram.ext import BasePersistence
from typing import DefaultDict, Dict, Any, Tuple, Optional
from telegram.utils.types import ConversationDict
class DictPersistence(BasePersistence): class DictPersistence(BasePersistence):
@ -106,20 +106,20 @@ class DictPersistence(BasePersistence):
try: try:
self._user_data = decode_user_chat_data_from_json(user_data_json) self._user_data = decode_user_chat_data_from_json(user_data_json)
self._user_data_json = user_data_json self._user_data_json = user_data_json
except (ValueError, AttributeError): except (ValueError, AttributeError) as exc:
raise TypeError("Unable to deserialize user_data_json. Not valid JSON") raise TypeError("Unable to deserialize user_data_json. Not valid JSON") from exc
if chat_data_json: if chat_data_json:
try: try:
self._chat_data = decode_user_chat_data_from_json(chat_data_json) self._chat_data = decode_user_chat_data_from_json(chat_data_json)
self._chat_data_json = chat_data_json self._chat_data_json = chat_data_json
except (ValueError, AttributeError): except (ValueError, AttributeError) as exc:
raise TypeError("Unable to deserialize chat_data_json. Not valid JSON") raise TypeError("Unable to deserialize chat_data_json. Not valid JSON") from exc
if bot_data_json: if bot_data_json:
try: try:
self._bot_data = json.loads(bot_data_json) self._bot_data = json.loads(bot_data_json)
self._bot_data_json = bot_data_json self._bot_data_json = bot_data_json
except (ValueError, AttributeError): except (ValueError, AttributeError) as exc:
raise TypeError("Unable to deserialize bot_data_json. Not valid JSON") raise TypeError("Unable to deserialize bot_data_json. Not valid JSON") from exc
if not isinstance(self._bot_data, dict): if not isinstance(self._bot_data, dict):
raise TypeError("bot_data_json must be serialized dict") raise TypeError("bot_data_json must be serialized dict")
@ -127,8 +127,10 @@ class DictPersistence(BasePersistence):
try: try:
self._conversations = decode_conversations_from_json(conversations_json) self._conversations = decode_conversations_from_json(conversations_json)
self._conversations_json = conversations_json self._conversations_json = conversations_json
except (ValueError, AttributeError): except (ValueError, AttributeError) as exc:
raise TypeError("Unable to deserialize conversations_json. Not valid JSON") raise TypeError(
"Unable to deserialize conversations_json. Not valid JSON"
) from exc
@property @property
def user_data(self) -> Optional[DefaultDict[int, Dict]]: def user_data(self) -> Optional[DefaultDict[int, Dict]]:
@ -140,7 +142,6 @@ class DictPersistence(BasePersistence):
""":obj:`str`: The user_data serialized as a JSON-string.""" """:obj:`str`: The user_data serialized as a JSON-string."""
if self._user_data_json: if self._user_data_json:
return self._user_data_json return self._user_data_json
else:
return json.dumps(self.user_data) return json.dumps(self.user_data)
@property @property
@ -153,7 +154,6 @@ class DictPersistence(BasePersistence):
""":obj:`str`: The chat_data serialized as a JSON-string.""" """:obj:`str`: The chat_data serialized as a JSON-string."""
if self._chat_data_json: if self._chat_data_json:
return self._chat_data_json return self._chat_data_json
else:
return json.dumps(self.chat_data) return json.dumps(self.chat_data)
@property @property
@ -166,7 +166,6 @@ class DictPersistence(BasePersistence):
""":obj:`str`: The bot_data serialized as a JSON-string.""" """:obj:`str`: The bot_data serialized as a JSON-string."""
if self._bot_data_json: if self._bot_data_json:
return self._bot_data_json return self._bot_data_json
else:
return json.dumps(self.bot_data) return json.dumps(self.bot_data)
@property @property
@ -179,7 +178,6 @@ class DictPersistence(BasePersistence):
""":obj:`str`: The conversations serialized as a JSON-string.""" """:obj:`str`: The conversations serialized as a JSON-string."""
if self._conversations_json: if self._conversations_json:
return self._conversations_json return self._conversations_json
else:
return encode_conversations_to_json(self.conversations) # type: ignore[arg-type] return encode_conversations_to_json(self.conversations) # type: ignore[arg-type]
def get_user_data(self) -> DefaultDict[int, Dict[Any, Any]]: def get_user_data(self) -> DefaultDict[int, Dict[Any, Any]]:

View file

@ -21,23 +21,20 @@
import logging import logging
import warnings import warnings
import weakref import weakref
from functools import wraps
from threading import Thread, Lock, Event, current_thread, BoundedSemaphore
from time import sleep
from uuid import uuid4
from collections import defaultdict from collections import defaultdict
from functools import wraps
from queue import Queue, Empty from queue import Empty, Queue
from threading import BoundedSemaphore, Event, Lock, Thread, current_thread
from time import sleep
from typing import TYPE_CHECKING, Any, Callable, DefaultDict, Dict, List, Optional, Set, Union
from uuid import uuid4
from telegram import TelegramError, Update from telegram import TelegramError, Update
from telegram.ext.handler import Handler from telegram.ext import BasePersistence
from telegram.ext.callbackcontext import CallbackContext from telegram.ext.callbackcontext import CallbackContext
from telegram.ext.handler import Handler
from telegram.utils.deprecate import TelegramDeprecationWarning from telegram.utils.deprecate import TelegramDeprecationWarning
from telegram.utils.promise import Promise from telegram.utils.promise import Promise
from telegram.ext import BasePersistence
from typing import Any, Callable, TYPE_CHECKING, Optional, Union, DefaultDict, Dict, List, Set
from telegram.utils.types import HandlerArg from telegram.utils.types import HandlerArg
if TYPE_CHECKING: if TYPE_CHECKING:
@ -74,7 +71,7 @@ def run_async(
TelegramDeprecationWarning, TelegramDeprecationWarning,
stacklevel=2, stacklevel=2,
) )
return Dispatcher.get_instance()._run_async( return Dispatcher.get_instance()._run_async( # pylint: disable=W0212
func, *args, update=None, error_handling=False, **kwargs func, *args, update=None, error_handling=False, **kwargs
) )
@ -245,10 +242,7 @@ class Dispatcher:
""" """
if cls.__singleton is not None: if cls.__singleton is not None:
return cls.__singleton() # type: ignore[return-value] # pylint: disable=not-callable return cls.__singleton() # type: ignore[return-value] # pylint: disable=not-callable
else: raise RuntimeError('{} not initialized or multiple instances exist'.format(cls.__name__))
raise RuntimeError(
'{} not initialized or multiple instances exist'.format(cls.__name__)
)
def _pooled(self) -> None: def _pooled(self) -> None:
thr_name = current_thread().getName() thr_name = current_thread().getName()
@ -328,7 +322,7 @@ class Dispatcher:
*args: Any, *args: Any,
update: HandlerArg = None, update: HandlerArg = None,
error_handling: bool = True, error_handling: bool = True,
**kwargs: Any, **kwargs: Any, # pylint: disable=W0613
) -> Promise: ) -> Promise:
# TODO: Remove error_handling parameter once we drop the @run_async decorator # TODO: Remove error_handling parameter once we drop the @run_async decorator
promise = Promise(func, args, kwargs, update=update, error_handling=error_handling) promise = Promise(func, args, kwargs, update=update, error_handling=error_handling)
@ -371,12 +365,12 @@ class Dispatcher:
if self.__stop_event.is_set(): if self.__stop_event.is_set():
self.logger.debug('orderly stopping') self.logger.debug('orderly stopping')
break break
elif self.__exception_event.is_set(): if self.__exception_event.is_set():
self.logger.critical('stopping due to exception in another thread') self.logger.critical('stopping due to exception in another thread')
break break
continue continue
self.logger.debug('Processing Update: %s' % update) self.logger.debug('Processing Update: %s', update)
self.process_update(update) self.process_update(update)
self.update_queue.task_done() self.update_queue.task_done()
@ -401,10 +395,10 @@ class Dispatcher:
self.__async_queue.put(None) self.__async_queue.put(None)
for i, thr in enumerate(threads): for i, thr in enumerate(threads):
self.logger.debug('Waiting for async thread {}/{} to end'.format(i + 1, total)) self.logger.debug('Waiting for async thread %s/%s to end', i + 1, total)
thr.join() thr.join()
self.__async_threads.remove(thr) self.__async_threads.remove(thr)
self.logger.debug('async thread {}/{} has ended'.format(i + 1, total)) self.logger.debug('async thread %s/%s has ended', i + 1, total)
@property @property
def has_running_threads(self) -> bool: def has_running_threads(self) -> bool:
@ -450,9 +444,9 @@ class Dispatcher:
break break
# Dispatch any error. # Dispatch any error.
except Exception as e: except Exception as exc:
try: try:
self.dispatch_error(update, e) self.dispatch_error(update, exc)
except DispatcherHandlerStop: except DispatcherHandlerStop:
self.logger.debug('Error handler stopped further handlers') self.logger.debug('Error handler stopped further handlers')
break break
@ -486,7 +480,7 @@ class Dispatcher:
""" """
# Unfortunately due to circular imports this has to be here # Unfortunately due to circular imports this has to be here
from .conversationhandler import ConversationHandler from .conversationhandler import ConversationHandler # pylint: disable=C0415
if not isinstance(handler, Handler): if not isinstance(handler, Handler):
raise TypeError('handler is not an instance of {}'.format(Handler.__name__)) raise TypeError('handler is not an instance of {}'.format(Handler.__name__))
@ -552,9 +546,9 @@ class Dispatcher:
if self.persistence.store_bot_data: if self.persistence.store_bot_data:
try: try:
self.persistence.update_bot_data(self.bot_data) self.persistence.update_bot_data(self.bot_data)
except Exception as e: except Exception as exc:
try: try:
self.dispatch_error(update, e) self.dispatch_error(update, exc)
except Exception: except Exception:
message = ( message = (
'Saving bot data raised an error and an ' 'Saving bot data raised an error and an '
@ -566,9 +560,9 @@ class Dispatcher:
for chat_id in chat_ids: for chat_id in chat_ids:
try: try:
self.persistence.update_chat_data(chat_id, self.chat_data[chat_id]) self.persistence.update_chat_data(chat_id, self.chat_data[chat_id])
except Exception as e: except Exception as exc:
try: try:
self.dispatch_error(update, e) self.dispatch_error(update, exc)
except Exception: except Exception:
message = ( message = (
'Saving chat data raised an error and an ' 'Saving chat data raised an error and an '
@ -580,9 +574,9 @@ class Dispatcher:
for user_id in user_ids: for user_id in user_ids:
try: try:
self.persistence.update_user_data(user_id, self.user_data[user_id]) self.persistence.update_user_data(user_id, self.user_data[user_id])
except Exception as e: except Exception as exc:
try: try:
self.dispatch_error(update, e) self.dispatch_error(update, exc)
except Exception: except Exception:
message = ( message = (
'Saving user data raised an error and an ' 'Saving user data raised an error and an '
@ -592,7 +586,9 @@ class Dispatcher:
self.logger.exception(message) self.logger.exception(message)
def add_error_handler( def add_error_handler(
self, callback: Callable[[Any, CallbackContext], None], run_async: bool = False self,
callback: Callable[[Any, CallbackContext], None],
run_async: bool = False, # pylint: disable=W0621
) -> None: ) -> None:
"""Registers an error handler in the Dispatcher. This handler will receive every error """Registers an error handler in the Dispatcher. This handler will receive every error
which happens in your bot. which happens in your bot.
@ -647,7 +643,7 @@ class Dispatcher:
async_kwargs = None if not promise else promise.kwargs async_kwargs = None if not promise else promise.kwargs
if self.error_handlers: if self.error_handlers:
for callback, run_async in self.error_handlers.items(): for callback, run_async in self.error_handlers.items(): # pylint: disable=W0621
if self.use_context: if self.use_context:
context = CallbackContext.from_error( context = CallbackContext.from_error(
update, error, self, async_args=async_args, async_kwargs=async_kwargs update, error, self, async_args=async_args, async_kwargs=async_kwargs

View file

@ -16,6 +16,7 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
# pylint: disable=C0112, C0103, W0221
"""This module contains the Filters for use with the MessageHandler class.""" """This module contains the Filters for use with the MessageHandler class."""
import re import re
@ -23,10 +24,9 @@ import warnings
from abc import ABC, abstractmethod from abc import ABC, abstractmethod
from threading import Lock from threading import Lock
from typing import Dict, FrozenSet, List, Match, Optional, Pattern, Set, Union, cast
from telegram import Chat, Update, MessageEntity, Message from telegram import Chat, Message, MessageEntity, Update
from typing import Optional, Dict, Union, List, Pattern, Match, cast, Set, FrozenSet
__all__ = [ __all__ = [
'Filters', 'Filters',
@ -223,7 +223,8 @@ class MergedFilter(UpdateFilter):
if self.or_filter and not isinstance(self.and_filter, bool) and self.or_filter.data_filter: if self.or_filter and not isinstance(self.and_filter, bool) and self.or_filter.data_filter:
self.data_filter = True self.data_filter = True
def _merge(self, base_output: Union[bool, Dict], comp_output: Union[bool, Dict]) -> Dict: @staticmethod
def _merge(base_output: Union[bool, Dict], comp_output: Union[bool, Dict]) -> Dict:
base = base_output if isinstance(base_output, dict) else {} base = base_output if isinstance(base_output, dict) else {}
comp = comp_output if isinstance(comp_output, dict) else {} comp = comp_output if isinstance(comp_output, dict) else {}
for k in comp.keys(): for k in comp.keys():
@ -239,7 +240,7 @@ class MergedFilter(UpdateFilter):
base[k] = comp_value base[k] = comp_value
return base return base
def filter(self, update: Update) -> Union[bool, Dict]: def filter(self, update: Update) -> Union[bool, Dict]: # pylint: disable=R0911
base_output = self.base_filter(update) base_output = self.base_filter(update)
# We need to check if the filters are data filters and if so return the merged data. # We need to check if the filters are data filters and if so return the merged data.
# If it's not a data filter or an or_filter but no matches return bool # If it's not a data filter or an or_filter but no matches return bool
@ -259,7 +260,7 @@ class MergedFilter(UpdateFilter):
if self.data_filter: if self.data_filter:
return base_output return base_output
return True return True
else:
comp_output = self.or_filter(update) comp_output = self.or_filter(update)
if comp_output: if comp_output:
if self.data_filter: if self.data_filter:
@ -296,7 +297,6 @@ class _DiceEmoji(MessageFilter):
) -> Union[bool, '_DiceValues']: ) -> Union[bool, '_DiceValues']:
if isinstance(update, Update): if isinstance(update, Update):
return self.filter(update.effective_message) return self.filter(update.effective_message)
else:
return self._DiceValues(update, self.name, emoji=self.emoji) return self._DiceValues(update, self.name, emoji=self.emoji)
def filter(self, message: Message) -> bool: def filter(self, message: Message) -> bool:
@ -344,7 +344,6 @@ class Filters:
) -> Union[bool, '_TextStrings']: ) -> Union[bool, '_TextStrings']:
if isinstance(update, Update): if isinstance(update, Update):
return self.filter(update.effective_message) return self.filter(update.effective_message)
else:
return self._TextStrings(update) return self._TextStrings(update)
def filter(self, message: Message) -> bool: def filter(self, message: Message) -> bool:
@ -396,7 +395,6 @@ class Filters:
) -> Union[bool, '_CaptionStrings']: ) -> Union[bool, '_CaptionStrings']:
if isinstance(update, Update): if isinstance(update, Update):
return self.filter(update.effective_message) return self.filter(update.effective_message)
else:
return self._CaptionStrings(update) return self._CaptionStrings(update)
def filter(self, message: Message) -> bool: def filter(self, message: Message) -> bool:
@ -433,7 +431,6 @@ class Filters:
) -> Union[bool, '_CommandOnlyStart']: ) -> Union[bool, '_CommandOnlyStart']:
if isinstance(update, Update): if isinstance(update, Update):
return self.filter(update.effective_message) return self.filter(update.effective_message)
else:
return self._CommandOnlyStart(update) return self._CommandOnlyStart(update)
def filter(self, message: Message) -> bool: def filter(self, message: Message) -> bool:

View file

@ -19,11 +19,11 @@
"""This module contains the base class for handlers as used by the Dispatcher.""" """This module contains the base class for handlers as used by the Dispatcher."""
from abc import ABC, abstractmethod from abc import ABC, abstractmethod
from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, TypeVar, Union
from telegram import Update
from telegram.utils.promise import Promise from telegram.utils.promise import Promise
from telegram.utils.types import HandlerArg from telegram.utils.types import HandlerArg
from telegram import Update
from typing import Callable, TYPE_CHECKING, Any, Optional, Union, TypeVar, Dict
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram.ext import CallbackContext, Dispatcher from telegram.ext import CallbackContext, Dispatcher
@ -147,15 +147,13 @@ class Handler(ABC):
self.collect_additional_context(context, update, dispatcher, check_result) self.collect_additional_context(context, update, dispatcher, check_result)
if self.run_async: if self.run_async:
return dispatcher.run_async(self.callback, update, context, update=update) return dispatcher.run_async(self.callback, update, context, update=update)
else:
return self.callback(update, context) return self.callback(update, context)
else:
optional_args = self.collect_optional_args(dispatcher, update, check_result) optional_args = self.collect_optional_args(dispatcher, update, check_result)
if self.run_async: if self.run_async:
return dispatcher.run_async( return dispatcher.run_async(
self.callback, dispatcher.bot, update, update=update, **optional_args self.callback, dispatcher.bot, update, update=update, **optional_args
) )
else:
return self.callback(dispatcher.bot, update, **optional_args) # type: ignore return self.callback(dispatcher.bot, update, **optional_args) # type: ignore
def collect_additional_context( def collect_additional_context(
@ -174,10 +172,12 @@ class Handler(ABC):
check_result: The result (return value) from :attr:`check_update`. check_result: The result (return value) from :attr:`check_update`.
""" """
pass
def collect_optional_args( def collect_optional_args(
self, dispatcher: 'Dispatcher', update: HandlerArg = None, check_result: Any = None self,
dispatcher: 'Dispatcher',
update: HandlerArg = None,
check_result: Any = None, # pylint: disable=W0613
) -> Dict[str, Any]: ) -> Dict[str, Any]:
""" """
Prepares the optional arguments. If the handler has additional optional args, Prepares the optional arguments. If the handler has additional optional args,

View file

@ -18,25 +18,24 @@
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
""" This module contains the InlineQueryHandler class """ """ This module contains the InlineQueryHandler class """
import re import re
from telegram import Update
from .handler import Handler
from telegram.utils.types import HandlerArg
from typing import ( from typing import (
Callable,
TYPE_CHECKING, TYPE_CHECKING,
Any, Any,
Optional, Callable,
Union,
TypeVar,
Dict, Dict,
Pattern,
Match, Match,
Optional,
Pattern,
TypeVar,
Union,
cast, cast,
) )
from telegram import Update
from telegram.utils.types import HandlerArg
from .handler import Handler
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram.ext import CallbackContext, Dispatcher from telegram.ext import CallbackContext, Dispatcher

View file

@ -16,25 +16,25 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
# pylint: disable=E0401
"""This module contains the classes JobQueue and Job.""" """This module contains the classes JobQueue and Job."""
import datetime import datetime
import logging import logging
import pytz from typing import TYPE_CHECKING, Any, Callable, List, Optional, Tuple, Union, cast, overload
import pytz
from apscheduler.events import EVENT_JOB_ERROR, EVENT_JOB_EXECUTED, JobEvent
from apscheduler.schedulers.background import BackgroundScheduler from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger
from apscheduler.triggers.combining import OrTrigger from apscheduler.triggers.combining import OrTrigger
from apscheduler.events import EVENT_JOB_EXECUTED, EVENT_JOB_ERROR, JobEvent from apscheduler.triggers.cron import CronTrigger
from telegram.ext.callbackcontext import CallbackContext from telegram.ext.callbackcontext import CallbackContext
from typing import TYPE_CHECKING, Union, Callable, Tuple, Optional, List, Any, cast, overload
from telegram.utils.types import JSONDict from telegram.utils.types import JSONDict
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram.ext import Dispatcher
from telegram import Bot from telegram import Bot
from telegram.ext import Dispatcher
class Days: class Days:
@ -76,7 +76,7 @@ class JobQueue:
def _tz_now(self) -> datetime.datetime: def _tz_now(self) -> datetime.datetime:
return datetime.datetime.now(self.scheduler.timezone) return datetime.datetime.now(self.scheduler.timezone)
def _update_persistence(self, event: JobEvent) -> None: def _update_persistence(self, event: JobEvent) -> None: # pylint: disable=W0613
self._dispatcher.update_persistence() self._dispatcher.update_persistence()
def _dispatch_error(self, event: JobEvent) -> None: def _dispatch_error(self, event: JobEvent) -> None:
@ -114,14 +114,14 @@ class JobQueue:
if isinstance(time, datetime.timedelta): if isinstance(time, datetime.timedelta):
return self._tz_now() + time return self._tz_now() + time
if isinstance(time, datetime.time): if isinstance(time, datetime.time):
dt = datetime.datetime.combine( date_time = datetime.datetime.combine(
datetime.datetime.now(tz=time.tzinfo or self.scheduler.timezone).date(), time datetime.datetime.now(tz=time.tzinfo or self.scheduler.timezone).date(), time
) )
if dt.tzinfo is None: if date_time.tzinfo is None:
dt = self.scheduler.timezone.localize(dt) date_time = self.scheduler.timezone.localize(date_time)
if shift_day and dt <= datetime.datetime.now(pytz.utc): if shift_day and date_time <= datetime.datetime.now(pytz.utc):
dt += datetime.timedelta(days=1) date_time += datetime.timedelta(days=1)
return dt return date_time
# isinstance(time, datetime.datetime): # isinstance(time, datetime.datetime):
return time return time
@ -190,15 +190,15 @@ class JobQueue:
name = name or callback.__name__ name = name or callback.__name__
job = Job(callback, context, name, self) job = Job(callback, context, name, self)
dt = self._parse_time_input(when, shift_day=True) date_time = self._parse_time_input(when, shift_day=True)
j = self.scheduler.add_job( j = self.scheduler.add_job(
callback, callback,
name=name, name=name,
trigger='date', trigger='date',
run_date=dt, run_date=date_time,
args=self._build_args(job), args=self._build_args(job),
timezone=dt.tzinfo or self.scheduler.timezone, timezone=date_time.tzinfo or self.scheduler.timezone,
**job_kwargs, **job_kwargs,
) )
@ -568,9 +568,9 @@ class Job:
self.callback(CallbackContext.from_job(self, dispatcher)) self.callback(CallbackContext.from_job(self, dispatcher))
else: else:
self.callback(dispatcher.bot, self) # type: ignore[arg-type,call-arg] self.callback(dispatcher.bot, self) # type: ignore[arg-type,call-arg]
except Exception as e: except Exception as exc:
try: try:
dispatcher.dispatch_error(None, e) dispatcher.dispatch_error(None, exc)
# Errors should not stop the thread. # Errors should not stop the thread.
except Exception: except Exception:
dispatcher.logger.exception( dispatcher.logger.exception(

View file

@ -19,15 +19,14 @@
# TODO: Remove allow_edited # TODO: Remove allow_edited
"""This module contains the MessageHandler class.""" """This module contains the MessageHandler class."""
import warnings import warnings
from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, TypeVar, Union
from telegram.utils.deprecate import TelegramDeprecationWarning
from telegram import Update from telegram import Update
from telegram.ext import Filters, BaseFilter from telegram.ext import BaseFilter, Filters
from .handler import Handler from telegram.utils.deprecate import TelegramDeprecationWarning
from telegram.utils.types import HandlerArg from telegram.utils.types import HandlerArg
from typing import Callable, TYPE_CHECKING, Any, Optional, Union, TypeVar, Dict
from .handler import Handler
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram.ext import CallbackContext, Dispatcher from telegram.ext import CallbackContext, Dispatcher

View file

@ -20,14 +20,13 @@
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/] # along with this program. If not, see [http://www.gnu.org/licenses/]
"""A throughput-limiting message processor for Telegram bots.""" """A throughput-limiting message processor for Telegram bots."""
from telegram.utils import promise
import functools import functools
import time
import threading
import queue as q import queue as q
import threading
import time
from typing import TYPE_CHECKING, Any, Callable, List, NoReturn
from typing import Callable, Any, TYPE_CHECKING, List, NoReturn from telegram.utils.promise import Promise
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram import Bot from telegram import Bot
@ -39,8 +38,6 @@ curtime = time.perf_counter
class DelayQueueError(RuntimeError): class DelayQueueError(RuntimeError):
"""Indicates processing errors.""" """Indicates processing errors."""
pass
class DelayQueue(threading.Thread): class DelayQueue(threading.Thread):
""" """
@ -304,12 +301,13 @@ def queuedmessage(method: Callable) -> Callable:
@functools.wraps(method) @functools.wraps(method)
def wrapped(self: 'Bot', *args: Any, **kwargs: Any) -> Any: def wrapped(self: 'Bot', *args: Any, **kwargs: Any) -> Any:
# pylint: disable=W0212
queued = kwargs.pop( queued = kwargs.pop(
'queued', self._is_messages_queued_default # type: ignore[attr-defined] 'queued', self._is_messages_queued_default # type: ignore[attr-defined]
) )
isgroup = kwargs.pop('isgroup', False) isgroup = kwargs.pop('isgroup', False)
if queued: if queued:
prom = promise.Promise(method, (self,) + args, kwargs) prom = Promise(method, (self,) + args, kwargs)
return self._msg_queue(prom, isgroup) # type: ignore[attr-defined] return self._msg_queue(prom, isgroup) # type: ignore[attr-defined]
return method(self, *args, **kwargs) return method(self, *args, **kwargs)

View file

@ -20,10 +20,9 @@
import pickle import pickle
from collections import defaultdict from collections import defaultdict
from copy import deepcopy from copy import deepcopy
from typing import Any, DefaultDict, Dict, Optional, Tuple
from telegram.ext import BasePersistence from telegram.ext import BasePersistence
from typing import DefaultDict, Dict, Any, Tuple, Optional
from telegram.utils.types import ConversationDict from telegram.utils.types import ConversationDict
@ -99,8 +98,8 @@ class PicklePersistence(BasePersistence):
def load_singlefile(self) -> None: def load_singlefile(self) -> None:
try: try:
filename = self.filename filename = self.filename
with open(self.filename, "rb") as f: with open(self.filename, "rb") as file:
data = pickle.load(f) data = pickle.load(file)
self.user_data = defaultdict(dict, data['user_data']) self.user_data = defaultdict(dict, data['user_data'])
self.chat_data = defaultdict(dict, data['chat_data']) self.chat_data = defaultdict(dict, data['chat_data'])
# For backwards compatibility with files not containing bot data # For backwards compatibility with files not containing bot data
@ -111,35 +110,37 @@ class PicklePersistence(BasePersistence):
self.user_data = defaultdict(dict) self.user_data = defaultdict(dict)
self.chat_data = defaultdict(dict) self.chat_data = defaultdict(dict)
self.bot_data = {} self.bot_data = {}
except pickle.UnpicklingError: except pickle.UnpicklingError as exc:
raise TypeError("File {} does not contain valid pickle data".format(filename)) raise TypeError("File {} does not contain valid pickle data".format(filename)) from exc
except Exception: except Exception as exc:
raise TypeError("Something went wrong unpickling {}".format(filename)) raise TypeError("Something went wrong unpickling {}".format(filename)) from exc
def load_file(self, filename: str) -> Any: @staticmethod
def load_file(filename: str) -> Any:
try: try:
with open(filename, "rb") as f: with open(filename, "rb") as file:
return pickle.load(f) return pickle.load(file)
except IOError: except IOError:
return None return None
except pickle.UnpicklingError: except pickle.UnpicklingError as exc:
raise TypeError("File {} does not contain valid pickle data".format(filename)) raise TypeError("File {} does not contain valid pickle data".format(filename)) from exc
except Exception: except Exception as exc:
raise TypeError("Something went wrong unpickling {}".format(filename)) raise TypeError("Something went wrong unpickling {}".format(filename)) from exc
def dump_singlefile(self) -> None: def dump_singlefile(self) -> None:
with open(self.filename, "wb") as f: with open(self.filename, "wb") as file:
data = { data = {
'conversations': self.conversations, 'conversations': self.conversations,
'user_data': self.user_data, 'user_data': self.user_data,
'chat_data': self.chat_data, 'chat_data': self.chat_data,
'bot_data': self.bot_data, 'bot_data': self.bot_data,
} }
pickle.dump(data, f) pickle.dump(data, file)
def dump_file(self, filename: str, data: Any) -> None: @staticmethod
with open(filename, "wb") as f: def dump_file(filename: str, data: Any) -> None:
pickle.dump(data, f) with open(filename, "wb") as file:
pickle.dump(data, file)
def get_user_data(self) -> DefaultDict[int, Dict[Any, Any]]: def get_user_data(self) -> DefaultDict[int, Dict[Any, Any]]:
"""Returns the user_data from the pickle file if it exists or an empty :obj:`defaultdict`. """Returns the user_data from the pickle file if it exists or an empty :obj:`defaultdict`.

View file

@ -16,12 +16,13 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the PollAnswerHandler class."""
from telegram import Update from telegram import Update
from .handler import Handler
from telegram.utils.types import HandlerArg from telegram.utils.types import HandlerArg
from .handler import Handler
class PollAnswerHandler(Handler): class PollAnswerHandler(Handler):
"""Handler class to handle Telegram updates that contain a poll answer. """Handler class to handle Telegram updates that contain a poll answer.

View file

@ -16,12 +16,13 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the PollHandler classes."""
from telegram import Update from telegram import Update
from .handler import Handler
from telegram.utils.types import HandlerArg from telegram.utils.types import HandlerArg
from .handler import Handler
class PollHandler(Handler): class PollHandler(Handler):
"""Handler class to handle Telegram updates that contain a poll. """Handler class to handle Telegram updates that contain a poll.

View file

@ -19,10 +19,10 @@
"""This module contains the PreCheckoutQueryHandler class.""" """This module contains the PreCheckoutQueryHandler class."""
from telegram import Update from telegram import Update
from .handler import Handler
from telegram.utils.types import HandlerArg from telegram.utils.types import HandlerArg
from .handler import Handler
class PreCheckoutQueryHandler(Handler): class PreCheckoutQueryHandler(Handler):
"""Handler class to handle Telegram PreCheckout callback queries. """Handler class to handle Telegram PreCheckout callback queries.

View file

@ -20,13 +20,11 @@
"""This module contains the RegexHandler class.""" """This module contains the RegexHandler class."""
import warnings import warnings
from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, Pattern, TypeVar, Union
from telegram.ext import Filters, MessageHandler
from telegram.utils.deprecate import TelegramDeprecationWarning from telegram.utils.deprecate import TelegramDeprecationWarning
from telegram.ext import MessageHandler, Filters
from telegram.utils.types import HandlerArg from telegram.utils.types import HandlerArg
from typing import Callable, TYPE_CHECKING, Any, Optional, Union, TypeVar, Dict, Pattern
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram.ext import CallbackContext, Dispatcher from telegram.ext import CallbackContext, Dispatcher
@ -119,7 +117,7 @@ class RegexHandler(MessageHandler):
pass_job_queue: bool = False, pass_job_queue: bool = False,
pass_user_data: bool = False, pass_user_data: bool = False,
pass_chat_data: bool = False, pass_chat_data: bool = False,
allow_edited: bool = False, allow_edited: bool = False, # pylint: disable=W0613
message_updates: bool = True, message_updates: bool = True,
channel_post_updates: bool = False, channel_post_updates: bool = False,
edited_updates: bool = False, edited_updates: bool = False,

View file

@ -19,10 +19,10 @@
"""This module contains the ShippingQueryHandler class.""" """This module contains the ShippingQueryHandler class."""
from telegram import Update from telegram import Update
from .handler import Handler
from telegram.utils.types import HandlerArg from telegram.utils.types import HandlerArg
from .handler import Handler
class ShippingQueryHandler(Handler): class ShippingQueryHandler(Handler):
"""Handler class to handle Telegram shipping callback queries. """Handler class to handle Telegram shipping callback queries.

View file

@ -18,10 +18,11 @@
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the StringCommandHandler class.""" """This module contains the StringCommandHandler class."""
from .handler import Handler from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, TypeVar
from telegram.utils.types import HandlerArg from telegram.utils.types import HandlerArg
from typing import Callable, TYPE_CHECKING, Any, Optional, TypeVar, Dict, List
from .handler import Handler
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram.ext import CallbackContext, Dispatcher from telegram.ext import CallbackContext, Dispatcher

View file

@ -19,12 +19,12 @@
"""This module contains the StringRegexHandler class.""" """This module contains the StringRegexHandler class."""
import re import re
from typing import TYPE_CHECKING, Any, Callable, Dict, Match, Optional, Pattern, TypeVar, Union
from telegram.utils.types import HandlerArg
from .handler import Handler from .handler import Handler
from typing import Callable, TYPE_CHECKING, Optional, TypeVar, Match, Dict, Any, Union, Pattern
from telegram.utils.types import HandlerArg
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram.ext import CallbackContext, Dispatcher from telegram.ext import CallbackContext, Dispatcher

View file

@ -18,11 +18,10 @@
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the TypeHandler class.""" """This module contains the TypeHandler class."""
from typing import TYPE_CHECKING, Any, Callable, Type, TypeVar
from .handler import Handler from .handler import Handler
from typing import Callable, TYPE_CHECKING, TypeVar, Type, Any
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram.ext import CallbackContext from telegram.ext import CallbackContext
@ -76,7 +75,7 @@ class TypeHandler(Handler):
def __init__( def __init__(
self, self,
type: Type, type: Type, # pylint: disable=W0622
callback: Callable[[Any, 'CallbackContext'], RT], callback: Callable[[Any, 'CallbackContext'], RT],
strict: bool = False, strict: bool = False,
pass_update_queue: bool = False, pass_update_queue: bool = False,
@ -104,5 +103,4 @@ class TypeHandler(Handler):
""" """
if not self.strict: if not self.strict:
return isinstance(update, self.type) return isinstance(update, self.type)
else: return type(update) is self.type # pylint: disable=C0123
return type(update) is self.type

View file

@ -21,20 +21,19 @@
import logging import logging
import ssl import ssl
import warnings import warnings
from threading import Thread, Lock, current_thread, Event
from time import sleep
from signal import signal, SIGINT, SIGTERM, SIGABRT
from queue import Queue from queue import Queue
from signal import SIGABRT, SIGINT, SIGTERM, signal
from threading import Event, Lock, Thread, current_thread
from time import sleep
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union, no_type_check
from telegram import Bot, TelegramError from telegram import Bot, TelegramError
from telegram.error import InvalidToken, RetryAfter, TimedOut, Unauthorized
from telegram.ext import Dispatcher, JobQueue from telegram.ext import Dispatcher, JobQueue
from telegram.error import Unauthorized, InvalidToken, RetryAfter, TimedOut
from telegram.utils.deprecate import TelegramDeprecationWarning from telegram.utils.deprecate import TelegramDeprecationWarning
from telegram.utils.helpers import get_signal_name from telegram.utils.helpers import get_signal_name
from telegram.utils.request import Request from telegram.utils.request import Request
from telegram.utils.webhookhandler import WebhookServer, WebhookAppClass from telegram.utils.webhookhandler import WebhookAppClass, WebhookServer
from typing import Callable, Dict, TYPE_CHECKING, Any, List, Union, Tuple, no_type_check, Optional
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram.ext import BasePersistence, Defaults from telegram.ext import BasePersistence, Defaults
@ -232,14 +231,14 @@ class Updater:
def _thread_wrapper(self, target: Callable, *args: Any, **kwargs: Any) -> None: def _thread_wrapper(self, target: Callable, *args: Any, **kwargs: Any) -> None:
thr_name = current_thread().name thr_name = current_thread().name
self.logger.debug('{} - started'.format(thr_name)) self.logger.debug('%s - started', thr_name)
try: try:
target(*args, **kwargs) target(*args, **kwargs)
except Exception: except Exception:
self.__exception_event.set() self.__exception_event.set()
self.logger.exception('unhandled exception in %s', thr_name) self.logger.exception('unhandled exception in %s', thr_name)
raise raise
self.logger.debug('{} - ended'.format(thr_name)) self.logger.debug('%s - ended', thr_name)
def start_polling( def start_polling(
self, self,
@ -465,9 +464,9 @@ class Updater:
try: try:
if not action_cb(): if not action_cb():
break break
except RetryAfter as e: except RetryAfter as exc:
self.logger.info('%s', e) self.logger.info('%s', exc)
cur_interval = 0.5 + e.retry_after cur_interval = 0.5 + exc.retry_after
except TimedOut as toe: except TimedOut as toe:
self.logger.debug('Timed out %s: %s', description, toe) self.logger.debug('Timed out %s: %s', description, toe)
# If failure is due to timeout, we should retry asap. # If failure is due to timeout, we should retry asap.
@ -475,9 +474,9 @@ class Updater:
except InvalidToken as pex: except InvalidToken as pex:
self.logger.error('Invalid token; aborting') self.logger.error('Invalid token; aborting')
raise pex raise pex
except TelegramError as te: except TelegramError as telegram_exc:
self.logger.error('Error while %s: %s', description, te) self.logger.error('Error while %s: %s', description, telegram_exc)
onerr_cb(te) onerr_cb(telegram_exc)
cur_interval = self._increase_poll_interval(cur_interval) cur_interval = self._increase_poll_interval(cur_interval)
else: else:
cur_interval = interval cur_interval = interval
@ -525,8 +524,8 @@ class Updater:
try: try:
ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
ssl_ctx.load_cert_chain(cert, key) ssl_ctx.load_cert_chain(cert, key)
except ssl.SSLError: except ssl.SSLError as exc:
raise TelegramError('Invalid SSL Certificate') raise TelegramError('Invalid SSL Certificate') from exc
else: else:
ssl_ctx = None ssl_ctx = None
@ -661,9 +660,9 @@ class Updater:
@no_type_check @no_type_check
def _join_threads(self) -> None: def _join_threads(self) -> None:
for thr in self.__threads: for thr in self.__threads:
self.logger.debug('Waiting for {} thread to end'.format(thr.name)) self.logger.debug('Waiting for %s thread to end', thr.name)
thr.join() thr.join()
self.logger.debug('{} thread has ended'.format(thr.name)) self.logger.debug('%s thread has ended', thr.name)
self.__threads = [] self.__threads = []
@no_type_check @no_type_check
@ -671,7 +670,7 @@ class Updater:
self.is_idle = False self.is_idle = False
if self.running: if self.running:
self.logger.info( self.logger.info(
'Received signal {} ({}), stopping...'.format(signum, get_signal_name(signum)) 'Received signal %s (%s), stopping...', signum, get_signal_name(signum)
) )
if self.persistence: if self.persistence:
# Update user_data, chat_data and bot_data before flushing # Update user_data, chat_data and bot_data before flushing
@ -682,6 +681,7 @@ class Updater:
self.user_sig_handler(signum, frame) self.user_sig_handler(signum, frame)
else: else:
self.logger.warning('Exiting immediately!') self.logger.warning('Exiting immediately!')
# pylint: disable=C0415,W0212
import os import os
os._exit(1) os._exit(1)

View file

@ -17,11 +17,10 @@
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram Animation.""" """This module contains an object that represents a Telegram Animation."""
from telegram import PhotoSize from typing import TYPE_CHECKING, Any, Optional
from telegram import TelegramObject
from telegram import PhotoSize, TelegramObject
from telegram.utils.types import JSONDict from telegram.utils.types import JSONDict
from typing import Any, Optional, TYPE_CHECKING
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram import Bot, File from telegram import Bot, File
@ -66,7 +65,7 @@ class Animation(TelegramObject):
""" """
def __init__( def __init__(
self, self, # pylint: disable=W0613
file_id: str, file_id: str,
file_unique_id: str, file_unique_id: str,
width: int, width: int,

View file

@ -18,10 +18,10 @@
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram Audio.""" """This module contains an object that represents a Telegram Audio."""
from telegram import TelegramObject, PhotoSize from typing import TYPE_CHECKING, Any, Optional
from telegram import PhotoSize, TelegramObject
from telegram.utils.types import JSONDict from telegram.utils.types import JSONDict
from typing import Any, Optional, TYPE_CHECKING
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram import Bot, File from telegram import Bot, File
@ -67,7 +67,7 @@ class Audio(TelegramObject):
""" """
def __init__( def __init__(
self, self, # pylint: disable=W0613
file_id: str, file_id: str,
file_unique_id: str, file_unique_id: str,
duration: int, duration: int,

View file

@ -17,9 +17,9 @@
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram ChatPhoto.""" """This module contains an object that represents a Telegram ChatPhoto."""
from telegram import TelegramObject from typing import TYPE_CHECKING, Any
from typing import Any, TYPE_CHECKING from telegram import TelegramObject
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram import Bot, File from telegram import Bot, File
@ -63,7 +63,7 @@ class ChatPhoto(TelegramObject):
""" """
def __init__( def __init__(
self, self, # pylint: disable=W0613
small_file_id: str, small_file_id: str,
small_file_unique_id: str, small_file_unique_id: str,
big_file_id: str, big_file_id: str,

View file

@ -18,9 +18,10 @@
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram Contact.""" """This module contains an object that represents a Telegram Contact."""
from telegram import TelegramObject
from typing import Any from typing import Any
from telegram import TelegramObject
class Contact(TelegramObject): class Contact(TelegramObject):
"""This object represents a phone contact. """This object represents a phone contact.
@ -46,7 +47,7 @@ class Contact(TelegramObject):
""" """
def __init__( def __init__(
self, self, # pylint: disable=W0613
phone_number: str, phone_number: str,
first_name: str, first_name: str,
last_name: str = None, last_name: str = None,

View file

@ -18,10 +18,10 @@
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram Document.""" """This module contains an object that represents a Telegram Document."""
from telegram import PhotoSize, TelegramObject from typing import TYPE_CHECKING, Any, Optional
from telegram import PhotoSize, TelegramObject
from telegram.utils.types import JSONDict from telegram.utils.types import JSONDict
from typing import Any, Optional, TYPE_CHECKING
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram import Bot, File from telegram import Bot, File
@ -62,7 +62,7 @@ class Document(TelegramObject):
_id_keys = ('file_id',) _id_keys = ('file_id',)
def __init__( def __init__(
self, self, # pylint: disable=W0613
file_id: str, file_id: str,
file_unique_id: str, file_unique_id: str,
thumb: PhotoSize = None, thumb: PhotoSize = None,

View file

@ -17,17 +17,15 @@
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram File.""" """This module contains an object that represents a Telegram File."""
import os
import urllib.parse as urllib_parse
from base64 import b64decode from base64 import b64decode
from os.path import basename from os.path import basename
import os from typing import IO, TYPE_CHECKING, Any, Optional, Union
import urllib.parse as urllib_parse
from telegram import TelegramObject from telegram import TelegramObject
from telegram.passport.credentials import decrypt from telegram.passport.credentials import decrypt
from typing import Any, Optional, IO, Union, TYPE_CHECKING
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram import Bot, FileCredentials from telegram import Bot, FileCredentials
@ -70,7 +68,7 @@ class File(TelegramObject):
""" """
def __init__( def __init__(
self, self, # pylint: disable=W0613
file_id: str, file_id: str,
file_unique_id: str, file_unique_id: str,
bot: 'Bot' = None, bot: 'Bot' = None,
@ -132,7 +130,7 @@ class File(TelegramObject):
) )
out.write(buf) out.write(buf)
return out return out
else:
if custom_path: if custom_path:
filename = custom_path filename = custom_path
elif self.file_path: elif self.file_path:

View file

@ -22,12 +22,11 @@
import imghdr import imghdr
import mimetypes import mimetypes
import os import os
from typing import IO, Optional, Tuple
from uuid import uuid4 from uuid import uuid4
from telegram import TelegramError from telegram import TelegramError
from typing import IO, Tuple, Optional
DEFAULT_MIME_TYPE = 'application/octet-stream' DEFAULT_MIME_TYPE = 'application/octet-stream'

View file

@ -18,11 +18,10 @@
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""Base class for Telegram InputMedia Objects.""" """Base class for Telegram InputMedia Objects."""
from telegram import TelegramObject, InputFile, PhotoSize, Animation, Video, Audio, Document from typing import IO, Union, cast
from telegram import Animation, Audio, Document, InputFile, PhotoSize, TelegramObject, Video
from telegram.utils.helpers import DEFAULT_NONE, DefaultValue from telegram.utils.helpers import DEFAULT_NONE, DefaultValue
from typing import Union, IO, cast
from telegram.utils.types import FileLike from telegram.utils.types import FileLike
@ -35,8 +34,6 @@ class InputMedia(TelegramObject):
""" """
pass
class InputMediaAnimation(InputMedia): class InputMediaAnimation(InputMedia):
"""Represents an animation file (GIF or H.264/MPEG-4 AVC video without sound) to be sent. """Represents an animation file (GIF or H.264/MPEG-4 AVC video without sound) to be sent.

View file

@ -18,9 +18,10 @@
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram Location.""" """This module contains an object that represents a Telegram Location."""
from telegram import TelegramObject
from typing import Any from typing import Any
from telegram import TelegramObject
class Location(TelegramObject): class Location(TelegramObject):
"""This object represents a point on the map. """This object represents a point on the map.
@ -39,7 +40,7 @@ class Location(TelegramObject):
""" """
def __init__(self, longitude: float, latitude: float, **kwargs: Any): def __init__(self, longitude: float, latitude: float, **kwargs: Any): # pylint: disable=W0613
# Required # Required
self.longitude = float(longitude) self.longitude = float(longitude)
self.latitude = float(latitude) self.latitude = float(latitude)

View file

@ -18,9 +18,10 @@
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram PhotoSize.""" """This module contains an object that represents a Telegram PhotoSize."""
from typing import TYPE_CHECKING, Any
from telegram import TelegramObject from telegram import TelegramObject
from telegram.utils.types import JSONDict from telegram.utils.types import JSONDict
from typing import Any, TYPE_CHECKING
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram import Bot, File from telegram import Bot, File
@ -57,7 +58,7 @@ class PhotoSize(TelegramObject):
""" """
def __init__( def __init__(
self, self, # pylint: disable=W0613
file_id: str, file_id: str,
file_unique_id: str, file_unique_id: str,
width: int, width: int,

View file

@ -18,9 +18,10 @@
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains objects that represents stickers.""" """This module contains objects that represents stickers."""
from typing import TYPE_CHECKING, Any, List, Optional, ClassVar
from telegram import PhotoSize, TelegramObject, constants from telegram import PhotoSize, TelegramObject, constants
from telegram.utils.types import JSONDict from telegram.utils.types import JSONDict
from typing import Any, Optional, List, TYPE_CHECKING, ClassVar
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram import Bot, File from telegram import Bot, File
@ -73,7 +74,7 @@ class Sticker(TelegramObject):
""" """
def __init__( def __init__(
self, self, # pylint: disable=W0613
file_id: str, file_id: str,
file_unique_id: str, file_unique_id: str,
width: int, width: int,
@ -162,13 +163,13 @@ class StickerSet(TelegramObject):
""" """
def __init__( def __init__(
self, self, # pylint: disable=W0613
name: str, name: str,
title: str, title: str,
is_animated: bool, is_animated: bool,
contains_masks: bool, contains_masks: bool,
stickers: List[Sticker], stickers: List[Sticker],
bot: 'Bot' = None, bot: 'Bot' = None, # pylint: disable=W0613
thumb: PhotoSize = None, thumb: PhotoSize = None,
**kwargs: Any, **kwargs: Any,
): ):
@ -242,7 +243,9 @@ class MaskPosition(TelegramObject):
CHIN: ClassVar[str] = constants.STICKER_CHIN CHIN: ClassVar[str] = constants.STICKER_CHIN
""":const:`telegram.constants.STICKER_CHIN`""" """:const:`telegram.constants.STICKER_CHIN`"""
def __init__(self, point: str, x_shift: float, y_shift: float, scale: float, **kwargs: Any): def __init__(
self, point: str, x_shift: float, y_shift: float, scale: float, **kwargs: Any
): # pylint: disable=W0613
self.point = point self.point = point
self.x_shift = x_shift self.x_shift = x_shift
self.y_shift = y_shift self.y_shift = y_shift

View file

@ -18,9 +18,10 @@
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram Venue.""" """This module contains an object that represents a Telegram Venue."""
from telegram import TelegramObject, Location from typing import TYPE_CHECKING, Any, Optional
from telegram import Location, TelegramObject
from telegram.utils.types import JSONDict from telegram.utils.types import JSONDict
from typing import Any, Optional, TYPE_CHECKING
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram import Bot from telegram import Bot
@ -52,7 +53,7 @@ class Venue(TelegramObject):
""" """
def __init__( def __init__(
self, self, # pylint: disable=W0613
location: Location, location: Location,
title: str, title: str,
address: str, address: str,

View file

@ -18,9 +18,10 @@
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram Video.""" """This module contains an object that represents a Telegram Video."""
from typing import TYPE_CHECKING, Any, Optional
from telegram import PhotoSize, TelegramObject from telegram import PhotoSize, TelegramObject
from telegram.utils.types import JSONDict from telegram.utils.types import JSONDict
from typing import Any, Optional, TYPE_CHECKING
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram import Bot, File from telegram import Bot, File
@ -63,7 +64,7 @@ class Video(TelegramObject):
""" """
def __init__( def __init__(
self, self, # pylint: disable=W0613
file_id: str, file_id: str,
file_unique_id: str, file_unique_id: str,
width: int, width: int,

View file

@ -18,9 +18,10 @@
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram VideoNote.""" """This module contains an object that represents a Telegram VideoNote."""
from typing import TYPE_CHECKING, Any, Optional
from telegram import PhotoSize, TelegramObject from telegram import PhotoSize, TelegramObject
from telegram.utils.types import JSONDict from telegram.utils.types import JSONDict
from typing import Any, Optional, TYPE_CHECKING
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram import Bot, File from telegram import Bot, File
@ -60,7 +61,7 @@ class VideoNote(TelegramObject):
""" """
def __init__( def __init__(
self, self, # pylint: disable=W0613
file_id: str, file_id: str,
file_unique_id: str, file_unique_id: str,
length: int, length: int,

View file

@ -18,9 +18,10 @@
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram Voice.""" """This module contains an object that represents a Telegram Voice."""
from typing import TYPE_CHECKING, Any
from telegram import TelegramObject from telegram import TelegramObject
from telegram.utils.types import JSONDict from telegram.utils.types import JSONDict
from typing import Any, TYPE_CHECKING
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram import Bot, File from telegram import Bot, File
@ -57,7 +58,7 @@ class Voice(TelegramObject):
""" """
def __init__( def __init__(
self, self, # pylint: disable=W0613
file_id: str, file_id: str,
file_unique_id: str, file_unique_id: str,
duration: int, duration: int,

View file

@ -18,9 +18,10 @@
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram ForceReply.""" """This module contains an object that represents a Telegram ForceReply."""
from telegram import ReplyMarkup
from typing import Any from typing import Any
from telegram import ReplyMarkup
class ForceReply(ReplyMarkup): class ForceReply(ReplyMarkup):
""" """
@ -49,7 +50,9 @@ class ForceReply(ReplyMarkup):
""" """
def __init__(self, force_reply: bool = True, selective: bool = False, **kwargs: Any): def __init__(
self, force_reply: bool = True, selective: bool = False, **kwargs: Any
): # pylint: disable=W0613
# Required # Required
self.force_reply = bool(force_reply) self.force_reply = bool(force_reply)
# Optionals # Optionals

View file

@ -19,10 +19,10 @@
"""This module contains an object that represents a Telegram Game.""" """This module contains an object that represents a Telegram Game."""
import sys import sys
from typing import TYPE_CHECKING, Any, Dict, List, Optional
from telegram import MessageEntity, TelegramObject, Animation, PhotoSize from telegram import Animation, MessageEntity, PhotoSize, TelegramObject
from telegram.utils.types import JSONDict from telegram.utils.types import JSONDict
from typing import List, Any, Dict, Optional, TYPE_CHECKING
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram import Bot from telegram import Bot
@ -68,7 +68,7 @@ class Game(TelegramObject):
""" """
def __init__( def __init__(
self, self, # pylint: disable=W0613
title: str, title: str,
description: str, description: str,
photo: List[PhotoSize], photo: List[PhotoSize],
@ -135,7 +135,6 @@ class Game(TelegramObject):
# Is it a narrow build, if so we don't need to convert # Is it a narrow build, if so we don't need to convert
if sys.maxunicode == 0xFFFF: if sys.maxunicode == 0xFFFF:
return self.text[entity.offset : entity.offset + entity.length] return self.text[entity.offset : entity.offset + entity.length]
else:
entity_text = self.text.encode('utf-16-le') entity_text = self.text.encode('utf-16-le')
entity_text = entity_text[entity.offset * 2 : (entity.offset + entity.length) * 2] entity_text = entity_text[entity.offset * 2 : (entity.offset + entity.length) * 2]

View file

@ -18,9 +18,10 @@
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram GameHighScore.""" """This module contains an object that represents a Telegram GameHighScore."""
from typing import TYPE_CHECKING, Optional
from telegram import TelegramObject, User from telegram import TelegramObject, User
from telegram.utils.types import JSONDict from telegram.utils.types import JSONDict
from typing import Optional, TYPE_CHECKING
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram import Bot from telegram import Bot

View file

@ -18,8 +18,9 @@
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram InlineKeyboardButton.""" """This module contains an object that represents a Telegram InlineKeyboardButton."""
from typing import TYPE_CHECKING, Any
from telegram import TelegramObject from telegram import TelegramObject
from typing import Any, TYPE_CHECKING
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram import CallbackGame, LoginUrl from telegram import CallbackGame, LoginUrl
@ -83,7 +84,7 @@ class InlineKeyboardButton(TelegramObject):
""" """
def __init__( def __init__(
self, self, # pylint: disable=W0613
text: str, text: str,
url: str = None, url: str = None,
callback_data: str = None, callback_data: str = None,

View file

@ -18,9 +18,10 @@
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram InlineKeyboardMarkup.""" """This module contains an object that represents a Telegram InlineKeyboardMarkup."""
from telegram import ReplyMarkup, InlineKeyboardButton from typing import TYPE_CHECKING, Any, List, Optional
from telegram import InlineKeyboardButton, ReplyMarkup
from telegram.utils.types import JSONDict from telegram.utils.types import JSONDict
from typing import Any, List, Optional, TYPE_CHECKING
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram import Bot from telegram import Bot
@ -44,7 +45,9 @@ class InlineKeyboardMarkup(ReplyMarkup):
""" """
def __init__(self, inline_keyboard: List[List[InlineKeyboardButton]], **kwargs: Any): def __init__(
self, inline_keyboard: List[List[InlineKeyboardButton]], **kwargs: Any
): # pylint: disable=W0613
# Required # Required
self.inline_keyboard = inline_keyboard self.inline_keyboard = inline_keyboard
@ -138,7 +141,7 @@ class InlineKeyboardMarkup(ReplyMarkup):
if button != other.inline_keyboard[idx][jdx]: if button != other.inline_keyboard[idx][jdx]:
return False return False
return True return True
return super(InlineKeyboardMarkup, self).__eq__(other) # pylint: disable=no-member return super().__eq__(other)
def __hash__(self) -> int: def __hash__(self) -> int:
return hash(tuple(tuple(button for button in row) for row in self.inline_keyboard)) return hash(tuple(tuple(button for button in row) for row in self.inline_keyboard))

View file

@ -1,5 +1,5 @@
#!/usr/bin/env python #!/usr/bin/env python
# pylint: disable=R0902,R0912,R0913 # pylint: disable=R0902,R0913
# #
# A library that provides a Python interface to the Telegram Bot API # A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2020 # Copyright (C) 2015-2020
@ -19,9 +19,10 @@
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram InlineQuery.""" """This module contains an object that represents a Telegram InlineQuery."""
from telegram import TelegramObject, User, Location from typing import TYPE_CHECKING, Any, Optional
from telegram import Location, TelegramObject, User
from telegram.utils.types import JSONDict from telegram.utils.types import JSONDict
from typing import Any, Optional, TYPE_CHECKING
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram import Bot from telegram import Bot
@ -59,8 +60,8 @@ class InlineQuery(TelegramObject):
""" """
def __init__( def __init__(
self, self, # pylint: disable=W0613
id: str, id: str, # pylint: disable=W0622
from_user: User, from_user: User,
query: str, query: str,
offset: str, offset: str,
@ -69,7 +70,7 @@ class InlineQuery(TelegramObject):
**kwargs: Any, **kwargs: Any,
): ):
# Required # Required
self.id = id self.id = id # pylint: disable=C0103
self.from_user = from_user self.from_user = from_user
self.query = query self.query = query
self.offset = offset self.offset = offset

View file

@ -16,11 +16,13 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
# pylint: disable=W0622
"""This module contains the classes that represent Telegram InlineQueryResult.""" """This module contains the classes that represent Telegram InlineQueryResult."""
from telegram import TelegramObject
from typing import Any from typing import Any
from telegram import TelegramObject
class InlineQueryResult(TelegramObject): class InlineQueryResult(TelegramObject):
"""Baseclass for the InlineQueryResult* classes. """Baseclass for the InlineQueryResult* classes.
@ -39,10 +41,10 @@ class InlineQueryResult(TelegramObject):
""" """
def __init__(self, type: str, id: str, **kwargs: Any): def __init__(self, type: str, id: str, **kwargs: Any): # pylint: disable=W0613
# Required # Required
self.type = str(type) self.type = str(type)
self.id = str(id) self.id = str(id) # pylint: disable=C0103
self._id_attrs = (self.id,) self._id_attrs = (self.id,)

View file

@ -18,8 +18,9 @@
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultArticle.""" """This module contains the classes that represent Telegram InlineQueryResultArticle."""
from typing import TYPE_CHECKING, Any
from telegram import InlineQueryResult from telegram import InlineQueryResult
from typing import Any, TYPE_CHECKING
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram import InputMessageContent, ReplyMarkup from telegram import InputMessageContent, ReplyMarkup
@ -64,7 +65,7 @@ class InlineQueryResultArticle(InlineQueryResult):
def __init__( def __init__(
self, self,
id: str, id: str, # pylint: disable=W0622
title: str, title: str,
input_message_content: 'InputMessageContent', input_message_content: 'InputMessageContent',
reply_markup: 'ReplyMarkup' = None, reply_markup: 'ReplyMarkup' = None,
@ -74,7 +75,7 @@ class InlineQueryResultArticle(InlineQueryResult):
thumb_url: str = None, thumb_url: str = None,
thumb_width: int = None, thumb_width: int = None,
thumb_height: int = None, thumb_height: int = None,
**kwargs: Any, **kwargs: Any, # pylint: disable=W0613
): ):
# Required # Required

View file

@ -18,9 +18,10 @@
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultAudio.""" """This module contains the classes that represent Telegram InlineQueryResultAudio."""
from typing import TYPE_CHECKING, Any, Union
from telegram import InlineQueryResult from telegram import InlineQueryResult
from telegram.utils.helpers import DEFAULT_NONE, DefaultValue from telegram.utils.helpers import DEFAULT_NONE, DefaultValue
from typing import Any, Union, TYPE_CHECKING
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram import InputMessageContent, ReplyMarkup from telegram import InputMessageContent, ReplyMarkup
@ -68,7 +69,7 @@ class InlineQueryResultAudio(InlineQueryResult):
def __init__( def __init__(
self, self,
id: str, id: str, # pylint: disable=W0622
audio_url: str, audio_url: str,
title: str, title: str,
performer: str = None, performer: str = None,
@ -77,7 +78,7 @@ class InlineQueryResultAudio(InlineQueryResult):
reply_markup: 'ReplyMarkup' = None, reply_markup: 'ReplyMarkup' = None,
input_message_content: 'InputMessageContent' = None, input_message_content: 'InputMessageContent' = None,
parse_mode: Union[str, DefaultValue] = DEFAULT_NONE, parse_mode: Union[str, DefaultValue] = DEFAULT_NONE,
**kwargs: Any, **kwargs: Any, # pylint: disable=W0613
): ):
# Required # Required

View file

@ -18,9 +18,10 @@
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultCachedAudio.""" """This module contains the classes that represent Telegram InlineQueryResultCachedAudio."""
from typing import TYPE_CHECKING, Any, Union
from telegram import InlineQueryResult from telegram import InlineQueryResult
from telegram.utils.helpers import DEFAULT_NONE, DefaultValue from telegram.utils.helpers import DEFAULT_NONE, DefaultValue
from typing import Any, Union, TYPE_CHECKING
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram import InputMessageContent, ReplyMarkup from telegram import InputMessageContent, ReplyMarkup
@ -62,13 +63,13 @@ class InlineQueryResultCachedAudio(InlineQueryResult):
def __init__( def __init__(
self, self,
id: str, id: str, # pylint: disable=W0622
audio_file_id: str, audio_file_id: str,
caption: str = None, caption: str = None,
reply_markup: 'ReplyMarkup' = None, reply_markup: 'ReplyMarkup' = None,
input_message_content: 'InputMessageContent' = None, input_message_content: 'InputMessageContent' = None,
parse_mode: Union[str, DefaultValue] = DEFAULT_NONE, parse_mode: Union[str, DefaultValue] = DEFAULT_NONE,
**kwargs: Any, **kwargs: Any, # pylint: disable=W0613
): ):
# Required # Required
super().__init__('audio', id) super().__init__('audio', id)

View file

@ -16,11 +16,13 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
# pylint: disable=W0622
"""This module contains the classes that represent Telegram InlineQueryResultCachedDocument.""" """This module contains the classes that represent Telegram InlineQueryResultCachedDocument."""
from typing import TYPE_CHECKING, Any, Union
from telegram import InlineQueryResult from telegram import InlineQueryResult
from telegram.utils.helpers import DEFAULT_NONE, DefaultValue from telegram.utils.helpers import DEFAULT_NONE, DefaultValue
from typing import Any, Union, TYPE_CHECKING
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram import InputMessageContent, ReplyMarkup from telegram import InputMessageContent, ReplyMarkup
@ -68,7 +70,7 @@ class InlineQueryResultCachedDocument(InlineQueryResult):
def __init__( def __init__(
self, self,
id: str, id: str, # pylint: disable=W0622
title: str, title: str,
document_file_id: str, document_file_id: str,
description: str = None, description: str = None,
@ -76,7 +78,7 @@ class InlineQueryResultCachedDocument(InlineQueryResult):
reply_markup: 'ReplyMarkup' = None, reply_markup: 'ReplyMarkup' = None,
input_message_content: 'InputMessageContent' = None, input_message_content: 'InputMessageContent' = None,
parse_mode: Union[str, DefaultValue] = DEFAULT_NONE, parse_mode: Union[str, DefaultValue] = DEFAULT_NONE,
**kwargs: Any, **kwargs: Any, # pylint: disable=W0613
): ):
# Required # Required
super().__init__('document', id) super().__init__('document', id)

View file

@ -18,9 +18,10 @@
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultCachedGif.""" """This module contains the classes that represent Telegram InlineQueryResultCachedGif."""
from typing import TYPE_CHECKING, Any, Union
from telegram import InlineQueryResult from telegram import InlineQueryResult
from telegram.utils.helpers import DEFAULT_NONE, DefaultValue from telegram.utils.helpers import DEFAULT_NONE, DefaultValue
from typing import Any, Union, TYPE_CHECKING
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram import InputMessageContent, ReplyMarkup from telegram import InputMessageContent, ReplyMarkup
@ -67,14 +68,14 @@ class InlineQueryResultCachedGif(InlineQueryResult):
def __init__( def __init__(
self, self,
id: str, id: str, # pylint: disable=W0622
gif_file_id: str, gif_file_id: str,
title: str = None, title: str = None,
caption: str = None, caption: str = None,
reply_markup: 'ReplyMarkup' = None, reply_markup: 'ReplyMarkup' = None,
input_message_content: 'InputMessageContent' = None, input_message_content: 'InputMessageContent' = None,
parse_mode: Union[str, DefaultValue] = DEFAULT_NONE, parse_mode: Union[str, DefaultValue] = DEFAULT_NONE,
**kwargs: Any, **kwargs: Any, # pylint: disable=W0613
): ):
# Required # Required
super().__init__('gif', id) super().__init__('gif', id)

View file

@ -18,9 +18,10 @@
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultMpeg4Gif.""" """This module contains the classes that represent Telegram InlineQueryResultMpeg4Gif."""
from typing import TYPE_CHECKING, Any, Union
from telegram import InlineQueryResult from telegram import InlineQueryResult
from telegram.utils.helpers import DEFAULT_NONE, DefaultValue from telegram.utils.helpers import DEFAULT_NONE, DefaultValue
from typing import Any, Union, TYPE_CHECKING
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram import InputMessageContent, ReplyMarkup from telegram import InputMessageContent, ReplyMarkup
@ -67,14 +68,14 @@ class InlineQueryResultCachedMpeg4Gif(InlineQueryResult):
def __init__( def __init__(
self, self,
id: str, id: str, # pylint: disable=W0622
mpeg4_file_id: str, mpeg4_file_id: str,
title: str = None, title: str = None,
caption: str = None, caption: str = None,
reply_markup: 'ReplyMarkup' = None, reply_markup: 'ReplyMarkup' = None,
input_message_content: 'InputMessageContent' = None, input_message_content: 'InputMessageContent' = None,
parse_mode: Union[str, DefaultValue] = DEFAULT_NONE, parse_mode: Union[str, DefaultValue] = DEFAULT_NONE,
**kwargs: Any, **kwargs: Any, # pylint: disable=W0613
): ):
# Required # Required
super().__init__('mpeg4_gif', id) super().__init__('mpeg4_gif', id)

View file

@ -16,11 +16,13 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
# pylint: disable=W0622
"""This module contains the classes that represent Telegram InlineQueryResultPhoto""" """This module contains the classes that represent Telegram InlineQueryResultPhoto"""
from typing import TYPE_CHECKING, Any, Union
from telegram import InlineQueryResult from telegram import InlineQueryResult
from telegram.utils.helpers import DEFAULT_NONE, DefaultValue from telegram.utils.helpers import DEFAULT_NONE, DefaultValue
from typing import Any, Union, TYPE_CHECKING
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram import InputMessageContent, ReplyMarkup from telegram import InputMessageContent, ReplyMarkup
@ -69,7 +71,7 @@ class InlineQueryResultCachedPhoto(InlineQueryResult):
def __init__( def __init__(
self, self,
id: str, id: str, # pylint: disable=W0622
photo_file_id: str, photo_file_id: str,
title: str = None, title: str = None,
description: str = None, description: str = None,
@ -77,7 +79,7 @@ class InlineQueryResultCachedPhoto(InlineQueryResult):
reply_markup: 'ReplyMarkup' = None, reply_markup: 'ReplyMarkup' = None,
input_message_content: 'InputMessageContent' = None, input_message_content: 'InputMessageContent' = None,
parse_mode: Union[str, DefaultValue] = DEFAULT_NONE, parse_mode: Union[str, DefaultValue] = DEFAULT_NONE,
**kwargs: Any, **kwargs: Any, # pylint: disable=W0613
): ):
# Required # Required
super().__init__('photo', id) super().__init__('photo', id)

View file

@ -18,11 +18,12 @@
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultCachedSticker.""" """This module contains the classes that represent Telegram InlineQueryResultCachedSticker."""
from typing import TYPE_CHECKING, Any
from telegram import InlineQueryResult from telegram import InlineQueryResult
from typing import Any, TYPE_CHECKING
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram import ReplyMarkup, InputMessageContent from telegram import InputMessageContent, ReplyMarkup
class InlineQueryResultCachedSticker(InlineQueryResult): class InlineQueryResultCachedSticker(InlineQueryResult):
@ -53,11 +54,11 @@ class InlineQueryResultCachedSticker(InlineQueryResult):
def __init__( def __init__(
self, self,
id: str, id: str, # pylint: disable=W0622
sticker_file_id: str, sticker_file_id: str,
reply_markup: 'ReplyMarkup' = None, reply_markup: 'ReplyMarkup' = None,
input_message_content: 'InputMessageContent' = None, input_message_content: 'InputMessageContent' = None,
**kwargs: Any, **kwargs: Any, # pylint: disable=W0613
): ):
# Required # Required
super().__init__('sticker', id) super().__init__('sticker', id)

View file

@ -18,9 +18,10 @@
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultCachedVideo.""" """This module contains the classes that represent Telegram InlineQueryResultCachedVideo."""
from typing import TYPE_CHECKING, Any, Union
from telegram import InlineQueryResult from telegram import InlineQueryResult
from telegram.utils.helpers import DEFAULT_NONE, DefaultValue from telegram.utils.helpers import DEFAULT_NONE, DefaultValue
from typing import Any, Union, TYPE_CHECKING
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram import InputMessageContent, ReplyMarkup from telegram import InputMessageContent, ReplyMarkup
@ -69,7 +70,7 @@ class InlineQueryResultCachedVideo(InlineQueryResult):
def __init__( def __init__(
self, self,
id: str, id: str, # pylint: disable=W0622
video_file_id: str, video_file_id: str,
title: str, title: str,
description: str = None, description: str = None,
@ -77,7 +78,7 @@ class InlineQueryResultCachedVideo(InlineQueryResult):
reply_markup: 'ReplyMarkup' = None, reply_markup: 'ReplyMarkup' = None,
input_message_content: 'InputMessageContent' = None, input_message_content: 'InputMessageContent' = None,
parse_mode: Union[str, DefaultValue] = DEFAULT_NONE, parse_mode: Union[str, DefaultValue] = DEFAULT_NONE,
**kwargs: Any, **kwargs: Any, # pylint: disable=W0613
): ):
# Required # Required
super().__init__('video', id) super().__init__('video', id)

View file

@ -18,9 +18,10 @@
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultCachedVoice.""" """This module contains the classes that represent Telegram InlineQueryResultCachedVoice."""
from typing import TYPE_CHECKING, Any, Union
from telegram import InlineQueryResult from telegram import InlineQueryResult
from telegram.utils.helpers import DEFAULT_NONE, DefaultValue from telegram.utils.helpers import DEFAULT_NONE, DefaultValue
from typing import Any, Union, TYPE_CHECKING
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram import InputMessageContent, ReplyMarkup from telegram import InputMessageContent, ReplyMarkup
@ -64,14 +65,14 @@ class InlineQueryResultCachedVoice(InlineQueryResult):
def __init__( def __init__(
self, self,
id: str, id: str, # pylint: disable=W0622
voice_file_id: str, voice_file_id: str,
title: str, title: str,
caption: str = None, caption: str = None,
reply_markup: 'ReplyMarkup' = None, reply_markup: 'ReplyMarkup' = None,
input_message_content: 'InputMessageContent' = None, input_message_content: 'InputMessageContent' = None,
parse_mode: Union[str, DefaultValue] = DEFAULT_NONE, parse_mode: Union[str, DefaultValue] = DEFAULT_NONE,
**kwargs: Any, **kwargs: Any, # pylint: disable=W0613
): ):
# Required # Required
super().__init__('voice', id) super().__init__('voice', id)

View file

@ -18,11 +18,12 @@
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultContact.""" """This module contains the classes that represent Telegram InlineQueryResultContact."""
from typing import TYPE_CHECKING, Any
from telegram import InlineQueryResult from telegram import InlineQueryResult
from typing import Any, TYPE_CHECKING
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram import ReplyMarkup, InputMessageContent from telegram import InputMessageContent, ReplyMarkup
class InlineQueryResultContact(InlineQueryResult): class InlineQueryResultContact(InlineQueryResult):
@ -67,7 +68,7 @@ class InlineQueryResultContact(InlineQueryResult):
def __init__( def __init__(
self, self,
id: str, id: str, # pylint: disable=W0622
phone_number: str, phone_number: str,
first_name: str, first_name: str,
last_name: str = None, last_name: str = None,
@ -77,7 +78,7 @@ class InlineQueryResultContact(InlineQueryResult):
thumb_width: int = None, thumb_width: int = None,
thumb_height: int = None, thumb_height: int = None,
vcard: str = None, vcard: str = None,
**kwargs: Any, **kwargs: Any, # pylint: disable=W0613
): ):
# Required # Required
super().__init__('contact', id) super().__init__('contact', id)

View file

@ -18,9 +18,10 @@
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultDocument""" """This module contains the classes that represent Telegram InlineQueryResultDocument"""
from typing import TYPE_CHECKING, Any, Union
from telegram import InlineQueryResult from telegram import InlineQueryResult
from telegram.utils.helpers import DEFAULT_NONE, DefaultValue from telegram.utils.helpers import DEFAULT_NONE, DefaultValue
from typing import Any, Union, TYPE_CHECKING
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram import InputMessageContent, ReplyMarkup from telegram import InputMessageContent, ReplyMarkup
@ -79,7 +80,7 @@ class InlineQueryResultDocument(InlineQueryResult):
def __init__( def __init__(
self, self,
id: str, id: str, # pylint: disable=W0622
document_url: str, document_url: str,
title: str, title: str,
mime_type: str, mime_type: str,
@ -91,7 +92,7 @@ class InlineQueryResultDocument(InlineQueryResult):
thumb_width: int = None, thumb_width: int = None,
thumb_height: int = None, thumb_height: int = None,
parse_mode: Union[str, DefaultValue] = DEFAULT_NONE, parse_mode: Union[str, DefaultValue] = DEFAULT_NONE,
**kwargs: Any, **kwargs: Any, # pylint: disable=W0613
): ):
# Required # Required
super().__init__('document', id) super().__init__('document', id)

View file

@ -18,8 +18,9 @@
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultGame.""" """This module contains the classes that represent Telegram InlineQueryResultGame."""
from typing import TYPE_CHECKING, Any
from telegram import InlineQueryResult from telegram import InlineQueryResult
from typing import Any, TYPE_CHECKING
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram import ReplyMarkup from telegram import ReplyMarkup
@ -45,11 +46,15 @@ class InlineQueryResultGame(InlineQueryResult):
""" """
def __init__( def __init__(
self, id: str, game_short_name: str, reply_markup: 'ReplyMarkup' = None, **kwargs: Any self,
id: str, # pylint: disable=W0622
game_short_name: str,
reply_markup: 'ReplyMarkup' = None,
**kwargs: Any,
): ):
# Required # Required
super().__init__('game', id) super().__init__('game', id)
self.id = id self.id = id # pylint: disable=W0622
self.game_short_name = game_short_name self.game_short_name = game_short_name
self.reply_markup = reply_markup self.reply_markup = reply_markup

View file

@ -16,11 +16,13 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
# pylint: disable=W0622
"""This module contains the classes that represent Telegram InlineQueryResultGif.""" """This module contains the classes that represent Telegram InlineQueryResultGif."""
from typing import TYPE_CHECKING, Any, Union
from telegram import InlineQueryResult from telegram import InlineQueryResult
from telegram.utils.helpers import DEFAULT_NONE, DefaultValue from telegram.utils.helpers import DEFAULT_NONE, DefaultValue
from typing import Any, Union, TYPE_CHECKING
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram import InputMessageContent, ReplyMarkup from telegram import InputMessageContent, ReplyMarkup
@ -79,7 +81,7 @@ class InlineQueryResultGif(InlineQueryResult):
def __init__( def __init__(
self, self,
id: str, id: str, # pylint: disable=W0622
gif_url: str, gif_url: str,
thumb_url: str, thumb_url: str,
gif_width: int = None, gif_width: int = None,
@ -91,7 +93,7 @@ class InlineQueryResultGif(InlineQueryResult):
gif_duration: int = None, gif_duration: int = None,
parse_mode: Union[str, DefaultValue] = DEFAULT_NONE, parse_mode: Union[str, DefaultValue] = DEFAULT_NONE,
thumb_mime_type: str = None, thumb_mime_type: str = None,
**kwargs: Any, **kwargs: Any, # pylint: disable=W0613
): ):
# Required # Required

View file

@ -18,11 +18,12 @@
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultLocation.""" """This module contains the classes that represent Telegram InlineQueryResultLocation."""
from typing import TYPE_CHECKING, Any
from telegram import InlineQueryResult from telegram import InlineQueryResult
from typing import Any, TYPE_CHECKING
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram import ReplyMarkup, InputMessageContent from telegram import InputMessageContent, ReplyMarkup
class InlineQueryResultLocation(InlineQueryResult): class InlineQueryResultLocation(InlineQueryResult):
@ -67,7 +68,7 @@ class InlineQueryResultLocation(InlineQueryResult):
def __init__( def __init__(
self, self,
id: str, id: str, # pylint: disable=W0622
latitude: float, latitude: float,
longitude: float, longitude: float,
title: str, title: str,
@ -77,7 +78,7 @@ class InlineQueryResultLocation(InlineQueryResult):
thumb_url: str = None, thumb_url: str = None,
thumb_width: int = None, thumb_width: int = None,
thumb_height: int = None, thumb_height: int = None,
**kwargs: Any, **kwargs: Any, # pylint: disable=W0613
): ):
# Required # Required
super().__init__('location', id) super().__init__('location', id)

View file

@ -18,9 +18,10 @@
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultMpeg4Gif.""" """This module contains the classes that represent Telegram InlineQueryResultMpeg4Gif."""
from typing import TYPE_CHECKING, Any, Union
from telegram import InlineQueryResult from telegram import InlineQueryResult
from telegram.utils.helpers import DEFAULT_NONE, DefaultValue from telegram.utils.helpers import DEFAULT_NONE, DefaultValue
from typing import Any, Union, TYPE_CHECKING
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram import InputMessageContent, ReplyMarkup from telegram import InputMessageContent, ReplyMarkup
@ -79,7 +80,7 @@ class InlineQueryResultMpeg4Gif(InlineQueryResult):
def __init__( def __init__(
self, self,
id: str, id: str, # pylint: disable=W0622
mpeg4_url: str, mpeg4_url: str,
thumb_url: str, thumb_url: str,
mpeg4_width: int = None, mpeg4_width: int = None,
@ -91,7 +92,7 @@ class InlineQueryResultMpeg4Gif(InlineQueryResult):
mpeg4_duration: int = None, mpeg4_duration: int = None,
parse_mode: Union[str, DefaultValue] = DEFAULT_NONE, parse_mode: Union[str, DefaultValue] = DEFAULT_NONE,
thumb_mime_type: str = None, thumb_mime_type: str = None,
**kwargs: Any, **kwargs: Any, # pylint: disable=W0613
): ):
# Required # Required

View file

@ -18,9 +18,10 @@
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultPhoto.""" """This module contains the classes that represent Telegram InlineQueryResultPhoto."""
from typing import TYPE_CHECKING, Any, Union
from telegram import InlineQueryResult from telegram import InlineQueryResult
from telegram.utils.helpers import DEFAULT_NONE, DefaultValue from telegram.utils.helpers import DEFAULT_NONE, DefaultValue
from typing import Any, Union, TYPE_CHECKING
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram import InputMessageContent, ReplyMarkup from telegram import InputMessageContent, ReplyMarkup
@ -76,7 +77,7 @@ class InlineQueryResultPhoto(InlineQueryResult):
def __init__( def __init__(
self, self,
id: str, id: str, # pylint: disable=W0622
photo_url: str, photo_url: str,
thumb_url: str, thumb_url: str,
photo_width: int = None, photo_width: int = None,
@ -87,7 +88,7 @@ class InlineQueryResultPhoto(InlineQueryResult):
reply_markup: 'ReplyMarkup' = None, reply_markup: 'ReplyMarkup' = None,
input_message_content: 'InputMessageContent' = None, input_message_content: 'InputMessageContent' = None,
parse_mode: Union[str, DefaultValue] = DEFAULT_NONE, parse_mode: Union[str, DefaultValue] = DEFAULT_NONE,
**kwargs: Any, **kwargs: Any, # pylint: disable=W0613
): ):
# Required # Required
super().__init__('photo', id) super().__init__('photo', id)

View file

@ -18,11 +18,12 @@
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultVenue.""" """This module contains the classes that represent Telegram InlineQueryResultVenue."""
from typing import TYPE_CHECKING, Any
from telegram import InlineQueryResult from telegram import InlineQueryResult
from typing import Any, TYPE_CHECKING
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram import ReplyMarkup, InputMessageContent from telegram import InputMessageContent, ReplyMarkup
class InlineQueryResultVenue(InlineQueryResult): class InlineQueryResultVenue(InlineQueryResult):
@ -73,7 +74,7 @@ class InlineQueryResultVenue(InlineQueryResult):
def __init__( def __init__(
self, self,
id: str, id: str, # pylint: disable=W0622
latitude: float, latitude: float,
longitude: float, longitude: float,
title: str, title: str,
@ -85,7 +86,7 @@ class InlineQueryResultVenue(InlineQueryResult):
thumb_url: str = None, thumb_url: str = None,
thumb_width: int = None, thumb_width: int = None,
thumb_height: int = None, thumb_height: int = None,
**kwargs: Any, **kwargs: Any, # pylint: disable=W0613
): ):
# Required # Required

View file

@ -18,9 +18,10 @@
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultVideo.""" """This module contains the classes that represent Telegram InlineQueryResultVideo."""
from typing import TYPE_CHECKING, Any, Union
from telegram import InlineQueryResult from telegram import InlineQueryResult
from telegram.utils.helpers import DEFAULT_NONE, DefaultValue from telegram.utils.helpers import DEFAULT_NONE, DefaultValue
from typing import Any, Union, TYPE_CHECKING
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram import InputMessageContent, ReplyMarkup from telegram import InputMessageContent, ReplyMarkup
@ -86,7 +87,7 @@ class InlineQueryResultVideo(InlineQueryResult):
def __init__( def __init__(
self, self,
id: str, id: str, # pylint: disable=W0622
video_url: str, video_url: str,
mime_type: str, mime_type: str,
thumb_url: str, thumb_url: str,
@ -99,7 +100,7 @@ class InlineQueryResultVideo(InlineQueryResult):
reply_markup: 'ReplyMarkup' = None, reply_markup: 'ReplyMarkup' = None,
input_message_content: 'InputMessageContent' = None, input_message_content: 'InputMessageContent' = None,
parse_mode: Union[str, DefaultValue] = DEFAULT_NONE, parse_mode: Union[str, DefaultValue] = DEFAULT_NONE,
**kwargs: Any, **kwargs: Any, # pylint: disable=W0613
): ):
# Required # Required

View file

@ -18,9 +18,10 @@
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultVoice.""" """This module contains the classes that represent Telegram InlineQueryResultVoice."""
from typing import TYPE_CHECKING, Any, Union
from telegram import InlineQueryResult from telegram import InlineQueryResult
from telegram.utils.helpers import DEFAULT_NONE, DefaultValue from telegram.utils.helpers import DEFAULT_NONE, DefaultValue
from typing import Any, Union, TYPE_CHECKING
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram import InputMessageContent, ReplyMarkup from telegram import InputMessageContent, ReplyMarkup
@ -67,7 +68,7 @@ class InlineQueryResultVoice(InlineQueryResult):
def __init__( def __init__(
self, self,
id: str, id: str, # pylint: disable=W0622
voice_url: str, voice_url: str,
title: str, title: str,
voice_duration: int = None, voice_duration: int = None,
@ -75,7 +76,7 @@ class InlineQueryResultVoice(InlineQueryResult):
reply_markup: 'ReplyMarkup' = None, reply_markup: 'ReplyMarkup' = None,
input_message_content: 'InputMessageContent' = None, input_message_content: 'InputMessageContent' = None,
parse_mode: Union[str, DefaultValue] = DEFAULT_NONE, parse_mode: Union[str, DefaultValue] = DEFAULT_NONE,
**kwargs: Any, **kwargs: Any, # pylint: disable=W0613
): ):
# Required # Required

View file

@ -18,9 +18,10 @@
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InputContactMessageContent.""" """This module contains the classes that represent Telegram InputContactMessageContent."""
from telegram import InputMessageContent
from typing import Any from typing import Any
from telegram import InputMessageContent
class InputContactMessageContent(InputMessageContent): class InputContactMessageContent(InputMessageContent):
"""Represents the content of a contact message to be sent as the result of an inline query. """Represents the content of a contact message to be sent as the result of an inline query.
@ -46,7 +47,7 @@ class InputContactMessageContent(InputMessageContent):
""" """
def __init__( def __init__(
self, self, # pylint: disable=W0613
phone_number: str, phone_number: str,
first_name: str, first_name: str,
last_name: str = None, last_name: str = None,

View file

@ -18,9 +18,10 @@
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InputLocationMessageContent.""" """This module contains the classes that represent Telegram InputLocationMessageContent."""
from telegram import InputMessageContent
from typing import Any from typing import Any
from telegram import InputMessageContent
class InputLocationMessageContent(InputMessageContent): class InputLocationMessageContent(InputMessageContent):
# fmt: off # fmt: off
@ -46,7 +47,9 @@ class InputLocationMessageContent(InputMessageContent):
""" """
# fmt: on # fmt: on
def __init__(self, latitude: float, longitude: float, live_period: int = None, **kwargs: Any): def __init__(
self, latitude: float, longitude: float, live_period: int = None, **kwargs: Any
): # pylint: disable=W0613
# Required # Required
self.latitude = latitude self.latitude = latitude
self.longitude = longitude self.longitude = longitude

View file

@ -18,9 +18,10 @@
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InputTextMessageContent.""" """This module contains the classes that represent Telegram InputTextMessageContent."""
from typing import Any, Union
from telegram import InputMessageContent from telegram import InputMessageContent
from telegram.utils.helpers import DEFAULT_NONE, DefaultValue from telegram.utils.helpers import DEFAULT_NONE, DefaultValue
from typing import Any, Union
class InputTextMessageContent(InputMessageContent): class InputTextMessageContent(InputMessageContent):
@ -52,7 +53,7 @@ class InputTextMessageContent(InputMessageContent):
""" """
def __init__( def __init__(
self, self, # pylint: disable=W0613
message_text: str, message_text: str,
parse_mode: Union[str, DefaultValue] = DEFAULT_NONE, parse_mode: Union[str, DefaultValue] = DEFAULT_NONE,
disable_web_page_preview: Union[bool, DefaultValue] = DEFAULT_NONE, disable_web_page_preview: Union[bool, DefaultValue] = DEFAULT_NONE,

Some files were not shown because too many files have changed in this diff Show more