Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Asyncio #2731

Merged
merged 171 commits into from Apr 24, 2022
Merged

Asyncio #2731

Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
171 commits
Select commit Hold shift + click to select a range
f52a96d
Single, squashed commit
Bibo-Joshi Feb 6, 2022
ea70388
Get CH to roughly work
Bibo-Joshi Feb 8, 2022
c8b114f
Merge branch 'v14' into asyncio
Bibo-Joshi Feb 9, 2022
362e7b2
Start fixing some sphinx warnings
Bibo-Joshi Feb 9, 2022
ecd909d
More reference fixes
Bibo-Joshi Feb 9, 2022
d0565fc
Try fixing wrong source links on RTD
Bibo-Joshi Feb 10, 2022
985d24f
Slowly get started on request tests
Bibo-Joshi Feb 10, 2022
916fc20
More request tests
Bibo-Joshi Feb 12, 2022
c6b898a
Add two comments
Bibo-Joshi Feb 12, 2022
3008aad
Rework persistence logic
Bibo-Joshi Feb 13, 2022
f44ec18
Change pool timeout logic in HTTPXRequest
Bibo-Joshi Feb 14, 2022
6dbafc2
Handle unknown RequestResponse paramas
Bibo-Joshi Feb 15, 2022
6541090
Work on TrackingDict + tests
Bibo-Joshi Feb 15, 2022
fb76b4f
Re-add test_callbackdatacache.py
Bibo-Joshi Feb 15, 2022
70820ea
re-add test_filters.py
Bibo-Joshi Feb 15, 2022
1f564e3
Try fixing stuck CI
Bibo-Joshi Feb 16, 2022
d3d99cf
Get started on builder tests
Bibo-Joshi Feb 16, 2022
ac07df1
Builder tests
Bibo-Joshi Feb 17, 2022
ff04f65
Builder tests
Bibo-Joshi Feb 17, 2022
21c7cb7
Builder tests finished
Bibo-Joshi Feb 18, 2022
b7d007f
rename a file
Bibo-Joshi Feb 18, 2022
683edf6
Get started on updater tests
Bibo-Joshi Feb 20, 2022
01cb345
One more test & some code simplifications
Bibo-Joshi Feb 22, 2022
aa8ea12
Tests for Updater.start_polling
Bibo-Joshi Feb 22, 2022
884eb4e
First webhook test
Bibo-Joshi Feb 23, 2022
f55ab05
test arbitrary callback data
Bibo-Joshi Feb 24, 2022
d4d28f5
test webhooks with ssl
Bibo-Joshi Feb 24, 2022
29a2860
Another test
Bibo-Joshi Feb 24, 2022
c9180fa
adjust ssl handling in webhooks
Bibo-Joshi Feb 25, 2022
8b4aa7a
Finish Updater tests
Bibo-Joshi Feb 25, 2022
f262457
Try fixing existing tests
Bibo-Joshi Feb 26, 2022
a4080a4
Try harder
Bibo-Joshi Feb 26, 2022
e2a3907
Get started on application tests
Bibo-Joshi Feb 26, 2022
88978ff
Improve & tests logic if initializing, shutdown, start & stop
Bibo-Joshi Feb 26, 2022
254a65e
Further improve & test logic if initializing, shutdown, start & stop
Bibo-Joshi Feb 27, 2022
f3671fe
Few more application tests
Bibo-Joshi Feb 28, 2022
1ac116e
Few more application tests
Bibo-Joshi Mar 1, 2022
d6f95a9
fix updater tests
Bibo-Joshi Mar 2, 2022
af42aaf
More application tests - move tests for persistence integration into …
Bibo-Joshi Mar 6, 2022
611c780
Merge remote-tracking branch 'origin/asyncio' into asyncio
Bibo-Joshi Mar 6, 2022
a7b5fbd
jobqueue tests - jk, it's still application tests
Bibo-Joshi Mar 6, 2022
59c96fa
you guessed it: application tests
Bibo-Joshi Mar 7, 2022
ddf4bb3
Fix tests
Bibo-Joshi Mar 7, 2022
ed0ae0a
Simplify a type hint
Bibo-Joshi Mar 9, 2022
30bf475
Test run_polling/updater
Bibo-Joshi Mar 9, 2022
74aab4c
Merge remote-tracking branch 'origin/asyncio' into asyncio
Bibo-Joshi Mar 9, 2022
24dc3e6
skip more tests on windows
Bibo-Joshi Mar 10, 2022
8ab79f3
Small fix for applicationbuilder
Bibo-Joshi Mar 10, 2022
c97a532
Test a few more edge cases for application
Bibo-Joshi Mar 10, 2022
272da63
Make test suit run on PRs against asyncio branch
Bibo-Joshi Mar 10, 2022
b130115
Remove doubled assertion
Bibo-Joshi Mar 10, 2022
9a347ca
Slowly get started on testing persistence integration
Bibo-Joshi Mar 10, 2022
83d7367
also test conversationhandler-persistence-integration
Bibo-Joshi Mar 10, 2022
98d35af
Actually write some tests
Bibo-Joshi Mar 10, 2022
d6c8652
Small fix for persistence init
Bibo-Joshi Mar 10, 2022
6bc2abd
Merge branch 'asyncio' into asyncio-tests
Bibo-Joshi Mar 10, 2022
988b300
More persistence integration tests
Bibo-Joshi Mar 11, 2022
5509d71
fix smaller bugs that surfaced while testing persistence integration
Bibo-Joshi Mar 11, 2022
2d2a287
Merge branch 'asyncio' into asyncio-tests
Bibo-Joshi Mar 11, 2022
464253f
Review + according tests
Bibo-Joshi Mar 12, 2022
0094683
Merge branch 'v14' into asyncio
Bibo-Joshi Mar 12, 2022
14e4277
Try fixing tests
Bibo-Joshi Mar 12, 2022
b2a7520
Try harder
Bibo-Joshi Mar 12, 2022
dd761be
Merge branch 'asyncio' into asyncio-tests
Bibo-Joshi Mar 12, 2022
326117a
rename test_persistence_integration.py to test_basepersistence.py
Bibo-Joshi Mar 12, 2022
037f53c
Add some basic BasePersistence tests & adjust to the dropped replace…
Bibo-Joshi Mar 12, 2022
82bfb01
Try stabilizing on macOS
Bibo-Joshi Mar 13, 2022
cb7934e
Try again
Bibo-Joshi Mar 13, 2022
8fd6659
Test drop/migrate data
Bibo-Joshi Mar 13, 2022
a3f15f9
Add a convenience utility to conftest
Bibo-Joshi Mar 13, 2022
4122450
test Updater.start_* return value
Bibo-Joshi Mar 15, 2022
9e6c4d8
Large parts of review
Bibo-Joshi Mar 17, 2022
cee0d3c
More review
Bibo-Joshi Mar 18, 2022
7546bbf
Merge branch 'asyncio' into asyncio-tests
Bibo-Joshi Mar 18, 2022
234858c
make meta-tests path-agnostic
Bibo-Joshi Mar 18, 2022
3ef4d67
fix join request test
Bibo-Joshi Mar 18, 2022
745bfd1
Remove a sleep
Bibo-Joshi Mar 18, 2022
02940bb
revert catching cancelledError on polling stop
Bibo-Joshi Mar 18, 2022
baddee6
Merge branch 'asyncio' into asyncio-tests
Bibo-Joshi Mar 18, 2022
257b161
Adjust tests for now bahvior of adding ConversationHandler after init
Bibo-Joshi Mar 19, 2022
38df2b7
Allow App.process_update only after App. initialize was called
Bibo-Joshi Mar 19, 2022
89ba4a4
Merge branch 'asyncio' into asyncio-tests
Bibo-Joshi Mar 19, 2022
aa864e9
adjust tests
Bibo-Joshi Mar 19, 2022
27d439a
Fix run_* tests on non-windows
Bibo-Joshi Mar 19, 2022
2e897f0
Review
Bibo-Joshi Mar 22, 2022
af8a57a
More review
Bibo-Joshi Mar 22, 2022
7ae7d48
Merge branch 'asyncio' into asyncio-tests
Bibo-Joshi Mar 22, 2022
0996559
Change error types
Bibo-Joshi Mar 22, 2022
7a60432
Merge branch 'asyncio' into asyncio-tests
Bibo-Joshi Mar 22, 2022
ab891d1
adjust tests
Bibo-Joshi Mar 22, 2022
7672789
Two more BP tests
Bibo-Joshi Mar 23, 2022
43ede97
fix a test
Bibo-Joshi Mar 23, 2022
bdef5fd
one more BP test
Bibo-Joshi Mar 23, 2022
b3564c2
review
Bibo-Joshi Mar 23, 2022
79de11c
Remove remaining threading logic
Bibo-Joshi Mar 24, 2022
476a68d
Add notes on testing CH-BP integration and postpone that for now
Bibo-Joshi Mar 24, 2022
cae4e18
Test CallbackContext
Bibo-Joshi Mar 24, 2022
f90cd50
Test Defaults
Bibo-Joshi Mar 24, 2022
6012501
Get started on JobQueue Tests - half of them is still failing
Bibo-Joshi Mar 24, 2022
cc46bbf
Make JobQueue.start asyncio
Bibo-Joshi Mar 24, 2022
68e3471
Merge branch 'asyncio' into asyncio-tests
Bibo-Joshi Mar 24, 2022
ececf9f
adjust tests
Bibo-Joshi Mar 24, 2022
06ebc12
Merge remote-tracking branch 'origin/asyncio' into asyncio
Bibo-Joshi Mar 24, 2022
138ba20
finish up job_queue tests
Bibo-Joshi Mar 25, 2022
363bfef
some JQ tweaks
Bibo-Joshi Mar 25, 2022
901b936
Merge branch 'asyncio' into asyncio-tests
Bibo-Joshi Mar 25, 2022
a852ec6
Test all handles except for CH
Bibo-Joshi Mar 26, 2022
346ac17
fix the test suite
Bibo-Joshi Mar 26, 2022
424f810
small tweak in DictPersistence
Bibo-Joshi Mar 27, 2022
d9e0eda
Try to improve non-blocking logic of CH
Bibo-Joshi Mar 30, 2022
2fc5eeb
Remove some resolved todo items
Bibo-Joshi Mar 30, 2022
737e013
some more
Bibo-Joshi Mar 30, 2022
d14e55d
fix a typo
Bibo-Joshi Mar 30, 2022
0f69b02
Rename App.dispatch_error to App.process_error
Bibo-Joshi Apr 1, 2022
e31419c
fix a bug in persisting non-blocking conversations
Bibo-Joshi Apr 1, 2022
d189ce3
Review
Bibo-Joshi Apr 3, 2022
a4b37fd
Small adjustments for persistence
Bibo-Joshi Apr 3, 2022
a0204c6
Fix persistence of nested conversations
Bibo-Joshi Apr 3, 2022
655d080
Remove unused method from webhook setup
Bibo-Joshi Apr 3, 2022
c99645e
Review
Bibo-Joshi Apr 4, 2022
40f886b
more adjusting
Bibo-Joshi Apr 4, 2022
02f3bf3
Review
Bibo-Joshi Apr 5, 2022
ed2a39e
Make CH.persistent immutable
Bibo-Joshi Apr 5, 2022
9891fd4
Merge remote-tracking branch 'origin/asyncio' into asyncio
Bibo-Joshi Apr 5, 2022
51b4044
typo
Bibo-Joshi Apr 7, 2022
1a16bda
Remove falsely committed debug print
Bibo-Joshi Apr 8, 2022
92e2cdd
Review
Bibo-Joshi Apr 10, 2022
62fc4ff
Updating the examples (#2937)
Poolitzer Apr 10, 2022
8411d62
log errors in Update.de_json in Updater
Bibo-Joshi Apr 10, 2022
59e0c0a
Merge remote-tracking branch 'origin/asyncio' into asyncio
Bibo-Joshi Apr 10, 2022
c116f2e
Stabilize startup of App.run()
Bibo-Joshi Apr 12, 2022
43ca1da
Add another warning about CH timeout not working if JQ is not running
Bibo-Joshi Apr 12, 2022
87e977f
change blocking-resolution order in CH
Bibo-Joshi Apr 16, 2022
ef4bc43
small fix
Bibo-Joshi Apr 16, 2022
c46fcdd
Docs/CSI for asyncio (#2926)
harshil21 Apr 17, 2022
e8fdd13
Asyncio Tests (#2936)
Bibo-Joshi Apr 17, 2022
bafd4ed
pre-commit
Bibo-Joshi Apr 17, 2022
0c9be83
some typos, wording etc
Bibo-Joshi Apr 17, 2022
696e622
Apply black style to code blocks in docs
Bibo-Joshi Apr 17, 2022
b0605a7
avoid the term "asynchronously"
Bibo-Joshi Apr 17, 2022
6938ed8
Some docstring improvements for app
Bibo-Joshi Apr 17, 2022
6828757
Fix a warning on custom CC attributes
Bibo-Joshi Apr 17, 2022
ec784a7
Improve usage of AbstractAsyncContextManager
Bibo-Joshi Apr 17, 2022
26b0dc4
Some versioning directives
Bibo-Joshi Apr 17, 2022
d7ff692
fix tests
Bibo-Joshi Apr 17, 2022
d7b9643
small edits for tests
Bibo-Joshi Apr 17, 2022
b6eef7e
Review
Bibo-Joshi Apr 17, 2022
c61afc8
Update timerbot a bit
Bibo-Joshi Apr 17, 2022
70ee0ff
shutdown with signal handlers
Bibo-Joshi Apr 17, 2022
54c83dc
try improving tests
Bibo-Joshi Apr 17, 2022
b8f41a5
try again
Bibo-Joshi Apr 17, 2022
0a83834
One last try
Bibo-Joshi Apr 17, 2022
193c435
fix some docs of HTTPXRequest
Bibo-Joshi Apr 18, 2022
079fca1
move definition of InitAppBuilder type alias to bottom of file
harshil21 Apr 18, 2022
a1bf431
try to make codacy happy w.r.t hardcoded token in example
harshil21 Apr 18, 2022
74bf2df
add a debug print to failing test
Bibo-Joshi Apr 18, 2022
bd8fe9e
try fixing the failing test
Bibo-Joshi Apr 18, 2022
a7a11bc
create_task while not running: warn instead of log
Bibo-Joshi Apr 18, 2022
9a541f0
second try for failing test
Bibo-Joshi Apr 18, 2022
c7677c2
tiny doc fix
Bibo-Joshi Apr 19, 2022
b4fa728
Another small doc fix
Bibo-Joshi Apr 19, 2022
12f1322
jobqueue doc fixes
harshil21 Apr 20, 2022
bafe934
Rework uploading files - tests for RequestData are not yet adjusted
Bibo-Joshi Apr 21, 2022
f36aafb
Merge remote-tracking branch 'origin/asyncio' into asyncio
Bibo-Joshi Apr 21, 2022
0086ad5
doc adjustments
Bibo-Joshi Apr 22, 2022
1aa2fc1
Test RequestData
Bibo-Joshi Apr 22, 2022
f1f7e24
document a limit about send_document/voice
harshil21 Apr 22, 2022
88b8e19
Fix: Small doc fixes + improvements
Poolitzer Apr 23, 2022
58c7781
forgot to commit review
Bibo-Joshi Apr 24, 2022
66d9a13
fix pre-commit
Bibo-Joshi Apr 24, 2022
9389bc9
finally fix certificate passing
Bibo-Joshi Apr 24, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 5 additions & 5 deletions telegram/_bot.py
Expand Up @@ -1036,7 +1036,7 @@ async def send_audio(
if caption_entities:
data['caption_entities'] = caption_entities
if thumb:
data['thumb'] = parse_file_input(thumb)
data['thumb'] = parse_file_input(thumb, attach=True)
harshil21 marked this conversation as resolved.
Show resolved Hide resolved

return await self._send_message( # type: ignore[return-value]
'sendAudio',
Expand Down Expand Up @@ -1171,7 +1171,7 @@ async def send_document(
if disable_content_type_detection is not None:
data['disable_content_type_detection'] = disable_content_type_detection
if thumb:
data['thumb'] = parse_file_input(thumb)
data['thumb'] = parse_file_input(thumb, attach=True)

return await self._send_message( # type: ignore[return-value]
'sendDocument',
Expand Down Expand Up @@ -1410,7 +1410,7 @@ async def send_video(
if height:
data['height'] = height
if thumb:
data['thumb'] = parse_file_input(thumb)
data['thumb'] = parse_file_input(thumb, attach=True)

return await self._send_message( # type: ignore[return-value]
'sendVideo',
Expand Down Expand Up @@ -1533,7 +1533,7 @@ async def send_video_note(
if length is not None:
data['length'] = length
if thumb:
data['thumb'] = parse_file_input(thumb)
data['thumb'] = parse_file_input(thumb, attach=True)

return await self._send_message( # type: ignore[return-value]
'sendVideoNote',
Expand Down Expand Up @@ -1673,7 +1673,7 @@ async def send_animation(
if height:
data['height'] = height
if thumb:
data['thumb'] = parse_file_input(thumb)
data['thumb'] = parse_file_input(thumb, attach=True)
if caption:
data['caption'] = caption
if caption_entities:
Expand Down
20 changes: 14 additions & 6 deletions telegram/_files/inputfile.py
Expand Up @@ -49,25 +49,32 @@ class InputFile:
.. versionchanged:: 14.0
Accept string input.
filename (:obj:`str`, optional): Filename for this InputFile.
attach (:obj:`bool`, optional): Pass :obj:`True` if the parameter this file belongs to in
the request to Telegram should point to the multipart data via an ``attach://`` URI.
Defaults to `False`.

Attributes:
input_file_content (:obj:`bytes`): The binary content of the file to send.
attach_name (:obj:`str`): Attach name.
attach_name (:obj:`str`, Optional ): If present, the parameter this file belongs to in
Bibo-Joshi marked this conversation as resolved.
Show resolved Hide resolved
the request to Telegram should point to the multipart data via a an URI of the form
``attach://<attach_name>`` URI.
filename (:obj:`str`): Filename for the file to be sent.
mimetype (:obj:`str`): The mimetype inferred from the file to be sent.

"""

__slots__ = ('filename', 'attach_name', 'input_file_content', 'mimetype')

def __init__(self, obj: Union[IO[bytes], bytes, str], filename: str = None):
def __init__(
self, obj: Union[IO[bytes], bytes, str], filename: str = None, attach: bool = False
):
if isinstance(obj, bytes):
self.input_file_content = obj
elif isinstance(obj, str):
self.input_file_content = obj.encode('utf-8')
else:
self.input_file_content = obj.read()
self.attach_name = 'attached' + uuid4().hex
self.attach_name: Optional[str] = 'attached' + uuid4().hex if attach else None

if (
not filename
Expand Down Expand Up @@ -119,6 +126,7 @@ def field_tuple(self) -> FieldTuple:
return self.filename, self.input_file_content, self.mimetype

@property
def attach_uri(self) -> str:
"""URI to insert into the JSON data for uploading the file."""
return f'attach://{self.attach_name}'
def attach_uri(self) -> Optional[str]:
"""URI to insert into the JSON data for uploading the file. Returns :obj:`None`, if
:attr:`attach_name` is :obj:`None`."""
return f'attach://{self.attach_name}' if self.attach_name else None
12 changes: 6 additions & 6 deletions telegram/_files/inputmedia.py
Expand Up @@ -103,7 +103,7 @@ def to_dict(self) -> JSONDict:

@staticmethod
def _parse_thumb_input(thumb: Optional[FileInput]) -> Optional[Union[str, InputFile]]:
return parse_file_input(thumb) if thumb is not None else thumb
return parse_file_input(thumb, attach=True) if thumb is not None else thumb


class InputMediaAnimation(InputMedia):
Expand Down Expand Up @@ -184,7 +184,7 @@ def __init__(
duration = media.duration if duration is None else duration
media = media.file_id
else:
media = parse_file_input(media, filename=filename)
media = parse_file_input(media, filename=filename, attach=True)

super().__init__(InputMediaType.ANIMATION, media, caption, caption_entities, parse_mode)
self.thumb = self._parse_thumb_input(thumb)
Expand Down Expand Up @@ -240,7 +240,7 @@ def __init__(
caption_entities: Union[List[MessageEntity], Tuple[MessageEntity, ...]] = None,
filename: str = None,
):
media = parse_file_input(media, PhotoSize, filename=filename)
media = parse_file_input(media, PhotoSize, filename=filename, attach=True)
super().__init__(InputMediaType.PHOTO, media, caption, caption_entities, parse_mode)


Expand Down Expand Up @@ -331,7 +331,7 @@ def __init__(
duration = duration if duration is not None else media.duration
media = media.file_id
else:
media = parse_file_input(media, filename=filename)
media = parse_file_input(media, filename=filename, attach=True)

super().__init__(InputMediaType.VIDEO, media, caption, caption_entities, parse_mode)
self.width = width
Expand Down Expand Up @@ -422,7 +422,7 @@ def __init__(
title = media.title if title is None else title
media = media.file_id
else:
media = parse_file_input(media, filename=filename)
media = parse_file_input(media, filename=filename, attach=True)

super().__init__(InputMediaType.AUDIO, media, caption, caption_entities, parse_mode)
self.thumb = self._parse_thumb_input(thumb)
Expand Down Expand Up @@ -496,7 +496,7 @@ def __init__(
caption_entities: Union[List[MessageEntity], Tuple[MessageEntity, ...]] = None,
filename: str = None,
):
media = parse_file_input(media, Document, filename=filename)
media = parse_file_input(media, Document, filename=filename, attach=True)
super().__init__(InputMediaType.DOCUMENT, media, caption, caption_entities, parse_mode)
self.thumb = self._parse_thumb_input(thumb)
self.disable_content_type_detection = disable_content_type_detection
36 changes: 36 additions & 0 deletions telegram/_utils/enum.py
@@ -0,0 +1,36 @@
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2022
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# 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
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a helper class for Enums that should be subclasses of `str`.

Warning:
Contents of this module are intended to be used internally by the library and *not* by the
user. Changes to this module are not considered breaking changes and may not be documented in
the changelog.
"""
from enum import Enum


class StringEnum(str, Enum):
"""Helper class for string enums where the value is not important to be displayed on
stringification.
"""

__slots__ = ()

def __repr__(self) -> str:
return f'<{self.__class__.__name__}.{self.name}>'
8 changes: 6 additions & 2 deletions telegram/_utils/files.py
Expand Up @@ -58,6 +58,7 @@ def parse_file_input(
file_input: Union[FileInput, 'TelegramObject'],
tg_type: Type['TelegramObject'] = None,
filename: str = None,
attach: bool = False,
) -> Union[str, 'InputFile', Any]:
"""
Parses input for sending files:
Expand All @@ -77,6 +78,9 @@ def parse_file_input(
:class:`telegram.Animation`.
filename (:obj:`str`, optional): The filename. Only relevant in case an
:class:`telegram.InputFile` is returned.
attach (:obj:`bool`, optional): Pass :obj:`True` if the parameter this file belongs to in
the request to Telegram should point to the multipart data via an ``attach://`` URI.
Defaults to `False`. Only relevant if an :class:`telegram.InputFile` is returned.

Returns:
:obj:`str` | :class:`telegram.InputFile` | :obj:`object`: The parsed input or the untouched
Expand All @@ -94,9 +98,9 @@ def parse_file_input(
out = file_input # type: ignore[assignment]
return out
if isinstance(file_input, bytes):
return InputFile(file_input, filename=filename)
return InputFile(file_input, filename=filename, attach=attach)
if hasattr(file_input, 'read'):
return InputFile(cast(IO, file_input), filename=filename)
return InputFile(cast(IO, file_input), filename=filename, attach=attach)
if tg_type and isinstance(file_input, tg_type):
return file_input.file_id # type: ignore[attr-defined]
return file_input
42 changes: 16 additions & 26 deletions telegram/constants.py
Expand Up @@ -63,20 +63,10 @@
'UpdateType',
]

from enum import Enum, IntEnum
from enum import IntEnum
from typing import List


class _StringEnum(str, Enum):
"""Helper class for string enums where the value is not important to be displayed on
stringification.
"""

__slots__ = ()

def __repr__(self) -> str:
return f'<{self.__class__.__name__}.{self.name}>'

from telegram._utils.enum import StringEnum

BOT_API_VERSION = '5.7'

Expand All @@ -85,7 +75,7 @@ def __repr__(self) -> str:
SUPPORTED_WEBHOOK_PORTS: List[int] = [443, 80, 88, 8443]


class BotCommandScopeType(_StringEnum):
class BotCommandScopeType(StringEnum):
"""This enum contains the available types of :class:`telegram.BotCommandScope`. The enum
members of this enumeration are instances of :class:`str` and can be treated as such.

Expand Down Expand Up @@ -125,7 +115,7 @@ class CallbackQueryLimit(IntEnum):
:meth:`telegram.Bot.answer_callback_query`."""


class ChatAction(_StringEnum):
class ChatAction(StringEnum):
"""This enum contains the available chat actions for :meth:`telegram.Bot.send_chat_action`.
The enum members of this enumeration are instances of :class:`str` and can be treated as such.

Expand Down Expand Up @@ -210,7 +200,7 @@ class ChatInviteLinkLimit(IntEnum):
:meth:`telegram.Bot.create_chat_invite_link` and :meth:`telegram.Bot.edit_chat_invite_link`."""


class ChatMemberStatus(_StringEnum):
class ChatMemberStatus(StringEnum):
"""This enum contains the available states for :class:`telegram.ChatMember`. The enum
members of this enumeration are instances of :class:`str` and can be treated as such.

Expand All @@ -233,7 +223,7 @@ class ChatMemberStatus(_StringEnum):
""":obj:`str`: A :class:`telegram.ChatMember` who was restricted in this chat."""


class ChatType(_StringEnum):
class ChatType(StringEnum):
"""This enum contains the available types of :class:`telegram.Chat`. The enum
members of this enumeration are instances of :class:`str` and can be treated as such.

Expand All @@ -255,7 +245,7 @@ class ChatType(_StringEnum):
""":obj:`str`: A :class:`telegram.Chat` that is a channel."""


class DiceEmoji(_StringEnum):
class DiceEmoji(StringEnum):
"""This enum contains the available emoji for :class:`telegram.Dice`/
:meth:`telegram.Bot.send_dice`. The enum
members of this enumeration are instances of :class:`str` and can be treated as such.
Expand Down Expand Up @@ -344,7 +334,7 @@ class InlineKeyboardMarkupLimit(IntEnum):
"""


class InputMediaType(_StringEnum):
class InputMediaType(StringEnum):
"""This enum contains the available types of :class:`telegram.InputMedia`. The enum
members of this enumeration are instances of :class:`str` and can be treated as such.

Expand Down Expand Up @@ -383,7 +373,7 @@ class InlineQueryLimit(IntEnum):
:meth:`telegram.Bot.answer_inline_query`."""


class InlineQueryResultType(_StringEnum):
class InlineQueryResultType(StringEnum):
"""This enum contains the available types of :class:`telegram.InlineQueryResult`. The enum
members of this enumeration are instances of :class:`str` and can be treated as such.

Expand Down Expand Up @@ -457,7 +447,7 @@ class LocationLimit(IntEnum):
"""


class MaskPosition(_StringEnum):
class MaskPosition(StringEnum):
"""This enum contains the available positions for :class:`telegram.MaskPosition`. The enum
members of this enumeration are instances of :class:`str` and can be treated as such.

Expand All @@ -476,7 +466,7 @@ class MaskPosition(_StringEnum):
""":obj:`str`: Mask position for a sticker on the chin."""


class MessageAttachmentType(_StringEnum):
class MessageAttachmentType(StringEnum):
"""This enum contains the available types of :class:`telegram.Message` that can bee seens
as attachment. The enum
members of this enumeration are instances of :class:`str` and can be treated as such.
Expand Down Expand Up @@ -525,7 +515,7 @@ class MessageAttachmentType(_StringEnum):
""":obj:`str`: Messages with :attr:`telegram.Message.venue`."""


class MessageEntityType(_StringEnum):
class MessageEntityType(StringEnum):
"""This enum contains the available types of :class:`telegram.MessageEntity`. The enum
members of this enumeration are instances of :class:`str` and can be treated as such.

Expand Down Expand Up @@ -592,7 +582,7 @@ class MessageLimit(IntEnum):
"""


class MessageType(_StringEnum):
class MessageType(StringEnum):
"""This enum contains the available types of :class:`telegram.Message` that can be seen
as attachment. The enum
members of this enumeration are instances of :class:`str` and can be treated as such.
Expand Down Expand Up @@ -679,7 +669,7 @@ class MessageType(_StringEnum):
""":obj:`str`: Messages with :attr:`telegram.Message.voice_chat_participants_invited`."""


class ParseMode(_StringEnum):
class ParseMode(StringEnum):
"""This enum contains the available parse modes. The enum
members of this enumeration are instances of :class:`str` and can be treated as such.

Expand Down Expand Up @@ -719,7 +709,7 @@ class PollLimit(IntEnum):
""":obj:`str`: Maximum number of available options for the poll."""


class PollType(_StringEnum):
class PollType(StringEnum):
"""This enum contains the available types for :class:`telegram.Poll`/
:meth:`telegram.Bot.send_poll`. The enum
members of this enumeration are instances of :class:`str` and can be treated as such.
Expand All @@ -735,7 +725,7 @@ class PollType(_StringEnum):
""":obj:`str`: quiz polls."""


class UpdateType(_StringEnum):
class UpdateType(StringEnum):
"""This enum contains the available types of :class:`telegram.Update`. The enum
members of this enumeration are instances of :class:`str` and can be treated as such.

Expand Down
2 changes: 0 additions & 2 deletions telegram/request/_baserequest.py
Expand Up @@ -18,7 +18,6 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an abstract class to make POST and GET requests."""
import abc
import traceback
from contextlib import AbstractAsyncContextManager
from http import HTTPStatus
from types import TracebackType
Expand Down Expand Up @@ -280,7 +279,6 @@ async def _request_wrapper(
except TelegramError as exc:
raise exc
except Exception as exc:
traceback.print_tb(exc.__traceback__)
raise NetworkError(f"Unknown error in HTTP implementation: {repr(exc)}") from exc

if HTTPStatus.OK <= code <= 299:
Expand Down