Skip to content

Refactor handling of default_quote #1965

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 14 commits into from
Jul 19, 2020
14 changes: 0 additions & 14 deletions telegram/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,9 +192,6 @@ def _message(self, endpoint, data, reply_to_message_id=None, disable_notificatio
if result is True:
return result

if self.defaults:
result['default_quote'] = self.defaults.quote

return Message.de_json(result, self)

@property
Expand Down Expand Up @@ -1114,10 +1111,6 @@ def send_media_group(self,

result = self._post('sendMediaGroup', data, timeout=timeout, api_kwargs=api_kwargs)

if self.defaults:
for res in result:
res['default_quote'] = self.defaults.quote

return [Message.de_json(res, self) for res in result]

@log
Expand Down Expand Up @@ -2137,10 +2130,6 @@ def get_updates(self,
else:
self.logger.debug('No new updates found.')

if self.defaults:
for u in result:
u['default_quote'] = self.defaults.quote

return [Update.de_json(u, self) for u in result]

@log
Expand Down Expand Up @@ -2301,9 +2290,6 @@ def get_chat(self, chat_id, timeout=None, api_kwargs=None):

result = self._post('getChat', data, timeout=timeout, api_kwargs=api_kwargs)

if self.defaults:
result['default_quote'] = self.defaults.quote

return Chat.de_json(result, self)

@log
Expand Down
5 changes: 1 addition & 4 deletions telegram/callbackquery.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,10 +105,7 @@ def de_json(cls, data, bot):
data = super().de_json(data, bot)

data['from_user'] = User.de_json(data.get('from'), bot)
message = data.get('message')
if message:
message['default_quote'] = data.get('default_quote')
data['message'] = Message.de_json(message, bot)
data['message'] = Message.de_json(data.get('message'), bot)

return cls(bot=bot, **data)

Expand Down
5 changes: 1 addition & 4 deletions telegram/chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,10 +144,7 @@ def de_json(cls, data, bot):

data['photo'] = ChatPhoto.de_json(data.get('photo'), bot)
from telegram import Message
pinned_message = data.get('pinned_message')
if pinned_message:
pinned_message['default_quote'] = data.get('default_quote')
data['pinned_message'] = Message.de_json(pinned_message, bot)
data['pinned_message'] = Message.de_json(data.get('pinned_message'), bot)
data['permissions'] = ChatPermissions.de_json(data.get('permissions'), bot)

return cls(bot=bot, **data)
Expand Down
14 changes: 9 additions & 5 deletions telegram/ext/updater.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

import logging
import ssl
import warnings
from threading import Thread, Lock, current_thread, Event
from time import sleep
from signal import signal, SIGINT, SIGTERM, SIGABRT
Expand All @@ -28,6 +29,7 @@
from telegram import Bot, TelegramError
from telegram.ext import Dispatcher, JobQueue
from telegram.error import Unauthorized, InvalidToken, RetryAfter, TimedOut
from telegram.utils.deprecate import TelegramDeprecationWarning
from telegram.utils.helpers import get_signal_name
from telegram.utils.request import Request
from telegram.utils.webhookhandler import (WebhookServer, WebhookAppClass)
Expand Down Expand Up @@ -116,6 +118,12 @@ def __init__(self,
dispatcher=None,
base_file_url=None):

if defaults and bot:
warnings.warn('Passing defaults to an Updater has no effect when a Bot is passed '
'as well. Pass them to the Bot instead.',
TelegramDeprecationWarning,
stacklevel=2)

if dispatcher is None:
if (token is None) and (bot is None):
raise ValueError('`token` or `bot` must be passed')
Expand Down Expand Up @@ -197,9 +205,6 @@ def __init__(self,
self.__lock = Lock()
self.__threads = []

# Just for passing to WebhookAppClass
self._default_quote = defaults.quote if defaults else None

def _init_thread(self, target, name, *args, **kwargs):
thr = Thread(target=self._thread_wrapper,
name="Bot:{}:{}".format(self.bot.id, name),
Expand Down Expand Up @@ -417,8 +422,7 @@ def _start_webhook(self, listen, port, url_path, cert, key, bootstrap_retries, c
url_path = '/{}'.format(url_path)

# Create Tornado app instance
app = WebhookAppClass(url_path, self.bot, self.update_queue,
default_quote=self._default_quote)
app = WebhookAppClass(url_path, self.bot, self.update_queue)

# Form SSL Context
# An SSLError is raised if the private key does not match with the certificate
Expand Down
34 changes: 10 additions & 24 deletions telegram/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,8 +114,6 @@ class Message(TelegramObject):
reply_markup (:class:`telegram.InlineKeyboardMarkup`): Optional. Inline keyboard attached
to the message.
bot (:class:`telegram.Bot`): Optional. The Bot to use for instance methods.
default_quote (:obj:`bool`): Optional. Default setting for the `quote` parameter of the
:attr:`reply_text` and friends.

Args:
message_id (:obj:`int`): Unique message identifier inside this chat.
Expand Down Expand Up @@ -223,8 +221,7 @@ class Message(TelegramObject):
via_bot (:class:`telegram.User`, optional): Message was sent through an inline bot.
reply_markup (:class:`telegram.InlineKeyboardMarkup`, optional): Inline keyboard attached
to the message. login_url buttons are represented as ordinary url buttons.
default_quote (:obj:`bool`, optional): Default setting for the `quote` parameter of the
:attr:`reply_text` and friends.
bot (:class:`telegram.Bot`, optional): The Bot to use for instance methods.

"""

Expand Down Expand Up @@ -288,7 +285,6 @@ def __init__(self,
forward_sender_name=None,
reply_markup=None,
bot=None,
default_quote=None,
dice=None,
via_bot=None,
**kwargs):
Expand Down Expand Up @@ -344,7 +340,6 @@ def __init__(self,
self.via_bot = via_bot
self.reply_markup = reply_markup
self.bot = bot
self.default_quote = default_quote

self._id_attrs = (self.message_id, self.chat)

Expand Down Expand Up @@ -375,22 +370,13 @@ def de_json(cls, data, bot):

data['from_user'] = User.de_json(data.get('from'), bot)
data['date'] = from_timestamp(data['date'])
chat = data.get('chat')
if chat:
chat['default_quote'] = data.get('default_quote')
data['chat'] = Chat.de_json(chat, bot)
data['chat'] = Chat.de_json(data.get('chat'), bot)
data['entities'] = MessageEntity.de_list(data.get('entities'), bot)
data['caption_entities'] = MessageEntity.de_list(data.get('caption_entities'), bot)
data['forward_from'] = User.de_json(data.get('forward_from'), bot)
forward_from_chat = data.get('forward_from_chat')
if forward_from_chat:
forward_from_chat['default_quote'] = data.get('default_quote')
data['forward_from_chat'] = Chat.de_json(forward_from_chat, bot)
data['forward_from_chat'] = Chat.de_json(data.get('forward_from_chat'), bot)
data['forward_date'] = from_timestamp(data.get('forward_date'))
reply_to_message = data.get('reply_to_message')
if reply_to_message:
reply_to_message['default_quote'] = data.get('default_quote')
data['reply_to_message'] = Message.de_json(reply_to_message, bot)
data['reply_to_message'] = Message.de_json(data.get('reply_to_message'), bot)
data['edit_date'] = from_timestamp(data.get('edit_date'))
data['audio'] = Audio.de_json(data.get('audio'), bot)
data['document'] = Document.de_json(data.get('document'), bot)
Expand All @@ -407,10 +393,7 @@ def de_json(cls, data, bot):
data['new_chat_members'] = User.de_list(data.get('new_chat_members'), bot)
data['left_chat_member'] = User.de_json(data.get('left_chat_member'), bot)
data['new_chat_photo'] = PhotoSize.de_list(data.get('new_chat_photo'), bot)
pinned_message = data.get('pinned_message')
if pinned_message:
pinned_message['default_quote'] = data.get('default_quote')
data['pinned_message'] = Message.de_json(pinned_message, bot)
data['pinned_message'] = Message.de_json(data.get('pinned_message'), bot)
data['invoice'] = Invoice.de_json(data.get('invoice'), bot)
data['successful_payment'] = SuccessfulPayment.de_json(data.get('successful_payment'), bot)
data['passport_data'] = PassportData.de_json(data.get('passport_data'), bot)
Expand Down Expand Up @@ -495,8 +478,11 @@ def _quote(self, kwargs):
del kwargs['quote']

else:
if ((self.default_quote is None and self.chat.type != Chat.PRIVATE)
or self.default_quote):
if self.bot.defaults:
default_quote = self.bot.defaults.quote
else:
default_quote = None
if (default_quote is None and self.chat.type != Chat.PRIVATE) or default_quote:
kwargs['reply_to_message_id'] = self.message_id

def reply_text(self, *args, **kwargs):
Expand Down
25 changes: 5 additions & 20 deletions telegram/update.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,31 +228,16 @@ def de_json(cls, data, bot):

data = super().de_json(data, bot)

message = data.get('message')
if message:
message['default_quote'] = data.get('default_quote')
data['message'] = Message.de_json(message, bot)
edited_message = data.get('edited_message')
if edited_message:
edited_message['default_quote'] = data.get('default_quote')
data['edited_message'] = Message.de_json(edited_message, bot)
data['message'] = Message.de_json(data.get('message'), bot)
data['edited_message'] = Message.de_json(data.get('edited_message'), bot)
data['inline_query'] = InlineQuery.de_json(data.get('inline_query'), bot)
data['chosen_inline_result'] = ChosenInlineResult.de_json(
data.get('chosen_inline_result'), bot)
callback_query = data.get('callback_query')
if callback_query:
callback_query['default_quote'] = data.get('default_quote')
data['callback_query'] = CallbackQuery.de_json(callback_query, bot)
data['callback_query'] = CallbackQuery.de_json(data.get('callback_query'), bot)
data['shipping_query'] = ShippingQuery.de_json(data.get('shipping_query'), bot)
data['pre_checkout_query'] = PreCheckoutQuery.de_json(data.get('pre_checkout_query'), bot)
channel_post = data.get('channel_post')
if channel_post:
channel_post['default_quote'] = data.get('default_quote')
data['channel_post'] = Message.de_json(channel_post, bot)
edited_channel_post = data.get('edited_channel_post')
if edited_channel_post:
edited_channel_post['default_quote'] = data.get('default_quote')
data['edited_channel_post'] = Message.de_json(edited_channel_post, bot)
data['channel_post'] = Message.de_json(data.get('channel_post'), bot)
data['edited_channel_post'] = Message.de_json(data.get('edited_channel_post'), bot)
data['poll'] = Poll.de_json(data.get('poll'), bot)
data['poll_answer'] = PollAnswer.de_json(data.get('poll_answer'), bot)

Expand Down
9 changes: 3 additions & 6 deletions telegram/utils/webhookhandler.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,9 +68,8 @@ def handle_error(self, request, client_address):

class WebhookAppClass(tornado.web.Application):

def __init__(self, webhook_path, bot, update_queue, default_quote=None):
self.shared_objects = {"bot": bot, "update_queue": update_queue,
"default_quote": default_quote}
def __init__(self, webhook_path, bot, update_queue):
self.shared_objects = {"bot": bot, "update_queue": update_queue}
handlers = [
(r"{}/?".format(webhook_path), WebhookHandler,
self.shared_objects)
Expand Down Expand Up @@ -118,10 +117,9 @@ def _init_asyncio_patch(self):
# fallback to the pre-3.8 default of Selector
asyncio.set_event_loop_policy(WindowsSelectorEventLoopPolicy())

def initialize(self, bot, update_queue, default_quote=None):
def initialize(self, bot, update_queue):
self.bot = bot
self.update_queue = update_queue
self._default_quote = default_quote

def set_default_headers(self):
self.set_header("Content-Type", 'application/json; charset="utf-8"')
Expand All @@ -133,7 +131,6 @@ def post(self):
data = json.loads(json_string)
self.set_status(200)
self.logger.debug('Webhook received data: ' + json_string)
data['default_quote'] = self._default_quote
update = Update.de_json(data, self.bot)
self.logger.debug('Received Update with ID %d on Webhook' % update.update_id)
self.update_queue.put(update)
Expand Down
21 changes: 0 additions & 21 deletions tests/test_bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -631,20 +631,6 @@ def test_get_chat(self, bot, super_group_id):
assert chat.title == '>>> telegram.Bot(test) @{}'.format(bot.username)
assert chat.id == int(super_group_id)

# TODO: Add bot to group to test there too
@flaky(3, 1)
@pytest.mark.timeout(10)
@pytest.mark.parametrize('default_bot', [{'quote': True}], indirect=True)
def test_get_chat_default_quote(self, default_bot, super_group_id):
message = default_bot.send_message(super_group_id, text="test_get_chat_default_quote")
assert default_bot.pin_chat_message(chat_id=super_group_id, message_id=message.message_id,
disable_notification=True)

chat = default_bot.get_chat(super_group_id)
assert chat.pinned_message.default_quote is True

assert default_bot.unpinChatMessage(super_group_id)

@flaky(3, 1)
@pytest.mark.timeout(10)
def test_get_chat_administrators(self, bot, channel_id):
Expand Down Expand Up @@ -1003,13 +989,6 @@ def test_send_message_default_parse_mode(self, default_bot, chat_id):
assert message.text == test_markdown_string
assert message.text_markdown == escape_markdown(test_markdown_string)

@flaky(3, 1)
@pytest.mark.timeout(10)
@pytest.mark.parametrize('default_bot', [{'quote': True}], indirect=True)
def test_send_message_default_quote(self, default_bot, chat_id):
message = default_bot.send_message(chat_id, 'test')
assert message.default_quote is True

@flaky(3, 1)
@pytest.mark.timeout(10)
def test_set_and_get_my_commands(self, bot):
Expand Down
4 changes: 1 addition & 3 deletions tests/test_callbackquery.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,15 +53,13 @@ def test_de_json(self, bot):
'message': self.message.to_dict(),
'data': self.data,
'inline_message_id': self.inline_message_id,
'game_short_name': self.game_short_name,
'default_quote': True}
'game_short_name': self.game_short_name}
callback_query = CallbackQuery.de_json(json_dict, bot)

assert callback_query.id == self.id_
assert callback_query.from_user == self.from_user
assert callback_query.chat_instance == self.chat_instance
assert callback_query.message == self.message
assert callback_query.message.default_quote is True
assert callback_query.data == self.data
assert callback_query.inline_message_id == self.inline_message_id
assert callback_query.game_short_name == self.game_short_name
Expand Down
18 changes: 1 addition & 17 deletions tests/test_chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
import pytest

from telegram import Chat, ChatAction, ChatPermissions
from telegram import User, Message
from telegram import User


@pytest.fixture(scope='class')
Expand Down Expand Up @@ -72,22 +72,6 @@ def test_de_json(self, bot):
assert chat.permissions == self.permissions
assert chat.slow_mode_delay == self.slow_mode_delay

def test_de_json_default_quote(self, bot):
json_dict = {
'id': self.id_,
'type': self.type_,
'pinned_message': Message(
message_id=123,
from_user=None,
date=None,
chat=None
).to_dict(),
'default_quote': True
}
chat = Chat.de_json(json_dict, bot)

assert chat.pinned_message.default_quote is True

def test_to_dict(self, chat):
chat_dict = chat.to_dict()

Expand Down
7 changes: 0 additions & 7 deletions tests/test_inputmedia.py
Original file line number Diff line number Diff line change
Expand Up @@ -334,13 +334,6 @@ def func():
assert all([isinstance(mes, Message) for mes in messages])
assert all([mes.media_group_id == messages[0].media_group_id for mes in messages])

@flaky(3, 1)
@pytest.mark.timeout(10)
@pytest.mark.parametrize('default_bot', [{'quote': True}], indirect=True)
def test_send_media_group_default_quote(self, default_bot, chat_id, media_group):
messages = default_bot.send_media_group(chat_id, media_group)
assert all([mes.default_quote is True for mes in messages])

@flaky(3, 1)
@pytest.mark.timeout(10)
def test_edit_message_media(self, bot, chat_id, media_group):
Expand Down
8 changes: 5 additions & 3 deletions tests/test_message.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
from telegram import (Update, Message, User, MessageEntity, Chat, Audio, Document, Animation,
Game, PhotoSize, Sticker, Video, Voice, VideoNote, Contact, Location, Venue,
Invoice, SuccessfulPayment, PassportData, ParseMode, Poll, PollOption, Dice)
from telegram.ext import Defaults
from tests.test_passport import RAW_PASSPORT_DATA


Expand Down Expand Up @@ -805,18 +806,19 @@ def test(*args, **kwargs):
assert message.delete()

def test_default_quote(self, message):
message.bot.defaults = Defaults()
kwargs = {}

message.default_quote = False
message.bot.defaults._quote = False
message._quote(kwargs)
assert 'reply_to_message_id' not in kwargs

message.default_quote = True
message.bot.defaults._quote = True
message._quote(kwargs)
assert 'reply_to_message_id' in kwargs

kwargs = {}
message.default_quote = None
message.bot.defaults._quote = None
message.chat.type = Chat.PRIVATE
message._quote(kwargs)
assert 'reply_to_message_id' not in kwargs
Expand Down
Loading