- Notifications
You must be signed in to change notification settings - Fork5.7k
Extend Customization Support forBot.base_(file_)url
#4632
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.
Already on GitHub?Sign in to your account
Merged
Uh oh!
There was an error while loading.Please reload this page.
Merged
Changes fromall commits
Commits
Show all changes
8 commits Select commitHold shift + click to select a range
8897ae2
Extend Customization Support for `Bot.base_(file_)url`
Bibo-Joshic4548b7
parametrize with list instead of set
Bibo-Joshi652aeba
Merge branch 'master' into feature/test-env
Bibo-Joshi790cd47
try fixing log assertions
Bibo-Joshi660ec21
fix other affected test
Bibo-Joshia7f50c4
Merge branch 'master' into feature/test-env
Bibo-Joshi936ed20
Merge branch 'master' into feature/test-env
Bibo-Joshid4cb684
review
Bibo-JoshiFile filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Diff view
Diff view
There are no files selected for viewing
89 changes: 80 additions & 9 deletionstelegram/_bot.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -96,7 +96,14 @@ | ||
from telegram._utils.logging import get_logger | ||
from telegram._utils.repr import build_repr_with_selected_attrs | ||
from telegram._utils.strings import to_camel_case | ||
from telegram._utils.types import ( | ||
BaseUrl, | ||
CorrectOptionID, | ||
FileInput, | ||
JSONDict, | ||
ODVInput, | ||
ReplyMarkup, | ||
) | ||
from telegram._utils.warnings import warn | ||
from telegram._webhookinfo import WebhookInfo | ||
from telegram.constants import InlineQueryLimit, ReactionEmoji | ||
@@ -126,6 +133,35 @@ | ||
BT = TypeVar("BT", bound="Bot") | ||
# Even though we document only {token} as supported insertion, we are a bit more flexible | ||
# internally and support additional variants. At the very least, we don't want the insertion | ||
# to be case sensitive. | ||
_SUPPORTED_INSERTIONS = {"token", "TOKEN", "bot_token", "BOT_TOKEN", "bot-token", "BOT-TOKEN"} | ||
_INSERTION_STRINGS = {f"{{{insertion}}}" for insertion in _SUPPORTED_INSERTIONS} | ||
class _TokenDict(dict): | ||
__slots__ = ("token",) | ||
# small helper to make .format_map work without knowing which exact insertion name is used | ||
def __init__(self, token: str): | ||
self.token = token | ||
super().__init__() | ||
def __missing__(self, key: str) -> str: | ||
if key in _SUPPORTED_INSERTIONS: | ||
return self.token | ||
raise KeyError(f"Base URL string contains unsupported insertion: {key}") | ||
def _parse_base_url(value: BaseUrl, token: str) -> str: | ||
if callable(value): | ||
return value(token) | ||
if any(insertion in value for insertion in _INSERTION_STRINGS): | ||
return value.format_map(_TokenDict(token)) | ||
harshil21 marked this conversation as resolved. Show resolvedHide resolvedUh oh!There was an error while loading.Please reload this page. | ||
return value + token | ||
class Bot(TelegramObject, contextlib.AbstractAsyncContextManager["Bot"]): | ||
"""This object represents a Telegram Bot. | ||
@@ -193,8 +229,40 @@ class Bot(TelegramObject, contextlib.AbstractAsyncContextManager["Bot"]): | ||
Args: | ||
token (:obj:`str`): Bot's unique authentication token. | ||
base_url (:obj:`str` | Callable[[:obj:`str`], :obj:`str`], optional): Telegram Bot API | ||
harshil21 marked this conversation as resolved. Show resolvedHide resolvedUh oh!There was an error while loading.Please reload this page. | ||
service URL. If the string contains ``{token}``, it will be replaced with the bot's | ||
token. If a callable is passed, it will be called with the bot's token as the only | ||
argument and must return the base URL. Otherwise, the token will be appended to the | ||
string. Defaults to ``"https://api.telegram.org/bot"``. | ||
Tip: | ||
Customizing the base URL can be used to run a bot against | ||
:wiki:`Local Bot API Server <Local-Bot-API-Server>` or using Telegrams | ||
`test environment \ | ||
<https://core.telegram.org/bots/features#dedicated-test-environment>`_. | ||
Example: | ||
``"https://api.telegram.org/bot{token}/test"`` | ||
.. versionchanged:: NEXT.VERSION | ||
Supports callable input and string formatting. | ||
base_file_url (:obj:`str`, optional): Telegram Bot API file URL. | ||
If the string contains ``{token}``, it will be replaced with the bot's | ||
token. If a callable is passed, it will be called with the bot's token as the only | ||
argument and must return the base URL. Otherwise, the token will be appended to the | ||
string. Defaults to ``"https://api.telegram.org/bot"``. | ||
Tip: | ||
Customizing the base URL can be used to run a bot against | ||
:wiki:`Local Bot API Server <Local-Bot-API-Server>` or using Telegrams | ||
`test environment \ | ||
<https://core.telegram.org/bots/features#dedicated-test-environment>`_. | ||
Example: | ||
``"https://api.telegram.org/file/bot{token}/test"`` | ||
.. versionchanged:: NEXT.VERSION | ||
Supports callable input and string formatting. | ||
request (:class:`telegram.request.BaseRequest`, optional): Pre initialized | ||
:class:`telegram.request.BaseRequest` instances. Will be used for all bot methods | ||
*except* for :meth:`get_updates`. If not passed, an instance of | ||
@@ -239,8 +307,8 @@ class Bot(TelegramObject, contextlib.AbstractAsyncContextManager["Bot"]): | ||
def __init__( | ||
self, | ||
token: str, | ||
base_url:BaseUrl = "https://api.telegram.org/bot", | ||
base_file_url:BaseUrl = "https://api.telegram.org/file/bot", | ||
request: Optional[BaseRequest] = None, | ||
get_updates_request: Optional[BaseRequest] = None, | ||
private_key: Optional[bytes] = None, | ||
@@ -252,8 +320,11 @@ def __init__( | ||
raise InvalidToken("You must pass the token you received from https://t.me/Botfather!") | ||
self._token: str = token | ||
self._base_url: str = _parse_base_url(base_url, self._token) | ||
self._base_file_url: str = _parse_base_url(base_file_url, self._token) | ||
self._LOGGER.debug("Set Bot API URL: %s", self._base_url) | ||
self._LOGGER.debug("Set Bot API File URL: %s", self._base_file_url) | ||
self._local_mode: bool = local_mode | ||
self._bot_user: Optional[User] = None | ||
self._private_key: Optional[bytes] = None | ||
@@ -264,7 +335,7 @@ def __init__( | ||
HTTPXRequest() if request is None else request, | ||
) | ||
# this section is about issuing a warning when using HTTP/2 and connect to a self-hosted | ||
# bot api instance, which currently only supports HTTP/1.1. Checking if a custom base url | ||
# is set is the best way to do that. | ||
@@ -273,14 +344,14 @@ def __init__( | ||
if ( | ||
isinstance(self._request[0], HTTPXRequest) | ||
and self._request[0].http_version == "2" | ||
and notself.base_url.startswith("https://api.telegram.org/bot") | ||
): | ||
warning_string = "get_updates_request" | ||
if ( | ||
isinstance(self._request[1], HTTPXRequest) | ||
and self._request[1].http_version == "2" | ||
and notself.base_url.startswith("https://api.telegram.org/bot") | ||
): | ||
if warning_string: | ||
warning_string += " and request" | ||
4 changes: 3 additions & 1 deletiontelegram/_utils/types.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
30 changes: 23 additions & 7 deletionstelegram/ext/_applicationbuilder.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
21 changes: 14 additions & 7 deletionstelegram/ext/_extbot.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
72 changes: 70 additions & 2 deletionstests/test_bot.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Oops, something went wrong.
Uh oh!
There was an error while loading.Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.