2015-09-11 01:06:27 +02:00
|
|
|
#!/usr/bin/env python
|
|
|
|
#
|
|
|
|
# A library that provides a Python interface to the Telegram Bot API
|
2024-02-19 20:06:25 +01:00
|
|
|
# Copyright (C) 2015-2024
|
2016-01-05 14:12:03 +01:00
|
|
|
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
2015-09-11 01:06:27 +02:00
|
|
|
#
|
|
|
|
# This program is free software: you can redistribute it and/or modify
|
2017-08-11 23:58:41 +02:00
|
|
|
# it under the terms of the GNU Lesser Public License as published by
|
2015-09-11 01:06:27 +02:00
|
|
|
# the Free Software Foundation, either version 3 of the License, or
|
|
|
|
# (at your option) any later version.
|
|
|
|
#
|
|
|
|
# This program is distributed in the hope that it will be useful,
|
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
2017-08-11 23:58:41 +02:00
|
|
|
# GNU Lesser Public License for more details.
|
2015-09-11 01:06:27 +02:00
|
|
|
#
|
2017-08-11 23:58:41 +02:00
|
|
|
# You should have received a copy of the GNU Lesser Public License
|
2015-09-11 01:06:27 +02:00
|
|
|
# along with this program. If not, see [http://www.gnu.org/licenses/].
|
2022-04-24 12:38:09 +02:00
|
|
|
import asyncio
|
2022-10-31 09:46:56 +01:00
|
|
|
import copy
|
2022-05-05 09:27:54 +02:00
|
|
|
import datetime as dtm
|
2021-02-19 19:07:48 +01:00
|
|
|
import inspect
|
2021-10-03 20:06:07 +02:00
|
|
|
import logging
|
2022-03-12 12:27:18 +01:00
|
|
|
import pickle
|
2022-12-27 19:02:50 +01:00
|
|
|
import re
|
2022-05-05 09:27:54 +02:00
|
|
|
import socket
|
2016-10-09 12:39:05 +02:00
|
|
|
import time
|
2021-06-06 11:48:48 +02:00
|
|
|
from collections import defaultdict
|
2023-11-27 18:24:21 +01:00
|
|
|
from http import HTTPStatus
|
2024-02-07 22:35:09 +01:00
|
|
|
from io import BytesIO
|
|
|
|
from typing import Tuple
|
2016-04-27 00:28:21 +02:00
|
|
|
|
2023-11-26 16:44:18 +01:00
|
|
|
import httpx
|
2017-08-11 23:58:41 +02:00
|
|
|
import pytest
|
2015-12-31 20:33:37 +01:00
|
|
|
|
2020-10-09 17:22:07 +02:00
|
|
|
from telegram import (
|
|
|
|
Bot,
|
|
|
|
BotCommand,
|
2022-05-05 09:27:54 +02:00
|
|
|
BotCommandScopeChat,
|
2023-03-25 11:47:26 +01:00
|
|
|
BotDescription,
|
2023-05-07 13:44:34 +02:00
|
|
|
BotName,
|
2023-03-25 11:47:26 +01:00
|
|
|
BotShortDescription,
|
2021-06-06 11:48:48 +02:00
|
|
|
CallbackQuery,
|
|
|
|
Chat,
|
2022-05-05 09:27:54 +02:00
|
|
|
ChatAdministratorRights,
|
|
|
|
ChatPermissions,
|
|
|
|
Dice,
|
|
|
|
InlineKeyboardButton,
|
|
|
|
InlineKeyboardMarkup,
|
|
|
|
InlineQueryResultArticle,
|
|
|
|
InlineQueryResultDocument,
|
2023-05-07 13:44:34 +02:00
|
|
|
InlineQueryResultsButton,
|
2022-05-05 09:27:54 +02:00
|
|
|
InlineQueryResultVoice,
|
2022-09-19 22:31:23 +02:00
|
|
|
InputFile,
|
2024-02-07 22:35:09 +01:00
|
|
|
InputMediaDocument,
|
2024-02-08 17:12:00 +01:00
|
|
|
InputMediaPhoto,
|
2022-10-31 09:46:56 +01:00
|
|
|
InputMessageContent,
|
2022-05-05 09:27:54 +02:00
|
|
|
InputTextMessageContent,
|
|
|
|
LabeledPrice,
|
2024-02-08 17:12:00 +01:00
|
|
|
LinkPreviewOptions,
|
2022-05-03 18:21:50 +02:00
|
|
|
MenuButton,
|
|
|
|
MenuButtonCommands,
|
|
|
|
MenuButtonDefault,
|
2022-05-05 09:27:54 +02:00
|
|
|
MenuButtonWebApp,
|
|
|
|
Message,
|
|
|
|
MessageEntity,
|
|
|
|
Poll,
|
|
|
|
PollOption,
|
2024-02-08 17:12:00 +01:00
|
|
|
ReactionTypeCustomEmoji,
|
|
|
|
ReactionTypeEmoji,
|
|
|
|
ReplyParameters,
|
2022-05-05 09:27:54 +02:00
|
|
|
SentWebAppMessage,
|
|
|
|
ShippingOption,
|
|
|
|
Update,
|
|
|
|
User,
|
|
|
|
WebAppInfo,
|
2020-10-09 17:22:07 +02:00
|
|
|
)
|
2022-10-31 10:12:18 +01:00
|
|
|
from telegram._utils.datetime import UTC, from_timestamp, to_timestamp
|
2022-12-12 10:51:33 +01:00
|
|
|
from telegram._utils.defaultvalue import DEFAULT_NONE
|
2024-02-07 22:35:09 +01:00
|
|
|
from telegram._utils.strings import to_camel_case
|
2022-11-14 20:08:16 +01:00
|
|
|
from telegram.constants import (
|
|
|
|
ChatAction,
|
|
|
|
InlineQueryLimit,
|
|
|
|
InlineQueryResultType,
|
|
|
|
MenuButtonType,
|
|
|
|
ParseMode,
|
2024-02-08 17:12:00 +01:00
|
|
|
ReactionEmoji,
|
2022-11-14 20:08:16 +01:00
|
|
|
)
|
2024-02-07 22:35:09 +01:00
|
|
|
from telegram.error import BadRequest, EndPointNotFound, InvalidToken, NetworkError
|
2022-05-05 09:27:54 +02:00
|
|
|
from telegram.ext import ExtBot, InvalidCallbackData
|
2021-10-13 08:12:48 +02:00
|
|
|
from telegram.helpers import escape_markdown
|
2022-05-05 09:27:54 +02:00
|
|
|
from telegram.request import BaseRequest, HTTPXRequest, RequestData
|
2023-11-27 18:24:21 +01:00
|
|
|
from telegram.warnings import PTBDeprecationWarning, PTBUserWarning
|
2022-12-12 10:51:33 +01:00
|
|
|
from tests.auxil.bot_method_checks import check_defaults_handling
|
2023-02-22 20:19:46 +01:00
|
|
|
from tests.auxil.ci_bots import FALLBACKS
|
|
|
|
from tests.auxil.envvars import GITHUB_ACTION, TEST_WITH_OPT_DEPS
|
|
|
|
from tests.auxil.files import data_file
|
|
|
|
from tests.auxil.networking import expect_bad_request
|
|
|
|
from tests.auxil.pytest_classes import PytestBot, PytestExtBot, make_bot
|
|
|
|
from tests.auxil.slots import mro_slots
|
2021-01-17 09:23:36 +01:00
|
|
|
|
2024-02-08 17:12:00 +01:00
|
|
|
from ._files.test_photo import photo_file
|
|
|
|
from .auxil.build_messages import make_message
|
|
|
|
|
2015-09-11 01:06:27 +02:00
|
|
|
|
2023-03-25 19:18:04 +01:00
|
|
|
@pytest.fixture()
|
2023-02-11 10:45:17 +01:00
|
|
|
async def message(bot, chat_id): # mostly used in tests for edit_message
|
2022-12-15 15:00:36 +01:00
|
|
|
out = await bot.send_message(
|
2023-02-11 10:45:17 +01:00
|
|
|
chat_id, "Text", disable_web_page_preview=True, disable_notification=True
|
2020-10-09 17:22:07 +02:00
|
|
|
)
|
2022-12-15 15:00:36 +01:00
|
|
|
out._unfreeze()
|
|
|
|
return out
|
2017-07-01 17:08:45 +02:00
|
|
|
|
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
@pytest.fixture(scope="module")
|
2022-04-24 12:38:09 +02:00
|
|
|
async def media_message(bot, chat_id):
|
2022-05-05 17:40:22 +02:00
|
|
|
with data_file("telegram.ogg").open("rb") as f:
|
|
|
|
return await bot.send_voice(chat_id, voice=f, caption="my caption", read_timeout=10)
|
2015-09-11 01:06:27 +02:00
|
|
|
|
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
@pytest.fixture(scope="module")
|
2019-09-06 21:41:43 +02:00
|
|
|
def chat_permissions():
|
|
|
|
return ChatPermissions(can_send_messages=False, can_change_info=False, can_invite_users=False)
|
|
|
|
|
|
|
|
|
2020-09-27 14:11:49 +02:00
|
|
|
def inline_results_callback(page=None):
|
|
|
|
if not page:
|
|
|
|
return [InlineQueryResultArticle(i, str(i), None) for i in range(1, 254)]
|
2021-05-27 09:38:17 +02:00
|
|
|
if page <= 5:
|
2020-10-09 17:22:07 +02:00
|
|
|
return [
|
|
|
|
InlineQueryResultArticle(i, str(i), None)
|
|
|
|
for i in range(page * 5 + 1, (page + 1) * 5 + 1)
|
|
|
|
]
|
2020-09-27 14:11:49 +02:00
|
|
|
return None
|
|
|
|
|
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
@pytest.fixture(scope="module")
|
2020-09-27 14:11:49 +02:00
|
|
|
def inline_results():
|
|
|
|
return inline_results_callback()
|
|
|
|
|
|
|
|
|
2021-05-19 13:33:41 +02:00
|
|
|
BASE_GAME_SCORE = 60 # Base game score for game tests
|
|
|
|
|
|
|
|
xfail = pytest.mark.xfail(
|
|
|
|
bool(GITHUB_ACTION), # This condition is only relevant for github actions game tests.
|
2023-09-22 18:19:21 +02:00
|
|
|
reason=(
|
|
|
|
"Can fail due to race conditions when multiple test suites "
|
|
|
|
"with the same bot token are run at the same time"
|
|
|
|
),
|
2021-05-19 13:33:41 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
|
2024-02-07 22:35:09 +01:00
|
|
|
def bot_methods(ext_bot=True, include_camel_case=False, include_do_api_request=False):
|
2022-07-10 15:37:12 +02:00
|
|
|
arg_values = []
|
|
|
|
ids = []
|
|
|
|
non_api_methods = [
|
|
|
|
"de_json",
|
|
|
|
"de_list",
|
|
|
|
"to_dict",
|
|
|
|
"to_json",
|
|
|
|
"parse_data",
|
|
|
|
"get_bot",
|
|
|
|
"set_bot",
|
|
|
|
"initialize",
|
|
|
|
"shutdown",
|
|
|
|
"insert_callback_data",
|
|
|
|
]
|
2024-02-07 22:35:09 +01:00
|
|
|
if not include_do_api_request:
|
|
|
|
non_api_methods.append("do_api_request")
|
|
|
|
|
2022-07-10 15:37:12 +02:00
|
|
|
classes = (Bot, ExtBot) if ext_bot else (Bot,)
|
|
|
|
for cls in classes:
|
|
|
|
for name, attribute in inspect.getmembers(cls, predicate=inspect.isfunction):
|
|
|
|
if name.startswith("_") or name in non_api_methods:
|
|
|
|
continue
|
2023-02-11 10:45:17 +01:00
|
|
|
if not include_camel_case and any(x.isupper() for x in name):
|
|
|
|
continue
|
2022-07-10 15:37:12 +02:00
|
|
|
arg_values.append((cls, name, attribute))
|
|
|
|
ids.append(f"{cls.__name__}.{name}")
|
|
|
|
|
|
|
|
return pytest.mark.parametrize(
|
|
|
|
argnames="bot_class, bot_method_name,bot_method", argvalues=arg_values, ids=ids
|
|
|
|
)
|
|
|
|
|
|
|
|
|
2024-02-08 17:12:00 +01:00
|
|
|
class InputMessageContentLPO(InputMessageContent):
|
2022-10-31 09:46:56 +01:00
|
|
|
"""
|
|
|
|
This is here to cover the case of InputMediaContent classes in testing answer_ilq that have
|
2024-02-08 17:12:00 +01:00
|
|
|
`link_preview_options` but not `parse_mode`. Unlikely to ever happen, but better be save
|
2022-10-31 09:46:56 +01:00
|
|
|
than sorry …
|
|
|
|
"""
|
|
|
|
|
2024-02-08 17:12:00 +01:00
|
|
|
__slots__ = ("entities", "link_preview_options", "message_text", "parse_mode")
|
2022-10-31 09:46:56 +01:00
|
|
|
|
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
message_text: str,
|
2024-02-08 17:12:00 +01:00
|
|
|
link_preview_options=DEFAULT_NONE,
|
2022-10-31 09:46:56 +01:00
|
|
|
*,
|
|
|
|
api_kwargs=None,
|
|
|
|
):
|
|
|
|
super().__init__(api_kwargs=api_kwargs)
|
2023-01-01 13:04:37 +01:00
|
|
|
self._unfreeze()
|
2022-10-31 09:46:56 +01:00
|
|
|
self.message_text = message_text
|
2024-02-08 17:12:00 +01:00
|
|
|
self.link_preview_options = link_preview_options
|
2022-10-31 09:46:56 +01:00
|
|
|
|
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
class TestBotWithoutRequest:
|
2021-06-06 11:48:48 +02:00
|
|
|
"""
|
|
|
|
Most are executed on tg.ext.ExtBot, as that class only extends the functionality of tg.bot
|
2022-10-31 10:12:18 +01:00
|
|
|
|
|
|
|
Behavior for init of ExtBot with missing optional dependency cachetools (for CallbackDataCache)
|
|
|
|
is tested in `test_callbackdatacache`
|
2021-06-06 11:48:48 +02:00
|
|
|
"""
|
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
test_flag = None
|
|
|
|
|
2023-03-25 19:18:04 +01:00
|
|
|
@pytest.fixture(autouse=True)
|
|
|
|
def _reset(self):
|
2022-04-24 12:38:09 +02:00
|
|
|
self.test_flag = None
|
|
|
|
|
2022-05-05 17:40:22 +02:00
|
|
|
@pytest.mark.parametrize("bot_class", [Bot, ExtBot])
|
2023-02-22 20:19:46 +01:00
|
|
|
def test_slot_behaviour(self, bot_class, bot):
|
2022-04-24 12:38:09 +02:00
|
|
|
inst = bot_class(bot.token)
|
2021-05-29 16:18:16 +02:00
|
|
|
for attr in inst.__slots__:
|
2022-05-05 17:40:22 +02:00
|
|
|
assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'"
|
2021-05-29 16:18:16 +02:00
|
|
|
assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot"
|
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
async def test_no_token_passed(self):
|
|
|
|
with pytest.raises(InvalidToken, match="You must pass the token"):
|
|
|
|
Bot("")
|
|
|
|
|
2023-09-15 21:35:45 +02:00
|
|
|
async def test_repr(self):
|
|
|
|
bot = Bot(token="some_token", base_file_url="")
|
|
|
|
assert repr(bot) == "Bot[token=some_token]"
|
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
async def test_to_dict(self, bot):
|
|
|
|
to_dict_bot = bot.to_dict()
|
|
|
|
|
|
|
|
assert isinstance(to_dict_bot, dict)
|
|
|
|
assert to_dict_bot["id"] == bot.id
|
|
|
|
assert to_dict_bot["username"] == bot.username
|
|
|
|
assert to_dict_bot["first_name"] == bot.first_name
|
|
|
|
if bot.last_name:
|
|
|
|
assert to_dict_bot["last_name"] == bot.last_name
|
|
|
|
|
2023-02-22 20:19:46 +01:00
|
|
|
async def test_initialize_and_shutdown(self, bot: PytestExtBot, monkeypatch):
|
2022-04-24 12:38:09 +02:00
|
|
|
async def initialize(*args, **kwargs):
|
2022-05-05 17:40:22 +02:00
|
|
|
self.test_flag = ["initialize"]
|
2022-04-24 12:38:09 +02:00
|
|
|
|
|
|
|
async def stop(*args, **kwargs):
|
2022-05-05 17:40:22 +02:00
|
|
|
self.test_flag.append("stop")
|
2022-04-24 12:38:09 +02:00
|
|
|
|
2023-02-22 20:19:46 +01:00
|
|
|
temp_bot = PytestBot(token=bot.token)
|
2022-04-24 12:38:09 +02:00
|
|
|
orig_stop = temp_bot.request.shutdown
|
|
|
|
|
|
|
|
try:
|
2022-05-05 17:40:22 +02:00
|
|
|
monkeypatch.setattr(temp_bot.request, "initialize", initialize)
|
|
|
|
monkeypatch.setattr(temp_bot.request, "shutdown", stop)
|
2022-04-24 12:38:09 +02:00
|
|
|
await temp_bot.initialize()
|
2022-05-05 17:40:22 +02:00
|
|
|
assert self.test_flag == ["initialize"]
|
2022-04-24 12:38:09 +02:00
|
|
|
assert temp_bot.bot == bot.bot
|
|
|
|
|
|
|
|
await temp_bot.shutdown()
|
2022-05-05 17:40:22 +02:00
|
|
|
assert self.test_flag == ["initialize", "stop"]
|
2022-04-24 12:38:09 +02:00
|
|
|
finally:
|
|
|
|
await orig_stop()
|
|
|
|
|
|
|
|
async def test_multiple_inits_and_shutdowns(self, bot, monkeypatch):
|
|
|
|
self.received = defaultdict(int)
|
|
|
|
|
|
|
|
async def initialize(*args, **kwargs):
|
2022-05-05 17:40:22 +02:00
|
|
|
self.received["init"] += 1
|
2022-04-24 12:38:09 +02:00
|
|
|
|
|
|
|
async def shutdown(*args, **kwargs):
|
2022-05-05 17:40:22 +02:00
|
|
|
self.received["shutdown"] += 1
|
2022-04-24 12:38:09 +02:00
|
|
|
|
2022-05-05 17:40:22 +02:00
|
|
|
monkeypatch.setattr(HTTPXRequest, "initialize", initialize)
|
|
|
|
monkeypatch.setattr(HTTPXRequest, "shutdown", shutdown)
|
2022-04-24 12:38:09 +02:00
|
|
|
|
2023-02-22 20:19:46 +01:00
|
|
|
test_bot = PytestBot(bot.token)
|
2022-04-24 12:38:09 +02:00
|
|
|
await test_bot.initialize()
|
|
|
|
await test_bot.initialize()
|
|
|
|
await test_bot.initialize()
|
|
|
|
await test_bot.shutdown()
|
|
|
|
await test_bot.shutdown()
|
|
|
|
await test_bot.shutdown()
|
|
|
|
|
|
|
|
# 2 instead of 1 since we have to request objects for each bot
|
2022-05-05 17:40:22 +02:00
|
|
|
assert self.received["init"] == 2
|
|
|
|
assert self.received["shutdown"] == 2
|
2022-04-24 12:38:09 +02:00
|
|
|
|
|
|
|
async def test_context_manager(self, monkeypatch, bot):
|
|
|
|
async def initialize():
|
2022-05-05 17:40:22 +02:00
|
|
|
self.test_flag = ["initialize"]
|
2022-04-24 12:38:09 +02:00
|
|
|
|
|
|
|
async def shutdown(*args):
|
2022-05-05 17:40:22 +02:00
|
|
|
self.test_flag.append("stop")
|
2022-04-24 12:38:09 +02:00
|
|
|
|
2022-05-05 17:40:22 +02:00
|
|
|
monkeypatch.setattr(bot, "initialize", initialize)
|
|
|
|
monkeypatch.setattr(bot, "shutdown", shutdown)
|
2022-04-24 12:38:09 +02:00
|
|
|
|
|
|
|
async with bot:
|
|
|
|
pass
|
|
|
|
|
2022-05-05 17:40:22 +02:00
|
|
|
assert self.test_flag == ["initialize", "stop"]
|
2022-04-24 12:38:09 +02:00
|
|
|
|
|
|
|
async def test_context_manager_exception_on_init(self, monkeypatch, bot):
|
|
|
|
async def initialize():
|
2022-05-05 17:40:22 +02:00
|
|
|
raise RuntimeError("initialize")
|
2022-04-24 12:38:09 +02:00
|
|
|
|
|
|
|
async def shutdown():
|
2022-05-05 17:40:22 +02:00
|
|
|
self.test_flag = "stop"
|
2022-04-24 12:38:09 +02:00
|
|
|
|
2022-05-05 17:40:22 +02:00
|
|
|
monkeypatch.setattr(bot, "initialize", initialize)
|
|
|
|
monkeypatch.setattr(bot, "shutdown", shutdown)
|
2022-04-24 12:38:09 +02:00
|
|
|
|
2022-05-05 17:40:22 +02:00
|
|
|
with pytest.raises(RuntimeError, match="initialize"):
|
2022-04-24 12:38:09 +02:00
|
|
|
async with bot:
|
|
|
|
pass
|
|
|
|
|
2022-05-05 17:40:22 +02:00
|
|
|
assert self.test_flag == "stop"
|
2022-04-24 12:38:09 +02:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
async def test_equality(self):
|
|
|
|
async with make_bot(token=FALLBACKS[0]["token"]) as a, make_bot(
|
|
|
|
token=FALLBACKS[0]["token"]
|
2023-12-10 20:17:11 +01:00
|
|
|
) as b, Bot(token=FALLBACKS[0]["token"]) as c, make_bot(token=FALLBACKS[1]["token"]) as d:
|
2023-02-11 10:45:17 +01:00
|
|
|
e = Update(123456789)
|
2023-12-10 20:17:11 +01:00
|
|
|
f = Bot(token=FALLBACKS[0]["token"])
|
2015-09-11 01:06:27 +02:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
assert a == b
|
|
|
|
assert hash(a) == hash(b)
|
|
|
|
assert a is not b
|
2020-06-30 22:07:38 +02:00
|
|
|
|
2023-12-10 20:17:11 +01:00
|
|
|
assert a == c
|
|
|
|
assert hash(a) == hash(c)
|
2020-06-30 22:07:38 +02:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
assert a != d
|
|
|
|
assert hash(a) != hash(d)
|
2016-03-11 07:37:43 +01:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
assert a != e
|
|
|
|
assert hash(a) != hash(e)
|
2021-01-17 09:23:36 +01:00
|
|
|
|
2023-12-10 20:17:11 +01:00
|
|
|
# We cant check equality for unintialized Bot object
|
|
|
|
assert hash(a) != hash(f)
|
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
@pytest.mark.parametrize(
|
2022-05-05 17:40:22 +02:00
|
|
|
"attribute",
|
2022-04-24 12:38:09 +02:00
|
|
|
[
|
2022-05-05 17:40:22 +02:00
|
|
|
"id",
|
|
|
|
"username",
|
|
|
|
"first_name",
|
|
|
|
"last_name",
|
|
|
|
"name",
|
|
|
|
"can_join_groups",
|
|
|
|
"can_read_all_group_messages",
|
|
|
|
"supports_inline_queries",
|
|
|
|
"link",
|
2022-04-24 12:38:09 +02:00
|
|
|
],
|
|
|
|
)
|
|
|
|
async def test_get_me_and_properties_not_initialized(self, bot: Bot, attribute):
|
|
|
|
bot = Bot(token=bot.token)
|
|
|
|
try:
|
2022-05-05 17:40:22 +02:00
|
|
|
with pytest.raises(RuntimeError, match="not properly initialized"):
|
2022-04-24 12:38:09 +02:00
|
|
|
bot[attribute]
|
|
|
|
finally:
|
|
|
|
await bot.shutdown()
|
2021-01-17 09:23:36 +01:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
async def test_get_me_and_properties(self, bot):
|
|
|
|
get_me_bot = await ExtBot(bot.token).get_me()
|
2022-12-15 15:00:36 +01:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
assert isinstance(get_me_bot, User)
|
|
|
|
assert get_me_bot.id == bot.id
|
|
|
|
assert get_me_bot.username == bot.username
|
|
|
|
assert get_me_bot.first_name == bot.first_name
|
|
|
|
assert get_me_bot.last_name == bot.last_name
|
|
|
|
assert get_me_bot.name == bot.name
|
|
|
|
assert get_me_bot.can_join_groups == bot.can_join_groups
|
|
|
|
assert get_me_bot.can_read_all_group_messages == bot.can_read_all_group_messages
|
|
|
|
assert get_me_bot.supports_inline_queries == bot.supports_inline_queries
|
|
|
|
assert f"https://t.me/{get_me_bot.username}" == bot.link
|
2019-10-12 22:40:42 +02:00
|
|
|
|
2022-03-12 12:27:18 +01:00
|
|
|
def test_bot_pickling_error(self, bot):
|
|
|
|
with pytest.raises(pickle.PicklingError, match="Bot objects cannot be pickled"):
|
|
|
|
pickle.dumps(bot)
|
|
|
|
|
2022-12-30 10:50:49 +01:00
|
|
|
def test_bot_deepcopy_error(self, bot):
|
|
|
|
with pytest.raises(TypeError, match="Bot objects cannot be deepcopied"):
|
|
|
|
copy.deepcopy(bot)
|
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
@bot_methods(ext_bot=False)
|
|
|
|
def test_api_methods_have_log_decorator(self, bot_class, bot_method_name, bot_method):
|
|
|
|
"""Check that all bot methods have the log decorator ..."""
|
|
|
|
# not islower() skips the camelcase aliases
|
|
|
|
if not bot_method_name.islower():
|
|
|
|
return
|
|
|
|
source = inspect.getsource(bot_method)
|
|
|
|
assert (
|
|
|
|
# Use re.match to only match at *the beginning* of the string
|
|
|
|
re.match(rf"\s*\@\_log\s*async def {bot_method_name}", source)
|
|
|
|
), f"{bot_method_name} is missing the @_log decorator"
|
|
|
|
|
2023-04-10 17:01:35 +02:00
|
|
|
@pytest.mark.parametrize(
|
|
|
|
("cls", "logger_name"), [(Bot, "telegram.Bot"), (ExtBot, "telegram.ext.ExtBot")]
|
|
|
|
)
|
|
|
|
async def test_log_decorator(self, bot: PytestExtBot, cls, logger_name, caplog):
|
2023-02-11 10:45:17 +01:00
|
|
|
# Second argument makes sure that we ignore logs from e.g. httpx
|
|
|
|
with caplog.at_level(logging.DEBUG, logger="telegram"):
|
2023-04-10 17:01:35 +02:00
|
|
|
await cls(bot.token).get_me()
|
2023-02-11 10:45:17 +01:00
|
|
|
# Only for stabilizing this test-
|
|
|
|
if len(caplog.records) == 4:
|
|
|
|
for idx, record in enumerate(caplog.records):
|
|
|
|
print(record)
|
|
|
|
if record.getMessage().startswith("Task was destroyed but it is pending"):
|
|
|
|
caplog.records.pop(idx)
|
|
|
|
if record.getMessage().startswith("Task exception was never retrieved"):
|
|
|
|
caplog.records.pop(idx)
|
|
|
|
assert len(caplog.records) == 3
|
2023-04-10 17:01:35 +02:00
|
|
|
|
|
|
|
assert all(caplog.records[i].name == logger_name for i in [-1, 0])
|
2023-02-11 10:45:17 +01:00
|
|
|
assert caplog.records[0].getMessage().startswith("Entering: get_me")
|
|
|
|
assert caplog.records[-1].getMessage().startswith("Exiting: get_me")
|
|
|
|
|
|
|
|
@bot_methods()
|
|
|
|
def test_camel_case_aliases(self, bot_class, bot_method_name, bot_method):
|
|
|
|
camel_case_name = to_camel_case(bot_method_name)
|
|
|
|
camel_case_function = getattr(bot_class, camel_case_name, False)
|
|
|
|
assert camel_case_function is not False, f"{camel_case_name} not found"
|
|
|
|
assert camel_case_function is bot_method, f"{camel_case_name} is not {bot_method}"
|
|
|
|
|
2024-02-07 22:35:09 +01:00
|
|
|
@bot_methods(include_do_api_request=True)
|
2023-02-11 10:45:17 +01:00
|
|
|
def test_coroutine_functions(self, bot_class, bot_method_name, bot_method):
|
|
|
|
"""Check that all bot methods are defined as async def ..."""
|
|
|
|
meth = getattr(bot_method, "__wrapped__", bot_method) # to unwrap the @_log decorator
|
|
|
|
assert inspect.iscoroutinefunction(meth), f"{bot_method_name} must be a coroutine function"
|
|
|
|
|
2024-02-07 22:35:09 +01:00
|
|
|
@bot_methods(include_do_api_request=True)
|
2023-02-11 10:45:17 +01:00
|
|
|
def test_api_kwargs_and_timeouts_present(self, bot_class, bot_method_name, bot_method):
|
|
|
|
"""Check that all bot methods have `api_kwargs` and timeout params."""
|
|
|
|
param_names = inspect.signature(bot_method).parameters.keys()
|
|
|
|
params = ("pool_timeout", "read_timeout", "connect_timeout", "write_timeout", "api_kwargs")
|
|
|
|
|
|
|
|
for param in params:
|
|
|
|
assert param in param_names, f"{bot_method_name} is missing the parameter `{param}`"
|
|
|
|
|
|
|
|
rate_arg = "rate_limit_args"
|
|
|
|
if bot_method_name.replace("_", "").lower() != "getupdates" and bot_class is ExtBot:
|
|
|
|
assert rate_arg in param_names, f"{bot_method} is missing the parameter `{rate_arg}`"
|
|
|
|
|
2022-07-10 15:37:12 +02:00
|
|
|
@bot_methods(ext_bot=False)
|
|
|
|
async def test_defaults_handling(
|
2023-02-11 10:45:17 +01:00
|
|
|
self,
|
|
|
|
bot_class,
|
|
|
|
bot_method_name: str,
|
|
|
|
bot_method,
|
2023-02-22 20:19:46 +01:00
|
|
|
bot: PytestExtBot,
|
|
|
|
raw_bot: PytestBot,
|
2022-07-10 15:37:12 +02:00
|
|
|
):
|
2021-02-19 19:07:48 +01:00
|
|
|
"""
|
2021-10-03 15:10:13 +02:00
|
|
|
Here we check that the bot methods handle tg.ext.Defaults correctly. This has two parts:
|
|
|
|
|
|
|
|
1. Check that ExtBot actually inserts the defaults values correctly
|
|
|
|
2. Check that tg.Bot just replaces `DefaultValue(obj)` with `obj`, i.e. that it doesn't
|
|
|
|
pass any `DefaultValue` instances to Request. See the docstring of
|
|
|
|
tg.Bot._insert_defaults for details on why we need that
|
|
|
|
|
|
|
|
As for most defaults,
|
2021-02-19 19:07:48 +01:00
|
|
|
we can't really check the effect, we just check if we're passing the correct kwargs to
|
|
|
|
Request.post. As bot method tests a scattered across the different test files, we do
|
|
|
|
this here in one place.
|
|
|
|
|
|
|
|
The same test is also run for all the shortcuts (Message.reply_text) etc in the
|
|
|
|
corresponding tests.
|
|
|
|
|
|
|
|
Finally, there are some tests for Defaults.{parse_mode, quote, allow_sending_without_reply}
|
|
|
|
at the appropriate places, as those are the only things we can actually check.
|
|
|
|
"""
|
2023-03-25 19:18:04 +01:00
|
|
|
# Mocking get_me within check_defaults_handling messes with the cached values like
|
|
|
|
# Bot.{bot, username, id, …}` unless we return the expected User object.
|
|
|
|
return_value = bot.bot if bot_method_name.lower().replace("_", "") == "getme" else None
|
2022-12-12 10:51:33 +01:00
|
|
|
|
|
|
|
# Check that ExtBot does the right thing
|
|
|
|
bot_method = getattr(bot, bot_method_name)
|
|
|
|
raw_bot_method = getattr(raw_bot, bot_method_name)
|
|
|
|
assert await check_defaults_handling(bot_method, bot, return_value=return_value)
|
|
|
|
assert await check_defaults_handling(raw_bot_method, raw_bot, return_value=return_value)
|
2021-10-03 15:10:13 +02:00
|
|
|
|
2024-02-08 17:12:00 +01:00
|
|
|
@pytest.mark.parametrize(
|
|
|
|
("name", "method"), inspect.getmembers(Bot, predicate=inspect.isfunction)
|
|
|
|
)
|
|
|
|
def test_ext_bot_signature(self, name, method):
|
2021-06-06 11:48:48 +02:00
|
|
|
"""
|
|
|
|
Here we make sure that all methods of ext.ExtBot have the same signature as the
|
|
|
|
corresponding methods of tg.Bot.
|
|
|
|
"""
|
|
|
|
# Some methods of ext.ExtBot
|
2022-08-26 06:50:03 +02:00
|
|
|
global_extra_args = {"rate_limit_args"}
|
2021-10-03 15:10:13 +02:00
|
|
|
extra_args_per_method = defaultdict(
|
2022-08-26 06:50:03 +02:00
|
|
|
set, {"__init__": {"arbitrary_callback_data", "defaults", "rate_limiter"}}
|
2021-10-03 15:10:13 +02:00
|
|
|
)
|
2022-05-05 17:40:22 +02:00
|
|
|
different_hints_per_method = defaultdict(set, {"__setattr__": {"ext_bot"}})
|
2021-06-06 11:48:48 +02:00
|
|
|
|
2024-02-08 17:12:00 +01:00
|
|
|
signature = inspect.signature(method)
|
|
|
|
ext_signature = inspect.signature(getattr(ExtBot, name))
|
2021-06-06 11:48:48 +02:00
|
|
|
|
2024-02-08 17:12:00 +01:00
|
|
|
assert (
|
|
|
|
ext_signature.return_annotation == signature.return_annotation
|
|
|
|
), f"Wrong return annotation for method {name}"
|
|
|
|
assert (
|
|
|
|
set(signature.parameters)
|
|
|
|
== set(ext_signature.parameters) - global_extra_args - extra_args_per_method[name]
|
|
|
|
), f"Wrong set of parameters for method {name}"
|
|
|
|
for param_name, param in signature.parameters.items():
|
|
|
|
if param_name in different_hints_per_method[name]:
|
|
|
|
continue
|
2021-06-06 11:48:48 +02:00
|
|
|
assert (
|
2024-02-08 17:12:00 +01:00
|
|
|
param.annotation == ext_signature.parameters[param_name].annotation
|
|
|
|
), f"Wrong annotation for parameter {param_name} of method {name}"
|
2021-06-06 11:48:48 +02:00
|
|
|
assert (
|
2024-02-08 17:12:00 +01:00
|
|
|
param.default == ext_signature.parameters[param_name].default
|
|
|
|
), f"Wrong default value for parameter {param_name} of method {name}"
|
|
|
|
assert (
|
|
|
|
param.kind == ext_signature.parameters[param_name].kind
|
|
|
|
), f"Wrong parameter kind for parameter {param_name} of method {name}"
|
2021-06-06 11:48:48 +02:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
async def test_unknown_kwargs(self, bot, monkeypatch):
|
|
|
|
async def post(url, request_data: RequestData, *args, **kwargs):
|
|
|
|
data = request_data.json_parameters
|
|
|
|
if not all([data["unknown_kwarg_1"] == "7", data["unknown_kwarg_2"] == "5"]):
|
|
|
|
pytest.fail("got wrong parameters")
|
|
|
|
return True
|
2016-10-13 21:52:53 +02:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
monkeypatch.setattr(bot.request, "post", post)
|
|
|
|
await bot.send_message(
|
|
|
|
123, "text", api_kwargs={"unknown_kwarg_1": 7, "unknown_kwarg_2": 5}
|
2022-04-24 12:38:09 +02:00
|
|
|
)
|
2022-01-03 08:13:33 +01:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
async def test_answer_web_app_query(self, bot, raw_bot, monkeypatch):
|
|
|
|
params = False
|
2022-01-03 08:13:33 +01:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
# For now just test that our internals pass the correct data
|
2017-05-12 17:40:57 +02:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
|
|
|
|
nonlocal params
|
|
|
|
params = request_data.parameters == {
|
|
|
|
"web_app_query_id": "12345",
|
|
|
|
"result": {
|
|
|
|
"title": "title",
|
|
|
|
"input_message_content": {
|
|
|
|
"message_text": "text",
|
|
|
|
},
|
|
|
|
"type": InlineQueryResultType.ARTICLE,
|
|
|
|
"id": "1",
|
|
|
|
},
|
|
|
|
}
|
2023-03-25 19:18:04 +01:00
|
|
|
return SentWebAppMessage("321").to_dict()
|
2017-05-12 17:40:57 +02:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
# We test different result types more thoroughly for answer_inline_query, so we just
|
|
|
|
# use the one type here
|
|
|
|
result = InlineQueryResultArticle("1", "title", InputTextMessageContent("text"))
|
|
|
|
copied_result = copy.copy(result)
|
2017-08-11 23:58:41 +02:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
ext_bot = bot
|
|
|
|
for bot in (ext_bot, raw_bot):
|
|
|
|
# We need to test 1) below both the bot and raw_bot and setting this up with
|
|
|
|
# pytest.parametrize appears to be difficult ...
|
|
|
|
monkeypatch.setattr(bot.request, "post", make_assertion)
|
|
|
|
web_app_msg = await bot.answer_web_app_query("12345", result)
|
|
|
|
assert params, "something went wrong with passing arguments to the request"
|
|
|
|
assert isinstance(web_app_msg, SentWebAppMessage)
|
|
|
|
assert web_app_msg.inline_message_id == "321"
|
2017-05-12 17:40:57 +02:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
# 1)
|
|
|
|
# make sure that the results were not edited in-place
|
|
|
|
assert result == copied_result
|
|
|
|
assert (
|
|
|
|
result.input_message_content.parse_mode
|
|
|
|
== copied_result.input_message_content.parse_mode
|
|
|
|
)
|
2019-08-23 21:20:41 +02:00
|
|
|
|
2020-10-09 17:22:07 +02:00
|
|
|
@pytest.mark.parametrize(
|
2023-02-11 10:45:17 +01:00
|
|
|
"default_bot",
|
|
|
|
[{"parse_mode": "Markdown", "disable_web_page_preview": True}],
|
|
|
|
indirect=True,
|
|
|
|
)
|
|
|
|
@pytest.mark.parametrize(
|
2023-03-25 19:18:04 +01:00
|
|
|
("ilq_result", "expected_params"),
|
2020-10-09 17:22:07 +02:00
|
|
|
[
|
2023-02-11 10:45:17 +01:00
|
|
|
(
|
|
|
|
InlineQueryResultArticle("1", "title", InputTextMessageContent("text")),
|
|
|
|
{
|
|
|
|
"web_app_query_id": "12345",
|
|
|
|
"result": {
|
|
|
|
"title": "title",
|
|
|
|
"input_message_content": {
|
|
|
|
"message_text": "text",
|
|
|
|
"parse_mode": "Markdown",
|
2024-02-08 17:12:00 +01:00
|
|
|
"link_preview_options": {
|
|
|
|
"is_disabled": True,
|
|
|
|
},
|
2023-02-11 10:45:17 +01:00
|
|
|
},
|
|
|
|
"type": InlineQueryResultType.ARTICLE,
|
|
|
|
"id": "1",
|
|
|
|
},
|
|
|
|
},
|
|
|
|
),
|
|
|
|
(
|
|
|
|
InlineQueryResultArticle(
|
|
|
|
"1",
|
|
|
|
"title",
|
|
|
|
InputTextMessageContent(
|
|
|
|
"text", parse_mode="HTML", disable_web_page_preview=False
|
|
|
|
),
|
|
|
|
),
|
|
|
|
{
|
|
|
|
"web_app_query_id": "12345",
|
|
|
|
"result": {
|
|
|
|
"title": "title",
|
|
|
|
"input_message_content": {
|
|
|
|
"message_text": "text",
|
|
|
|
"parse_mode": "HTML",
|
2024-02-08 17:12:00 +01:00
|
|
|
"link_preview_options": {
|
|
|
|
"is_disabled": False,
|
|
|
|
},
|
2023-02-11 10:45:17 +01:00
|
|
|
},
|
|
|
|
"type": InlineQueryResultType.ARTICLE,
|
|
|
|
"id": "1",
|
|
|
|
},
|
|
|
|
},
|
|
|
|
),
|
|
|
|
(
|
|
|
|
InlineQueryResultArticle(
|
|
|
|
"1",
|
|
|
|
"title",
|
|
|
|
InputTextMessageContent(
|
|
|
|
"text", parse_mode=None, disable_web_page_preview="False"
|
|
|
|
),
|
|
|
|
),
|
|
|
|
{
|
|
|
|
"web_app_query_id": "12345",
|
|
|
|
"result": {
|
|
|
|
"title": "title",
|
|
|
|
"input_message_content": {
|
|
|
|
"message_text": "text",
|
2024-02-08 17:12:00 +01:00
|
|
|
"link_preview_options": {
|
|
|
|
"is_disabled": "False",
|
|
|
|
},
|
2023-02-11 10:45:17 +01:00
|
|
|
},
|
|
|
|
"type": InlineQueryResultType.ARTICLE,
|
|
|
|
"id": "1",
|
|
|
|
},
|
|
|
|
},
|
2020-10-09 17:22:07 +02:00
|
|
|
),
|
|
|
|
],
|
|
|
|
)
|
2023-02-11 10:45:17 +01:00
|
|
|
async def test_answer_web_app_query_defaults(
|
|
|
|
self, default_bot, ilq_result, expected_params, monkeypatch
|
|
|
|
):
|
|
|
|
bot = default_bot
|
|
|
|
params = False
|
2019-08-23 21:20:41 +02:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
# For now just test that our internals pass the correct data
|
2020-03-29 09:52:30 +02:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
|
|
|
|
nonlocal params
|
|
|
|
params = request_data.parameters == expected_params
|
2023-03-25 19:18:04 +01:00
|
|
|
return SentWebAppMessage("321").to_dict()
|
2019-08-23 21:20:41 +02:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
monkeypatch.setattr(bot.request, "post", make_assertion)
|
2020-05-02 11:56:52 +02:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
# We test different result types more thoroughly for answer_inline_query, so we just
|
|
|
|
# use the one type here
|
|
|
|
copied_result = copy.copy(ilq_result)
|
2020-05-02 11:56:52 +02:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
web_app_msg = await bot.answer_web_app_query("12345", ilq_result)
|
|
|
|
assert params, "something went wrong with passing arguments to the request"
|
|
|
|
assert isinstance(web_app_msg, SentWebAppMessage)
|
|
|
|
assert web_app_msg.inline_message_id == "321"
|
2020-05-02 11:56:52 +02:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
# make sure that the results were not edited in-place
|
|
|
|
assert ilq_result == copied_result
|
|
|
|
assert (
|
|
|
|
ilq_result.input_message_content.parse_mode
|
|
|
|
== copied_result.input_message_content.parse_mode
|
2020-10-09 17:22:07 +02:00
|
|
|
)
|
2020-09-27 12:59:48 +02:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
# TODO: Needs improvement. We need incoming inline query to test answer.
|
2023-09-03 14:23:48 +02:00
|
|
|
@pytest.mark.parametrize("button_type", ["start", "web_app"])
|
2023-05-07 13:44:34 +02:00
|
|
|
async def test_answer_inline_query(self, monkeypatch, bot, raw_bot, button_type):
|
2023-02-11 10:45:17 +01:00
|
|
|
# For now just test that our internals pass the correct data
|
|
|
|
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
|
2023-05-07 13:44:34 +02:00
|
|
|
expected = {
|
2023-02-11 10:45:17 +01:00
|
|
|
"cache_time": 300,
|
|
|
|
"results": [
|
|
|
|
{
|
|
|
|
"title": "first",
|
|
|
|
"id": "11",
|
|
|
|
"type": "article",
|
|
|
|
"input_message_content": {"message_text": "first"},
|
|
|
|
},
|
|
|
|
{
|
|
|
|
"title": "second",
|
|
|
|
"id": "12",
|
|
|
|
"type": "article",
|
|
|
|
"input_message_content": {"message_text": "second"},
|
|
|
|
},
|
|
|
|
{
|
|
|
|
"title": "test_result",
|
|
|
|
"id": "123",
|
|
|
|
"type": "document",
|
2023-09-22 18:19:21 +02:00
|
|
|
"document_url": (
|
|
|
|
"https://raw.githubusercontent.com/python-telegram-bot"
|
|
|
|
"/logos/master/logo/png/ptb-logo_240.png"
|
|
|
|
),
|
2023-02-11 10:45:17 +01:00
|
|
|
"mime_type": "image/png",
|
|
|
|
"caption": "ptb_logo",
|
|
|
|
"input_message_content": {"message_text": "imc"},
|
|
|
|
},
|
|
|
|
],
|
|
|
|
"next_offset": "42",
|
|
|
|
"inline_query_id": 1234,
|
|
|
|
"is_personal": True,
|
|
|
|
}
|
|
|
|
|
2023-09-03 14:23:48 +02:00
|
|
|
if button_type == "start":
|
2023-05-07 13:44:34 +02:00
|
|
|
button_dict = {"text": "button_text", "start_parameter": "start_parameter"}
|
|
|
|
else:
|
|
|
|
button_dict = {
|
|
|
|
"text": "button_text",
|
|
|
|
"web_app": {"url": "https://python-telegram-bot.org"},
|
|
|
|
}
|
|
|
|
|
|
|
|
expected["button"] = button_dict
|
|
|
|
|
|
|
|
return request_data.parameters == expected
|
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
results = [
|
|
|
|
InlineQueryResultArticle("11", "first", InputTextMessageContent("first")),
|
2024-02-08 17:12:00 +01:00
|
|
|
InlineQueryResultArticle("12", "second", InputMessageContentLPO("second")),
|
2023-02-11 10:45:17 +01:00
|
|
|
InlineQueryResultDocument(
|
|
|
|
id="123",
|
2023-09-22 18:19:21 +02:00
|
|
|
document_url=(
|
|
|
|
"https://raw.githubusercontent.com/python-telegram-bot/logos/master/"
|
|
|
|
"logo/png/ptb-logo_240.png"
|
|
|
|
),
|
2023-02-11 10:45:17 +01:00
|
|
|
title="test_result",
|
|
|
|
mime_type="image/png",
|
|
|
|
caption="ptb_logo",
|
2024-02-08 17:12:00 +01:00
|
|
|
input_message_content=InputMessageContentLPO("imc"),
|
2023-02-11 10:45:17 +01:00
|
|
|
),
|
|
|
|
]
|
|
|
|
|
2023-05-07 13:44:34 +02:00
|
|
|
if button_type == "start":
|
|
|
|
button = InlineQueryResultsButton(
|
|
|
|
text="button_text", start_parameter="start_parameter"
|
|
|
|
)
|
|
|
|
elif button_type == "web_app":
|
|
|
|
button = InlineQueryResultsButton(
|
|
|
|
text="button_text", web_app=WebAppInfo("https://python-telegram-bot.org")
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
button = None
|
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
copied_results = copy.copy(results)
|
|
|
|
ext_bot = bot
|
|
|
|
for bot in (ext_bot, raw_bot):
|
|
|
|
# We need to test 1) below both the bot and raw_bot and setting this up with
|
|
|
|
# pytest.parametrize appears to be difficult ...
|
|
|
|
monkeypatch.setattr(bot.request, "post", make_assertion)
|
|
|
|
assert await bot.answer_inline_query(
|
|
|
|
1234,
|
|
|
|
results=results,
|
|
|
|
cache_time=300,
|
|
|
|
is_personal=True,
|
|
|
|
next_offset="42",
|
2023-05-07 13:44:34 +02:00
|
|
|
button=button,
|
2023-02-11 10:45:17 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
# 1)
|
|
|
|
# make sure that the results were not edited in-place
|
|
|
|
assert results == copied_results
|
|
|
|
for idx, result in enumerate(results):
|
|
|
|
if hasattr(result, "parse_mode"):
|
|
|
|
assert result.parse_mode == copied_results[idx].parse_mode
|
|
|
|
if hasattr(result, "input_message_content"):
|
|
|
|
assert getattr(result.input_message_content, "parse_mode", None) == getattr(
|
|
|
|
copied_results[idx].input_message_content, "parse_mode", None
|
|
|
|
)
|
|
|
|
assert getattr(
|
|
|
|
result.input_message_content, "disable_web_page_preview", None
|
|
|
|
) == getattr(
|
|
|
|
copied_results[idx].input_message_content, "disable_web_page_preview", None
|
|
|
|
)
|
|
|
|
|
|
|
|
monkeypatch.delattr(bot.request, "post")
|
|
|
|
|
|
|
|
async def test_answer_inline_query_no_default_parse_mode(self, monkeypatch, bot):
|
|
|
|
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
|
|
|
|
return request_data.parameters == {
|
|
|
|
"cache_time": 300,
|
|
|
|
"results": [
|
|
|
|
{
|
|
|
|
"title": "first",
|
|
|
|
"id": "11",
|
|
|
|
"type": "article",
|
|
|
|
"input_message_content": {"message_text": "first"},
|
|
|
|
},
|
|
|
|
{
|
|
|
|
"title": "second",
|
|
|
|
"id": "12",
|
|
|
|
"type": "article",
|
|
|
|
"input_message_content": {"message_text": "second"},
|
|
|
|
},
|
|
|
|
{
|
|
|
|
"title": "test_result",
|
|
|
|
"id": "123",
|
|
|
|
"type": "document",
|
2023-09-22 18:19:21 +02:00
|
|
|
"document_url": (
|
|
|
|
"https://raw.githubusercontent.com/"
|
|
|
|
"python-telegram-bot/logos/master/logo/png/"
|
|
|
|
"ptb-logo_240.png"
|
|
|
|
),
|
2023-02-11 10:45:17 +01:00
|
|
|
"mime_type": "image/png",
|
|
|
|
"caption": "ptb_logo",
|
|
|
|
"input_message_content": {"message_text": "imc"},
|
|
|
|
},
|
|
|
|
],
|
|
|
|
"next_offset": "42",
|
|
|
|
"inline_query_id": 1234,
|
|
|
|
"is_personal": True,
|
|
|
|
}
|
|
|
|
|
|
|
|
monkeypatch.setattr(bot.request, "post", make_assertion)
|
|
|
|
results = [
|
|
|
|
InlineQueryResultArticle("11", "first", InputTextMessageContent("first")),
|
2024-02-08 17:12:00 +01:00
|
|
|
InlineQueryResultArticle("12", "second", InputMessageContentLPO("second")),
|
2023-02-11 10:45:17 +01:00
|
|
|
InlineQueryResultDocument(
|
|
|
|
id="123",
|
2023-09-22 18:19:21 +02:00
|
|
|
document_url=(
|
|
|
|
"https://raw.githubusercontent.com/python-telegram-bot/logos/master/"
|
|
|
|
"logo/png/ptb-logo_240.png"
|
|
|
|
),
|
2023-02-11 10:45:17 +01:00
|
|
|
title="test_result",
|
|
|
|
mime_type="image/png",
|
|
|
|
caption="ptb_logo",
|
2024-02-08 17:12:00 +01:00
|
|
|
input_message_content=InputMessageContentLPO("imc"),
|
2023-02-11 10:45:17 +01:00
|
|
|
),
|
|
|
|
]
|
|
|
|
|
|
|
|
copied_results = copy.copy(results)
|
|
|
|
assert await bot.answer_inline_query(
|
|
|
|
1234,
|
|
|
|
results=results,
|
|
|
|
cache_time=300,
|
|
|
|
is_personal=True,
|
|
|
|
next_offset="42",
|
|
|
|
)
|
|
|
|
# make sure that the results were not edited in-place
|
|
|
|
assert results == copied_results
|
|
|
|
for idx, result in enumerate(results):
|
|
|
|
if hasattr(result, "parse_mode"):
|
|
|
|
assert result.parse_mode == copied_results[idx].parse_mode
|
|
|
|
if hasattr(result, "input_message_content"):
|
|
|
|
assert getattr(result.input_message_content, "parse_mode", None) == getattr(
|
|
|
|
copied_results[idx].input_message_content, "parse_mode", None
|
|
|
|
)
|
|
|
|
assert getattr(
|
|
|
|
result.input_message_content, "disable_web_page_preview", None
|
|
|
|
) == getattr(
|
|
|
|
copied_results[idx].input_message_content, "disable_web_page_preview", None
|
|
|
|
)
|
|
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
|
|
"default_bot",
|
|
|
|
[{"parse_mode": "Markdown", "disable_web_page_preview": True}],
|
|
|
|
indirect=True,
|
|
|
|
)
|
|
|
|
async def test_answer_inline_query_default_parse_mode(self, monkeypatch, default_bot):
|
|
|
|
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
|
|
|
|
return request_data.parameters == {
|
|
|
|
"cache_time": 300,
|
|
|
|
"results": [
|
|
|
|
{
|
|
|
|
"title": "first",
|
|
|
|
"id": "11",
|
2024-02-08 17:12:00 +01:00
|
|
|
"type": InlineQueryResultType.ARTICLE,
|
2023-02-11 10:45:17 +01:00
|
|
|
"input_message_content": {
|
|
|
|
"message_text": "first",
|
|
|
|
"parse_mode": "Markdown",
|
2024-02-08 17:12:00 +01:00
|
|
|
"link_preview_options": {
|
|
|
|
"is_disabled": True,
|
|
|
|
},
|
2023-02-11 10:45:17 +01:00
|
|
|
},
|
|
|
|
},
|
|
|
|
{
|
|
|
|
"title": "second",
|
|
|
|
"id": "12",
|
2024-02-08 17:12:00 +01:00
|
|
|
"type": InlineQueryResultType.ARTICLE,
|
2023-02-11 10:45:17 +01:00
|
|
|
"input_message_content": {
|
|
|
|
"message_text": "second",
|
2024-02-08 17:12:00 +01:00
|
|
|
"link_preview_options": {
|
|
|
|
"is_disabled": True,
|
|
|
|
},
|
2023-02-11 10:45:17 +01:00
|
|
|
},
|
|
|
|
},
|
|
|
|
{
|
|
|
|
"title": "test_result",
|
|
|
|
"id": "123",
|
2024-02-08 17:12:00 +01:00
|
|
|
"type": InlineQueryResultType.DOCUMENT,
|
2023-09-22 18:19:21 +02:00
|
|
|
"document_url": (
|
|
|
|
"https://raw.githubusercontent.com/"
|
|
|
|
"python-telegram-bot/logos/master/logo/png/"
|
|
|
|
"ptb-logo_240.png"
|
|
|
|
),
|
2023-02-11 10:45:17 +01:00
|
|
|
"mime_type": "image/png",
|
|
|
|
"caption": "ptb_logo",
|
|
|
|
"parse_mode": "Markdown",
|
|
|
|
"input_message_content": {
|
|
|
|
"message_text": "imc",
|
2024-02-08 17:12:00 +01:00
|
|
|
"link_preview_options": {
|
|
|
|
"is_disabled": True,
|
|
|
|
},
|
2023-02-11 10:45:17 +01:00
|
|
|
"parse_mode": "Markdown",
|
|
|
|
},
|
|
|
|
},
|
|
|
|
],
|
|
|
|
"next_offset": "42",
|
|
|
|
"inline_query_id": 1234,
|
|
|
|
"is_personal": True,
|
|
|
|
}
|
|
|
|
|
|
|
|
monkeypatch.setattr(default_bot.request, "post", make_assertion)
|
|
|
|
results = [
|
|
|
|
InlineQueryResultArticle("11", "first", InputTextMessageContent("first")),
|
2024-02-08 17:12:00 +01:00
|
|
|
InlineQueryResultArticle("12", "second", InputMessageContentLPO("second")),
|
2023-02-11 10:45:17 +01:00
|
|
|
InlineQueryResultDocument(
|
|
|
|
id="123",
|
2023-09-22 18:19:21 +02:00
|
|
|
document_url=(
|
|
|
|
"https://raw.githubusercontent.com/python-telegram-bot/logos/master/"
|
|
|
|
"logo/png/ptb-logo_240.png"
|
|
|
|
),
|
2023-02-11 10:45:17 +01:00
|
|
|
title="test_result",
|
|
|
|
mime_type="image/png",
|
|
|
|
caption="ptb_logo",
|
|
|
|
input_message_content=InputTextMessageContent("imc"),
|
|
|
|
),
|
|
|
|
]
|
|
|
|
|
|
|
|
copied_results = copy.copy(results)
|
|
|
|
assert await default_bot.answer_inline_query(
|
|
|
|
1234,
|
|
|
|
results=results,
|
|
|
|
cache_time=300,
|
|
|
|
is_personal=True,
|
|
|
|
next_offset="42",
|
|
|
|
)
|
|
|
|
# make sure that the results were not edited in-place
|
|
|
|
assert results == copied_results
|
|
|
|
for idx, result in enumerate(results):
|
|
|
|
if hasattr(result, "parse_mode"):
|
|
|
|
assert result.parse_mode == copied_results[idx].parse_mode
|
|
|
|
if hasattr(result, "input_message_content"):
|
|
|
|
assert getattr(result.input_message_content, "parse_mode", None) == getattr(
|
|
|
|
copied_results[idx].input_message_content, "parse_mode", None
|
|
|
|
)
|
|
|
|
assert getattr(
|
|
|
|
result.input_message_content, "disable_web_page_preview", None
|
|
|
|
) == getattr(
|
|
|
|
copied_results[idx].input_message_content, "disable_web_page_preview", None
|
|
|
|
)
|
|
|
|
|
|
|
|
@pytest.mark.parametrize(
|
2023-03-25 19:18:04 +01:00
|
|
|
("current_offset", "num_results", "id_offset", "expected_next_offset"),
|
2023-02-11 10:45:17 +01:00
|
|
|
[
|
|
|
|
("", InlineQueryLimit.RESULTS, 1, 1),
|
|
|
|
(1, InlineQueryLimit.RESULTS, 51, 2),
|
|
|
|
(5, 3, 251, ""),
|
|
|
|
],
|
|
|
|
)
|
|
|
|
async def test_answer_inline_query_current_offset_1(
|
|
|
|
self,
|
|
|
|
monkeypatch,
|
|
|
|
bot,
|
|
|
|
inline_results,
|
|
|
|
current_offset,
|
|
|
|
num_results,
|
|
|
|
id_offset,
|
|
|
|
expected_next_offset,
|
|
|
|
):
|
|
|
|
# For now just test that our internals pass the correct data
|
|
|
|
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
|
|
|
|
data = request_data.parameters
|
|
|
|
results = data["results"]
|
|
|
|
length_matches = len(results) == num_results
|
|
|
|
ids_match = all(int(res["id"]) == id_offset + i for i, res in enumerate(results))
|
|
|
|
next_offset_matches = data["next_offset"] == str(expected_next_offset)
|
|
|
|
return length_matches and ids_match and next_offset_matches
|
|
|
|
|
|
|
|
monkeypatch.setattr(bot.request, "post", make_assertion)
|
|
|
|
|
|
|
|
assert await bot.answer_inline_query(
|
|
|
|
1234, results=inline_results, current_offset=current_offset
|
|
|
|
)
|
|
|
|
|
|
|
|
async def test_answer_inline_query_current_offset_2(self, monkeypatch, bot, inline_results):
|
|
|
|
# For now just test that our internals pass the correct data
|
|
|
|
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
|
|
|
|
data = request_data.parameters
|
|
|
|
results = data["results"]
|
|
|
|
length_matches = len(results) == InlineQueryLimit.RESULTS
|
|
|
|
ids_match = all(int(res["id"]) == 1 + i for i, res in enumerate(results))
|
|
|
|
next_offset_matches = data["next_offset"] == "1"
|
|
|
|
return length_matches and ids_match and next_offset_matches
|
|
|
|
|
|
|
|
monkeypatch.setattr(bot.request, "post", make_assertion)
|
|
|
|
|
|
|
|
assert await bot.answer_inline_query(1234, results=inline_results, current_offset=0)
|
|
|
|
|
|
|
|
inline_results = inline_results[:30]
|
|
|
|
|
|
|
|
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
|
|
|
|
data = request_data.parameters
|
|
|
|
results = data["results"]
|
|
|
|
length_matches = len(results) == 30
|
|
|
|
ids_match = all(int(res["id"]) == 1 + i for i, res in enumerate(results))
|
2023-03-25 19:18:04 +01:00
|
|
|
next_offset_matches = not data["next_offset"]
|
2023-02-11 10:45:17 +01:00
|
|
|
return length_matches and ids_match and next_offset_matches
|
|
|
|
|
|
|
|
monkeypatch.setattr(bot.request, "post", make_assertion)
|
|
|
|
|
|
|
|
assert await bot.answer_inline_query(1234, results=inline_results, current_offset=0)
|
|
|
|
|
2023-04-10 17:01:35 +02:00
|
|
|
async def test_answer_inline_query_current_offset_callback(self, monkeypatch, bot):
|
2023-02-11 10:45:17 +01:00
|
|
|
# For now just test that our internals pass the correct data
|
|
|
|
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
|
|
|
|
data = request_data.parameters
|
|
|
|
results = data["results"]
|
|
|
|
length = len(results) == 5
|
|
|
|
ids = all(int(res["id"]) == 6 + i for i, res in enumerate(results))
|
|
|
|
next_offset = data["next_offset"] == "2"
|
|
|
|
return length and ids and next_offset
|
|
|
|
|
|
|
|
monkeypatch.setattr(bot.request, "post", make_assertion)
|
|
|
|
|
|
|
|
assert await bot.answer_inline_query(
|
|
|
|
1234, results=inline_results_callback, current_offset=1
|
|
|
|
)
|
|
|
|
|
|
|
|
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
|
|
|
|
data = request_data.parameters
|
|
|
|
results = data["results"]
|
|
|
|
length = results == []
|
2023-03-25 19:18:04 +01:00
|
|
|
next_offset = not data["next_offset"]
|
2023-02-11 10:45:17 +01:00
|
|
|
return length and next_offset
|
|
|
|
|
|
|
|
monkeypatch.setattr(bot.request, "post", make_assertion)
|
|
|
|
|
|
|
|
assert await bot.answer_inline_query(
|
|
|
|
1234, results=inline_results_callback, current_offset=6
|
|
|
|
)
|
|
|
|
|
2024-02-08 17:12:00 +01:00
|
|
|
async def test_send_edit_message_mutually_exclusive_link_preview(self, bot, chat_id):
|
|
|
|
"""Test that link_preview is mutually exclusive with disable_web_page_preview."""
|
2024-02-25 10:34:47 +01:00
|
|
|
with pytest.raises(ValueError, match="`link_preview_options` are mutually exclusive"):
|
2024-02-08 17:12:00 +01:00
|
|
|
await bot.send_message(
|
|
|
|
chat_id, "text", disable_web_page_preview=True, link_preview_options="something"
|
|
|
|
)
|
|
|
|
|
2024-02-25 10:34:47 +01:00
|
|
|
with pytest.raises(ValueError, match="`link_preview_options` are mutually exclusive"):
|
2024-02-08 17:12:00 +01:00
|
|
|
await bot.edit_message_text(
|
|
|
|
"text", chat_id, 1, disable_web_page_preview=True, link_preview_options="something"
|
|
|
|
)
|
|
|
|
|
|
|
|
async def test_rtm_aswr_mutually_exclusive_reply_parameters(self, bot, chat_id):
|
|
|
|
"""Test that reply_to_message_id and allow_sending_without_reply are mutually exclusive
|
|
|
|
with reply_parameters."""
|
|
|
|
with pytest.raises(ValueError, match="`reply_to_message_id` and"):
|
|
|
|
await bot.send_message(chat_id, "text", reply_to_message_id=1, reply_parameters=True)
|
|
|
|
|
|
|
|
with pytest.raises(ValueError, match="`allow_sending_without_reply` and"):
|
|
|
|
await bot.send_message(
|
|
|
|
chat_id, "text", allow_sending_without_reply=True, reply_parameters=True
|
|
|
|
)
|
|
|
|
|
|
|
|
# Test with copy message
|
|
|
|
with pytest.raises(ValueError, match="`reply_to_message_id` and"):
|
|
|
|
await bot.copy_message(
|
|
|
|
chat_id, chat_id, 1, reply_to_message_id=1, reply_parameters=True
|
|
|
|
)
|
|
|
|
|
|
|
|
with pytest.raises(ValueError, match="`allow_sending_without_reply` and"):
|
|
|
|
await bot.copy_message(
|
|
|
|
chat_id, chat_id, 1, allow_sending_without_reply=True, reply_parameters=True
|
|
|
|
)
|
|
|
|
|
|
|
|
# Test with send media group
|
|
|
|
media = InputMediaPhoto(photo_file)
|
|
|
|
with pytest.raises(ValueError, match="`reply_to_message_id` and"):
|
|
|
|
await bot.send_media_group(
|
|
|
|
chat_id, media, reply_to_message_id=1, reply_parameters=True
|
|
|
|
)
|
|
|
|
|
|
|
|
with pytest.raises(ValueError, match="`allow_sending_without_reply` and"):
|
|
|
|
await bot.send_media_group(
|
|
|
|
chat_id, media, allow_sending_without_reply=True, reply_parameters=True
|
|
|
|
)
|
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
# get_file is tested multiple times in the test_*media* modules.
|
|
|
|
# Here we only test the behaviour for bot apis in local mode
|
|
|
|
async def test_get_file_local_mode(self, bot, monkeypatch):
|
|
|
|
path = str(data_file("game.gif"))
|
|
|
|
|
|
|
|
async def make_assertion(*args, **kwargs):
|
|
|
|
return {
|
|
|
|
"file_id": None,
|
|
|
|
"file_unique_id": None,
|
|
|
|
"file_size": None,
|
|
|
|
"file_path": path,
|
|
|
|
}
|
|
|
|
|
|
|
|
monkeypatch.setattr(bot, "_post", make_assertion)
|
|
|
|
|
|
|
|
resulting_path = (await bot.get_file("file_id")).file_path
|
|
|
|
assert bot.token not in resulting_path
|
|
|
|
assert resulting_path == path
|
|
|
|
|
|
|
|
# TODO: Needs improvement. No feasible way to test until bots can add members.
|
|
|
|
async def test_ban_chat_member(self, monkeypatch, bot):
|
|
|
|
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
|
|
|
|
data = request_data.json_parameters
|
|
|
|
chat_id = data["chat_id"] == "2"
|
|
|
|
user_id = data["user_id"] == "32"
|
|
|
|
until_date = data.get("until_date", "1577887200") == "1577887200"
|
|
|
|
revoke_msgs = data.get("revoke_messages", "true") == "true"
|
|
|
|
return chat_id and user_id and until_date and revoke_msgs
|
|
|
|
|
|
|
|
monkeypatch.setattr(bot.request, "post", make_assertion)
|
|
|
|
until = from_timestamp(1577887200)
|
|
|
|
|
|
|
|
assert await bot.ban_chat_member(2, 32)
|
|
|
|
assert await bot.ban_chat_member(2, 32, until_date=until)
|
|
|
|
assert await bot.ban_chat_member(2, 32, until_date=1577887200)
|
|
|
|
assert await bot.ban_chat_member(2, 32, revoke_messages=True)
|
|
|
|
|
|
|
|
async def test_ban_chat_member_default_tz(self, monkeypatch, tz_bot):
|
|
|
|
until = dtm.datetime(2020, 1, 11, 16, 13)
|
|
|
|
until_timestamp = to_timestamp(until, tzinfo=tz_bot.defaults.tzinfo)
|
|
|
|
|
|
|
|
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
|
|
|
|
data = request_data.parameters
|
|
|
|
chat_id = data["chat_id"] == 2
|
|
|
|
user_id = data["user_id"] == 32
|
|
|
|
until_date = data.get("until_date", until_timestamp) == until_timestamp
|
|
|
|
return chat_id and user_id and until_date
|
|
|
|
|
|
|
|
monkeypatch.setattr(tz_bot.request, "post", make_assertion)
|
|
|
|
|
|
|
|
assert await tz_bot.ban_chat_member(2, 32)
|
|
|
|
assert await tz_bot.ban_chat_member(2, 32, until_date=until)
|
|
|
|
assert await tz_bot.ban_chat_member(2, 32, until_date=until_timestamp)
|
|
|
|
|
|
|
|
async def test_ban_chat_sender_chat(self, monkeypatch, bot):
|
|
|
|
# For now, we just test that we pass the correct data to TG
|
|
|
|
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
|
|
|
|
data = request_data.parameters
|
|
|
|
chat_id = data["chat_id"] == 2
|
|
|
|
sender_chat_id = data["sender_chat_id"] == 32
|
|
|
|
return chat_id and sender_chat_id
|
|
|
|
|
|
|
|
monkeypatch.setattr(bot.request, "post", make_assertion)
|
|
|
|
assert await bot.ban_chat_sender_chat(2, 32)
|
|
|
|
|
|
|
|
# TODO: Needs improvement.
|
|
|
|
@pytest.mark.parametrize("only_if_banned", [True, False, None])
|
|
|
|
async def test_unban_chat_member(self, monkeypatch, bot, only_if_banned):
|
|
|
|
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
|
|
|
|
data = request_data.parameters
|
|
|
|
chat_id = data["chat_id"] == 2
|
|
|
|
user_id = data["user_id"] == 32
|
|
|
|
o_i_b = data.get("only_if_banned", None) == only_if_banned
|
|
|
|
return chat_id and user_id and o_i_b
|
|
|
|
|
|
|
|
monkeypatch.setattr(bot.request, "post", make_assertion)
|
|
|
|
|
|
|
|
assert await bot.unban_chat_member(2, 32, only_if_banned=only_if_banned)
|
|
|
|
|
|
|
|
async def test_unban_chat_sender_chat(self, monkeypatch, bot):
|
|
|
|
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
|
|
|
|
data = request_data.json_parameters
|
|
|
|
chat_id = data["chat_id"] == "2"
|
|
|
|
sender_chat_id = data["sender_chat_id"] == "32"
|
|
|
|
return chat_id and sender_chat_id
|
|
|
|
|
|
|
|
monkeypatch.setattr(bot.request, "post", make_assertion)
|
|
|
|
assert await bot.unban_chat_sender_chat(2, 32)
|
|
|
|
|
|
|
|
async def test_set_chat_permissions(self, monkeypatch, bot, chat_permissions):
|
|
|
|
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
|
|
|
|
data = request_data.json_parameters
|
|
|
|
chat_id = data["chat_id"] == "2"
|
|
|
|
permissions = data["permissions"] == chat_permissions.to_json()
|
|
|
|
use_independent_chat_permissions = data["use_independent_chat_permissions"]
|
|
|
|
return chat_id and permissions and use_independent_chat_permissions
|
|
|
|
|
|
|
|
monkeypatch.setattr(bot.request, "post", make_assertion)
|
|
|
|
|
|
|
|
assert await bot.set_chat_permissions(2, chat_permissions, True)
|
|
|
|
|
|
|
|
async def test_set_chat_administrator_custom_title(self, monkeypatch, bot):
|
|
|
|
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
|
|
|
|
data = request_data.parameters
|
|
|
|
chat_id = data["chat_id"] == 2
|
|
|
|
user_id = data["user_id"] == 32
|
|
|
|
custom_title = data["custom_title"] == "custom_title"
|
|
|
|
return chat_id and user_id and custom_title
|
|
|
|
|
|
|
|
monkeypatch.setattr(bot.request, "post", make_assertion)
|
|
|
|
assert await bot.set_chat_administrator_custom_title(2, 32, "custom_title")
|
|
|
|
|
|
|
|
# TODO: Needs improvement. Need an incoming callbackquery to test
|
|
|
|
async def test_answer_callback_query(self, monkeypatch, bot):
|
|
|
|
# For now just test that our internals pass the correct data
|
|
|
|
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
|
|
|
|
return request_data.parameters == {
|
|
|
|
"callback_query_id": 23,
|
|
|
|
"show_alert": True,
|
|
|
|
"url": "no_url",
|
|
|
|
"cache_time": 1,
|
|
|
|
"text": "answer",
|
|
|
|
}
|
|
|
|
|
|
|
|
monkeypatch.setattr(bot.request, "post", make_assertion)
|
|
|
|
|
|
|
|
assert await bot.answer_callback_query(
|
|
|
|
23, text="answer", show_alert=True, url="no_url", cache_time=1
|
|
|
|
)
|
|
|
|
|
|
|
|
@pytest.mark.parametrize("drop_pending_updates", [True, False])
|
|
|
|
async def test_set_webhook_delete_webhook_drop_pending_updates(
|
|
|
|
self, bot, drop_pending_updates, monkeypatch
|
|
|
|
):
|
|
|
|
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
|
|
|
|
data = request_data.parameters
|
|
|
|
return data.get("drop_pending_updates") == drop_pending_updates
|
|
|
|
|
|
|
|
monkeypatch.setattr(bot.request, "post", make_assertion)
|
|
|
|
|
|
|
|
assert await bot.set_webhook("", drop_pending_updates=drop_pending_updates)
|
|
|
|
assert await bot.delete_webhook(drop_pending_updates=drop_pending_updates)
|
|
|
|
|
|
|
|
@pytest.mark.parametrize("local_file", ["str", "Path", False])
|
|
|
|
async def test_set_webhook_params(self, bot, monkeypatch, local_file):
|
|
|
|
# actually making calls to TG is done in
|
|
|
|
# test_set_webhook_get_webhook_info_and_delete_webhook. Sadly secret_token can't be tested
|
|
|
|
# there so we have this function \o/
|
|
|
|
async def make_assertion(*args, **_):
|
|
|
|
kwargs = args[1]
|
|
|
|
|
|
|
|
if local_file is False:
|
|
|
|
cert_assertion = (
|
|
|
|
kwargs["certificate"].input_file_content
|
|
|
|
== data_file("sslcert.pem").read_bytes()
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
cert_assertion = data_file("sslcert.pem").as_uri()
|
|
|
|
|
|
|
|
return (
|
|
|
|
kwargs["url"] == "example.com"
|
|
|
|
and cert_assertion
|
|
|
|
and kwargs["max_connections"] == 7
|
|
|
|
and kwargs["allowed_updates"] == ["messages"]
|
|
|
|
and kwargs["ip_address"] == "127.0.0.1"
|
|
|
|
and kwargs["drop_pending_updates"]
|
|
|
|
and kwargs["secret_token"] == "SoSecretToken"
|
|
|
|
)
|
|
|
|
|
|
|
|
monkeypatch.setattr(bot, "_post", make_assertion)
|
|
|
|
|
|
|
|
cert_path = data_file("sslcert.pem")
|
|
|
|
if local_file == "str":
|
|
|
|
certificate = str(cert_path)
|
|
|
|
elif local_file == "Path":
|
|
|
|
certificate = cert_path
|
|
|
|
else:
|
|
|
|
certificate = cert_path.read_bytes()
|
|
|
|
|
|
|
|
assert await bot.set_webhook(
|
|
|
|
"example.com",
|
|
|
|
certificate,
|
|
|
|
7,
|
|
|
|
["messages"],
|
|
|
|
"127.0.0.1",
|
|
|
|
True,
|
|
|
|
"SoSecretToken",
|
|
|
|
)
|
|
|
|
|
|
|
|
# TODO: Needs improvement. Need incoming shipping queries to test
|
|
|
|
async def test_answer_shipping_query_ok(self, monkeypatch, bot):
|
|
|
|
# For now just test that our internals pass the correct data
|
|
|
|
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
|
|
|
|
return request_data.parameters == {
|
|
|
|
"shipping_query_id": 1,
|
|
|
|
"ok": True,
|
|
|
|
"shipping_options": [
|
|
|
|
{"title": "option1", "prices": [{"label": "price", "amount": 100}], "id": 1}
|
|
|
|
],
|
|
|
|
}
|
|
|
|
|
|
|
|
monkeypatch.setattr(bot.request, "post", make_assertion)
|
|
|
|
shipping_options = ShippingOption(1, "option1", [LabeledPrice("price", 100)])
|
|
|
|
assert await bot.answer_shipping_query(1, True, shipping_options=[shipping_options])
|
|
|
|
|
|
|
|
async def test_answer_shipping_query_error_message(self, monkeypatch, bot):
|
|
|
|
# For now just test that our internals pass the correct data
|
|
|
|
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
|
|
|
|
return request_data.parameters == {
|
|
|
|
"shipping_query_id": 1,
|
|
|
|
"error_message": "Not enough fish",
|
|
|
|
"ok": False,
|
|
|
|
}
|
|
|
|
|
|
|
|
monkeypatch.setattr(bot.request, "post", make_assertion)
|
|
|
|
assert await bot.answer_shipping_query(1, False, error_message="Not enough fish")
|
|
|
|
|
|
|
|
# TODO: Needs improvement. Need incoming pre checkout queries to test
|
|
|
|
async def test_answer_pre_checkout_query_ok(self, monkeypatch, bot):
|
|
|
|
# For now just test that our internals pass the correct data
|
|
|
|
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
|
|
|
|
return request_data.parameters == {"pre_checkout_query_id": 1, "ok": True}
|
|
|
|
|
|
|
|
monkeypatch.setattr(bot.request, "post", make_assertion)
|
|
|
|
assert await bot.answer_pre_checkout_query(1, True)
|
|
|
|
|
|
|
|
async def test_answer_pre_checkout_query_error_message(self, monkeypatch, bot):
|
|
|
|
# For now just test that our internals pass the correct data
|
|
|
|
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
|
|
|
|
return request_data.parameters == {
|
|
|
|
"pre_checkout_query_id": 1,
|
|
|
|
"error_message": "Not enough fish",
|
|
|
|
"ok": False,
|
|
|
|
}
|
2020-09-27 12:59:48 +02:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
monkeypatch.setattr(bot.request, "post", make_assertion)
|
|
|
|
assert await bot.answer_pre_checkout_query(1, False, error_message="Not enough fish")
|
2020-09-27 12:59:48 +02:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
async def test_restrict_chat_member(self, bot, chat_permissions, monkeypatch):
|
|
|
|
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
|
|
|
|
data = request_data.json_parameters
|
|
|
|
chat_id = data["chat_id"] == "@chat"
|
|
|
|
user_id = data["user_id"] == "2"
|
|
|
|
permissions = data["permissions"] == chat_permissions.to_json()
|
|
|
|
until_date = data["until_date"] == "200"
|
|
|
|
use_independent_chat_permissions = data["use_independent_chat_permissions"]
|
|
|
|
return (
|
|
|
|
chat_id
|
|
|
|
and user_id
|
|
|
|
and permissions
|
|
|
|
and until_date
|
|
|
|
and use_independent_chat_permissions
|
|
|
|
)
|
2020-09-27 12:59:48 +02:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
monkeypatch.setattr(bot.request, "post", make_assertion)
|
2020-11-29 16:20:46 +01:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
assert await bot.restrict_chat_member("@chat", 2, chat_permissions, 200, True)
|
2020-11-29 16:20:46 +01:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
async def test_restrict_chat_member_default_tz(
|
|
|
|
self, monkeypatch, tz_bot, channel_id, chat_permissions
|
|
|
|
):
|
|
|
|
until = dtm.datetime(2020, 1, 11, 16, 13)
|
|
|
|
until_timestamp = to_timestamp(until, tzinfo=tz_bot.defaults.tzinfo)
|
2020-05-02 11:56:52 +02:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
|
|
|
|
return request_data.parameters.get("until_date", until_timestamp) == until_timestamp
|
|
|
|
|
|
|
|
monkeypatch.setattr(tz_bot.request, "post", make_assertion)
|
|
|
|
|
|
|
|
assert await tz_bot.restrict_chat_member(channel_id, 95205500, chat_permissions)
|
|
|
|
assert await tz_bot.restrict_chat_member(
|
|
|
|
channel_id, 95205500, chat_permissions, until_date=until
|
2020-10-09 17:22:07 +02:00
|
|
|
)
|
2023-02-11 10:45:17 +01:00
|
|
|
assert await tz_bot.restrict_chat_member(
|
|
|
|
channel_id, 95205500, chat_permissions, until_date=until_timestamp
|
2022-12-15 15:00:36 +01:00
|
|
|
)
|
2020-05-02 11:56:52 +02:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
@pytest.mark.parametrize("local_mode", [True, False])
|
|
|
|
async def test_set_chat_photo_local_files(self, monkeypatch, bot, chat_id, local_mode):
|
|
|
|
try:
|
|
|
|
bot._local_mode = local_mode
|
|
|
|
# For just test that the correct paths are passed as we have no local bot API set up
|
|
|
|
self.test_flag = False
|
|
|
|
file = data_file("telegram.jpg")
|
|
|
|
expected = file.as_uri()
|
|
|
|
|
|
|
|
async def make_assertion(_, data, *args, **kwargs):
|
|
|
|
if local_mode:
|
|
|
|
self.test_flag = data.get("photo") == expected
|
|
|
|
else:
|
|
|
|
self.test_flag = isinstance(data.get("photo"), InputFile)
|
|
|
|
|
|
|
|
monkeypatch.setattr(bot, "_post", make_assertion)
|
|
|
|
await bot.set_chat_photo(chat_id, file)
|
|
|
|
assert self.test_flag
|
|
|
|
finally:
|
|
|
|
bot._local_mode = False
|
|
|
|
|
|
|
|
async def test_timeout_propagation_explicit(self, monkeypatch, bot, chat_id):
|
|
|
|
# Use BaseException that's not a subclass of Exception such that
|
|
|
|
# OkException should not be caught anywhere
|
|
|
|
class OkException(BaseException):
|
|
|
|
pass
|
|
|
|
|
|
|
|
timeout = 42
|
|
|
|
|
|
|
|
async def do_request(*args, **kwargs):
|
|
|
|
obj = kwargs.get("read_timeout")
|
|
|
|
if obj == timeout:
|
|
|
|
raise OkException
|
|
|
|
|
|
|
|
return 200, b'{"ok": true, "result": []}'
|
|
|
|
|
|
|
|
monkeypatch.setattr(bot.request, "do_request", do_request)
|
|
|
|
|
|
|
|
# Test file uploading
|
|
|
|
with pytest.raises(OkException):
|
|
|
|
await bot.send_photo(
|
|
|
|
chat_id, data_file("telegram.jpg").open("rb"), read_timeout=timeout
|
|
|
|
)
|
|
|
|
|
|
|
|
# Test JSON submission
|
|
|
|
with pytest.raises(OkException):
|
|
|
|
await bot.get_chat_administrators(chat_id, read_timeout=timeout)
|
|
|
|
|
|
|
|
async def test_timeout_propagation_implicit(self, monkeypatch, bot, chat_id):
|
|
|
|
# Use BaseException that's not a subclass of Exception such that
|
|
|
|
# OkException should not be caught anywhere
|
|
|
|
class OkException(BaseException):
|
|
|
|
pass
|
|
|
|
|
2023-11-26 16:44:18 +01:00
|
|
|
async def request(*args, **kwargs):
|
|
|
|
timeout = kwargs.get("timeout")
|
|
|
|
if timeout.write == 20:
|
2023-02-11 10:45:17 +01:00
|
|
|
raise OkException
|
|
|
|
|
|
|
|
return 200, b'{"ok": true, "result": []}'
|
|
|
|
|
2023-11-26 16:44:18 +01:00
|
|
|
monkeypatch.setattr(httpx.AsyncClient, "request", request)
|
2023-02-11 10:45:17 +01:00
|
|
|
|
|
|
|
# Test file uploading
|
|
|
|
with pytest.raises(OkException):
|
|
|
|
await bot.send_photo(chat_id, data_file("telegram.jpg").open("rb"))
|
|
|
|
|
|
|
|
async def test_log_out(self, monkeypatch, bot):
|
|
|
|
# We don't actually make a request as to not break the test setup
|
|
|
|
async def assertion(url, request_data: RequestData, *args, **kwargs):
|
|
|
|
return request_data.json_parameters == {} and url.split("/")[-1] == "logOut"
|
|
|
|
|
|
|
|
monkeypatch.setattr(bot.request, "post", assertion)
|
|
|
|
|
|
|
|
assert await bot.log_out()
|
|
|
|
|
|
|
|
async def test_close(self, monkeypatch, bot):
|
|
|
|
# We don't actually make a request as to not break the test setup
|
|
|
|
async def assertion(url, request_data: RequestData, *args, **kwargs):
|
|
|
|
return request_data.json_parameters == {} and url.split("/")[-1] == "close"
|
|
|
|
|
|
|
|
monkeypatch.setattr(bot.request, "post", assertion)
|
|
|
|
|
|
|
|
assert await bot.close()
|
|
|
|
|
|
|
|
@pytest.mark.parametrize("json_keyboard", [True, False])
|
|
|
|
@pytest.mark.parametrize("caption", ["<b>Test</b>", "", None])
|
|
|
|
async def test_copy_message(
|
|
|
|
self, monkeypatch, bot, chat_id, media_message, json_keyboard, caption
|
|
|
|
):
|
|
|
|
keyboard = InlineKeyboardMarkup(
|
|
|
|
[[InlineKeyboardButton(text="test", callback_data="test2")]]
|
2020-10-09 17:22:07 +02:00
|
|
|
)
|
2020-05-02 11:56:52 +02:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
async def post(url, request_data: RequestData, *args, **kwargs):
|
|
|
|
data = request_data.parameters
|
|
|
|
if not all(
|
|
|
|
[
|
|
|
|
data["chat_id"] == chat_id,
|
|
|
|
data["from_chat_id"] == chat_id,
|
|
|
|
data["message_id"] == media_message.message_id,
|
|
|
|
data.get("caption") == caption,
|
|
|
|
data["parse_mode"] == ParseMode.HTML,
|
2024-02-08 17:12:00 +01:00
|
|
|
data["reply_parameters"]
|
|
|
|
== ReplyParameters(message_id=media_message.message_id).to_dict(),
|
2023-09-22 18:19:21 +02:00
|
|
|
(
|
|
|
|
data["reply_markup"] == keyboard.to_json()
|
|
|
|
if json_keyboard
|
|
|
|
else keyboard.to_dict()
|
|
|
|
),
|
2023-02-11 10:45:17 +01:00
|
|
|
data["disable_notification"] is True,
|
|
|
|
data["caption_entities"]
|
|
|
|
== [MessageEntity(MessageEntity.BOLD, 0, 4).to_dict()],
|
|
|
|
data["protect_content"] is True,
|
|
|
|
data["message_thread_id"] == 1,
|
|
|
|
]
|
|
|
|
):
|
|
|
|
pytest.fail("I got wrong parameters in post")
|
|
|
|
return data
|
|
|
|
|
|
|
|
monkeypatch.setattr(bot.request, "post", post)
|
|
|
|
await bot.copy_message(
|
|
|
|
chat_id,
|
|
|
|
from_chat_id=chat_id,
|
|
|
|
message_id=media_message.message_id,
|
|
|
|
caption=caption,
|
|
|
|
caption_entities=[MessageEntity(MessageEntity.BOLD, 0, 4)],
|
|
|
|
parse_mode=ParseMode.HTML,
|
|
|
|
reply_to_message_id=media_message.message_id,
|
|
|
|
reply_markup=keyboard.to_json() if json_keyboard else keyboard,
|
|
|
|
disable_notification=True,
|
|
|
|
protect_content=True,
|
|
|
|
message_thread_id=1,
|
2020-10-09 17:22:07 +02:00
|
|
|
)
|
2020-05-02 11:56:52 +02:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
# In the following tests we check that get_updates inserts callback data correctly if necessary
|
|
|
|
# The same must be done in the webhook updater. This is tested over at test_updater.py, but
|
|
|
|
# here we test more extensively.
|
|
|
|
|
2020-11-29 16:20:46 +01:00
|
|
|
@pytest.mark.parametrize(
|
2023-03-25 19:18:04 +01:00
|
|
|
("acd_in", "maxsize"),
|
2023-02-11 10:45:17 +01:00
|
|
|
[(True, 1024), (False, 1024), (0, 0), (None, None)],
|
2020-11-29 16:20:46 +01:00
|
|
|
)
|
2023-02-11 10:45:17 +01:00
|
|
|
async def test_callback_data_maxsize(self, bot_info, acd_in, maxsize):
|
|
|
|
async with make_bot(bot_info, arbitrary_callback_data=acd_in) as acd_bot:
|
|
|
|
if acd_in is not False:
|
|
|
|
assert acd_bot.callback_data_cache.maxsize == maxsize
|
|
|
|
else:
|
|
|
|
assert acd_bot.callback_data_cache is None
|
2020-11-29 16:20:46 +01:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
async def test_arbitrary_callback_data_no_insert(self, monkeypatch, cdc_bot):
|
|
|
|
"""Updates that don't need insertion shouldn't fail obviously"""
|
|
|
|
bot = cdc_bot
|
2022-01-07 17:02:23 +01:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
async def post(*args, **kwargs):
|
|
|
|
update = Update(
|
|
|
|
17,
|
|
|
|
poll=Poll(
|
|
|
|
"42",
|
|
|
|
"question",
|
|
|
|
options=[PollOption("option", 0)],
|
|
|
|
total_voter_count=0,
|
|
|
|
is_closed=False,
|
|
|
|
is_anonymous=True,
|
|
|
|
type=Poll.REGULAR,
|
|
|
|
allows_multiple_answers=False,
|
|
|
|
),
|
|
|
|
)
|
|
|
|
return [update.to_dict()]
|
2020-04-10 19:22:45 +02:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
try:
|
|
|
|
monkeypatch.setattr(BaseRequest, "post", post)
|
|
|
|
updates = await bot.get_updates(timeout=1)
|
|
|
|
|
|
|
|
assert len(updates) == 1
|
|
|
|
assert updates[0].update_id == 17
|
|
|
|
assert updates[0].poll.id == "42"
|
|
|
|
finally:
|
|
|
|
bot.callback_data_cache.clear_callback_data()
|
|
|
|
bot.callback_data_cache.clear_callback_queries()
|
2020-04-10 19:22:45 +02:00
|
|
|
|
2020-11-29 16:20:46 +01:00
|
|
|
@pytest.mark.parametrize(
|
2023-02-11 10:45:17 +01:00
|
|
|
"message_type", ["channel_post", "edited_channel_post", "message", "edited_message"]
|
2020-11-29 16:20:46 +01:00
|
|
|
)
|
2023-02-11 10:45:17 +01:00
|
|
|
async def test_arbitrary_callback_data_pinned_message_reply_to_message(
|
|
|
|
self, cdc_bot, monkeypatch, message_type
|
2022-04-24 12:38:09 +02:00
|
|
|
):
|
2023-02-11 10:45:17 +01:00
|
|
|
bot = cdc_bot
|
|
|
|
|
|
|
|
reply_markup = InlineKeyboardMarkup.from_button(
|
|
|
|
InlineKeyboardButton(text="text", callback_data="callback_data")
|
|
|
|
)
|
|
|
|
|
|
|
|
message = Message(
|
|
|
|
1,
|
|
|
|
dtm.datetime.utcnow(),
|
|
|
|
None,
|
|
|
|
reply_markup=bot.callback_data_cache.process_keyboard(reply_markup),
|
|
|
|
)
|
|
|
|
message._unfreeze()
|
|
|
|
# We do to_dict -> de_json to make sure those aren't the same objects
|
|
|
|
message.pinned_message = Message.de_json(message.to_dict(), bot)
|
|
|
|
|
|
|
|
async def post(*args, **kwargs):
|
|
|
|
update = Update(
|
|
|
|
17,
|
|
|
|
**{
|
|
|
|
message_type: Message(
|
|
|
|
1,
|
|
|
|
dtm.datetime.utcnow(),
|
|
|
|
None,
|
|
|
|
pinned_message=message,
|
|
|
|
reply_to_message=Message.de_json(message.to_dict(), bot),
|
|
|
|
)
|
|
|
|
},
|
2020-11-29 16:20:46 +01:00
|
|
|
)
|
2023-02-11 10:45:17 +01:00
|
|
|
return [update.to_dict()]
|
2020-11-29 16:20:46 +01:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
try:
|
|
|
|
monkeypatch.setattr(BaseRequest, "post", post)
|
|
|
|
updates = await bot.get_updates(timeout=1)
|
2022-01-07 17:02:23 +01:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
assert isinstance(updates, tuple)
|
|
|
|
assert len(updates) == 1
|
2022-07-10 17:14:45 +02:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
effective_message = updates[0][message_type]
|
|
|
|
assert (
|
|
|
|
effective_message.reply_to_message.reply_markup.inline_keyboard[0][0].callback_data
|
|
|
|
== "callback_data"
|
|
|
|
)
|
|
|
|
assert (
|
|
|
|
effective_message.pinned_message.reply_markup.inline_keyboard[0][0].callback_data
|
|
|
|
== "callback_data"
|
|
|
|
)
|
2017-08-11 23:58:41 +02:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
pinned_message = effective_message.reply_to_message.pinned_message
|
|
|
|
assert (
|
|
|
|
pinned_message.reply_markup.inline_keyboard[0][0].callback_data == "callback_data"
|
2023-01-01 17:00:49 +01:00
|
|
|
)
|
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
finally:
|
|
|
|
bot.callback_data_cache.clear_callback_data()
|
|
|
|
bot.callback_data_cache.clear_callback_queries()
|
2023-01-01 17:00:49 +01:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
async def test_get_updates_invalid_callback_data(self, cdc_bot, monkeypatch):
|
|
|
|
bot = cdc_bot
|
2022-07-10 15:37:12 +02:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
async def post(*args, **kwargs):
|
|
|
|
return [
|
|
|
|
Update(
|
|
|
|
17,
|
|
|
|
callback_query=CallbackQuery(
|
|
|
|
id=1,
|
|
|
|
from_user=None,
|
|
|
|
chat_instance=123,
|
|
|
|
data="invalid data",
|
|
|
|
message=Message(
|
|
|
|
1,
|
|
|
|
from_user=User(1, "", False),
|
|
|
|
date=dtm.datetime.utcnow(),
|
|
|
|
chat=Chat(1, ""),
|
|
|
|
text="Webhook",
|
|
|
|
),
|
|
|
|
),
|
|
|
|
).to_dict()
|
|
|
|
]
|
2022-05-03 18:21:50 +02:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
try:
|
|
|
|
monkeypatch.setattr(BaseRequest, "post", post)
|
|
|
|
updates = await bot.get_updates(timeout=1)
|
2022-05-03 18:21:50 +02:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
assert isinstance(updates, tuple)
|
|
|
|
assert len(updates) == 1
|
|
|
|
assert isinstance(updates[0].callback_query.data, InvalidCallbackData)
|
2022-11-14 20:08:16 +01:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
finally:
|
|
|
|
# Reset b/c bots scope is session
|
|
|
|
bot.callback_data_cache.clear_callback_data()
|
|
|
|
bot.callback_data_cache.clear_callback_queries()
|
2022-11-14 20:08:16 +01:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
# TODO: Needs improvement. We need incoming inline query to test answer.
|
|
|
|
async def test_replace_callback_data_answer_inline_query(self, monkeypatch, cdc_bot, chat_id):
|
|
|
|
bot = cdc_bot
|
|
|
|
|
|
|
|
# For now just test that our internals pass the correct data
|
|
|
|
async def make_assertion(
|
|
|
|
endpoint,
|
|
|
|
data=None,
|
|
|
|
*args,
|
|
|
|
**kwargs,
|
|
|
|
):
|
|
|
|
inline_keyboard = data["results"][0]["reply_markup"].inline_keyboard
|
|
|
|
assertion_1 = inline_keyboard[0][1] == no_replace_button
|
|
|
|
assertion_2 = inline_keyboard[0][0] != replace_button
|
|
|
|
keyboard, button = (
|
|
|
|
inline_keyboard[0][0].callback_data[:32],
|
|
|
|
inline_keyboard[0][0].callback_data[32:],
|
2022-11-14 20:08:16 +01:00
|
|
|
)
|
2023-02-11 10:45:17 +01:00
|
|
|
assertion_3 = (
|
|
|
|
bot.callback_data_cache._keyboard_data[keyboard].button_data[button]
|
|
|
|
== "replace_test"
|
|
|
|
)
|
|
|
|
assertion_4 = data["results"][1].reply_markup is None
|
|
|
|
return assertion_1 and assertion_2 and assertion_3 and assertion_4
|
2022-11-14 20:08:16 +01:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
try:
|
|
|
|
replace_button = InlineKeyboardButton(text="replace", callback_data="replace_test")
|
|
|
|
no_replace_button = InlineKeyboardButton(
|
|
|
|
text="no_replace", url="http://python-telegram-bot.org/"
|
|
|
|
)
|
|
|
|
reply_markup = InlineKeyboardMarkup.from_row(
|
|
|
|
[
|
|
|
|
replace_button,
|
|
|
|
no_replace_button,
|
|
|
|
]
|
|
|
|
)
|
|
|
|
|
|
|
|
bot.username # call this here so `bot.get_me()` won't be called after mocking
|
|
|
|
monkeypatch.setattr(bot, "_post", make_assertion)
|
|
|
|
results = [
|
2022-11-14 20:08:16 +01:00
|
|
|
InlineQueryResultArticle(
|
2023-02-11 10:45:17 +01:00
|
|
|
"11", "first", InputTextMessageContent("first"), reply_markup=reply_markup
|
2022-11-14 20:08:16 +01:00
|
|
|
),
|
2023-02-11 10:45:17 +01:00
|
|
|
InlineQueryResultVoice(
|
|
|
|
"22",
|
|
|
|
"https://python-telegram-bot.org/static/testfiles/telegram.ogg",
|
|
|
|
title="second",
|
2022-11-14 20:08:16 +01:00
|
|
|
),
|
2023-02-11 10:45:17 +01:00
|
|
|
]
|
2022-11-14 20:08:16 +01:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
assert await bot.answer_inline_query(chat_id, results=results)
|
2022-11-14 20:08:16 +01:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
finally:
|
|
|
|
bot.callback_data_cache.clear_callback_data()
|
|
|
|
bot.callback_data_cache.clear_callback_queries()
|
2022-11-14 20:08:16 +01:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
@pytest.mark.parametrize(
|
|
|
|
"message_type", ["channel_post", "edited_channel_post", "message", "edited_message"]
|
|
|
|
)
|
|
|
|
@pytest.mark.parametrize("self_sender", [True, False])
|
|
|
|
async def test_arbitrary_callback_data_via_bot(
|
|
|
|
self, cdc_bot, monkeypatch, self_sender, message_type
|
|
|
|
):
|
|
|
|
bot = cdc_bot
|
|
|
|
reply_markup = InlineKeyboardMarkup.from_button(
|
|
|
|
InlineKeyboardButton(text="text", callback_data="callback_data")
|
|
|
|
)
|
2022-11-14 20:08:16 +01:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
reply_markup = bot.callback_data_cache.process_keyboard(reply_markup)
|
|
|
|
message = Message(
|
|
|
|
1,
|
|
|
|
dtm.datetime.utcnow(),
|
|
|
|
None,
|
|
|
|
reply_markup=reply_markup,
|
|
|
|
via_bot=bot.bot if self_sender else User(1, "first", False),
|
|
|
|
)
|
2022-11-14 20:08:16 +01:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
async def post(*args, **kwargs):
|
|
|
|
return [Update(17, **{message_type: message}).to_dict()]
|
2022-05-03 18:21:50 +02:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
try:
|
|
|
|
monkeypatch.setattr(BaseRequest, "post", post)
|
|
|
|
updates = await bot.get_updates(timeout=1)
|
2022-11-14 20:08:16 +01:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
assert isinstance(updates, tuple)
|
|
|
|
assert len(updates) == 1
|
2017-08-11 23:58:41 +02:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
message = updates[0][message_type]
|
|
|
|
if self_sender:
|
|
|
|
assert message.reply_markup.inline_keyboard[0][0].callback_data == "callback_data"
|
|
|
|
else:
|
|
|
|
assert (
|
|
|
|
message.reply_markup.inline_keyboard[0][0].callback_data
|
|
|
|
== reply_markup.inline_keyboard[0][0].callback_data
|
|
|
|
)
|
|
|
|
finally:
|
|
|
|
bot.callback_data_cache.clear_callback_data()
|
|
|
|
bot.callback_data_cache.clear_callback_queries()
|
2017-08-11 23:58:41 +02:00
|
|
|
|
2023-04-27 22:36:04 +02:00
|
|
|
@pytest.mark.parametrize("bot_class", [Bot, ExtBot])
|
|
|
|
async def test_http2_runtime_error(self, recwarn, bot_class):
|
|
|
|
bot_class("12345:ABCDE", base_url="http://", request=HTTPXRequest(http_version="2"))
|
|
|
|
bot_class(
|
2023-03-12 16:30:39 +01:00
|
|
|
"12345:ABCDE",
|
|
|
|
base_url="http://",
|
|
|
|
get_updates_request=HTTPXRequest(http_version="2"),
|
|
|
|
)
|
2023-04-27 22:36:04 +02:00
|
|
|
bot_class(
|
2023-03-12 16:30:39 +01:00
|
|
|
"12345:ABCDE",
|
|
|
|
base_url="http://",
|
|
|
|
request=HTTPXRequest(http_version="2"),
|
|
|
|
get_updates_request=HTTPXRequest(http_version="2"),
|
|
|
|
)
|
2023-04-27 22:36:04 +02:00
|
|
|
assert len(recwarn) == 3
|
2023-03-12 16:30:39 +01:00
|
|
|
assert "You set the HTTP version for the request HTTPXRequest instance" in str(
|
|
|
|
recwarn[0].message
|
|
|
|
)
|
|
|
|
assert "You set the HTTP version for the get_updates_request HTTPXRequest instance" in str(
|
|
|
|
recwarn[1].message
|
|
|
|
)
|
|
|
|
assert (
|
|
|
|
"You set the HTTP version for the get_updates_request and request HTTPXRequest "
|
|
|
|
"instance" in str(recwarn[2].message)
|
|
|
|
)
|
2023-04-27 22:36:04 +02:00
|
|
|
for warning in recwarn:
|
|
|
|
assert warning.filename == __file__, "wrong stacklevel!"
|
|
|
|
assert warning.category is PTBUserWarning
|
2023-03-12 16:30:39 +01:00
|
|
|
|
2023-05-07 13:44:34 +02:00
|
|
|
async def test_set_get_my_name(self, bot, monkeypatch):
|
|
|
|
"""We only test that we pass the correct values to TG since this endpoint is heavily
|
|
|
|
rate limited which makes automated tests rather infeasible."""
|
|
|
|
default_name = "default_bot_name"
|
|
|
|
en_name = "en_bot_name"
|
|
|
|
de_name = "de_bot_name"
|
|
|
|
|
|
|
|
# We predefine the responses that we would TG expect to send us
|
|
|
|
set_stack = asyncio.Queue()
|
|
|
|
get_stack = asyncio.Queue()
|
|
|
|
await set_stack.put({"name": default_name})
|
|
|
|
await set_stack.put({"name": en_name, "language_code": "en"})
|
|
|
|
await set_stack.put({"name": de_name, "language_code": "de"})
|
|
|
|
await get_stack.put({"name": default_name, "language_code": None})
|
|
|
|
await get_stack.put({"name": en_name, "language_code": "en"})
|
|
|
|
await get_stack.put({"name": de_name, "language_code": "de"})
|
|
|
|
|
|
|
|
await set_stack.put({"name": default_name})
|
|
|
|
await set_stack.put({"language_code": "en"})
|
|
|
|
await set_stack.put({"language_code": "de"})
|
|
|
|
await get_stack.put({"name": default_name, "language_code": None})
|
|
|
|
await get_stack.put({"name": default_name, "language_code": "en"})
|
|
|
|
await get_stack.put({"name": default_name, "language_code": "de"})
|
|
|
|
|
|
|
|
async def post(url, request_data: RequestData, *args, **kwargs):
|
|
|
|
# The mock-post now just fetches the predefined responses from the queues
|
|
|
|
if "setMyName" in url:
|
|
|
|
expected = await set_stack.get()
|
|
|
|
assert request_data.json_parameters == expected
|
|
|
|
set_stack.task_done()
|
|
|
|
return True
|
|
|
|
|
|
|
|
bot_name = await get_stack.get()
|
|
|
|
if "language_code" in request_data.json_parameters:
|
|
|
|
assert request_data.json_parameters == {"language_code": bot_name["language_code"]}
|
|
|
|
else:
|
|
|
|
assert request_data.json_parameters == {}
|
|
|
|
get_stack.task_done()
|
|
|
|
return bot_name
|
|
|
|
|
|
|
|
monkeypatch.setattr(bot.request, "post", post)
|
|
|
|
|
|
|
|
# Set the names
|
|
|
|
assert all(
|
|
|
|
await asyncio.gather(
|
|
|
|
bot.set_my_name(default_name),
|
|
|
|
bot.set_my_name(en_name, language_code="en"),
|
|
|
|
bot.set_my_name(de_name, language_code="de"),
|
|
|
|
)
|
|
|
|
)
|
|
|
|
|
|
|
|
# Check that they were set correctly
|
|
|
|
assert await asyncio.gather(
|
|
|
|
bot.get_my_name(), bot.get_my_name("en"), bot.get_my_name("de")
|
|
|
|
) == [
|
|
|
|
BotName(default_name),
|
|
|
|
BotName(en_name),
|
|
|
|
BotName(de_name),
|
|
|
|
]
|
|
|
|
|
|
|
|
# Delete the names
|
|
|
|
assert all(
|
|
|
|
await asyncio.gather(
|
|
|
|
bot.set_my_name(default_name),
|
|
|
|
bot.set_my_name(None, language_code="en"),
|
|
|
|
bot.set_my_name(None, language_code="de"),
|
|
|
|
)
|
|
|
|
)
|
|
|
|
|
|
|
|
# Check that they were deleted correctly
|
|
|
|
assert await asyncio.gather(
|
|
|
|
bot.get_my_name(), bot.get_my_name("en"), bot.get_my_name("de")
|
|
|
|
) == 3 * [BotName(default_name)]
|
|
|
|
|
2024-02-08 17:12:00 +01:00
|
|
|
async def test_set_message_reaction(self, bot, monkeypatch):
|
|
|
|
"""This is here so we can test the convenient conversion we do in the function without
|
|
|
|
having to do multiple requests to Telegram"""
|
|
|
|
|
|
|
|
expected_param = [
|
|
|
|
[{"emoji": ReactionEmoji.THUMBS_UP, "type": "emoji"}],
|
|
|
|
[{"emoji": ReactionEmoji.RED_HEART, "type": "emoji"}],
|
|
|
|
[{"custom_emoji_id": "custom_emoji_1", "type": "custom_emoji"}],
|
|
|
|
[{"custom_emoji_id": "custom_emoji_2", "type": "custom_emoji"}],
|
|
|
|
[{"emoji": ReactionEmoji.THUMBS_DOWN, "type": "emoji"}],
|
|
|
|
[{"custom_emoji_id": "custom_emoji_3", "type": "custom_emoji"}],
|
|
|
|
[
|
|
|
|
{"emoji": ReactionEmoji.RED_HEART, "type": "emoji"},
|
|
|
|
{"custom_emoji_id": "custom_emoji_4", "type": "custom_emoji"},
|
|
|
|
{"emoji": ReactionEmoji.THUMBS_DOWN, "type": "emoji"},
|
|
|
|
{"custom_emoji_id": "custom_emoji_5", "type": "custom_emoji"},
|
|
|
|
],
|
|
|
|
[],
|
|
|
|
]
|
|
|
|
|
|
|
|
amount = 0
|
|
|
|
|
|
|
|
async def post(url, request_data: RequestData, *args, **kwargs):
|
|
|
|
# The mock-post now just fetches the predefined responses from the queues
|
|
|
|
assert request_data.json_parameters["chat_id"] == "1"
|
|
|
|
assert request_data.json_parameters["message_id"] == "2"
|
|
|
|
assert request_data.json_parameters["is_big"]
|
|
|
|
nonlocal amount
|
|
|
|
assert request_data.parameters["reaction"] == expected_param[amount]
|
|
|
|
amount += 1
|
|
|
|
|
|
|
|
monkeypatch.setattr(bot.request, "post", post)
|
|
|
|
await bot.set_message_reaction(1, 2, [ReactionTypeEmoji(ReactionEmoji.THUMBS_UP)], True)
|
|
|
|
await bot.set_message_reaction(1, 2, ReactionTypeEmoji(ReactionEmoji.RED_HEART), True)
|
|
|
|
await bot.set_message_reaction(1, 2, [ReactionTypeCustomEmoji("custom_emoji_1")], True)
|
|
|
|
await bot.set_message_reaction(1, 2, ReactionTypeCustomEmoji("custom_emoji_2"), True)
|
|
|
|
await bot.set_message_reaction(1, 2, ReactionEmoji.THUMBS_DOWN, True)
|
|
|
|
await bot.set_message_reaction(1, 2, "custom_emoji_3", True)
|
|
|
|
await bot.set_message_reaction(
|
|
|
|
1,
|
|
|
|
2,
|
|
|
|
[
|
|
|
|
ReactionTypeEmoji(ReactionEmoji.RED_HEART),
|
|
|
|
ReactionTypeCustomEmoji("custom_emoji_4"),
|
|
|
|
ReactionEmoji.THUMBS_DOWN,
|
|
|
|
ReactionTypeCustomEmoji("custom_emoji_5"),
|
|
|
|
],
|
|
|
|
True,
|
|
|
|
)
|
|
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
|
|
("default_bot", "custom"),
|
|
|
|
[
|
|
|
|
({"parse_mode": ParseMode.HTML}, None),
|
|
|
|
({"parse_mode": ParseMode.HTML}, ParseMode.MARKDOWN_V2),
|
|
|
|
({"parse_mode": None}, ParseMode.MARKDOWN_V2),
|
|
|
|
],
|
|
|
|
indirect=["default_bot"],
|
|
|
|
)
|
|
|
|
async def test_send_message_default_quote_parse_mode(
|
|
|
|
self, default_bot, chat_id, message, custom, monkeypatch
|
|
|
|
):
|
|
|
|
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
|
|
|
|
assert request_data.parameters["reply_parameters"].get("quote_parse_mode") == (
|
|
|
|
custom or default_bot.defaults.quote_parse_mode
|
|
|
|
)
|
|
|
|
return make_message("dummy reply").to_dict()
|
|
|
|
|
|
|
|
kwargs = {"message_id": 1}
|
|
|
|
if custom is not None:
|
|
|
|
kwargs["quote_parse_mode"] = custom
|
|
|
|
|
|
|
|
monkeypatch.setattr(default_bot.request, "post", make_assertion)
|
|
|
|
await default_bot.send_message(
|
|
|
|
chat_id, message, reply_parameters=ReplyParameters(**kwargs)
|
|
|
|
)
|
|
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
|
|
("default_bot", "custom"),
|
|
|
|
[
|
|
|
|
({"parse_mode": ParseMode.HTML}, None),
|
|
|
|
({"parse_mode": ParseMode.HTML}, ParseMode.MARKDOWN_V2),
|
|
|
|
({"parse_mode": None}, ParseMode.MARKDOWN_V2),
|
|
|
|
],
|
|
|
|
indirect=["default_bot"],
|
|
|
|
)
|
|
|
|
async def test_send_poll_default_quote_parse_mode(
|
|
|
|
self, default_bot, chat_id, custom, monkeypatch
|
|
|
|
):
|
|
|
|
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
|
|
|
|
assert request_data.parameters["reply_parameters"].get("quote_parse_mode") == (
|
|
|
|
custom or default_bot.defaults.quote_parse_mode
|
|
|
|
)
|
|
|
|
return make_message("dummy reply").to_dict()
|
|
|
|
|
|
|
|
kwargs = {"message_id": 1}
|
|
|
|
if custom is not None:
|
|
|
|
kwargs["quote_parse_mode"] = custom
|
|
|
|
|
|
|
|
monkeypatch.setattr(default_bot.request, "post", make_assertion)
|
|
|
|
await default_bot.send_poll(
|
|
|
|
chat_id,
|
|
|
|
question="question",
|
|
|
|
options=["option1", "option2"],
|
|
|
|
reply_parameters=ReplyParameters(**kwargs),
|
|
|
|
)
|
|
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
|
|
("default_bot", "custom"),
|
|
|
|
[
|
|
|
|
({"parse_mode": ParseMode.HTML}, None),
|
|
|
|
({"parse_mode": ParseMode.HTML}, ParseMode.MARKDOWN_V2),
|
|
|
|
({"parse_mode": None}, ParseMode.MARKDOWN_V2),
|
|
|
|
],
|
|
|
|
indirect=["default_bot"],
|
|
|
|
)
|
|
|
|
async def test_send_game_default_quote_parse_mode(
|
|
|
|
self, default_bot, chat_id, custom, monkeypatch
|
|
|
|
):
|
|
|
|
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
|
|
|
|
assert request_data.parameters["reply_parameters"].get("quote_parse_mode") == (
|
|
|
|
custom or default_bot.defaults.quote_parse_mode
|
|
|
|
)
|
|
|
|
return make_message("dummy reply").to_dict()
|
|
|
|
|
|
|
|
kwargs = {"message_id": 1}
|
|
|
|
if custom is not None:
|
|
|
|
kwargs["quote_parse_mode"] = custom
|
|
|
|
|
|
|
|
monkeypatch.setattr(default_bot.request, "post", make_assertion)
|
|
|
|
await default_bot.send_game(
|
|
|
|
chat_id, "game_short_name", reply_parameters=ReplyParameters(**kwargs)
|
|
|
|
)
|
|
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
|
|
("default_bot", "custom"),
|
|
|
|
[
|
|
|
|
({"parse_mode": ParseMode.HTML}, None),
|
|
|
|
({"parse_mode": ParseMode.HTML}, ParseMode.MARKDOWN_V2),
|
|
|
|
({"parse_mode": None}, ParseMode.MARKDOWN_V2),
|
|
|
|
],
|
|
|
|
indirect=["default_bot"],
|
|
|
|
)
|
|
|
|
async def test_copy_message_default_quote_parse_mode(
|
|
|
|
self, default_bot, chat_id, custom, monkeypatch
|
|
|
|
):
|
|
|
|
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
|
|
|
|
assert request_data.parameters["reply_parameters"].get("quote_parse_mode") == (
|
|
|
|
custom or default_bot.defaults.quote_parse_mode
|
|
|
|
)
|
|
|
|
return make_message("dummy reply").to_dict()
|
|
|
|
|
|
|
|
kwargs = {"message_id": 1}
|
|
|
|
if custom is not None:
|
|
|
|
kwargs["quote_parse_mode"] = custom
|
|
|
|
|
|
|
|
monkeypatch.setattr(default_bot.request, "post", make_assertion)
|
|
|
|
await default_bot.copy_message(chat_id, 1, 1, reply_parameters=ReplyParameters(**kwargs))
|
|
|
|
|
2024-02-07 22:35:09 +01:00
|
|
|
async def test_do_api_request_camel_case_conversion(self, bot, monkeypatch):
|
|
|
|
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
|
|
|
|
return url.endswith("camelCase")
|
|
|
|
|
|
|
|
monkeypatch.setattr(bot.request, "post", make_assertion)
|
|
|
|
assert await bot.do_api_request("camel_case")
|
|
|
|
|
|
|
|
async def test_do_api_request_media_write_timeout(self, bot, chat_id, monkeypatch):
|
|
|
|
test_flag = None
|
|
|
|
|
|
|
|
class CustomRequest(BaseRequest):
|
|
|
|
async def initialize(self_) -> None:
|
|
|
|
pass
|
|
|
|
|
|
|
|
async def shutdown(self_) -> None:
|
|
|
|
pass
|
|
|
|
|
|
|
|
async def do_request(self_, *args, **kwargs) -> Tuple[int, bytes]:
|
|
|
|
nonlocal test_flag
|
|
|
|
test_flag = (
|
|
|
|
kwargs.get("read_timeout"),
|
|
|
|
kwargs.get("connect_timeout"),
|
|
|
|
kwargs.get("write_timeout"),
|
|
|
|
kwargs.get("pool_timeout"),
|
|
|
|
)
|
|
|
|
return HTTPStatus.OK, b'{"ok": "True", "result": {}}'
|
|
|
|
|
|
|
|
custom_request = CustomRequest()
|
|
|
|
|
|
|
|
bot = Bot(bot.token, request=custom_request)
|
|
|
|
await bot.do_api_request(
|
|
|
|
"send_document",
|
|
|
|
api_kwargs={
|
|
|
|
"chat_id": chat_id,
|
|
|
|
"caption": "test_caption",
|
|
|
|
"document": InputFile(data_file("telegram.png").open("rb")),
|
|
|
|
},
|
|
|
|
)
|
|
|
|
assert test_flag == (
|
|
|
|
DEFAULT_NONE,
|
|
|
|
DEFAULT_NONE,
|
|
|
|
20,
|
|
|
|
DEFAULT_NONE,
|
|
|
|
)
|
|
|
|
|
|
|
|
async def test_do_api_request_default_timezone(self, tz_bot, monkeypatch):
|
|
|
|
until = dtm.datetime(2020, 1, 11, 16, 13)
|
|
|
|
until_timestamp = to_timestamp(until, tzinfo=tz_bot.defaults.tzinfo)
|
|
|
|
|
|
|
|
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
|
|
|
|
data = request_data.parameters
|
|
|
|
chat_id = data["chat_id"] == 2
|
|
|
|
user_id = data["user_id"] == 32
|
|
|
|
until_date = data.get("until_date", until_timestamp) == until_timestamp
|
|
|
|
return chat_id and user_id and until_date
|
|
|
|
|
|
|
|
monkeypatch.setattr(tz_bot.request, "post", make_assertion)
|
|
|
|
|
|
|
|
assert await tz_bot.do_api_request(
|
|
|
|
"banChatMember", api_kwargs={"chat_id": 2, "user_id": 32}
|
|
|
|
)
|
|
|
|
assert await tz_bot.do_api_request(
|
|
|
|
"banChatMember", api_kwargs={"chat_id": 2, "user_id": 32, "until_date": until}
|
|
|
|
)
|
|
|
|
assert await tz_bot.do_api_request(
|
|
|
|
"banChatMember",
|
|
|
|
api_kwargs={"chat_id": 2, "user_id": 32, "until_date": until_timestamp},
|
|
|
|
)
|
|
|
|
|
2022-10-31 09:46:56 +01:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
class TestBotWithRequest:
|
|
|
|
"""
|
|
|
|
Most are executed on tg.ext.ExtBot, as that class only extends the functionality of tg.bot
|
2022-10-31 09:46:56 +01:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
Behavior for init of ExtBot with missing optional dependency cachetools (for CallbackDataCache)
|
|
|
|
is tested in `test_callbackdatacache`
|
|
|
|
"""
|
2015-09-11 01:06:27 +02:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
async def test_invalid_token_server_response(self):
|
|
|
|
with pytest.raises(InvalidToken, match="The token `12` was rejected by the server."):
|
|
|
|
async with ExtBot(token="12"):
|
|
|
|
pass
|
|
|
|
|
|
|
|
async def test_multiple_init_cycles(self, bot):
|
|
|
|
# nothing really to assert - this should just not fail
|
|
|
|
test_bot = Bot(bot.token)
|
|
|
|
async with test_bot:
|
|
|
|
await test_bot.get_me()
|
|
|
|
async with test_bot:
|
|
|
|
await test_bot.get_me()
|
2020-02-08 17:52:23 +01:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
async def test_forward_message(self, bot, chat_id, message):
|
|
|
|
forward_message = await bot.forward_message(
|
|
|
|
chat_id, from_chat_id=chat_id, message_id=message.message_id
|
|
|
|
)
|
2020-10-09 17:22:07 +02:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
assert forward_message.text == message.text
|
2024-02-25 10:34:47 +01:00
|
|
|
assert forward_message.forward_origin.sender_user == message.from_user
|
|
|
|
assert isinstance(forward_message.forward_origin.date, dtm.datetime)
|
2023-02-11 10:45:17 +01:00
|
|
|
|
|
|
|
async def test_forward_protected_message(self, bot, chat_id):
|
|
|
|
tasks = asyncio.gather(
|
|
|
|
bot.send_message(chat_id, "cant forward me", protect_content=True),
|
|
|
|
bot.send_message(chat_id, "forward me", protect_content=False),
|
2020-10-09 17:22:07 +02:00
|
|
|
)
|
2023-02-11 10:45:17 +01:00
|
|
|
to_forward_protected, to_forward_unprotected = await tasks
|
|
|
|
|
|
|
|
assert to_forward_protected.has_protected_content
|
|
|
|
assert not to_forward_unprotected.has_protected_content
|
|
|
|
|
|
|
|
forwarded_but_now_protected = await to_forward_unprotected.forward(
|
|
|
|
chat_id, protect_content=True
|
|
|
|
)
|
|
|
|
assert forwarded_but_now_protected.has_protected_content
|
|
|
|
|
|
|
|
tasks = asyncio.gather(
|
|
|
|
to_forward_protected.forward(chat_id),
|
|
|
|
forwarded_but_now_protected.forward(chat_id),
|
|
|
|
return_exceptions=True,
|
|
|
|
)
|
|
|
|
result = await tasks
|
|
|
|
assert all("can't be forwarded" in str(exc) for exc in result)
|
|
|
|
|
2024-02-08 17:12:00 +01:00
|
|
|
async def test_forward_messages(self, bot, chat_id):
|
|
|
|
tasks = asyncio.gather(
|
|
|
|
bot.send_message(chat_id, text="will be forwarded"),
|
|
|
|
bot.send_message(chat_id, text="will be forwarded"),
|
|
|
|
)
|
|
|
|
|
|
|
|
msg1, msg2 = await tasks
|
|
|
|
|
|
|
|
forward_messages = await bot.forward_messages(
|
2024-02-25 10:34:47 +01:00
|
|
|
chat_id, from_chat_id=chat_id, message_ids=sorted((msg1.message_id, msg2.message_id))
|
2024-02-08 17:12:00 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
assert isinstance(forward_messages, tuple)
|
|
|
|
|
|
|
|
tasks = asyncio.gather(
|
|
|
|
bot.send_message(
|
|
|
|
chat_id, "temp 1", reply_to_message_id=forward_messages[0].message_id
|
|
|
|
),
|
|
|
|
bot.send_message(
|
|
|
|
chat_id, "temp 2", reply_to_message_id=forward_messages[1].message_id
|
|
|
|
),
|
|
|
|
)
|
|
|
|
|
|
|
|
temp_msg1, temp_msg2 = await tasks
|
|
|
|
forward_msg1 = temp_msg1.reply_to_message
|
|
|
|
forward_msg2 = temp_msg2.reply_to_message
|
|
|
|
|
|
|
|
assert forward_msg1.text == msg1.text
|
2024-02-25 10:34:47 +01:00
|
|
|
assert forward_msg1.forward_origin.sender_user == msg1.from_user
|
|
|
|
assert isinstance(forward_msg1.forward_origin.date, dtm.datetime)
|
2024-02-08 17:12:00 +01:00
|
|
|
|
|
|
|
assert forward_msg2.text == msg2.text
|
2024-02-25 10:34:47 +01:00
|
|
|
assert forward_msg2.forward_origin.sender_user == msg2.from_user
|
|
|
|
assert isinstance(forward_msg2.forward_origin.date, dtm.datetime)
|
2024-02-08 17:12:00 +01:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
async def test_delete_message(self, bot, chat_id):
|
|
|
|
message = await bot.send_message(chat_id, text="will be deleted")
|
|
|
|
await asyncio.sleep(2)
|
|
|
|
|
|
|
|
assert await bot.delete_message(chat_id=chat_id, message_id=message.message_id) is True
|
|
|
|
|
|
|
|
async def test_delete_message_old_message(self, bot, chat_id):
|
|
|
|
with pytest.raises(BadRequest):
|
|
|
|
# Considering that the first message is old enough
|
|
|
|
await bot.delete_message(chat_id=chat_id, message_id=1)
|
|
|
|
|
|
|
|
# send_photo, send_audio, send_document, send_sticker, send_video, send_voice, send_video_note,
|
2024-02-08 17:12:00 +01:00
|
|
|
# send_media_group, send_animation, get_user_chat_boosts are tested in their respective
|
|
|
|
# test modules. No need to duplicate here.
|
|
|
|
|
|
|
|
async def test_delete_messages(self, bot, chat_id):
|
|
|
|
msg1 = await bot.send_message(chat_id, text="will be deleted")
|
|
|
|
msg2 = await bot.send_message(chat_id, text="will be deleted")
|
|
|
|
await asyncio.sleep(2)
|
|
|
|
|
|
|
|
assert await bot.delete_messages(chat_id=chat_id, message_ids=(msg1.id, msg2.id)) is True
|
2023-02-11 10:45:17 +01:00
|
|
|
|
|
|
|
async def test_send_venue(self, bot, chat_id):
|
|
|
|
longitude = -46.788279
|
|
|
|
latitude = -23.691288
|
|
|
|
title = "title"
|
|
|
|
address = "address"
|
|
|
|
foursquare_id = "foursquare id"
|
|
|
|
foursquare_type = "foursquare type"
|
|
|
|
google_place_id = "google_place id"
|
|
|
|
google_place_type = "google_place type"
|
|
|
|
|
|
|
|
tasks = asyncio.gather(
|
|
|
|
*(
|
|
|
|
bot.send_venue(
|
|
|
|
chat_id=chat_id,
|
|
|
|
title=title,
|
|
|
|
address=address,
|
|
|
|
latitude=latitude,
|
|
|
|
longitude=longitude,
|
|
|
|
protect_content=True,
|
|
|
|
**i,
|
2022-10-31 09:46:56 +01:00
|
|
|
)
|
2023-02-11 10:45:17 +01:00
|
|
|
for i in (
|
|
|
|
{"foursquare_id": foursquare_id, "foursquare_type": foursquare_type},
|
|
|
|
{"google_place_id": google_place_id, "google_place_type": google_place_type},
|
2022-10-31 09:46:56 +01:00
|
|
|
)
|
2023-02-11 10:45:17 +01:00
|
|
|
),
|
|
|
|
)
|
2020-02-08 17:52:23 +01:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
message, message2 = await tasks
|
|
|
|
assert message.venue
|
|
|
|
assert message.venue.title == title
|
|
|
|
assert message.venue.address == address
|
|
|
|
assert message.venue.location.latitude == latitude
|
|
|
|
assert message.venue.location.longitude == longitude
|
|
|
|
assert message.venue.foursquare_id == foursquare_id
|
|
|
|
assert message.venue.foursquare_type == foursquare_type
|
|
|
|
assert message.venue.google_place_id is None
|
|
|
|
assert message.venue.google_place_type is None
|
|
|
|
assert message.has_protected_content
|
2020-02-08 17:52:23 +01:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
assert message2.venue
|
|
|
|
assert message2.venue.title == title
|
|
|
|
assert message2.venue.address == address
|
|
|
|
assert message2.venue.location.latitude == latitude
|
|
|
|
assert message2.venue.location.longitude == longitude
|
|
|
|
assert message2.venue.google_place_id == google_place_id
|
|
|
|
assert message2.venue.google_place_type == google_place_type
|
|
|
|
assert message2.venue.foursquare_id is None
|
|
|
|
assert message2.venue.foursquare_type is None
|
|
|
|
assert message2.has_protected_content
|
|
|
|
|
|
|
|
async def test_send_contact(self, bot, chat_id):
|
|
|
|
phone_number = "+11234567890"
|
|
|
|
first_name = "Leandro"
|
|
|
|
last_name = "Toledo"
|
|
|
|
message = await bot.send_contact(
|
|
|
|
chat_id=chat_id,
|
|
|
|
phone_number=phone_number,
|
|
|
|
first_name=first_name,
|
|
|
|
last_name=last_name,
|
|
|
|
protect_content=True,
|
|
|
|
)
|
|
|
|
|
|
|
|
assert message.contact
|
|
|
|
assert message.contact.phone_number == phone_number
|
|
|
|
assert message.contact.first_name == first_name
|
|
|
|
assert message.contact.last_name == last_name
|
|
|
|
assert message.has_protected_content
|
|
|
|
|
|
|
|
async def test_send_chat_action_all_args(self, bot, chat_id, monkeypatch):
|
|
|
|
async def make_assertion(*args, **_):
|
|
|
|
kwargs = args[1]
|
|
|
|
return (
|
|
|
|
kwargs["chat_id"] == chat_id
|
|
|
|
and kwargs["action"] == "action"
|
|
|
|
and kwargs["message_thread_id"] == 1
|
|
|
|
)
|
|
|
|
|
|
|
|
monkeypatch.setattr(bot, "_post", make_assertion)
|
|
|
|
assert await bot.send_chat_action(chat_id, "action", 1)
|
|
|
|
|
|
|
|
# TODO: Add bot to group to test polls too
|
|
|
|
@pytest.mark.parametrize(
|
|
|
|
"reply_markup",
|
|
|
|
[
|
|
|
|
None,
|
|
|
|
InlineKeyboardMarkup.from_button(
|
|
|
|
InlineKeyboardButton(text="text", callback_data="data")
|
2022-10-31 09:46:56 +01:00
|
|
|
),
|
2023-02-11 10:45:17 +01:00
|
|
|
InlineKeyboardMarkup.from_button(
|
|
|
|
InlineKeyboardButton(text="text", callback_data="data")
|
|
|
|
).to_dict(),
|
|
|
|
],
|
|
|
|
)
|
|
|
|
async def test_send_and_stop_poll(self, bot, super_group_id, reply_markup):
|
|
|
|
question = "Is this a test?"
|
|
|
|
answers = ["Yes", "No", "Maybe"]
|
|
|
|
explanation = "[Here is a link](https://google.com)"
|
|
|
|
explanation_entities = [
|
|
|
|
MessageEntity(MessageEntity.TEXT_LINK, 0, 14, url="https://google.com")
|
2020-10-09 17:22:07 +02:00
|
|
|
]
|
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
poll_task = asyncio.create_task(
|
|
|
|
bot.send_poll(
|
|
|
|
chat_id=super_group_id,
|
|
|
|
question=question,
|
|
|
|
options=answers,
|
|
|
|
is_anonymous=False,
|
|
|
|
allows_multiple_answers=True,
|
|
|
|
read_timeout=60,
|
|
|
|
protect_content=True,
|
|
|
|
)
|
2020-10-09 17:22:07 +02:00
|
|
|
)
|
2023-02-11 10:45:17 +01:00
|
|
|
quiz_task = asyncio.create_task(
|
|
|
|
bot.send_poll(
|
|
|
|
chat_id=super_group_id,
|
|
|
|
question=question,
|
|
|
|
options=answers,
|
|
|
|
type=Poll.QUIZ,
|
|
|
|
correct_option_id=2,
|
|
|
|
is_closed=True,
|
|
|
|
explanation=explanation,
|
|
|
|
explanation_parse_mode=ParseMode.MARKDOWN_V2,
|
|
|
|
)
|
|
|
|
)
|
|
|
|
|
|
|
|
message = await poll_task
|
|
|
|
assert message.poll
|
|
|
|
assert message.poll.question == question
|
|
|
|
assert message.poll.options[0].text == answers[0]
|
|
|
|
assert message.poll.options[1].text == answers[1]
|
|
|
|
assert message.poll.options[2].text == answers[2]
|
|
|
|
assert not message.poll.is_anonymous
|
|
|
|
assert message.poll.allows_multiple_answers
|
|
|
|
assert not message.poll.is_closed
|
|
|
|
assert message.poll.type == Poll.REGULAR
|
|
|
|
assert message.has_protected_content
|
|
|
|
|
|
|
|
# Since only the poll and not the complete message is returned, we can't check that the
|
|
|
|
# reply_markup is correct. So we just test that sending doesn't give an error.
|
|
|
|
poll = await bot.stop_poll(
|
|
|
|
chat_id=super_group_id,
|
|
|
|
message_id=message.message_id,
|
|
|
|
reply_markup=reply_markup,
|
|
|
|
read_timeout=60,
|
|
|
|
)
|
|
|
|
assert isinstance(poll, Poll)
|
|
|
|
assert poll.is_closed
|
|
|
|
assert poll.options[0].text == answers[0]
|
|
|
|
assert poll.options[0].voter_count == 0
|
|
|
|
assert poll.options[1].text == answers[1]
|
|
|
|
assert poll.options[1].voter_count == 0
|
|
|
|
assert poll.options[2].text == answers[2]
|
|
|
|
assert poll.options[2].voter_count == 0
|
|
|
|
assert poll.question == question
|
|
|
|
assert poll.total_voter_count == 0
|
2020-02-08 17:52:23 +01:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
message_quiz = await quiz_task
|
|
|
|
assert message_quiz.poll.correct_option_id == 2
|
|
|
|
assert message_quiz.poll.type == Poll.QUIZ
|
|
|
|
assert message_quiz.poll.is_closed
|
|
|
|
assert message_quiz.poll.explanation == "Here is a link"
|
|
|
|
assert message_quiz.poll.explanation_entities == tuple(explanation_entities)
|
2023-03-25 19:18:04 +01:00
|
|
|
assert poll_task.done()
|
|
|
|
assert quiz_task.done()
|
2020-10-09 17:22:07 +02:00
|
|
|
|
|
|
|
@pytest.mark.parametrize(
|
2023-03-25 19:18:04 +01:00
|
|
|
("open_period", "close_date"), [(5, None), (None, True)], ids=["open_period", "close_date"]
|
2020-10-09 17:22:07 +02:00
|
|
|
)
|
2023-02-11 10:45:17 +01:00
|
|
|
async def test_send_open_period(self, bot, super_group_id, open_period, close_date):
|
|
|
|
question = "Is this a test?"
|
|
|
|
answers = ["Yes", "No", "Maybe"]
|
|
|
|
reply_markup = InlineKeyboardMarkup.from_button(
|
|
|
|
InlineKeyboardButton(text="text", callback_data="data")
|
|
|
|
)
|
2020-09-27 14:11:49 +02:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
if close_date:
|
|
|
|
close_date = dtm.datetime.utcnow() + dtm.timedelta(seconds=5.05)
|
2020-09-27 14:11:49 +02:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
message = await bot.send_poll(
|
|
|
|
chat_id=super_group_id,
|
|
|
|
question=question,
|
|
|
|
options=answers,
|
|
|
|
is_anonymous=False,
|
|
|
|
allows_multiple_answers=True,
|
|
|
|
read_timeout=60,
|
|
|
|
open_period=open_period,
|
|
|
|
close_date=close_date,
|
|
|
|
)
|
|
|
|
await asyncio.sleep(5.1)
|
|
|
|
new_message = await bot.edit_message_reply_markup(
|
|
|
|
chat_id=super_group_id,
|
|
|
|
message_id=message.message_id,
|
|
|
|
reply_markup=reply_markup,
|
|
|
|
read_timeout=60,
|
2022-04-24 12:38:09 +02:00
|
|
|
)
|
2023-02-11 10:45:17 +01:00
|
|
|
assert new_message.poll.id == message.poll.id
|
|
|
|
assert new_message.poll.is_closed
|
2020-09-27 14:11:49 +02:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
async def test_send_close_date_default_tz(self, tz_bot, super_group_id):
|
|
|
|
question = "Is this a test?"
|
|
|
|
answers = ["Yes", "No", "Maybe"]
|
|
|
|
reply_markup = InlineKeyboardMarkup.from_button(
|
|
|
|
InlineKeyboardButton(text="text", callback_data="data")
|
|
|
|
)
|
2020-09-27 14:11:49 +02:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
aware_close_date = dtm.datetime.now(tz=tz_bot.defaults.tzinfo) + dtm.timedelta(seconds=5)
|
|
|
|
close_date = aware_close_date.replace(tzinfo=None)
|
2020-09-27 14:11:49 +02:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
msg = await tz_bot.send_poll( # The timezone returned from this is always converted to UTC
|
|
|
|
chat_id=super_group_id,
|
|
|
|
question=question,
|
|
|
|
options=answers,
|
|
|
|
close_date=close_date,
|
|
|
|
read_timeout=60,
|
|
|
|
)
|
|
|
|
msg.poll._unfreeze()
|
|
|
|
# Sometimes there can be a few seconds delay, so don't let the test fail due to that-
|
|
|
|
msg.poll.close_date = msg.poll.close_date.astimezone(aware_close_date.tzinfo)
|
|
|
|
assert abs(msg.poll.close_date - aware_close_date) <= dtm.timedelta(seconds=5)
|
2020-09-27 14:11:49 +02:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
await asyncio.sleep(5.1)
|
2020-09-27 14:11:49 +02:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
new_message = await tz_bot.edit_message_reply_markup(
|
|
|
|
chat_id=super_group_id,
|
|
|
|
message_id=msg.message_id,
|
|
|
|
reply_markup=reply_markup,
|
|
|
|
read_timeout=60,
|
|
|
|
)
|
|
|
|
assert new_message.poll.id == msg.poll.id
|
|
|
|
assert new_message.poll.is_closed
|
2020-09-27 14:11:49 +02:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
async def test_send_poll_explanation_entities(self, bot, chat_id):
|
|
|
|
test_string = "Italic Bold Code"
|
|
|
|
entities = [
|
|
|
|
MessageEntity(MessageEntity.ITALIC, 0, 6),
|
|
|
|
MessageEntity(MessageEntity.ITALIC, 7, 4),
|
|
|
|
MessageEntity(MessageEntity.ITALIC, 12, 4),
|
|
|
|
]
|
|
|
|
message = await bot.send_poll(
|
|
|
|
chat_id,
|
|
|
|
"question",
|
|
|
|
options=["a", "b"],
|
|
|
|
correct_option_id=0,
|
|
|
|
type=Poll.QUIZ,
|
|
|
|
explanation=test_string,
|
|
|
|
explanation_entities=entities,
|
|
|
|
)
|
2020-09-27 14:11:49 +02:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
assert message.poll.explanation == test_string
|
|
|
|
assert message.poll.explanation_entities == tuple(entities)
|
2020-09-27 14:11:49 +02:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
@pytest.mark.parametrize("default_bot", [{"parse_mode": "Markdown"}], indirect=True)
|
|
|
|
async def test_send_poll_default_parse_mode(self, default_bot, super_group_id):
|
|
|
|
explanation = "Italic Bold Code"
|
|
|
|
explanation_markdown = "_Italic_ *Bold* `Code`"
|
|
|
|
question = "Is this a test?"
|
|
|
|
answers = ["Yes", "No", "Maybe"]
|
2020-09-27 14:11:49 +02:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
tasks = asyncio.gather(
|
|
|
|
*(
|
|
|
|
default_bot.send_poll(
|
|
|
|
chat_id=super_group_id,
|
|
|
|
question=question,
|
|
|
|
options=answers,
|
|
|
|
type=Poll.QUIZ,
|
|
|
|
correct_option_id=2,
|
|
|
|
is_closed=True,
|
|
|
|
explanation=explanation_markdown,
|
|
|
|
**i,
|
|
|
|
)
|
|
|
|
for i in ({}, {"explanation_parse_mode": None}, {"explanation_parse_mode": "HTML"})
|
|
|
|
),
|
|
|
|
)
|
|
|
|
message1, message2, message3 = await tasks
|
|
|
|
assert message1.poll.explanation == explanation
|
|
|
|
assert message1.poll.explanation_entities == (
|
|
|
|
MessageEntity(MessageEntity.ITALIC, 0, 6),
|
|
|
|
MessageEntity(MessageEntity.BOLD, 7, 4),
|
|
|
|
MessageEntity(MessageEntity.CODE, 12, 4),
|
|
|
|
)
|
|
|
|
|
|
|
|
assert message2.poll.explanation == explanation_markdown
|
|
|
|
assert message2.poll.explanation_entities == ()
|
|
|
|
|
|
|
|
assert message3.poll.explanation == explanation_markdown
|
|
|
|
assert message3.poll.explanation_entities == ()
|
|
|
|
|
|
|
|
@pytest.mark.parametrize(
|
2023-03-25 19:18:04 +01:00
|
|
|
("default_bot", "custom"),
|
2023-02-11 10:45:17 +01:00
|
|
|
[
|
|
|
|
({"allow_sending_without_reply": True}, None),
|
|
|
|
({"allow_sending_without_reply": False}, None),
|
|
|
|
({"allow_sending_without_reply": False}, True),
|
|
|
|
],
|
|
|
|
indirect=["default_bot"],
|
|
|
|
)
|
|
|
|
async def test_send_poll_default_allow_sending_without_reply(
|
|
|
|
self, default_bot, chat_id, custom
|
|
|
|
):
|
|
|
|
question = "Is this a test?"
|
|
|
|
answers = ["Yes", "No", "Maybe"]
|
|
|
|
reply_to_message = await default_bot.send_message(chat_id, "test")
|
|
|
|
await reply_to_message.delete()
|
|
|
|
if custom is not None:
|
|
|
|
message = await default_bot.send_poll(
|
|
|
|
chat_id,
|
|
|
|
question=question,
|
|
|
|
options=answers,
|
|
|
|
allow_sending_without_reply=custom,
|
|
|
|
reply_to_message_id=reply_to_message.message_id,
|
|
|
|
)
|
|
|
|
assert message.reply_to_message is None
|
|
|
|
elif default_bot.defaults.allow_sending_without_reply:
|
|
|
|
message = await default_bot.send_poll(
|
|
|
|
chat_id,
|
|
|
|
question=question,
|
|
|
|
options=answers,
|
|
|
|
reply_to_message_id=reply_to_message.message_id,
|
|
|
|
)
|
|
|
|
assert message.reply_to_message is None
|
|
|
|
else:
|
2023-11-11 11:35:23 +01:00
|
|
|
with pytest.raises(BadRequest, match="Message to reply not found"):
|
2023-02-11 10:45:17 +01:00
|
|
|
await default_bot.send_poll(
|
|
|
|
chat_id,
|
|
|
|
question=question,
|
|
|
|
options=answers,
|
|
|
|
reply_to_message_id=reply_to_message.message_id,
|
|
|
|
)
|
|
|
|
|
|
|
|
@pytest.mark.parametrize("default_bot", [{"protect_content": True}], indirect=True)
|
|
|
|
async def test_send_poll_default_protect_content(self, chat_id, default_bot):
|
|
|
|
tasks = asyncio.gather(
|
|
|
|
default_bot.send_poll(chat_id, "Test", ["1", "2"]),
|
|
|
|
default_bot.send_poll(chat_id, "test", ["1", "2"], protect_content=False),
|
|
|
|
)
|
|
|
|
protected_poll, unprotect_poll = await tasks
|
|
|
|
assert protected_poll.has_protected_content
|
|
|
|
assert not unprotect_poll.has_protected_content
|
|
|
|
|
2023-03-25 19:18:04 +01:00
|
|
|
@pytest.mark.parametrize("emoji", [*Dice.ALL_EMOJI, None])
|
2023-02-11 10:45:17 +01:00
|
|
|
async def test_send_dice(self, bot, chat_id, emoji):
|
|
|
|
message = await bot.send_dice(chat_id, emoji=emoji, protect_content=True)
|
|
|
|
|
|
|
|
assert message.dice
|
|
|
|
assert message.has_protected_content
|
|
|
|
if emoji is None:
|
|
|
|
assert message.dice.emoji == Dice.DICE
|
|
|
|
else:
|
|
|
|
assert message.dice.emoji == emoji
|
|
|
|
|
|
|
|
@pytest.mark.parametrize(
|
2023-03-25 19:18:04 +01:00
|
|
|
("default_bot", "custom"),
|
2023-02-11 10:45:17 +01:00
|
|
|
[
|
|
|
|
({"allow_sending_without_reply": True}, None),
|
|
|
|
({"allow_sending_without_reply": False}, None),
|
|
|
|
({"allow_sending_without_reply": False}, True),
|
|
|
|
],
|
|
|
|
indirect=["default_bot"],
|
|
|
|
)
|
|
|
|
async def test_send_dice_default_allow_sending_without_reply(
|
|
|
|
self, default_bot, chat_id, custom
|
|
|
|
):
|
|
|
|
reply_to_message = await default_bot.send_message(chat_id, "test")
|
|
|
|
await reply_to_message.delete()
|
|
|
|
if custom is not None:
|
|
|
|
message = await default_bot.send_dice(
|
|
|
|
chat_id,
|
|
|
|
allow_sending_without_reply=custom,
|
|
|
|
reply_to_message_id=reply_to_message.message_id,
|
|
|
|
)
|
|
|
|
assert message.reply_to_message is None
|
|
|
|
elif default_bot.defaults.allow_sending_without_reply:
|
|
|
|
message = await default_bot.send_dice(
|
|
|
|
chat_id,
|
|
|
|
reply_to_message_id=reply_to_message.message_id,
|
|
|
|
)
|
|
|
|
assert message.reply_to_message is None
|
|
|
|
else:
|
2023-11-11 11:35:23 +01:00
|
|
|
with pytest.raises(BadRequest, match="Message to reply not found"):
|
2023-02-11 10:45:17 +01:00
|
|
|
await default_bot.send_dice(
|
|
|
|
chat_id, reply_to_message_id=reply_to_message.message_id
|
|
|
|
)
|
2020-09-27 14:11:49 +02:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
@pytest.mark.parametrize("default_bot", [{"protect_content": True}], indirect=True)
|
|
|
|
async def test_send_dice_default_protect_content(self, chat_id, default_bot):
|
|
|
|
tasks = asyncio.gather(
|
|
|
|
default_bot.send_dice(chat_id), default_bot.send_dice(chat_id, protect_content=False)
|
2022-04-24 12:38:09 +02:00
|
|
|
)
|
2023-02-11 10:45:17 +01:00
|
|
|
protected_dice, unprotected_dice = await tasks
|
|
|
|
assert protected_dice.has_protected_content
|
|
|
|
assert not unprotected_dice.has_protected_content
|
2020-09-27 14:11:49 +02:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
@pytest.mark.parametrize("chat_action", list(ChatAction))
|
|
|
|
async def test_send_chat_action(self, bot, chat_id, chat_action):
|
|
|
|
assert await bot.send_chat_action(chat_id, chat_action)
|
2020-09-27 14:11:49 +02:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
async def test_wrong_chat_action(self, bot, chat_id):
|
|
|
|
with pytest.raises(BadRequest, match="Wrong parameter action"):
|
|
|
|
await bot.send_chat_action(chat_id, "unknown action")
|
2020-09-27 14:11:49 +02:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
async def test_answer_inline_query_current_offset_error(self, bot, inline_results):
|
2023-09-22 18:19:21 +02:00
|
|
|
with pytest.raises(ValueError, match="`current_offset` and `next_offset`"):
|
2023-02-11 10:45:17 +01:00
|
|
|
await bot.answer_inline_query(
|
|
|
|
1234, results=inline_results, next_offset=42, current_offset=51
|
|
|
|
)
|
2020-09-27 14:11:49 +02:00
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
async def test_get_user_profile_photos(self, bot, chat_id):
|
|
|
|
user_profile_photos = await bot.get_user_profile_photos(chat_id)
|
2018-10-14 11:39:35 +02:00
|
|
|
assert user_profile_photos.photos[0][0].file_size == 5403
|
2015-09-11 01:06:27 +02:00
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
async def test_get_one_user_profile_photo(self, bot, chat_id):
|
|
|
|
user_profile_photos = await bot.get_user_profile_photos(chat_id, offset=0, limit=1)
|
2023-02-11 10:45:17 +01:00
|
|
|
assert user_profile_photos.total_count == 1
|
2018-10-14 11:39:35 +02:00
|
|
|
assert user_profile_photos.photos[0][0].file_size == 5403
|
2017-08-11 23:58:41 +02:00
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
async def test_edit_message_text(self, bot, message):
|
|
|
|
message = await bot.edit_message_text(
|
2022-05-05 17:40:22 +02:00
|
|
|
text="new_text",
|
2020-10-09 17:22:07 +02:00
|
|
|
chat_id=message.chat_id,
|
|
|
|
message_id=message.message_id,
|
2022-05-05 17:40:22 +02:00
|
|
|
parse_mode="HTML",
|
2020-10-09 17:22:07 +02:00
|
|
|
disable_web_page_preview=True,
|
|
|
|
)
|
2017-08-11 23:58:41 +02:00
|
|
|
|
2022-05-05 17:40:22 +02:00
|
|
|
assert message.text == "new_text"
|
2016-05-26 02:15:17 +02:00
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
async def test_edit_message_text_entities(self, bot, message):
|
2022-05-05 17:40:22 +02:00
|
|
|
test_string = "Italic Bold Code"
|
2020-11-29 16:20:46 +01:00
|
|
|
entities = [
|
|
|
|
MessageEntity(MessageEntity.ITALIC, 0, 6),
|
|
|
|
MessageEntity(MessageEntity.ITALIC, 7, 4),
|
|
|
|
MessageEntity(MessageEntity.ITALIC, 12, 4),
|
|
|
|
]
|
2022-04-24 12:38:09 +02:00
|
|
|
message = await bot.edit_message_text(
|
2020-11-29 16:20:46 +01:00
|
|
|
text=test_string,
|
|
|
|
chat_id=message.chat_id,
|
|
|
|
message_id=message.message_id,
|
|
|
|
entities=entities,
|
|
|
|
)
|
|
|
|
|
|
|
|
assert message.text == test_string
|
2022-12-15 15:00:36 +01:00
|
|
|
assert message.entities == tuple(entities)
|
2020-11-29 16:20:46 +01:00
|
|
|
|
2022-05-05 17:40:22 +02:00
|
|
|
@pytest.mark.parametrize("default_bot", [{"parse_mode": "Markdown"}], indirect=True)
|
2022-04-24 12:38:09 +02:00
|
|
|
async def test_edit_message_text_default_parse_mode(self, default_bot, message):
|
2022-05-05 17:40:22 +02:00
|
|
|
test_string = "Italic Bold Code"
|
|
|
|
test_markdown_string = "_Italic_ *Bold* `Code`"
|
2020-02-06 11:22:56 +01:00
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
message = await default_bot.edit_message_text(
|
2020-10-09 17:22:07 +02:00
|
|
|
text=test_markdown_string,
|
|
|
|
chat_id=message.chat_id,
|
|
|
|
message_id=message.message_id,
|
|
|
|
disable_web_page_preview=True,
|
|
|
|
)
|
2020-02-06 11:22:56 +01:00
|
|
|
assert message.text_markdown == test_markdown_string
|
|
|
|
assert message.text == test_string
|
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
message = await default_bot.edit_message_text(
|
2020-10-09 17:22:07 +02:00
|
|
|
text=test_markdown_string,
|
|
|
|
chat_id=message.chat_id,
|
|
|
|
message_id=message.message_id,
|
|
|
|
parse_mode=None,
|
|
|
|
disable_web_page_preview=True,
|
|
|
|
)
|
2020-02-06 11:22:56 +01:00
|
|
|
assert message.text == test_markdown_string
|
|
|
|
assert message.text_markdown == escape_markdown(test_markdown_string)
|
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
message = await default_bot.edit_message_text(
|
2020-10-09 17:22:07 +02:00
|
|
|
text=test_markdown_string,
|
|
|
|
chat_id=message.chat_id,
|
|
|
|
message_id=message.message_id,
|
|
|
|
disable_web_page_preview=True,
|
|
|
|
)
|
2022-04-24 12:38:09 +02:00
|
|
|
message = await default_bot.edit_message_text(
|
2020-10-09 17:22:07 +02:00
|
|
|
text=test_markdown_string,
|
|
|
|
chat_id=message.chat_id,
|
|
|
|
message_id=message.message_id,
|
2022-05-05 17:40:22 +02:00
|
|
|
parse_mode="HTML",
|
2020-10-09 17:22:07 +02:00
|
|
|
disable_web_page_preview=True,
|
|
|
|
)
|
2020-02-06 11:22:56 +01:00
|
|
|
assert message.text == test_markdown_string
|
|
|
|
assert message.text_markdown == escape_markdown(test_markdown_string)
|
|
|
|
|
2022-05-05 17:40:22 +02:00
|
|
|
@pytest.mark.skip(reason="need reference to an inline message")
|
2022-04-24 12:38:09 +02:00
|
|
|
async def test_edit_message_text_inline(self):
|
2017-08-11 23:58:41 +02:00
|
|
|
pass
|
2016-05-26 03:09:18 +02:00
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
async def test_edit_message_caption(self, bot, media_message):
|
|
|
|
message = await bot.edit_message_caption(
|
2022-05-05 17:40:22 +02:00
|
|
|
caption="new_caption",
|
2020-10-09 17:22:07 +02:00
|
|
|
chat_id=media_message.chat_id,
|
|
|
|
message_id=media_message.message_id,
|
|
|
|
)
|
2016-05-25 01:31:10 +02:00
|
|
|
|
2022-05-05 17:40:22 +02:00
|
|
|
assert message.caption == "new_caption"
|
2017-08-11 23:58:41 +02:00
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
async def test_edit_message_caption_entities(self, bot, media_message):
|
2022-05-05 17:40:22 +02:00
|
|
|
test_string = "Italic Bold Code"
|
2020-11-29 16:20:46 +01:00
|
|
|
entities = [
|
|
|
|
MessageEntity(MessageEntity.ITALIC, 0, 6),
|
|
|
|
MessageEntity(MessageEntity.ITALIC, 7, 4),
|
|
|
|
MessageEntity(MessageEntity.ITALIC, 12, 4),
|
|
|
|
]
|
2022-04-24 12:38:09 +02:00
|
|
|
message = await bot.edit_message_caption(
|
2020-11-29 16:20:46 +01:00
|
|
|
caption=test_string,
|
|
|
|
chat_id=media_message.chat_id,
|
|
|
|
message_id=media_message.message_id,
|
|
|
|
caption_entities=entities,
|
|
|
|
)
|
|
|
|
|
|
|
|
assert message.caption == test_string
|
2022-12-15 15:00:36 +01:00
|
|
|
assert message.caption_entities == tuple(entities)
|
2020-11-29 16:20:46 +01:00
|
|
|
|
Bot API 4.0 (#1168)
Telegram Passport (#1174):
- Add full support for telegram passport.
- New types: PassportData, PassportFile, EncryptedPassportElement, EncryptedCredentials, PassportElementError, PassportElementErrorDataField, PassportElementErrorFrontSide, PassportElementErrorReverseSide, PassportElementErrorSelfie, PassportElementErrorFile and PassportElementErrorFiles.
- New bot method: set_passport_data_errors
- New filter: Filters.passport_data
- Field passport_data field on Message
- PassportData is automagically decrypted when you specify your private key when creating Updater or Bot.
- PassportFiles is also automagically decrypted as you download/retrieve them.
- See new passportbot.py example for details on how to use, or go to our telegram passport wiki page for more info
- NOTE: Passport decryption requires new dependency `cryptography`.
Inputfile rework (#1184):
- Change how Inputfile is handled internally
- This allows support for specifying the thumbnails of photos and videos using the thumb= argument in the different send_ methods.
- Also allows Bot.send_media_group to actually finally send more than one media.
- Add thumb to Audio, Video and Videonote
- Add Bot.edit_message_media together with InputMediaAnimation, InputMediaAudio, and inputMediaDocument.
Other Bot API 4.0 changes:
- Add forusquare_type to Venue, InlineQueryResultVenue, InputVenueMessageContent, and Bot.send_venue. (#1170)
- Add vCard support by adding vcard field to Contact, InlineQueryResultContact, InputContactMessageContent, and Bot.send_contact. (#1166)
- Support new message entities: CASHTAG and PHONE_NUMBER. (#1179)
- Cashtag seems to be things like $USD and $GBP, but it seems telegram doesn't currently send them to bots.
- Phone number also seems to have limited support for now
- Add Bot.send_animation, add width, height, and duration to Animation, and add Filters.animation. (#1172)
Co-authored-by: Jasmin Bom <jsmnbom@gmail.com>
Co-authored-by: code1mountain <32801117+code1mountain@users.noreply.github.com>
Co-authored-by: Eldinnie <pieter.schutz+github@gmail.com>
Co-authored-by: mathefreak1 <mathefreak@hi2.in>
2018-08-29 14:18:58 +02:00
|
|
|
# edit_message_media is tested in test_inputmedia
|
|
|
|
|
2022-05-05 17:40:22 +02:00
|
|
|
@pytest.mark.parametrize("default_bot", [{"parse_mode": "Markdown"}], indirect=True)
|
2022-04-24 12:38:09 +02:00
|
|
|
async def test_edit_message_caption_default_parse_mode(self, default_bot, media_message):
|
2022-05-05 17:40:22 +02:00
|
|
|
test_string = "Italic Bold Code"
|
|
|
|
test_markdown_string = "_Italic_ *Bold* `Code`"
|
2020-02-06 11:22:56 +01:00
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
message = await default_bot.edit_message_caption(
|
2020-10-09 17:22:07 +02:00
|
|
|
caption=test_markdown_string,
|
|
|
|
chat_id=media_message.chat_id,
|
|
|
|
message_id=media_message.message_id,
|
|
|
|
)
|
2020-02-06 11:22:56 +01:00
|
|
|
assert message.caption_markdown == test_markdown_string
|
|
|
|
assert message.caption == test_string
|
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
message = await default_bot.edit_message_caption(
|
2020-10-09 17:22:07 +02:00
|
|
|
caption=test_markdown_string,
|
|
|
|
chat_id=media_message.chat_id,
|
|
|
|
message_id=media_message.message_id,
|
|
|
|
parse_mode=None,
|
|
|
|
)
|
2020-02-06 11:22:56 +01:00
|
|
|
assert message.caption == test_markdown_string
|
|
|
|
assert message.caption_markdown == escape_markdown(test_markdown_string)
|
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
message = await default_bot.edit_message_caption(
|
2020-10-09 17:22:07 +02:00
|
|
|
caption=test_markdown_string,
|
|
|
|
chat_id=media_message.chat_id,
|
|
|
|
message_id=media_message.message_id,
|
|
|
|
)
|
2022-04-24 12:38:09 +02:00
|
|
|
message = await default_bot.edit_message_caption(
|
2020-10-09 17:22:07 +02:00
|
|
|
caption=test_markdown_string,
|
|
|
|
chat_id=media_message.chat_id,
|
|
|
|
message_id=media_message.message_id,
|
2022-05-05 17:40:22 +02:00
|
|
|
parse_mode="HTML",
|
2020-10-09 17:22:07 +02:00
|
|
|
)
|
2020-02-06 11:22:56 +01:00
|
|
|
assert message.caption == test_markdown_string
|
|
|
|
assert message.caption_markdown == escape_markdown(test_markdown_string)
|
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
async def test_edit_message_caption_with_parse_mode(self, bot, media_message):
|
|
|
|
message = await bot.edit_message_caption(
|
2022-05-05 17:40:22 +02:00
|
|
|
caption="new *caption*",
|
|
|
|
parse_mode="Markdown",
|
2020-10-09 17:22:07 +02:00
|
|
|
chat_id=media_message.chat_id,
|
|
|
|
message_id=media_message.message_id,
|
|
|
|
)
|
2018-02-18 16:11:04 +01:00
|
|
|
|
2022-05-05 17:40:22 +02:00
|
|
|
assert message.caption == "new caption"
|
2018-02-18 16:11:04 +01:00
|
|
|
|
2022-05-05 17:40:22 +02:00
|
|
|
@pytest.mark.skip(reason="need reference to an inline message")
|
2022-04-24 12:38:09 +02:00
|
|
|
async def test_edit_message_caption_inline(self):
|
2017-08-11 23:58:41 +02:00
|
|
|
pass
|
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
async def test_edit_reply_markup(self, bot, message):
|
2022-05-05 17:40:22 +02:00
|
|
|
new_markup = InlineKeyboardMarkup([[InlineKeyboardButton(text="test", callback_data="1")]])
|
2022-04-24 12:38:09 +02:00
|
|
|
message = await bot.edit_message_reply_markup(
|
2020-10-09 17:22:07 +02:00
|
|
|
chat_id=message.chat_id, message_id=message.message_id, reply_markup=new_markup
|
|
|
|
)
|
2017-08-11 23:58:41 +02:00
|
|
|
|
|
|
|
assert message is not True
|
|
|
|
|
2022-05-05 17:40:22 +02:00
|
|
|
@pytest.mark.skip(reason="need reference to an inline message")
|
2022-04-24 12:38:09 +02:00
|
|
|
async def test_edit_reply_markup_inline(self):
|
2017-08-11 23:58:41 +02:00
|
|
|
pass
|
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
@pytest.mark.xdist_group("getUpdates_and_webhook")
|
2017-08-11 23:58:41 +02:00
|
|
|
# TODO: Actually send updates to the test bot so this can be tested properly
|
2022-04-24 12:38:09 +02:00
|
|
|
async def test_get_updates(self, bot):
|
|
|
|
await bot.delete_webhook() # make sure there is no webhook set if webhook tests failed
|
|
|
|
updates = await bot.get_updates(timeout=1)
|
2017-08-11 23:58:41 +02:00
|
|
|
|
2022-12-15 15:00:36 +01:00
|
|
|
assert isinstance(updates, tuple)
|
2017-08-11 23:58:41 +02:00
|
|
|
if updates:
|
|
|
|
assert isinstance(updates[0], Update)
|
|
|
|
|
2023-11-27 18:24:21 +01:00
|
|
|
@pytest.mark.parametrize("bot_class", [Bot, ExtBot])
|
|
|
|
async def test_get_updates_read_timeout_deprecation_warning(
|
|
|
|
self, bot, recwarn, monkeypatch, bot_class
|
|
|
|
):
|
|
|
|
# Using the normal HTTPXRequest should not issue any warnings
|
|
|
|
await bot.get_updates()
|
|
|
|
assert len(recwarn) == 0
|
|
|
|
|
|
|
|
# Now let's test deprecation warning when using get_updates for other BaseRequest
|
|
|
|
# subclasses (we just monkeypatch the existing HTTPXRequest for this)
|
|
|
|
read_timeout = None
|
|
|
|
|
|
|
|
async def catch_timeouts(*args, **kwargs):
|
|
|
|
nonlocal read_timeout
|
|
|
|
read_timeout = kwargs.get("read_timeout")
|
|
|
|
return HTTPStatus.OK, b'{"ok": "True", "result": {}}'
|
|
|
|
|
|
|
|
monkeypatch.setattr(HTTPXRequest, "read_timeout", BaseRequest.read_timeout)
|
|
|
|
monkeypatch.setattr(HTTPXRequest, "do_request", catch_timeouts)
|
|
|
|
|
|
|
|
bot = bot_class(get_updates_request=HTTPXRequest(), token=bot.token)
|
|
|
|
await bot.get_updates()
|
|
|
|
|
|
|
|
assert len(recwarn) == 1
|
|
|
|
assert "does not override the property `read_timeout`" in str(recwarn[0].message)
|
|
|
|
assert recwarn[0].category is PTBDeprecationWarning
|
|
|
|
assert recwarn[0].filename == __file__, "wrong stacklevel"
|
|
|
|
|
|
|
|
assert read_timeout == 2
|
|
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
|
|
("read_timeout", "timeout", "expected"),
|
|
|
|
[
|
|
|
|
(None, None, 0),
|
|
|
|
(1, None, 1),
|
|
|
|
(None, 1, 1),
|
|
|
|
(DEFAULT_NONE, None, 10),
|
|
|
|
(DEFAULT_NONE, 1, 11),
|
|
|
|
(1, 2, 3),
|
|
|
|
],
|
|
|
|
)
|
|
|
|
async def test_get_updates_read_timeout_value_passing(
|
|
|
|
self, bot, read_timeout, timeout, expected, monkeypatch
|
|
|
|
):
|
|
|
|
caught_read_timeout = None
|
|
|
|
|
|
|
|
async def catch_timeouts(*args, **kwargs):
|
|
|
|
nonlocal caught_read_timeout
|
|
|
|
caught_read_timeout = kwargs.get("read_timeout")
|
|
|
|
return HTTPStatus.OK, b'{"ok": "True", "result": {}}'
|
|
|
|
|
|
|
|
monkeypatch.setattr(HTTPXRequest, "do_request", catch_timeouts)
|
|
|
|
|
|
|
|
bot = Bot(get_updates_request=HTTPXRequest(read_timeout=10), token=bot.token)
|
|
|
|
await bot.get_updates(read_timeout=read_timeout, timeout=timeout)
|
|
|
|
assert caught_read_timeout == expected
|
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
@pytest.mark.xdist_group("getUpdates_and_webhook")
|
2022-05-05 17:40:22 +02:00
|
|
|
@pytest.mark.parametrize("use_ip", [True, False])
|
2022-09-19 22:31:23 +02:00
|
|
|
# local file path as file_input is tested below in test_set_webhook_params
|
|
|
|
@pytest.mark.parametrize("file_input", ["bytes", "file_handle"])
|
|
|
|
async def test_set_webhook_get_webhook_info_and_delete_webhook(self, bot, use_ip, file_input):
|
2022-05-05 17:40:22 +02:00
|
|
|
url = "https://python-telegram-bot.org/test/webhook"
|
2022-04-24 12:38:09 +02:00
|
|
|
# Get the ip address of the website - dynamically just in case it ever changes
|
2022-05-05 17:40:22 +02:00
|
|
|
ip = socket.gethostbyname("python-telegram-bot.org")
|
2017-08-11 23:58:41 +02:00
|
|
|
max_connections = 7
|
2022-05-05 17:40:22 +02:00
|
|
|
allowed_updates = ["message"]
|
2022-09-19 22:31:23 +02:00
|
|
|
file_input = (
|
|
|
|
data_file("sslcert.pem").read_bytes()
|
|
|
|
if file_input == "bytes"
|
|
|
|
else data_file("sslcert.pem").open("rb")
|
|
|
|
)
|
2022-04-24 12:38:09 +02:00
|
|
|
await bot.set_webhook(
|
2020-11-29 16:20:46 +01:00
|
|
|
url,
|
|
|
|
max_connections=max_connections,
|
|
|
|
allowed_updates=allowed_updates,
|
2022-04-24 12:38:09 +02:00
|
|
|
ip_address=ip if use_ip else None,
|
2022-09-19 22:31:23 +02:00
|
|
|
certificate=file_input if use_ip else None,
|
2020-11-29 16:20:46 +01:00
|
|
|
)
|
2022-04-24 12:38:09 +02:00
|
|
|
|
|
|
|
await asyncio.sleep(1)
|
|
|
|
live_info = await bot.get_webhook_info()
|
2017-08-11 23:58:41 +02:00
|
|
|
assert live_info.url == url
|
|
|
|
assert live_info.max_connections == max_connections
|
2022-12-15 15:00:36 +01:00
|
|
|
assert live_info.allowed_updates == tuple(allowed_updates)
|
2022-04-24 12:38:09 +02:00
|
|
|
assert live_info.ip_address == ip
|
|
|
|
assert live_info.has_custom_certificate == use_ip
|
|
|
|
|
|
|
|
await bot.delete_webhook()
|
|
|
|
await asyncio.sleep(1)
|
|
|
|
info = await bot.get_webhook_info()
|
2023-03-25 19:18:04 +01:00
|
|
|
assert not info.url
|
2023-02-11 10:45:17 +01:00
|
|
|
assert info.ip_address is None
|
|
|
|
assert info.has_custom_certificate is False
|
2022-06-27 18:54:11 +02:00
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
async def test_leave_chat(self, bot):
|
2022-05-05 17:40:22 +02:00
|
|
|
with pytest.raises(BadRequest, match="Chat not found"):
|
2022-04-24 12:38:09 +02:00
|
|
|
await bot.leave_chat(-123456)
|
2017-08-11 23:58:41 +02:00
|
|
|
|
2022-05-05 17:40:22 +02:00
|
|
|
with pytest.raises(NetworkError, match="Chat not found"):
|
2022-04-24 12:38:09 +02:00
|
|
|
await bot.leave_chat(-123456)
|
2017-08-11 23:58:41 +02:00
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
async def test_get_chat(self, bot, super_group_id):
|
|
|
|
chat = await bot.get_chat(super_group_id)
|
2022-05-05 17:40:22 +02:00
|
|
|
assert chat.type == "supergroup"
|
|
|
|
assert chat.title == f">>> telegram.Bot(test) @{bot.username}"
|
2019-08-23 21:20:41 +02:00
|
|
|
assert chat.id == int(super_group_id)
|
2017-08-11 23:58:41 +02:00
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
async def test_get_chat_administrators(self, bot, channel_id):
|
|
|
|
admins = await bot.get_chat_administrators(channel_id)
|
2022-12-15 15:00:36 +01:00
|
|
|
assert isinstance(admins, tuple)
|
2016-05-25 01:31:10 +02:00
|
|
|
|
|
|
|
for a in admins:
|
2022-05-05 17:40:22 +02:00
|
|
|
assert a.status in ("administrator", "creator")
|
2017-08-11 23:58:41 +02:00
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
async def test_get_chat_member_count(self, bot, channel_id):
|
|
|
|
count = await bot.get_chat_member_count(channel_id)
|
2017-08-11 23:58:41 +02:00
|
|
|
assert isinstance(count, int)
|
|
|
|
assert count > 3
|
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
async def test_get_chat_member(self, bot, channel_id, chat_id):
|
|
|
|
chat_member = await bot.get_chat_member(channel_id, chat_id)
|
2017-08-11 23:58:41 +02:00
|
|
|
|
2022-05-05 17:40:22 +02:00
|
|
|
assert chat_member.status == "administrator"
|
|
|
|
assert chat_member.user.first_name == "PTB"
|
|
|
|
assert chat_member.user.last_name == "Test user"
|
2017-08-11 23:58:41 +02:00
|
|
|
|
2022-02-02 21:05:46 +01:00
|
|
|
@pytest.mark.skip(reason="Not implemented since we need a supergroup with many members")
|
2022-04-24 12:38:09 +02:00
|
|
|
async def test_set_chat_sticker_set(self):
|
2017-10-14 20:03:02 +02:00
|
|
|
pass
|
|
|
|
|
2022-02-02 21:05:46 +01:00
|
|
|
@pytest.mark.skip(reason="Not implemented since we need a supergroup with many members")
|
2022-04-24 12:38:09 +02:00
|
|
|
async def test_delete_chat_sticker_set(self):
|
2017-10-14 20:03:02 +02:00
|
|
|
pass
|
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
async def test_send_game(self, bot, chat_id):
|
2022-05-05 17:40:22 +02:00
|
|
|
game_short_name = "test_game"
|
2022-04-24 12:38:09 +02:00
|
|
|
message = await bot.send_game(chat_id, game_short_name, protect_content=True)
|
2020-03-30 17:06:24 +02:00
|
|
|
|
|
|
|
assert message.game
|
2023-09-22 18:19:21 +02:00
|
|
|
assert (
|
|
|
|
message.game.description
|
|
|
|
== "A no-op test game, for python-telegram-bot bot framework testing."
|
2020-10-09 17:22:07 +02:00
|
|
|
)
|
2023-03-25 19:18:04 +01:00
|
|
|
assert message.game.animation.file_id
|
2020-12-30 15:39:38 +01:00
|
|
|
# We added some test bots later and for some reason the file size is not the same for them
|
2021-05-28 22:24:43 +02:00
|
|
|
# so we accept three different sizes here. Shouldn't be too much of
|
|
|
|
assert message.game.photo[0].file_size in [851, 4928, 850]
|
2022-01-03 08:13:33 +01:00
|
|
|
assert message.has_protected_content
|
2020-03-30 17:06:24 +02:00
|
|
|
|
2020-11-29 16:20:46 +01:00
|
|
|
@pytest.mark.parametrize(
|
2023-03-25 19:18:04 +01:00
|
|
|
("default_bot", "custom"),
|
2020-11-29 16:20:46 +01:00
|
|
|
[
|
2022-05-05 17:40:22 +02:00
|
|
|
({"allow_sending_without_reply": True}, None),
|
|
|
|
({"allow_sending_without_reply": False}, None),
|
|
|
|
({"allow_sending_without_reply": False}, True),
|
2020-11-29 16:20:46 +01:00
|
|
|
],
|
2022-05-05 17:40:22 +02:00
|
|
|
indirect=["default_bot"],
|
2020-11-29 16:20:46 +01:00
|
|
|
)
|
2022-04-24 12:38:09 +02:00
|
|
|
async def test_send_game_default_allow_sending_without_reply(
|
|
|
|
self, default_bot, chat_id, custom
|
|
|
|
):
|
2022-05-05 17:40:22 +02:00
|
|
|
game_short_name = "test_game"
|
|
|
|
reply_to_message = await default_bot.send_message(chat_id, "test")
|
2022-04-24 12:38:09 +02:00
|
|
|
await reply_to_message.delete()
|
2020-11-29 16:20:46 +01:00
|
|
|
if custom is not None:
|
2022-04-24 12:38:09 +02:00
|
|
|
message = await default_bot.send_game(
|
2020-11-29 16:20:46 +01:00
|
|
|
chat_id,
|
|
|
|
game_short_name,
|
|
|
|
allow_sending_without_reply=custom,
|
|
|
|
reply_to_message_id=reply_to_message.message_id,
|
|
|
|
)
|
|
|
|
assert message.reply_to_message is None
|
|
|
|
elif default_bot.defaults.allow_sending_without_reply:
|
2022-04-24 12:38:09 +02:00
|
|
|
message = await default_bot.send_game(
|
2020-11-29 16:20:46 +01:00
|
|
|
chat_id,
|
|
|
|
game_short_name,
|
|
|
|
reply_to_message_id=reply_to_message.message_id,
|
|
|
|
)
|
|
|
|
assert message.reply_to_message is None
|
|
|
|
else:
|
2023-11-11 11:35:23 +01:00
|
|
|
with pytest.raises(BadRequest, match="Message to reply not found"):
|
2022-04-24 12:38:09 +02:00
|
|
|
await default_bot.send_game(
|
2020-11-29 16:20:46 +01:00
|
|
|
chat_id, game_short_name, reply_to_message_id=reply_to_message.message_id
|
|
|
|
)
|
|
|
|
|
2022-01-07 17:02:23 +01:00
|
|
|
@pytest.mark.parametrize(
|
2023-03-25 19:18:04 +01:00
|
|
|
("default_bot", "val"),
|
2022-05-05 17:40:22 +02:00
|
|
|
[({"protect_content": True}, True), ({"protect_content": False}, None)],
|
|
|
|
indirect=["default_bot"],
|
2022-01-07 17:02:23 +01:00
|
|
|
)
|
2022-04-24 12:38:09 +02:00
|
|
|
async def test_send_game_default_protect_content(self, default_bot, chat_id, val):
|
2022-05-05 17:40:22 +02:00
|
|
|
protected = await default_bot.send_game(chat_id, "test_game", protect_content=val)
|
2022-01-07 17:02:23 +01:00
|
|
|
assert protected.has_protected_content is val
|
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
@pytest.mark.xdist_group("game")
|
2021-05-19 13:33:41 +02:00
|
|
|
@xfail
|
2022-04-24 12:38:09 +02:00
|
|
|
async def test_set_game_score_1(self, bot, chat_id):
|
2016-12-11 22:44:52 +01:00
|
|
|
# NOTE: numbering of methods assures proper order between test_set_game_scoreX methods
|
2021-05-19 13:33:41 +02:00
|
|
|
# First, test setting a score.
|
2022-05-05 17:40:22 +02:00
|
|
|
game_short_name = "test_game"
|
2022-04-24 12:38:09 +02:00
|
|
|
game = await bot.send_game(chat_id, game_short_name)
|
2016-10-09 12:39:05 +02:00
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
message = await bot.set_game_score(
|
2021-05-19 13:33:41 +02:00
|
|
|
user_id=chat_id,
|
|
|
|
score=BASE_GAME_SCORE, # Score value is relevant for other set_game_score_* tests!
|
|
|
|
chat_id=game.chat_id,
|
|
|
|
message_id=game.message_id,
|
|
|
|
)
|
2020-06-15 18:45:38 +02:00
|
|
|
|
2021-05-19 13:33:41 +02:00
|
|
|
assert message.game.description == game.game.description
|
|
|
|
assert message.game.photo[0].file_size == game.game.photo[0].file_size
|
|
|
|
assert message.game.animation.file_unique_id == game.game.animation.file_unique_id
|
|
|
|
assert message.game.text != game.game.text
|
2016-10-09 12:39:05 +02:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
@pytest.mark.xdist_group("game")
|
2021-05-19 13:33:41 +02:00
|
|
|
@xfail
|
2022-04-24 12:38:09 +02:00
|
|
|
async def test_set_game_score_2(self, bot, chat_id):
|
2016-12-11 22:44:52 +01:00
|
|
|
# NOTE: numbering of methods assures proper order between test_set_game_scoreX methods
|
2021-05-19 13:33:41 +02:00
|
|
|
# Test setting a score higher than previous
|
2022-05-05 17:40:22 +02:00
|
|
|
game_short_name = "test_game"
|
2022-04-24 12:38:09 +02:00
|
|
|
game = await bot.send_game(chat_id, game_short_name)
|
2016-12-11 22:44:52 +01:00
|
|
|
|
2021-05-19 13:33:41 +02:00
|
|
|
score = BASE_GAME_SCORE + 1
|
2016-12-11 22:44:52 +01:00
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
message = await bot.set_game_score(
|
2017-08-11 23:58:41 +02:00
|
|
|
user_id=chat_id,
|
2016-12-11 22:44:52 +01:00
|
|
|
score=score,
|
|
|
|
chat_id=game.chat_id,
|
|
|
|
message_id=game.message_id,
|
2020-10-09 17:22:07 +02:00
|
|
|
disable_edit_message=True,
|
|
|
|
)
|
2016-12-11 22:44:52 +01:00
|
|
|
|
2017-08-11 23:58:41 +02:00
|
|
|
assert message.game.description == game.game.description
|
|
|
|
assert message.game.photo[0].file_size == game.game.photo[0].file_size
|
2021-05-19 13:33:41 +02:00
|
|
|
assert message.game.animation.file_unique_id == game.game.animation.file_unique_id
|
2017-08-11 23:58:41 +02:00
|
|
|
assert message.game.text == game.game.text
|
2016-12-11 22:44:52 +01:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
@pytest.mark.xdist_group("game")
|
2021-05-19 13:33:41 +02:00
|
|
|
@xfail
|
2022-04-24 12:38:09 +02:00
|
|
|
async def test_set_game_score_3(self, bot, chat_id):
|
2016-12-11 22:44:52 +01:00
|
|
|
# NOTE: numbering of methods assures proper order between test_set_game_scoreX methods
|
2021-05-19 13:33:41 +02:00
|
|
|
# Test setting a score lower than previous (should raise error)
|
2022-05-05 17:40:22 +02:00
|
|
|
game_short_name = "test_game"
|
2022-04-24 12:38:09 +02:00
|
|
|
game = await bot.send_game(chat_id, game_short_name)
|
2016-12-11 22:44:52 +01:00
|
|
|
|
2021-05-19 13:33:41 +02:00
|
|
|
score = BASE_GAME_SCORE # Even a score equal to previous raises an error.
|
2016-12-11 22:44:52 +01:00
|
|
|
|
2022-05-05 17:40:22 +02:00
|
|
|
with pytest.raises(BadRequest, match="Bot_score_not_modified"):
|
2022-04-24 12:38:09 +02:00
|
|
|
await bot.set_game_score(
|
2020-10-09 17:22:07 +02:00
|
|
|
user_id=chat_id, score=score, chat_id=game.chat_id, message_id=game.message_id
|
|
|
|
)
|
2016-12-11 22:44:52 +01:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
@pytest.mark.xdist_group("game")
|
2021-05-19 13:33:41 +02:00
|
|
|
@xfail
|
2022-04-24 12:38:09 +02:00
|
|
|
async def test_set_game_score_4(self, bot, chat_id):
|
2016-12-11 22:44:52 +01:00
|
|
|
# NOTE: numbering of methods assures proper order between test_set_game_scoreX methods
|
2021-05-19 13:33:41 +02:00
|
|
|
# Test force setting a lower score
|
2022-05-05 17:40:22 +02:00
|
|
|
game_short_name = "test_game"
|
2022-04-24 12:38:09 +02:00
|
|
|
game = await bot.send_game(chat_id, game_short_name)
|
2022-05-05 09:27:54 +02:00
|
|
|
await asyncio.sleep(1.5)
|
2016-12-11 22:44:52 +01:00
|
|
|
|
2021-05-19 13:33:41 +02:00
|
|
|
score = BASE_GAME_SCORE - 10
|
2016-12-11 22:44:52 +01:00
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
message = await bot.set_game_score(
|
2017-08-11 23:58:41 +02:00
|
|
|
user_id=chat_id,
|
2016-12-11 22:44:52 +01:00
|
|
|
score=score,
|
|
|
|
chat_id=game.chat_id,
|
|
|
|
message_id=game.message_id,
|
2020-10-09 17:22:07 +02:00
|
|
|
force=True,
|
|
|
|
)
|
2016-12-11 22:44:52 +01:00
|
|
|
|
2017-08-11 23:58:41 +02:00
|
|
|
assert message.game.description == game.game.description
|
|
|
|
assert message.game.photo[0].file_size == game.game.photo[0].file_size
|
2021-05-19 13:33:41 +02:00
|
|
|
assert message.game.animation.file_unique_id == game.game.animation.file_unique_id
|
2016-12-11 22:44:52 +01:00
|
|
|
|
2021-05-19 13:33:41 +02:00
|
|
|
# For some reason the returned message doesn't contain the updated score. need to fetch
|
|
|
|
# the game again... (the service message is also absent when running the test suite)
|
2022-04-24 12:38:09 +02:00
|
|
|
game2 = await bot.send_game(chat_id, game_short_name)
|
2017-08-11 23:58:41 +02:00
|
|
|
assert str(score) in game2.game.text
|
2016-12-11 22:44:52 +01:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
@pytest.mark.xdist_group("game")
|
2021-05-19 13:33:41 +02:00
|
|
|
@xfail
|
2022-04-24 12:38:09 +02:00
|
|
|
async def test_get_game_high_scores(self, bot, chat_id):
|
2017-08-11 23:58:41 +02:00
|
|
|
# We need a game to get the scores for
|
2022-05-05 17:40:22 +02:00
|
|
|
game_short_name = "test_game"
|
2022-04-24 12:38:09 +02:00
|
|
|
game = await bot.send_game(chat_id, game_short_name)
|
|
|
|
high_scores = await bot.get_game_high_scores(chat_id, game.chat_id, game.message_id)
|
2017-08-11 23:58:41 +02:00
|
|
|
# We assume that the other game score tests ran within 20 sec
|
2021-05-19 13:33:41 +02:00
|
|
|
assert high_scores[0].score == BASE_GAME_SCORE - 10
|
2017-08-11 23:58:41 +02:00
|
|
|
|
2022-06-27 18:54:11 +02:00
|
|
|
# send_invoice and create_invoice_link is tested in test_invoice
|
2022-04-24 12:38:09 +02:00
|
|
|
async def test_promote_chat_member(self, bot, channel_id, monkeypatch):
|
2017-08-11 23:58:41 +02:00
|
|
|
# TODO: Add bot to supergroup so this can be tested properly / give bot perms
|
2022-05-05 17:40:22 +02:00
|
|
|
with pytest.raises(BadRequest, match="Not enough rights"):
|
2022-04-24 12:38:09 +02:00
|
|
|
assert await bot.promote_chat_member(
|
2020-10-09 17:22:07 +02:00
|
|
|
channel_id,
|
|
|
|
95205500,
|
2020-11-29 16:20:46 +01:00
|
|
|
is_anonymous=True,
|
2020-10-09 17:22:07 +02:00
|
|
|
can_change_info=True,
|
|
|
|
can_post_messages=True,
|
|
|
|
can_edit_messages=True,
|
|
|
|
can_delete_messages=True,
|
|
|
|
can_invite_users=True,
|
|
|
|
can_restrict_members=True,
|
|
|
|
can_pin_messages=True,
|
|
|
|
can_promote_members=True,
|
2021-03-14 16:41:35 +01:00
|
|
|
can_manage_chat=True,
|
2022-05-03 18:21:50 +02:00
|
|
|
can_manage_video_chats=True,
|
2022-11-22 10:43:50 +01:00
|
|
|
can_manage_topics=True,
|
2023-10-03 14:32:57 +02:00
|
|
|
can_post_stories=True,
|
|
|
|
can_edit_stories=True,
|
|
|
|
can_delete_stories=True,
|
2021-03-14 16:41:35 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
# Test that we pass the correct params to TG
|
2022-04-24 12:38:09 +02:00
|
|
|
async def make_assertion(*args, **_):
|
2021-03-14 16:41:35 +01:00
|
|
|
data = args[1]
|
|
|
|
return (
|
2022-05-05 17:40:22 +02:00
|
|
|
data.get("chat_id") == channel_id
|
|
|
|
and data.get("user_id") == 95205500
|
|
|
|
and data.get("is_anonymous") == 1
|
|
|
|
and data.get("can_change_info") == 2
|
|
|
|
and data.get("can_post_messages") == 3
|
|
|
|
and data.get("can_edit_messages") == 4
|
|
|
|
and data.get("can_delete_messages") == 5
|
|
|
|
and data.get("can_invite_users") == 6
|
|
|
|
and data.get("can_restrict_members") == 7
|
|
|
|
and data.get("can_pin_messages") == 8
|
|
|
|
and data.get("can_promote_members") == 9
|
|
|
|
and data.get("can_manage_chat") == 10
|
|
|
|
and data.get("can_manage_video_chats") == 11
|
2022-11-22 10:43:50 +01:00
|
|
|
and data.get("can_manage_topics") == 12
|
2023-10-03 14:32:57 +02:00
|
|
|
and data.get("can_post_stories") == 13
|
|
|
|
and data.get("can_edit_stories") == 14
|
|
|
|
and data.get("can_delete_stories") == 15
|
2020-10-09 17:22:07 +02:00
|
|
|
)
|
2017-08-11 23:58:41 +02:00
|
|
|
|
2022-05-05 17:40:22 +02:00
|
|
|
monkeypatch.setattr(bot, "_post", make_assertion)
|
2022-04-24 12:38:09 +02:00
|
|
|
assert await bot.promote_chat_member(
|
2021-03-14 16:41:35 +01:00
|
|
|
channel_id,
|
|
|
|
95205500,
|
|
|
|
is_anonymous=1,
|
|
|
|
can_change_info=2,
|
|
|
|
can_post_messages=3,
|
|
|
|
can_edit_messages=4,
|
|
|
|
can_delete_messages=5,
|
|
|
|
can_invite_users=6,
|
|
|
|
can_restrict_members=7,
|
|
|
|
can_pin_messages=8,
|
|
|
|
can_promote_members=9,
|
|
|
|
can_manage_chat=10,
|
2022-05-03 18:21:50 +02:00
|
|
|
can_manage_video_chats=11,
|
2022-11-22 10:43:50 +01:00
|
|
|
can_manage_topics=12,
|
2023-10-03 14:32:57 +02:00
|
|
|
can_post_stories=13,
|
|
|
|
can_edit_stories=14,
|
|
|
|
can_delete_stories=15,
|
2021-03-14 16:41:35 +01:00
|
|
|
)
|
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
async def test_export_chat_invite_link(self, bot, channel_id):
|
2017-08-11 23:58:41 +02:00
|
|
|
# Each link is unique apparently
|
2022-04-24 12:38:09 +02:00
|
|
|
invite_link = await bot.export_chat_invite_link(channel_id)
|
2020-06-15 18:20:51 +02:00
|
|
|
assert isinstance(invite_link, str)
|
2023-03-25 19:18:04 +01:00
|
|
|
assert invite_link
|
2017-08-11 23:58:41 +02:00
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
async def test_edit_revoke_chat_invite_link_passing_link_objects(self, bot, channel_id):
|
|
|
|
invite_link = await bot.create_chat_invite_link(chat_id=channel_id)
|
2021-11-29 20:32:26 +01:00
|
|
|
assert invite_link.name is None
|
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
edited_link = await bot.edit_chat_invite_link(
|
2022-05-05 17:40:22 +02:00
|
|
|
chat_id=channel_id, invite_link=invite_link, name="some_name"
|
2021-11-29 20:32:26 +01:00
|
|
|
)
|
|
|
|
assert edited_link == invite_link
|
2022-05-05 17:40:22 +02:00
|
|
|
assert edited_link.name == "some_name"
|
2021-11-29 20:32:26 +01:00
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
revoked_link = await bot.revoke_chat_invite_link(
|
|
|
|
chat_id=channel_id, invite_link=edited_link
|
|
|
|
)
|
2021-11-29 20:32:26 +01:00
|
|
|
assert revoked_link.invite_link == edited_link.invite_link
|
|
|
|
assert revoked_link.is_revoked is True
|
2022-05-05 17:40:22 +02:00
|
|
|
assert revoked_link.name == "some_name"
|
2021-11-29 20:32:26 +01:00
|
|
|
|
2022-05-05 17:40:22 +02:00
|
|
|
@pytest.mark.parametrize("creates_join_request", [True, False])
|
|
|
|
@pytest.mark.parametrize("name", [None, "name"])
|
2022-04-24 12:38:09 +02:00
|
|
|
async def test_create_chat_invite_link_basics(
|
|
|
|
self, bot, creates_join_request, name, channel_id
|
|
|
|
):
|
2021-11-08 19:02:20 +01:00
|
|
|
data = {}
|
|
|
|
if creates_join_request:
|
2022-05-05 17:40:22 +02:00
|
|
|
data["creates_join_request"] = True
|
2021-11-08 19:02:20 +01:00
|
|
|
if name:
|
2022-05-05 17:40:22 +02:00
|
|
|
data["name"] = name
|
2022-04-24 12:38:09 +02:00
|
|
|
invite_link = await bot.create_chat_invite_link(chat_id=channel_id, **data)
|
2021-11-08 19:02:20 +01:00
|
|
|
|
|
|
|
assert invite_link.member_limit is None
|
|
|
|
assert invite_link.expire_date is None
|
|
|
|
assert invite_link.creates_join_request == creates_join_request
|
|
|
|
assert invite_link.name == name
|
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
revoked_link = await bot.revoke_chat_invite_link(
|
2021-11-08 19:02:20 +01:00
|
|
|
chat_id=channel_id, invite_link=invite_link.invite_link
|
|
|
|
)
|
|
|
|
assert revoked_link.is_revoked
|
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
@pytest.mark.skipif(not TEST_WITH_OPT_DEPS, reason="This test's implementation requires pytz")
|
2022-05-05 17:40:22 +02:00
|
|
|
@pytest.mark.parametrize("datetime", argvalues=[True, False], ids=["datetime", "integer"])
|
2022-04-24 12:38:09 +02:00
|
|
|
async def test_advanced_chat_invite_links(self, bot, channel_id, datetime):
|
2021-03-14 16:41:35 +01:00
|
|
|
# we are testing this all in one function in order to save api calls
|
|
|
|
timestamp = dtm.datetime.utcnow()
|
|
|
|
add_seconds = dtm.timedelta(0, 70)
|
|
|
|
time_in_future = timestamp + add_seconds
|
|
|
|
expire_time = time_in_future if datetime else to_timestamp(time_in_future)
|
2023-02-11 10:45:17 +01:00
|
|
|
aware_time_in_future = UTC.localize(time_in_future)
|
2021-03-14 16:41:35 +01:00
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
invite_link = await bot.create_chat_invite_link(
|
2021-03-14 16:41:35 +01:00
|
|
|
channel_id, expire_date=expire_time, member_limit=10
|
|
|
|
)
|
2023-03-25 19:18:04 +01:00
|
|
|
assert invite_link.invite_link
|
2022-05-05 17:40:22 +02:00
|
|
|
assert not invite_link.invite_link.endswith("...")
|
2022-05-05 09:27:54 +02:00
|
|
|
assert abs(invite_link.expire_date - aware_time_in_future) < dtm.timedelta(seconds=1)
|
2021-03-14 16:41:35 +01:00
|
|
|
assert invite_link.member_limit == 10
|
|
|
|
|
|
|
|
add_seconds = dtm.timedelta(0, 80)
|
|
|
|
time_in_future = timestamp + add_seconds
|
|
|
|
expire_time = time_in_future if datetime else to_timestamp(time_in_future)
|
2023-02-11 10:45:17 +01:00
|
|
|
aware_time_in_future = UTC.localize(time_in_future)
|
2021-03-14 16:41:35 +01:00
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
edited_invite_link = await bot.edit_chat_invite_link(
|
2021-11-08 19:02:20 +01:00
|
|
|
channel_id,
|
|
|
|
invite_link.invite_link,
|
|
|
|
expire_date=expire_time,
|
|
|
|
member_limit=20,
|
2022-05-05 17:40:22 +02:00
|
|
|
name="NewName",
|
2021-03-14 16:41:35 +01:00
|
|
|
)
|
|
|
|
assert edited_invite_link.invite_link == invite_link.invite_link
|
2022-05-05 09:27:54 +02:00
|
|
|
assert abs(edited_invite_link.expire_date - aware_time_in_future) < dtm.timedelta(
|
|
|
|
seconds=1
|
|
|
|
)
|
2022-05-05 17:40:22 +02:00
|
|
|
assert edited_invite_link.name == "NewName"
|
2021-03-14 16:41:35 +01:00
|
|
|
assert edited_invite_link.member_limit == 20
|
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
edited_invite_link = await bot.edit_chat_invite_link(
|
2021-11-08 19:02:20 +01:00
|
|
|
channel_id,
|
|
|
|
invite_link.invite_link,
|
2022-05-05 17:40:22 +02:00
|
|
|
name="EvenNewerName",
|
2021-11-08 19:02:20 +01:00
|
|
|
creates_join_request=True,
|
|
|
|
)
|
|
|
|
assert edited_invite_link.invite_link == invite_link.invite_link
|
2022-05-05 09:27:54 +02:00
|
|
|
assert not edited_invite_link.expire_date
|
2022-05-05 17:40:22 +02:00
|
|
|
assert edited_invite_link.name == "EvenNewerName"
|
2022-05-05 09:27:54 +02:00
|
|
|
assert edited_invite_link.creates_join_request
|
2021-11-08 19:02:20 +01:00
|
|
|
assert edited_invite_link.member_limit is None
|
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
revoked_invite_link = await bot.revoke_chat_invite_link(
|
|
|
|
channel_id, invite_link.invite_link
|
|
|
|
)
|
2021-03-14 16:41:35 +01:00
|
|
|
assert revoked_invite_link.invite_link == invite_link.invite_link
|
2022-05-05 09:27:54 +02:00
|
|
|
assert revoked_invite_link.is_revoked
|
2021-03-14 16:41:35 +01:00
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
async def test_advanced_chat_invite_links_default_tzinfo(self, tz_bot, channel_id):
|
2021-03-14 16:41:35 +01:00
|
|
|
# we are testing this all in one function in order to save api calls
|
|
|
|
add_seconds = dtm.timedelta(0, 70)
|
|
|
|
aware_expire_date = dtm.datetime.now(tz=tz_bot.defaults.tzinfo) + add_seconds
|
|
|
|
time_in_future = aware_expire_date.replace(tzinfo=None)
|
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
invite_link = await tz_bot.create_chat_invite_link(
|
2021-03-14 16:41:35 +01:00
|
|
|
channel_id, expire_date=time_in_future, member_limit=10
|
|
|
|
)
|
2023-03-25 19:18:04 +01:00
|
|
|
assert invite_link.invite_link
|
2022-05-05 17:40:22 +02:00
|
|
|
assert not invite_link.invite_link.endswith("...")
|
2022-05-05 09:27:54 +02:00
|
|
|
assert abs(invite_link.expire_date - aware_expire_date) < dtm.timedelta(seconds=1)
|
2021-03-14 16:41:35 +01:00
|
|
|
assert invite_link.member_limit == 10
|
|
|
|
|
|
|
|
add_seconds = dtm.timedelta(0, 80)
|
|
|
|
aware_expire_date += add_seconds
|
|
|
|
time_in_future = aware_expire_date.replace(tzinfo=None)
|
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
edited_invite_link = await tz_bot.edit_chat_invite_link(
|
2021-11-08 19:02:20 +01:00
|
|
|
channel_id,
|
|
|
|
invite_link.invite_link,
|
|
|
|
expire_date=time_in_future,
|
|
|
|
member_limit=20,
|
2022-05-05 17:40:22 +02:00
|
|
|
name="NewName",
|
2021-03-14 16:41:35 +01:00
|
|
|
)
|
|
|
|
assert edited_invite_link.invite_link == invite_link.invite_link
|
2022-05-05 09:27:54 +02:00
|
|
|
assert abs(edited_invite_link.expire_date - aware_expire_date) < dtm.timedelta(seconds=1)
|
2022-05-05 17:40:22 +02:00
|
|
|
assert edited_invite_link.name == "NewName"
|
2021-03-14 16:41:35 +01:00
|
|
|
assert edited_invite_link.member_limit == 20
|
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
edited_invite_link = await tz_bot.edit_chat_invite_link(
|
2021-11-08 19:02:20 +01:00
|
|
|
channel_id,
|
|
|
|
invite_link.invite_link,
|
2022-05-05 17:40:22 +02:00
|
|
|
name="EvenNewerName",
|
2021-11-08 19:02:20 +01:00
|
|
|
creates_join_request=True,
|
|
|
|
)
|
|
|
|
assert edited_invite_link.invite_link == invite_link.invite_link
|
2022-05-05 09:27:54 +02:00
|
|
|
assert not edited_invite_link.expire_date
|
2022-05-05 17:40:22 +02:00
|
|
|
assert edited_invite_link.name == "EvenNewerName"
|
2022-05-05 09:27:54 +02:00
|
|
|
assert edited_invite_link.creates_join_request
|
2021-11-08 19:02:20 +01:00
|
|
|
assert edited_invite_link.member_limit is None
|
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
revoked_invite_link = await tz_bot.revoke_chat_invite_link(
|
|
|
|
channel_id, invite_link.invite_link
|
|
|
|
)
|
2021-03-14 16:41:35 +01:00
|
|
|
assert revoked_invite_link.invite_link == invite_link.invite_link
|
2022-05-05 09:27:54 +02:00
|
|
|
assert revoked_invite_link.is_revoked
|
2021-03-14 16:41:35 +01:00
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
async def test_approve_chat_join_request(self, bot, chat_id, channel_id):
|
2021-11-08 19:02:20 +01:00
|
|
|
# TODO: Need incoming join request to properly test
|
|
|
|
# Since we can't create join requests on the fly, we just tests the call to TG
|
|
|
|
# by checking that it complains about approving a user who is already in the chat
|
2022-05-05 17:40:22 +02:00
|
|
|
with pytest.raises(BadRequest, match="User_already_participant"):
|
2022-04-24 12:38:09 +02:00
|
|
|
await bot.approve_chat_join_request(chat_id=channel_id, user_id=chat_id)
|
2021-11-08 19:02:20 +01:00
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
async def test_decline_chat_join_request(self, bot, chat_id, channel_id):
|
2021-11-08 19:02:20 +01:00
|
|
|
# TODO: Need incoming join request to properly test
|
|
|
|
# Since we can't create join requests on the fly, we just tests the call to TG
|
|
|
|
# by checking that it complains about declining a user who is already in the chat
|
2022-04-24 12:38:09 +02:00
|
|
|
#
|
|
|
|
# The error message Hide_requester_missing started showing up instead of
|
|
|
|
# User_already_participant. Don't know why …
|
2022-05-05 17:40:22 +02:00
|
|
|
with pytest.raises(BadRequest, match="User_already_participant|Hide_requester_missing"):
|
2022-04-24 12:38:09 +02:00
|
|
|
await bot.decline_chat_join_request(chat_id=channel_id, user_id=chat_id)
|
2021-11-08 19:02:20 +01:00
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
async def test_set_chat_photo(self, bot, channel_id):
|
|
|
|
async def func():
|
|
|
|
assert await bot.set_chat_photo(channel_id, f)
|
2017-08-11 23:58:41 +02:00
|
|
|
|
2022-05-05 17:40:22 +02:00
|
|
|
with data_file("telegram_test_channel.jpg").open("rb") as f:
|
2022-04-24 12:38:09 +02:00
|
|
|
await expect_bad_request(
|
2022-05-05 17:40:22 +02:00
|
|
|
func, "Type of file mismatch", "Telegram did not accept the file."
|
2022-04-24 12:38:09 +02:00
|
|
|
)
|
2020-05-01 13:27:46 +02:00
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
async def test_delete_chat_photo(self, bot, channel_id):
|
|
|
|
async def func():
|
|
|
|
assert await bot.delete_chat_photo(channel_id)
|
2020-05-01 13:27:46 +02:00
|
|
|
|
2022-05-05 17:40:22 +02:00
|
|
|
await expect_bad_request(func, "Chat_not_modified", "Chat photo was not set.")
|
2020-03-30 17:06:24 +02:00
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
async def test_set_chat_title(self, bot, channel_id):
|
2022-05-05 17:40:22 +02:00
|
|
|
assert await bot.set_chat_title(channel_id, ">>> telegram.Bot() - Tests")
|
2017-08-11 23:58:41 +02:00
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
async def test_set_chat_description(self, bot, channel_id):
|
2022-05-05 17:40:22 +02:00
|
|
|
assert await bot.set_chat_description(channel_id, "Time: " + str(time.time()))
|
2017-08-11 23:58:41 +02:00
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
async def test_pin_and_unpin_message(self, bot, super_group_id):
|
2023-02-11 10:45:17 +01:00
|
|
|
messages = [] # contains the Messages we sent
|
|
|
|
pinned_messages_tasks = set() # contains the asyncio.Tasks that pin the messages
|
|
|
|
|
|
|
|
# Let's send 3 messages so we can pin them
|
|
|
|
awaitables = {bot.send_message(super_group_id, f"test_pin_message_{i}") for i in range(3)}
|
|
|
|
|
|
|
|
# We will pin the messages immediately after sending them
|
|
|
|
for sending_msg in asyncio.as_completed(awaitables): # as_completed sends the messages
|
|
|
|
msg = await sending_msg
|
|
|
|
coro = bot.pin_chat_message(super_group_id, msg.message_id, True, read_timeout=10)
|
|
|
|
pinned_messages_tasks.add(asyncio.create_task(coro)) # start pinning the message
|
|
|
|
messages.append(msg)
|
|
|
|
|
|
|
|
assert len(messages) == 3 # Check if we sent 3 messages
|
|
|
|
|
2023-03-25 19:18:04 +01:00
|
|
|
# Check if we pinned 3 messages
|
2023-04-05 20:52:52 +02:00
|
|
|
assert all([await i for i in pinned_messages_tasks])
|
2023-03-25 19:18:04 +01:00
|
|
|
assert all(i.done() for i in pinned_messages_tasks) # Check if all tasks are done
|
2023-02-11 10:45:17 +01:00
|
|
|
|
|
|
|
chat = await bot.get_chat(super_group_id) # get the chat to check the pinned message
|
|
|
|
assert chat.pinned_message in messages
|
|
|
|
|
|
|
|
# Determine which message is not the most recently pinned
|
|
|
|
for old_pin_msg in messages:
|
|
|
|
if chat.pinned_message != old_pin_msg:
|
|
|
|
break
|
|
|
|
|
|
|
|
# Test unpinning our messages
|
|
|
|
tasks = asyncio.gather(
|
|
|
|
bot.unpin_chat_message( # unpins any message except the most recent
|
|
|
|
chat_id=super_group_id, # because we don't want to accidentally unpin the same msg
|
|
|
|
message_id=old_pin_msg.message_id, # twice
|
|
|
|
read_timeout=10,
|
|
|
|
),
|
|
|
|
bot.unpin_chat_message(chat_id=super_group_id, read_timeout=10), # unpins most recent
|
2022-04-24 12:38:09 +02:00
|
|
|
)
|
2023-02-11 10:45:17 +01:00
|
|
|
assert all(await tasks)
|
2023-03-25 19:18:04 +01:00
|
|
|
assert all(i.done() for i in tasks)
|
2023-02-11 10:45:17 +01:00
|
|
|
assert await bot.unpin_all_chat_messages(super_group_id, read_timeout=10)
|
2017-08-11 23:58:41 +02:00
|
|
|
|
|
|
|
# get_sticker_set, upload_sticker_file, create_new_sticker_set, add_sticker_to_set,
|
2022-08-25 19:36:55 +02:00
|
|
|
# set_sticker_position_in_set, delete_sticker_from_set and get_custom_emoji_stickers
|
|
|
|
# are tested in the test_sticker module.
|
2019-02-13 16:04:48 +01:00
|
|
|
|
2023-01-01 17:00:49 +01:00
|
|
|
# get_forum_topic_icon_stickers, edit_forum_topic, general_forum etc...
|
2022-11-22 10:43:50 +01:00
|
|
|
# are tested in the test_forum module.
|
2024-02-08 17:12:00 +01:00
|
|
|
async def test_send_message_disable_web_page_preview(self, bot, chat_id):
|
|
|
|
"""Test that disable_web_page_preview is substituted for link_preview_options and that
|
|
|
|
it still works as expected for backward compatability."""
|
|
|
|
msg = await bot.send_message(
|
|
|
|
chat_id,
|
|
|
|
"https://github.com/python-telegram-bot/python-telegram-bot",
|
|
|
|
disable_web_page_preview=True,
|
|
|
|
)
|
|
|
|
assert msg.link_preview_options
|
|
|
|
assert msg.link_preview_options.is_disabled
|
|
|
|
|
|
|
|
async def test_send_message_link_preview_options(self, bot, chat_id):
|
|
|
|
"""Test whether link_preview_options is correctly passed to the API."""
|
|
|
|
# btw it is possible to have no url in the text, but set a url for the preview.
|
|
|
|
msg = await bot.send_message(
|
|
|
|
chat_id,
|
|
|
|
"https://github.com/python-telegram-bot/python-telegram-bot",
|
|
|
|
link_preview_options=LinkPreviewOptions(prefer_small_media=True, show_above_text=True),
|
|
|
|
)
|
|
|
|
assert msg.link_preview_options
|
|
|
|
assert not msg.link_preview_options.is_disabled
|
|
|
|
# The prefer_* options aren't very consistent on the client side (big pic shown) +
|
|
|
|
# they are not returned by the API.
|
|
|
|
# assert msg.link_preview_options.prefer_small_media
|
|
|
|
assert msg.link_preview_options.show_above_text
|
|
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
|
|
"default_bot",
|
|
|
|
[{"link_preview_options": LinkPreviewOptions(show_above_text=True)}],
|
|
|
|
indirect=True,
|
|
|
|
)
|
|
|
|
async def test_send_message_default_link_preview_options(self, default_bot, chat_id):
|
|
|
|
"""Test whether Defaults.link_preview_options is correctly fused with the passed LPO."""
|
|
|
|
github_url = "https://github.com/python-telegram-bot/python-telegram-bot"
|
|
|
|
website = "https://python-telegram-bot.org/"
|
|
|
|
|
|
|
|
# First test just the default passing:
|
|
|
|
coro1 = default_bot.send_message(chat_id, github_url)
|
|
|
|
# Next test fusion of both LPOs:
|
|
|
|
coro2 = default_bot.send_message(
|
|
|
|
chat_id,
|
|
|
|
github_url,
|
|
|
|
link_preview_options=LinkPreviewOptions(url=website, prefer_large_media=True),
|
|
|
|
)
|
|
|
|
# Now test fusion + overriding of passed LPO:
|
|
|
|
coro3 = default_bot.send_message(
|
|
|
|
chat_id,
|
|
|
|
github_url,
|
|
|
|
link_preview_options=LinkPreviewOptions(show_above_text=False, url=website),
|
|
|
|
)
|
|
|
|
# finally test explicitly setting to None
|
|
|
|
coro4 = default_bot.send_message(chat_id, github_url, link_preview_options=None)
|
|
|
|
|
|
|
|
msgs = asyncio.gather(coro1, coro2, coro3, coro4)
|
|
|
|
msg1, msg2, msg3, msg4 = await msgs
|
|
|
|
assert msg1.link_preview_options
|
|
|
|
assert msg1.link_preview_options.show_above_text
|
|
|
|
|
|
|
|
assert msg2.link_preview_options
|
|
|
|
assert msg2.link_preview_options.show_above_text
|
|
|
|
assert msg2.link_preview_options.url == website
|
|
|
|
assert msg2.link_preview_options.prefer_large_media # Now works correctly using new url..
|
|
|
|
|
|
|
|
assert msg3.link_preview_options
|
|
|
|
assert not msg3.link_preview_options.show_above_text
|
|
|
|
assert msg3.link_preview_options.url == website
|
|
|
|
|
|
|
|
assert msg4.link_preview_options == LinkPreviewOptions(url=github_url)
|
|
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
|
|
"default_bot",
|
|
|
|
[{"link_preview_options": LinkPreviewOptions(show_above_text=True)}],
|
|
|
|
indirect=True,
|
|
|
|
)
|
|
|
|
async def test_edit_message_text_default_link_preview_options(self, default_bot, chat_id):
|
|
|
|
"""Test whether Defaults.link_preview_options is correctly fused with the passed LPO."""
|
|
|
|
github_url = "https://github.com/python-telegram-bot/python-telegram-bot"
|
|
|
|
website = "https://python-telegram-bot.org/"
|
|
|
|
telegram_url = "https://telegram.org"
|
|
|
|
base_1, base_2, base_3, base_4 = await asyncio.gather(
|
|
|
|
*(default_bot.send_message(chat_id, telegram_url) for _ in range(4))
|
|
|
|
)
|
|
|
|
|
|
|
|
# First test just the default passing:
|
|
|
|
coro1 = base_1.edit_text(github_url)
|
|
|
|
# Next test fusion of both LPOs:
|
|
|
|
coro2 = base_2.edit_text(
|
|
|
|
github_url,
|
|
|
|
link_preview_options=LinkPreviewOptions(url=website, prefer_large_media=True),
|
|
|
|
)
|
|
|
|
# Now test fusion + overriding of passed LPO:
|
|
|
|
coro3 = base_3.edit_text(
|
|
|
|
github_url,
|
|
|
|
link_preview_options=LinkPreviewOptions(show_above_text=False, url=website),
|
|
|
|
)
|
|
|
|
# finally test explicitly setting to None
|
|
|
|
coro4 = base_4.edit_text(github_url, link_preview_options=None)
|
|
|
|
|
|
|
|
msgs = asyncio.gather(coro1, coro2, coro3, coro4)
|
|
|
|
msg1, msg2, msg3, msg4 = await msgs
|
|
|
|
assert msg1.link_preview_options
|
|
|
|
assert msg1.link_preview_options.show_above_text
|
|
|
|
|
|
|
|
assert msg2.link_preview_options
|
|
|
|
assert msg2.link_preview_options.show_above_text
|
|
|
|
assert msg2.link_preview_options.url == website
|
|
|
|
assert msg2.link_preview_options.prefer_large_media # Now works correctly using new url..
|
|
|
|
|
|
|
|
assert msg3.link_preview_options
|
|
|
|
assert not msg3.link_preview_options.show_above_text
|
|
|
|
assert msg3.link_preview_options.url == website
|
|
|
|
|
|
|
|
assert msg4.link_preview_options == LinkPreviewOptions(url=github_url)
|
2022-11-22 10:43:50 +01:00
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
async def test_send_message_entities(self, bot, chat_id):
|
2022-05-05 17:40:22 +02:00
|
|
|
test_string = "Italic Bold Code Spoiler"
|
2020-11-29 16:20:46 +01:00
|
|
|
entities = [
|
|
|
|
MessageEntity(MessageEntity.ITALIC, 0, 6),
|
|
|
|
MessageEntity(MessageEntity.ITALIC, 7, 4),
|
|
|
|
MessageEntity(MessageEntity.ITALIC, 12, 4),
|
2022-01-03 08:13:33 +01:00
|
|
|
MessageEntity(MessageEntity.SPOILER, 17, 7),
|
2020-11-29 16:20:46 +01:00
|
|
|
]
|
2022-04-24 12:38:09 +02:00
|
|
|
message = await bot.send_message(chat_id=chat_id, text=test_string, entities=entities)
|
2020-11-29 16:20:46 +01:00
|
|
|
assert message.text == test_string
|
2022-12-15 15:00:36 +01:00
|
|
|
assert message.entities == tuple(entities)
|
2020-11-29 16:20:46 +01:00
|
|
|
|
2022-05-05 17:40:22 +02:00
|
|
|
@pytest.mark.parametrize("default_bot", [{"parse_mode": "Markdown"}], indirect=True)
|
2022-04-24 12:38:09 +02:00
|
|
|
async def test_send_message_default_parse_mode(self, default_bot, chat_id):
|
2022-05-05 17:40:22 +02:00
|
|
|
test_string = "Italic Bold Code"
|
|
|
|
test_markdown_string = "_Italic_ *Bold* `Code`"
|
2020-02-06 11:22:56 +01:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
tasks = asyncio.gather(
|
|
|
|
*(
|
|
|
|
default_bot.send_message(chat_id, test_markdown_string, **i)
|
|
|
|
for i in ({}, {"parse_mode": None}, {"parse_mode": "HTML"})
|
|
|
|
)
|
|
|
|
)
|
|
|
|
msg1, msg2, msg3 = await tasks
|
|
|
|
assert msg1.text_markdown == test_markdown_string
|
|
|
|
assert msg1.text == test_string
|
2020-02-06 11:22:56 +01:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
assert msg2.text == test_markdown_string
|
|
|
|
assert msg2.text_markdown == escape_markdown(test_markdown_string)
|
2020-02-06 11:22:56 +01:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
assert msg3.text == test_markdown_string
|
|
|
|
assert msg3.text_markdown == escape_markdown(test_markdown_string)
|
2020-02-06 11:22:56 +01:00
|
|
|
|
2022-05-05 17:40:22 +02:00
|
|
|
@pytest.mark.parametrize("default_bot", [{"protect_content": True}], indirect=True)
|
2022-04-24 12:38:09 +02:00
|
|
|
async def test_send_message_default_protect_content(self, default_bot, chat_id):
|
2023-02-11 10:45:17 +01:00
|
|
|
tasks = asyncio.gather(
|
|
|
|
default_bot.send_message(chat_id, "test"),
|
|
|
|
default_bot.send_message(chat_id, "test", protect_content=False),
|
|
|
|
)
|
|
|
|
to_check, no_protect = await tasks
|
2022-01-07 17:02:23 +01:00
|
|
|
assert to_check.has_protected_content
|
|
|
|
assert not no_protect.has_protected_content
|
|
|
|
|
2020-11-29 16:20:46 +01:00
|
|
|
@pytest.mark.parametrize(
|
2023-03-25 19:18:04 +01:00
|
|
|
("default_bot", "custom"),
|
2020-11-29 16:20:46 +01:00
|
|
|
[
|
2022-05-05 17:40:22 +02:00
|
|
|
({"allow_sending_without_reply": True}, None),
|
|
|
|
({"allow_sending_without_reply": False}, None),
|
|
|
|
({"allow_sending_without_reply": False}, True),
|
2020-11-29 16:20:46 +01:00
|
|
|
],
|
2022-05-05 17:40:22 +02:00
|
|
|
indirect=["default_bot"],
|
2020-11-29 16:20:46 +01:00
|
|
|
)
|
2022-04-24 12:38:09 +02:00
|
|
|
async def test_send_message_default_allow_sending_without_reply(
|
|
|
|
self, default_bot, chat_id, custom
|
|
|
|
):
|
2022-05-05 17:40:22 +02:00
|
|
|
reply_to_message = await default_bot.send_message(chat_id, "test")
|
2022-04-24 12:38:09 +02:00
|
|
|
await reply_to_message.delete()
|
2020-11-29 16:20:46 +01:00
|
|
|
if custom is not None:
|
2022-04-24 12:38:09 +02:00
|
|
|
message = await default_bot.send_message(
|
2020-11-29 16:20:46 +01:00
|
|
|
chat_id,
|
2022-05-05 17:40:22 +02:00
|
|
|
"test",
|
2020-11-29 16:20:46 +01:00
|
|
|
allow_sending_without_reply=custom,
|
|
|
|
reply_to_message_id=reply_to_message.message_id,
|
|
|
|
)
|
|
|
|
assert message.reply_to_message is None
|
|
|
|
elif default_bot.defaults.allow_sending_without_reply:
|
2022-04-24 12:38:09 +02:00
|
|
|
message = await default_bot.send_message(
|
2022-05-05 17:40:22 +02:00
|
|
|
chat_id, "test", reply_to_message_id=reply_to_message.message_id
|
2020-11-29 16:20:46 +01:00
|
|
|
)
|
|
|
|
assert message.reply_to_message is None
|
|
|
|
else:
|
2023-11-11 11:35:23 +01:00
|
|
|
with pytest.raises(BadRequest, match="Message to reply not found"):
|
2022-04-24 12:38:09 +02:00
|
|
|
await default_bot.send_message(
|
2022-05-05 17:40:22 +02:00
|
|
|
chat_id, "test", reply_to_message_id=reply_to_message.message_id
|
2020-11-29 16:20:46 +01:00
|
|
|
)
|
|
|
|
|
2022-05-03 18:21:50 +02:00
|
|
|
async def test_get_set_my_default_administrator_rights(self, bot):
|
|
|
|
# Test that my default administrator rights for group are as all False
|
2023-02-11 10:45:17 +01:00
|
|
|
assert await bot.set_my_default_administrator_rights() # clear any set rights
|
2022-05-03 18:21:50 +02:00
|
|
|
my_admin_rights_grp = await bot.get_my_default_administrator_rights()
|
|
|
|
assert isinstance(my_admin_rights_grp, ChatAdministratorRights)
|
|
|
|
assert all(not getattr(my_admin_rights_grp, at) for at in my_admin_rights_grp.__slots__)
|
|
|
|
|
|
|
|
# Test setting my default admin rights for channel
|
|
|
|
my_rights = ChatAdministratorRights.all_rights()
|
2023-02-11 10:45:17 +01:00
|
|
|
assert await bot.set_my_default_administrator_rights(my_rights, for_channels=True)
|
2022-05-03 18:21:50 +02:00
|
|
|
my_admin_rights_ch = await bot.get_my_default_administrator_rights(for_channels=True)
|
2022-05-07 21:47:50 +02:00
|
|
|
assert my_admin_rights_ch.can_invite_users is my_rights.can_invite_users
|
|
|
|
# tg bug? is_anonymous is False despite setting it True for channels:
|
2022-05-03 18:21:50 +02:00
|
|
|
assert my_admin_rights_ch.is_anonymous is not my_rights.is_anonymous
|
|
|
|
|
|
|
|
assert my_admin_rights_ch.can_manage_chat is my_rights.can_manage_chat
|
|
|
|
assert my_admin_rights_ch.can_delete_messages is my_rights.can_delete_messages
|
|
|
|
assert my_admin_rights_ch.can_edit_messages is my_rights.can_edit_messages
|
|
|
|
assert my_admin_rights_ch.can_post_messages is my_rights.can_post_messages
|
|
|
|
assert my_admin_rights_ch.can_change_info is my_rights.can_change_info
|
|
|
|
assert my_admin_rights_ch.can_promote_members is my_rights.can_promote_members
|
|
|
|
assert my_admin_rights_ch.can_restrict_members is my_rights.can_restrict_members
|
|
|
|
assert my_admin_rights_ch.can_pin_messages is None # Not returned for channels
|
2022-11-22 10:43:50 +01:00
|
|
|
assert my_admin_rights_ch.can_manage_topics is None # Not returned for channels
|
2022-05-03 18:21:50 +02:00
|
|
|
|
|
|
|
async def test_get_set_chat_menu_button(self, bot, chat_id):
|
|
|
|
# Test our chat menu button is commands-
|
|
|
|
menu_button = await bot.get_chat_menu_button()
|
|
|
|
assert isinstance(menu_button, MenuButton)
|
|
|
|
assert isinstance(menu_button, MenuButtonCommands)
|
|
|
|
assert menu_button.type == MenuButtonType.COMMANDS
|
|
|
|
|
|
|
|
# Test setting our chat menu button to Webapp.
|
2022-05-05 17:40:22 +02:00
|
|
|
my_menu = MenuButtonWebApp("click me!", WebAppInfo("https://telegram.org/"))
|
2023-02-11 10:45:17 +01:00
|
|
|
assert await bot.set_chat_menu_button(chat_id=chat_id, menu_button=my_menu)
|
2022-05-03 18:21:50 +02:00
|
|
|
menu_button = await bot.get_chat_menu_button(chat_id)
|
|
|
|
assert isinstance(menu_button, MenuButtonWebApp)
|
|
|
|
assert menu_button.type == MenuButtonType.WEB_APP
|
|
|
|
assert menu_button.text == my_menu.text
|
|
|
|
assert menu_button.web_app.url == my_menu.web_app.url
|
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
assert await bot.set_chat_menu_button(chat_id=chat_id, menu_button=MenuButtonDefault())
|
2022-05-03 18:21:50 +02:00
|
|
|
menu_button = await bot.get_chat_menu_button(chat_id=chat_id)
|
|
|
|
assert isinstance(menu_button, MenuButtonDefault)
|
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
async def test_set_and_get_my_commands(self, bot):
|
2022-05-05 17:40:22 +02:00
|
|
|
commands = [BotCommand("cmd1", "descr1"), ["cmd2", "descr2"]]
|
2023-02-11 10:45:17 +01:00
|
|
|
assert await bot.set_my_commands([])
|
2022-12-15 15:00:36 +01:00
|
|
|
assert await bot.get_my_commands() == ()
|
2022-04-24 12:38:09 +02:00
|
|
|
assert await bot.set_my_commands(commands)
|
2020-04-10 19:22:45 +02:00
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
for i, bc in enumerate(await bot.get_my_commands()):
|
2024-01-15 20:15:33 +01:00
|
|
|
assert bc.command == f"cmd{i + 1}"
|
|
|
|
assert bc.description == f"descr{i + 1}"
|
2020-11-29 16:20:46 +01:00
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
async def test_get_set_delete_my_commands_with_scope(self, bot, super_group_id, chat_id):
|
2022-05-05 17:40:22 +02:00
|
|
|
group_cmds = [BotCommand("group_cmd", "visible to this supergroup only")]
|
|
|
|
private_cmds = [BotCommand("private_cmd", "visible to this private chat only")]
|
2021-07-01 17:45:19 +02:00
|
|
|
group_scope = BotCommandScopeChat(super_group_id)
|
|
|
|
private_scope = BotCommandScopeChat(chat_id)
|
|
|
|
|
|
|
|
# Set supergroup command list with lang code and check if the same can be returned from api
|
2023-02-11 10:45:17 +01:00
|
|
|
assert await bot.set_my_commands(group_cmds, scope=group_scope, language_code="en")
|
|
|
|
gotten_group_cmds = await bot.get_my_commands(scope=group_scope, language_code="en")
|
2020-11-29 16:20:46 +01:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
assert len(gotten_group_cmds) == len(group_cmds)
|
|
|
|
assert gotten_group_cmds[0].command == group_cmds[0].command
|
|
|
|
|
|
|
|
# Set private command list and check if same can be returned from the api
|
|
|
|
assert await bot.set_my_commands(private_cmds, scope=private_scope)
|
|
|
|
gotten_private_cmd = await bot.get_my_commands(scope=private_scope)
|
|
|
|
|
|
|
|
assert len(gotten_private_cmd) == len(private_cmds)
|
|
|
|
assert gotten_private_cmd[0].command == private_cmds[0].command
|
|
|
|
|
|
|
|
# Delete command list from that supergroup and private chat-
|
|
|
|
tasks = asyncio.gather(
|
|
|
|
bot.delete_my_commands(private_scope),
|
|
|
|
bot.delete_my_commands(group_scope, "en"),
|
2020-11-29 16:20:46 +01:00
|
|
|
)
|
2023-02-11 10:45:17 +01:00
|
|
|
assert all(await tasks)
|
|
|
|
|
|
|
|
# Check if its been deleted-
|
|
|
|
tasks = asyncio.gather(
|
|
|
|
bot.get_my_commands(private_scope),
|
|
|
|
bot.get_my_commands(group_scope, "en"),
|
|
|
|
)
|
|
|
|
deleted_priv_cmds, deleted_grp_cmds = await tasks
|
|
|
|
|
|
|
|
assert len(deleted_grp_cmds) == 0 == len(group_cmds) - 1
|
|
|
|
assert len(deleted_priv_cmds) == 0 == len(private_cmds) - 1
|
|
|
|
|
|
|
|
await bot.delete_my_commands() # Delete commands from default scope
|
|
|
|
assert len(await bot.get_my_commands()) == 0
|
2020-11-29 16:20:46 +01:00
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
async def test_copy_message_without_reply(self, bot, chat_id, media_message):
|
2020-11-29 16:20:46 +01:00
|
|
|
keyboard = InlineKeyboardMarkup(
|
|
|
|
[[InlineKeyboardButton(text="test", callback_data="test2")]]
|
|
|
|
)
|
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
returned = await bot.copy_message(
|
2020-11-29 16:20:46 +01:00
|
|
|
chat_id,
|
|
|
|
from_chat_id=chat_id,
|
|
|
|
message_id=media_message.message_id,
|
|
|
|
caption="<b>Test</b>",
|
|
|
|
parse_mode=ParseMode.HTML,
|
|
|
|
reply_to_message_id=media_message.message_id,
|
|
|
|
reply_markup=keyboard,
|
|
|
|
)
|
|
|
|
# we send a temp message which replies to the returned message id in order to get a
|
|
|
|
# message object
|
2022-04-24 12:38:09 +02:00
|
|
|
temp_message = await bot.send_message(
|
|
|
|
chat_id, "test", reply_to_message_id=returned.message_id
|
|
|
|
)
|
2020-11-29 16:20:46 +01:00
|
|
|
message = temp_message.reply_to_message
|
|
|
|
assert message.chat_id == int(chat_id)
|
|
|
|
assert message.caption == "Test"
|
|
|
|
assert len(message.caption_entities) == 1
|
|
|
|
assert message.reply_markup == keyboard
|
|
|
|
|
|
|
|
@pytest.mark.parametrize(
|
2022-05-05 17:40:22 +02:00
|
|
|
"default_bot",
|
2020-11-29 16:20:46 +01:00
|
|
|
[
|
2022-05-05 17:40:22 +02:00
|
|
|
({"parse_mode": ParseMode.HTML, "allow_sending_without_reply": True}),
|
|
|
|
({"parse_mode": None, "allow_sending_without_reply": True}),
|
|
|
|
({"parse_mode": None, "allow_sending_without_reply": False}),
|
2020-11-29 16:20:46 +01:00
|
|
|
],
|
2022-05-05 17:40:22 +02:00
|
|
|
indirect=["default_bot"],
|
2020-11-29 16:20:46 +01:00
|
|
|
)
|
2022-04-24 12:38:09 +02:00
|
|
|
async def test_copy_message_with_default(self, default_bot, chat_id, media_message):
|
2022-05-05 17:40:22 +02:00
|
|
|
reply_to_message = await default_bot.send_message(chat_id, "test")
|
2022-04-24 12:38:09 +02:00
|
|
|
await reply_to_message.delete()
|
2020-11-29 16:20:46 +01:00
|
|
|
if not default_bot.defaults.allow_sending_without_reply:
|
2022-05-05 17:40:22 +02:00
|
|
|
with pytest.raises(BadRequest, match="not found"):
|
2022-04-24 12:38:09 +02:00
|
|
|
await default_bot.copy_message(
|
2020-11-29 16:20:46 +01:00
|
|
|
chat_id,
|
|
|
|
from_chat_id=chat_id,
|
|
|
|
message_id=media_message.message_id,
|
|
|
|
caption="<b>Test</b>",
|
|
|
|
reply_to_message_id=reply_to_message.message_id,
|
|
|
|
)
|
|
|
|
return
|
2022-04-24 12:38:09 +02:00
|
|
|
returned = await default_bot.copy_message(
|
2021-05-27 09:38:17 +02:00
|
|
|
chat_id,
|
|
|
|
from_chat_id=chat_id,
|
|
|
|
message_id=media_message.message_id,
|
|
|
|
caption="<b>Test</b>",
|
|
|
|
reply_to_message_id=reply_to_message.message_id,
|
|
|
|
)
|
2020-11-29 16:20:46 +01:00
|
|
|
# we send a temp message which replies to the returned message id in order to get a
|
|
|
|
# message object
|
2022-04-24 12:38:09 +02:00
|
|
|
temp_message = await default_bot.send_message(
|
2020-11-29 16:20:46 +01:00
|
|
|
chat_id, "test", reply_to_message_id=returned.message_id
|
|
|
|
)
|
|
|
|
message = temp_message.reply_to_message
|
|
|
|
if default_bot.defaults.parse_mode:
|
|
|
|
assert len(message.caption_entities) == 1
|
|
|
|
else:
|
|
|
|
assert len(message.caption_entities) == 0
|
2021-06-06 11:48:48 +02:00
|
|
|
|
2024-02-08 17:12:00 +01:00
|
|
|
async def test_copy_messages(self, bot, chat_id):
|
|
|
|
tasks = asyncio.gather(
|
|
|
|
bot.send_message(chat_id, text="will be copied 1"),
|
|
|
|
bot.send_message(chat_id, text="will be copied 2"),
|
|
|
|
)
|
|
|
|
msg1, msg2 = await tasks
|
|
|
|
|
|
|
|
copy_messages = await bot.copy_messages(
|
|
|
|
chat_id, from_chat_id=chat_id, message_ids=(msg1.message_id, msg2.message_id)
|
|
|
|
)
|
|
|
|
assert isinstance(copy_messages, tuple)
|
|
|
|
|
|
|
|
tasks = asyncio.gather(
|
|
|
|
bot.send_message(chat_id, "temp 1", reply_to_message_id=copy_messages[0].message_id),
|
|
|
|
bot.send_message(chat_id, "temp 2", reply_to_message_id=copy_messages[1].message_id),
|
|
|
|
)
|
|
|
|
temp_msg1, temp_msg2 = await tasks
|
|
|
|
|
|
|
|
forward_msg1 = temp_msg1.reply_to_message
|
|
|
|
forward_msg2 = temp_msg2.reply_to_message
|
|
|
|
|
|
|
|
assert forward_msg1.text == msg1.text
|
|
|
|
assert forward_msg2.text == msg2.text
|
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
# Continue testing arbitrary callback data here with actual requests:
|
2022-10-07 10:18:08 +02:00
|
|
|
async def test_replace_callback_data_send_message(self, cdc_bot, chat_id):
|
|
|
|
bot = cdc_bot
|
|
|
|
|
2021-06-06 11:48:48 +02:00
|
|
|
try:
|
2022-05-05 17:40:22 +02:00
|
|
|
replace_button = InlineKeyboardButton(text="replace", callback_data="replace_test")
|
2021-06-06 11:48:48 +02:00
|
|
|
no_replace_button = InlineKeyboardButton(
|
2022-05-05 17:40:22 +02:00
|
|
|
text="no_replace", url="http://python-telegram-bot.org/"
|
2021-06-06 11:48:48 +02:00
|
|
|
)
|
|
|
|
reply_markup = InlineKeyboardMarkup.from_row(
|
|
|
|
[
|
|
|
|
replace_button,
|
|
|
|
no_replace_button,
|
|
|
|
]
|
|
|
|
)
|
2022-04-24 12:38:09 +02:00
|
|
|
message = await bot.send_message(
|
2022-05-05 17:40:22 +02:00
|
|
|
chat_id=chat_id, text="test", reply_markup=reply_markup
|
2022-04-24 12:38:09 +02:00
|
|
|
)
|
2021-06-06 11:48:48 +02:00
|
|
|
inline_keyboard = message.reply_markup.inline_keyboard
|
|
|
|
|
|
|
|
assert inline_keyboard[0][1] == no_replace_button
|
|
|
|
assert inline_keyboard[0][0] == replace_button
|
2023-08-02 11:51:17 +02:00
|
|
|
keyboard = next(iter(bot.callback_data_cache._keyboard_data))
|
|
|
|
data = next(
|
|
|
|
iter(bot.callback_data_cache._keyboard_data[keyboard].button_data.values())
|
|
|
|
)
|
2022-05-05 17:40:22 +02:00
|
|
|
assert data == "replace_test"
|
2021-06-06 11:48:48 +02:00
|
|
|
finally:
|
|
|
|
bot.callback_data_cache.clear_callback_data()
|
|
|
|
bot.callback_data_cache.clear_callback_queries()
|
|
|
|
|
2022-10-07 10:18:08 +02:00
|
|
|
async def test_replace_callback_data_stop_poll_and_repl_to_message(self, cdc_bot, chat_id):
|
|
|
|
bot = cdc_bot
|
|
|
|
|
2022-05-05 17:40:22 +02:00
|
|
|
poll_message = await bot.send_poll(chat_id=chat_id, question="test", options=["1", "2"])
|
2021-06-06 11:48:48 +02:00
|
|
|
try:
|
2022-05-05 17:40:22 +02:00
|
|
|
replace_button = InlineKeyboardButton(text="replace", callback_data="replace_test")
|
2021-06-06 11:48:48 +02:00
|
|
|
no_replace_button = InlineKeyboardButton(
|
2022-05-05 17:40:22 +02:00
|
|
|
text="no_replace", url="http://python-telegram-bot.org/"
|
2021-06-06 11:48:48 +02:00
|
|
|
)
|
|
|
|
reply_markup = InlineKeyboardMarkup.from_row(
|
|
|
|
[
|
|
|
|
replace_button,
|
|
|
|
no_replace_button,
|
|
|
|
]
|
|
|
|
)
|
2022-04-24 12:38:09 +02:00
|
|
|
await poll_message.stop_poll(reply_markup=reply_markup)
|
2022-05-05 17:40:22 +02:00
|
|
|
helper_message = await poll_message.reply_text("temp", quote=True)
|
2021-06-06 11:48:48 +02:00
|
|
|
message = helper_message.reply_to_message
|
|
|
|
inline_keyboard = message.reply_markup.inline_keyboard
|
|
|
|
|
|
|
|
assert inline_keyboard[0][1] == no_replace_button
|
|
|
|
assert inline_keyboard[0][0] == replace_button
|
2023-08-02 11:51:17 +02:00
|
|
|
keyboard = next(iter(bot.callback_data_cache._keyboard_data))
|
|
|
|
data = next(
|
|
|
|
iter(bot.callback_data_cache._keyboard_data[keyboard].button_data.values())
|
|
|
|
)
|
2022-05-05 17:40:22 +02:00
|
|
|
assert data == "replace_test"
|
2021-06-06 11:48:48 +02:00
|
|
|
finally:
|
|
|
|
bot.callback_data_cache.clear_callback_data()
|
|
|
|
bot.callback_data_cache.clear_callback_queries()
|
|
|
|
|
2022-10-07 10:18:08 +02:00
|
|
|
async def test_replace_callback_data_copy_message(self, cdc_bot, chat_id):
|
2021-06-06 11:48:48 +02:00
|
|
|
"""This also tests that data is inserted into the buttons of message.reply_to_message
|
|
|
|
where message is the return value of a bot method"""
|
2022-10-07 10:18:08 +02:00
|
|
|
bot = cdc_bot
|
|
|
|
|
2022-05-05 17:40:22 +02:00
|
|
|
original_message = await bot.send_message(chat_id=chat_id, text="original")
|
2021-06-06 11:48:48 +02:00
|
|
|
try:
|
2022-05-05 17:40:22 +02:00
|
|
|
replace_button = InlineKeyboardButton(text="replace", callback_data="replace_test")
|
2021-06-06 11:48:48 +02:00
|
|
|
no_replace_button = InlineKeyboardButton(
|
2022-05-05 17:40:22 +02:00
|
|
|
text="no_replace", url="http://python-telegram-bot.org/"
|
2021-06-06 11:48:48 +02:00
|
|
|
)
|
|
|
|
reply_markup = InlineKeyboardMarkup.from_row(
|
|
|
|
[
|
|
|
|
replace_button,
|
|
|
|
no_replace_button,
|
|
|
|
]
|
|
|
|
)
|
2022-04-24 12:38:09 +02:00
|
|
|
message_id = await original_message.copy(chat_id=chat_id, reply_markup=reply_markup)
|
|
|
|
helper_message = await bot.send_message(
|
2022-05-05 17:40:22 +02:00
|
|
|
chat_id=chat_id, reply_to_message_id=message_id.message_id, text="temp"
|
2021-06-06 11:48:48 +02:00
|
|
|
)
|
|
|
|
message = helper_message.reply_to_message
|
|
|
|
inline_keyboard = message.reply_markup.inline_keyboard
|
|
|
|
|
|
|
|
assert inline_keyboard[0][1] == no_replace_button
|
|
|
|
assert inline_keyboard[0][0] == replace_button
|
2023-08-02 11:51:17 +02:00
|
|
|
keyboard = next(iter(bot.callback_data_cache._keyboard_data))
|
|
|
|
data = next(
|
|
|
|
iter(bot.callback_data_cache._keyboard_data[keyboard].button_data.values())
|
|
|
|
)
|
2022-05-05 17:40:22 +02:00
|
|
|
assert data == "replace_test"
|
2021-06-06 11:48:48 +02:00
|
|
|
finally:
|
|
|
|
bot.callback_data_cache.clear_callback_data()
|
|
|
|
bot.callback_data_cache.clear_callback_queries()
|
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
async def test_get_chat_arbitrary_callback_data(self, channel_id, cdc_bot):
|
2022-10-07 10:18:08 +02:00
|
|
|
bot = cdc_bot
|
|
|
|
|
2021-06-06 11:48:48 +02:00
|
|
|
try:
|
|
|
|
reply_markup = InlineKeyboardMarkup.from_button(
|
2022-05-05 17:40:22 +02:00
|
|
|
InlineKeyboardButton(text="text", callback_data="callback_data")
|
2021-06-06 11:48:48 +02:00
|
|
|
)
|
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
message = await bot.send_message(
|
2023-02-11 10:45:17 +01:00
|
|
|
channel_id, text="get_chat_arbitrary_callback_data", reply_markup=reply_markup
|
2021-06-06 11:48:48 +02:00
|
|
|
)
|
2022-04-24 12:38:09 +02:00
|
|
|
await message.pin()
|
2021-06-06 11:48:48 +02:00
|
|
|
|
2023-08-02 11:51:17 +02:00
|
|
|
keyboard = next(iter(bot.callback_data_cache._keyboard_data))
|
|
|
|
data = next(
|
|
|
|
iter(bot.callback_data_cache._keyboard_data[keyboard].button_data.values())
|
|
|
|
)
|
2022-05-05 17:40:22 +02:00
|
|
|
assert data == "callback_data"
|
2021-06-06 11:48:48 +02:00
|
|
|
|
2023-02-11 10:45:17 +01:00
|
|
|
chat = await bot.get_chat(channel_id)
|
2021-06-06 11:48:48 +02:00
|
|
|
assert chat.pinned_message == message
|
|
|
|
assert chat.pinned_message.reply_markup == reply_markup
|
2023-02-11 10:45:17 +01:00
|
|
|
assert await message.unpin() # (not placed in finally block since msg can be unbound)
|
2021-06-06 11:48:48 +02:00
|
|
|
finally:
|
|
|
|
bot.callback_data_cache.clear_callback_data()
|
|
|
|
bot.callback_data_cache.clear_callback_queries()
|
|
|
|
|
2022-10-07 10:18:08 +02:00
|
|
|
async def test_arbitrary_callback_data_get_chat_no_pinned_message(
|
|
|
|
self, super_group_id, cdc_bot
|
|
|
|
):
|
|
|
|
bot = cdc_bot
|
2022-04-24 12:38:09 +02:00
|
|
|
await bot.unpin_all_chat_messages(super_group_id)
|
2021-06-06 11:48:48 +02:00
|
|
|
|
|
|
|
try:
|
2022-04-24 12:38:09 +02:00
|
|
|
chat = await bot.get_chat(super_group_id)
|
2021-06-06 11:48:48 +02:00
|
|
|
|
|
|
|
assert isinstance(chat, Chat)
|
|
|
|
assert int(chat.id) == int(super_group_id)
|
|
|
|
assert chat.pinned_message is None
|
|
|
|
finally:
|
2022-10-07 10:18:08 +02:00
|
|
|
bot.callback_data_cache.clear_callback_data()
|
|
|
|
bot.callback_data_cache.clear_callback_queries()
|
2023-03-25 11:47:26 +01:00
|
|
|
|
|
|
|
async def test_set_get_my_description(self, bot):
|
|
|
|
default_description = f"{bot.username} - default - {dtm.datetime.utcnow().isoformat()}"
|
|
|
|
en_description = f"{bot.username} - en - {dtm.datetime.utcnow().isoformat()}"
|
|
|
|
de_description = f"{bot.username} - de - {dtm.datetime.utcnow().isoformat()}"
|
|
|
|
|
|
|
|
# Set the descriptions
|
|
|
|
assert all(
|
|
|
|
await asyncio.gather(
|
|
|
|
bot.set_my_description(default_description),
|
|
|
|
bot.set_my_description(en_description, language_code="en"),
|
|
|
|
bot.set_my_description(de_description, language_code="de"),
|
|
|
|
)
|
|
|
|
)
|
|
|
|
|
|
|
|
# Check that they were set correctly
|
|
|
|
assert await asyncio.gather(
|
|
|
|
bot.get_my_description(), bot.get_my_description("en"), bot.get_my_description("de")
|
|
|
|
) == [
|
|
|
|
BotDescription(default_description),
|
|
|
|
BotDescription(en_description),
|
|
|
|
BotDescription(de_description),
|
|
|
|
]
|
|
|
|
|
|
|
|
# Delete the descriptions
|
|
|
|
assert all(
|
|
|
|
await asyncio.gather(
|
|
|
|
bot.set_my_description(None),
|
|
|
|
bot.set_my_description(None, language_code="en"),
|
|
|
|
bot.set_my_description(None, language_code="de"),
|
|
|
|
)
|
|
|
|
)
|
|
|
|
|
|
|
|
# Check that they were deleted correctly
|
|
|
|
assert await asyncio.gather(
|
|
|
|
bot.get_my_description(), bot.get_my_description("en"), bot.get_my_description("de")
|
|
|
|
) == 3 * [BotDescription("")]
|
|
|
|
|
|
|
|
async def test_set_get_my_short_description(self, bot):
|
|
|
|
default_short_description = (
|
|
|
|
f"{bot.username} - default - {dtm.datetime.utcnow().isoformat()}"
|
|
|
|
)
|
|
|
|
en_short_description = f"{bot.username} - en - {dtm.datetime.utcnow().isoformat()}"
|
|
|
|
de_short_description = f"{bot.username} - de - {dtm.datetime.utcnow().isoformat()}"
|
|
|
|
|
|
|
|
# Set the short_descriptions
|
|
|
|
assert all(
|
|
|
|
await asyncio.gather(
|
|
|
|
bot.set_my_short_description(default_short_description),
|
|
|
|
bot.set_my_short_description(en_short_description, language_code="en"),
|
|
|
|
bot.set_my_short_description(de_short_description, language_code="de"),
|
|
|
|
)
|
|
|
|
)
|
|
|
|
|
|
|
|
# Check that they were set correctly
|
|
|
|
assert await asyncio.gather(
|
|
|
|
bot.get_my_short_description(),
|
|
|
|
bot.get_my_short_description("en"),
|
|
|
|
bot.get_my_short_description("de"),
|
|
|
|
) == [
|
|
|
|
BotShortDescription(default_short_description),
|
|
|
|
BotShortDescription(en_short_description),
|
|
|
|
BotShortDescription(de_short_description),
|
|
|
|
]
|
|
|
|
|
|
|
|
# Delete the short_descriptions
|
|
|
|
assert all(
|
|
|
|
await asyncio.gather(
|
|
|
|
bot.set_my_short_description(None),
|
|
|
|
bot.set_my_short_description(None, language_code="en"),
|
|
|
|
bot.set_my_short_description(None, language_code="de"),
|
|
|
|
)
|
|
|
|
)
|
|
|
|
|
|
|
|
# Check that they were deleted correctly
|
|
|
|
assert await asyncio.gather(
|
|
|
|
bot.get_my_short_description(),
|
|
|
|
bot.get_my_short_description("en"),
|
|
|
|
bot.get_my_short_description("de"),
|
|
|
|
) == 3 * [BotShortDescription("")]
|
2024-02-07 22:35:09 +01:00
|
|
|
|
2024-02-08 17:12:00 +01:00
|
|
|
async def test_set_message_reaction(self, bot, chat_id, message):
|
|
|
|
assert await bot.set_message_reaction(
|
|
|
|
chat_id, message.message_id, ReactionEmoji.THUMBS_DOWN, True
|
|
|
|
)
|
|
|
|
|
2024-02-07 22:35:09 +01:00
|
|
|
@pytest.mark.parametrize("bot_class", [Bot, ExtBot])
|
|
|
|
async def test_do_api_request_warning_known_method(self, bot, bot_class):
|
|
|
|
with pytest.warns(PTBDeprecationWarning, match="Please use 'Bot.get_me'") as record:
|
|
|
|
await bot_class(bot.token).do_api_request("get_me")
|
|
|
|
|
|
|
|
assert record[0].filename == __file__, "Wrong stack level!"
|
|
|
|
|
|
|
|
async def test_do_api_request_unknown_method(self, bot):
|
|
|
|
with pytest.raises(EndPointNotFound, match="'unknownEndpoint' not found"):
|
|
|
|
await bot.do_api_request("unknown_endpoint")
|
|
|
|
|
|
|
|
async def test_do_api_request_invalid_token(self, bot):
|
|
|
|
# we do not initialize the bot here on purpose b/c that's the case were we actually
|
|
|
|
# do not know for sure if the token is invalid or the method was not found
|
|
|
|
with pytest.raises(
|
|
|
|
InvalidToken, match="token was rejected by Telegram or the endpoint 'getMe'"
|
|
|
|
):
|
|
|
|
await Bot("invalid_token").do_api_request("get_me")
|
|
|
|
|
|
|
|
# same test, but with a valid token bot and unknown endpoint
|
|
|
|
with pytest.raises(
|
|
|
|
InvalidToken, match="token was rejected by Telegram or the endpoint 'unknownEndpoint'"
|
|
|
|
):
|
|
|
|
await Bot(bot.token).do_api_request("unknown_endpoint")
|
|
|
|
|
|
|
|
@pytest.mark.parametrize("return_type", [Message, None])
|
|
|
|
async def test_do_api_request_basic_and_files(self, bot, chat_id, return_type):
|
|
|
|
result = await bot.do_api_request(
|
|
|
|
"send_document",
|
|
|
|
api_kwargs={
|
|
|
|
"chat_id": chat_id,
|
|
|
|
"caption": "test_caption",
|
|
|
|
"document": InputFile(data_file("telegram.png").open("rb")),
|
|
|
|
},
|
|
|
|
return_type=return_type,
|
|
|
|
)
|
|
|
|
if return_type is None:
|
|
|
|
assert isinstance(result, dict)
|
|
|
|
result = Message.de_json(result, bot)
|
|
|
|
|
|
|
|
assert isinstance(result, Message)
|
|
|
|
assert result.chat_id == int(chat_id)
|
|
|
|
assert result.caption == "test_caption"
|
|
|
|
out = BytesIO()
|
|
|
|
await (await result.document.get_file()).download_to_memory(out)
|
|
|
|
out.seek(0)
|
|
|
|
assert out.read() == data_file("telegram.png").open("rb").read()
|
|
|
|
assert result.document.file_name == "telegram.png"
|
|
|
|
|
|
|
|
@pytest.mark.parametrize("return_type", [Message, None])
|
|
|
|
async def test_do_api_request_list_return_type(self, bot, chat_id, return_type):
|
|
|
|
result = await bot.do_api_request(
|
|
|
|
"send_media_group",
|
|
|
|
api_kwargs={
|
|
|
|
"chat_id": chat_id,
|
|
|
|
"media": [
|
|
|
|
InputMediaDocument(
|
|
|
|
InputFile(
|
|
|
|
data_file("text_file.txt").open("rb"),
|
|
|
|
attach=True,
|
|
|
|
)
|
|
|
|
),
|
|
|
|
InputMediaDocument(
|
|
|
|
InputFile(
|
|
|
|
data_file("local_file.txt").open("rb"),
|
|
|
|
attach=True,
|
|
|
|
)
|
|
|
|
),
|
|
|
|
],
|
|
|
|
},
|
|
|
|
return_type=return_type,
|
|
|
|
)
|
|
|
|
if return_type is None:
|
|
|
|
assert isinstance(result, list)
|
|
|
|
for entry in result:
|
|
|
|
assert isinstance(entry, dict)
|
|
|
|
result = Message.de_list(result, bot)
|
|
|
|
|
|
|
|
for message, file_name in zip(result, ("text_file.txt", "local_file.txt")):
|
|
|
|
assert isinstance(message, Message)
|
|
|
|
assert message.chat_id == int(chat_id)
|
|
|
|
out = BytesIO()
|
|
|
|
await (await message.document.get_file()).download_to_memory(out)
|
|
|
|
out.seek(0)
|
|
|
|
assert out.read() == data_file(file_name).open("rb").read()
|
|
|
|
assert message.document.file_name == file_name
|
|
|
|
|
|
|
|
@pytest.mark.parametrize("return_type", [Message, None])
|
|
|
|
async def test_do_api_request_bool_return_type(self, bot, chat_id, return_type):
|
|
|
|
assert await bot.do_api_request("delete_my_commands", return_type=return_type) is True
|