Skip to content

Commit 8bf88c3

Browse files
Bibo-Joshideepsource-autofix[bot]Poolitzer
authored
Supplement Codacy with DeepSource (python-telegram-bot#2454)
* Add deepsource config * Update Badges * Update Badges some more * Stupid change to trigger analysis of all files * Try to get ignore right * Update badges again * Get started on fixing issues * Fix some more issues * Remove more plank lines * Docs for de_json/list & to_dict/json * Some improvements from deepcode.ai * Some more improvements * Some more improvements * More docstrnigs & let's run DS on the tests just for fun * Autofix issues in 10 files Resolved issues in the following files via DeepSource Autofix: 1. tests/conftest.py 2. tests/test_bot.py 3. tests/test_commandhandler.py 4. tests/test_conversationhandler.py 5. tests/test_dispatcher.py 6. tests/test_filters.py 7. tests/test_inputmedia.py 8. tests/test_messagehandler.py 9. tests/test_official.py 10. tests/test_persistence.py * Some more improvements for tests, but that shall be enough * Some more docstrings for functions * Some minor stuff, try to fix tests * Update DS config * Still more docs * Doc fixes * More fixes * Fix: indent docstring * Some fixes * Revert "Stupid change to trigger analysis of all files" This reverts commit dd46c26 * Review Co-authored-by: deepsource-autofix[bot] <62050782+deepsource-autofix[bot]@users.noreply.github.com> Co-authored-by: Poolitzer <[email protected]>
1 parent 1572c61 commit 8bf88c3

95 files changed

Lines changed: 674 additions & 492 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

.deepsource.toml

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
version = 1
2+
3+
test_patterns = ["tests/**"]
4+
5+
exclude_patterns = [
6+
"tests/**",
7+
"docs/**",
8+
"telegram/vendor/**",
9+
"setup.py",
10+
"setup-raw.py"
11+
]
12+
13+
[[analyzers]]
14+
name = "python"
15+
enabled = true
16+
17+
[analyzers.meta]
18+
runtime_version = "3.x.x"
19+
max_line_length = 99
20+
skip_doc_coverage = ["module", "magic", "init", "nonpublic"]

README.rst

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,10 +50,14 @@ We have a vibrant community of developers helping each other in our `Telegram gr
5050

5151
.. image:: https://api.codacy.com/project/badge/Grade/99d901eaa09b44b4819aec05c330c968
5252
:target: https://www.codacy.com/app/python-telegram-bot/python-telegram-bot?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=python-telegram-bot/python-telegram-bot&amp;utm_campaign=Badge_Grade
53-
:alt: Code quality
53+
:alt: Code quality: Codacy
54+
55+
.. image:: https://deepsource.io/gh/python-telegram-bot/python-telegram-bot.svg/?label=active+issues
56+
:target: https://deepsource.io/gh/python-telegram-bot/python-telegram-bot/?ref=repository-badge
57+
:alt: Code quality: DeepSource
5458

5559
.. image:: https://img.shields.io/badge/code%20style-black-000000.svg
56-
:target: https://github.com/psf/black
60+
:target: https://github.com/psf/black
5761

5862
.. image:: https://img.shields.io/badge/Telegram-Group-blue.svg?logo=telegram
5963
:target: https://telegram.me/pythontelegrambotgroup

README_RAW.rst

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,10 +50,14 @@ We have a vibrant community of developers helping each other in our `Telegram gr
5050

5151
.. image:: https://api.codacy.com/project/badge/Grade/99d901eaa09b44b4819aec05c330c968
5252
:target: https://www.codacy.com/app/python-telegram-bot/python-telegram-bot?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=python-telegram-bot/python-telegram-bot&amp;utm_campaign=Badge_Grade
53-
:alt: Code quality
53+
:alt: Code quality: Codacy
54+
55+
.. image:: https://deepsource.io/gh/python-telegram-bot/python-telegram-bot.svg/?label=active+issues
56+
:target: https://deepsource.io/gh/python-telegram-bot/python-telegram-bot/?ref=repository-badge
57+
:alt: Code quality: DeepSource
5458

5559
.. image:: https://img.shields.io/badge/code%20style-black-000000.svg
56-
:target: https://github.com/psf/black
60+
:target: https://github.com/psf/black
5761

5862
.. image:: https://img.shields.io/badge/Telegram-Group-blue.svg?logo=telegram
5963
:target: https://telegram.me/pythontelegrambotgroup

examples/passportbot.py

Lines changed: 21 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424

2525

2626
def msg(update: Update, _: CallbackContext) -> None:
27+
"""Downloads and prints the received passport data."""
2728
# Retrieve passport data
2829
passport_data = update.message.passport_data
2930
# If our nonce doesn't match what we think, this Update did not originate from us
@@ -61,21 +62,24 @@ def msg(update: Update, _: CallbackContext) -> None:
6162
actual_file = file.get_file()
6263
print(actual_file)
6364
actual_file.download()
64-
if data.type in ('passport', 'driver_license', 'identity_card', 'internal_passport'):
65-
if data.front_side:
66-
front_file = data.front_side.get_file()
67-
print(data.type, front_file)
68-
front_file.download()
69-
if data.type in ('driver_license' and 'identity_card'):
70-
if data.reverse_side:
71-
reverse_file = data.reverse_side.get_file()
72-
print(data.type, reverse_file)
73-
reverse_file.download()
74-
if data.type in ('passport', 'driver_license', 'identity_card', 'internal_passport'):
75-
if data.selfie:
76-
selfie_file = data.selfie.get_file()
77-
print(data.type, selfie_file)
78-
selfie_file.download()
65+
if (
66+
data.type in ('passport', 'driver_license', 'identity_card', 'internal_passport')
67+
and data.front_side
68+
):
69+
front_file = data.front_side.get_file()
70+
print(data.type, front_file)
71+
front_file.download()
72+
if data.type in ('driver_license' and 'identity_card') and data.reverse_side:
73+
reverse_file = data.reverse_side.get_file()
74+
print(data.type, reverse_file)
75+
reverse_file.download()
76+
if (
77+
data.type in ('passport', 'driver_license', 'identity_card', 'internal_passport')
78+
and data.selfie
79+
):
80+
selfie_file = data.selfie.get_file()
81+
print(data.type, selfie_file)
82+
selfie_file.download()
7983
if data.type in (
8084
'passport',
8185
'driver_license',
@@ -97,7 +101,8 @@ def msg(update: Update, _: CallbackContext) -> None:
97101
def main() -> None:
98102
"""Start the bot."""
99103
# Create the Updater and pass it your token and private key
100-
updater = Updater("TOKEN", private_key=open('private.key', 'rb').read())
104+
with open('private.key', 'rb') as private_key:
105+
updater = Updater("TOKEN", private_key=private_key.read())
101106

102107
# Get the dispatcher to register handlers
103108
dispatcher = updater.dispatcher

telegram/__main__.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,15 +29,15 @@
2929

3030
def _git_revision() -> Optional[str]:
3131
try:
32-
output = subprocess.check_output(
32+
output = subprocess.check_output( # skipcq: BAN-B607
3333
["git", "describe", "--long", "--tags"], stderr=subprocess.STDOUT
3434
)
3535
except (subprocess.SubprocessError, OSError):
3636
return None
3737
return output.decode().strip()
3838

3939

40-
def print_ver_info() -> None:
40+
def print_ver_info() -> None: # skipcq: PY-D0003
4141
git_revision = _git_revision()
4242
print(f'python-telegram-bot {telegram_ver}' + (f' ({git_revision})' if git_revision else ''))
4343
print(f'Bot API {BOT_API_VERSION}')
@@ -46,7 +46,7 @@ def print_ver_info() -> None:
4646
print(f'Python {sys_version}')
4747

4848

49-
def main() -> None:
49+
def main() -> None: # skipcq: PY-D0003
5050
print_ver_info()
5151

5252

telegram/base.py

Lines changed: 30 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@
3434

3535

3636
class TelegramObject:
37-
"""Base class for most telegram objects."""
37+
"""Base class for most Telegram objects."""
3838

3939
_id_attrs: Tuple[object, ...] = ()
4040

@@ -45,12 +45,22 @@ def __getitem__(self, item: str) -> object:
4545
return self.__dict__[item]
4646

4747
@staticmethod
48-
def parse_data(data: Optional[JSONDict]) -> Optional[JSONDict]:
48+
def _parse_data(data: Optional[JSONDict]) -> Optional[JSONDict]:
4949
return None if data is None else data.copy()
5050

5151
@classmethod
5252
def de_json(cls: Type[TO], data: Optional[JSONDict], bot: 'Bot') -> Optional[TO]:
53-
data = cls.parse_data(data)
53+
"""Converts JSON data to a Telegram object.
54+
55+
Args:
56+
data (Dict[:obj:`str`, ...]): The JSON data.
57+
bot (:class:`telegram.Bot`): The bot associated with this object.
58+
59+
Returns:
60+
The Telegram object.
61+
62+
"""
63+
data = cls._parse_data(data)
5464

5565
if data is None:
5666
return None
@@ -61,21 +71,35 @@ def de_json(cls: Type[TO], data: Optional[JSONDict], bot: 'Bot') -> Optional[TO]
6171

6272
@classmethod
6373
def de_list(cls: Type[TO], data: Optional[List[JSONDict]], bot: 'Bot') -> List[Optional[TO]]:
74+
"""Converts JSON data to a list of Telegram objects.
75+
76+
Args:
77+
data (Dict[:obj:`str`, ...]): The JSON data.
78+
bot (:class:`telegram.Bot`): The bot associated with these objects.
79+
80+
Returns:
81+
A list of Telegram objects.
82+
83+
"""
6484
if not data:
6585
return []
6686

6787
return [cls.de_json(d, bot) for d in data]
6888

6989
def to_json(self) -> str:
70-
"""
90+
"""Gives a JSON representation of object.
91+
7192
Returns:
7293
:obj:`str`
73-
7494
"""
75-
7695
return json.dumps(self.to_dict())
7796

7897
def to_dict(self) -> JSONDict:
98+
"""Gives representation of object as :obj:`dict`.
99+
100+
Returns:
101+
:obj:`dict`
102+
"""
79103
data = {}
80104

81105
for key in iter(self.__dict__):

telegram/bot.py

Lines changed: 3 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@
116116
RT = TypeVar('RT')
117117

118118

119-
def log(
119+
def log( # skipcq: PY-D0003
120120
func: Callable[..., RT], *args: object, **kwargs: object # pylint: disable=W0613
121121
) -> Callable[..., RT]:
122122
logger = logging.getLogger(func.__module__)
@@ -301,7 +301,7 @@ def _message(
301301
return Message.de_json(result, self) # type: ignore[return-value, arg-type]
302302

303303
@property
304-
def request(self) -> Request:
304+
def request(self) -> Request: # skip-cq: PY-D0003
305305
return self._request
306306

307307
@staticmethod
@@ -319,71 +319,60 @@ def _validate_token(token: str) -> str:
319319
@property
320320
def bot(self) -> User:
321321
""":class:`telegram.User`: User instance for the bot as returned by :meth:`get_me`."""
322-
323322
if self._bot is None:
324323
self._bot = self.get_me()
325324
return self._bot
326325

327326
@property
328327
def id(self) -> int: # pylint: disable=C0103
329328
""":obj:`int`: Unique identifier for this bot."""
330-
331329
return self.bot.id
332330

333331
@property
334332
def first_name(self) -> str:
335333
""":obj:`str`: Bot's first name."""
336-
337334
return self.bot.first_name
338335

339336
@property
340337
def last_name(self) -> str:
341338
""":obj:`str`: Optional. Bot's last name."""
342-
343339
return self.bot.last_name # type: ignore
344340

345341
@property
346342
def username(self) -> str:
347343
""":obj:`str`: Bot's username."""
348-
349344
return self.bot.username # type: ignore
350345

351346
@property
352347
def link(self) -> str:
353348
""":obj:`str`: Convenience property. Returns the t.me link of the bot."""
354-
355349
return f"https://t.me/{self.username}"
356350

357351
@property
358352
def can_join_groups(self) -> bool:
359353
""":obj:`bool`: Bot's :attr:`telegram.User.can_join_groups` attribute."""
360-
361354
return self.bot.can_join_groups # type: ignore
362355

363356
@property
364357
def can_read_all_group_messages(self) -> bool:
365358
""":obj:`bool`: Bot's :attr:`telegram.User.can_read_all_group_messages` attribute."""
366-
367359
return self.bot.can_read_all_group_messages # type: ignore
368360

369361
@property
370362
def supports_inline_queries(self) -> bool:
371363
""":obj:`bool`: Bot's :attr:`telegram.User.supports_inline_queries` attribute."""
372-
373364
return self.bot.supports_inline_queries # type: ignore
374365

375366
@property
376367
def commands(self) -> List[BotCommand]:
377368
"""List[:class:`BotCommand`]: Bot's commands."""
378-
379369
if self._commands is None:
380370
self._commands = self.get_my_commands()
381371
return self._commands
382372

383373
@property
384374
def name(self) -> str:
385375
""":obj:`str`: Bot's @username."""
386-
387376
return f'@{self.username}'
388377

389378
@log
@@ -2606,7 +2595,6 @@ def edit_message_media(
26062595
Raises:
26072596
:class:`telegram.error.TelegramError`
26082597
"""
2609-
26102598
if inline_message_id is None and (chat_id is None or message_id is None):
26112599
raise ValueError(
26122600
'edit_message_media: Both chat_id and message_id are required when '
@@ -4257,7 +4245,6 @@ def unpin_all_chat_messages(
42574245
:class:`telegram.error.TelegramError`
42584246
42594247
"""
4260-
42614248
data: JSONDict = {'chat_id': chat_id}
42624249

42634250
return self._post( # type: ignore[return-value]
@@ -5089,6 +5076,7 @@ def copy_message(
50895076
return MessageId.de_json(result, self) # type: ignore[return-value, arg-type]
50905077

50915078
def to_dict(self) -> JSONDict:
5079+
"""See :meth:`telegram.TelegramObject.to_dict`."""
50925080
data: JSONDict = {'id': self.id, 'username': self.username, 'first_name': self.first_name}
50935081

50945082
if self.last_name:

telegram/callbackquery.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,8 @@ def __init__(
113113

114114
@classmethod
115115
def de_json(cls, data: Optional[JSONDict], bot: 'Bot') -> Optional['CallbackQuery']:
116-
data = cls.parse_data(data)
116+
"""See :meth:`telegram.TelegramObject.de_json`."""
117+
data = cls._parse_data(data)
117118

118119
if not data:
119120
return None

telegram/chat.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -229,14 +229,16 @@ def full_name(self) -> Optional[str]:
229229
@property
230230
def link(self) -> Optional[str]:
231231
""":obj:`str`: Convenience property. If the chat has a :attr:`username`, returns a t.me
232-
link of the chat."""
232+
link of the chat.
233+
"""
233234
if self.username:
234235
return f"https://t.me/{self.username}"
235236
return None
236237

237238
@classmethod
238239
def de_json(cls, data: Optional[JSONDict], bot: 'Bot') -> Optional['Chat']:
239-
data = cls.parse_data(data)
240+
"""See :meth:`telegram.TelegramObject.de_json`."""
241+
data = cls._parse_data(data)
240242

241243
if not data:
242244
return None

telegram/chatinvitelink.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,8 @@ def __init__(
8484

8585
@classmethod
8686
def de_json(cls, data: Optional[JSONDict], bot: 'Bot') -> Optional['ChatInviteLink']:
87-
data = cls.parse_data(data)
87+
"""See :meth:`telegram.TelegramObject.de_json`."""
88+
data = cls._parse_data(data)
8889

8990
if not data:
9091
return None
@@ -95,6 +96,7 @@ def de_json(cls, data: Optional[JSONDict], bot: 'Bot') -> Optional['ChatInviteLi
9596
return cls(**data)
9697

9798
def to_dict(self) -> JSONDict:
99+
"""See :meth:`telegram.TelegramObject.to_dict`."""
98100
data = super().to_dict()
99101

100102
data['expire_date'] = to_timestamp(self.expire_date)

0 commit comments

Comments
 (0)