Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

v13#1982

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
Bibo-Joshi merged 9 commits intomasterfromv13
Oct 7, 2020
Merged

v13#1982

Show file tree
Hide file tree
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion.github/CONTRIBUTING.rst
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -68,7 +68,9 @@ Here's how to make a one-off code change.
- You can refer to relevant issues in the commit message by writing, e.g., "#105".

- Your code should adhere to the `PEP 8 Style Guide`_, with the exception that we have a maximum line length of 99.


- Provide static typing with signature annotations. The documentation of `MyPy`_ will be a good start, the cheat sheet is `here`_. We also have some custom type aliases in ``telegram.utils.helpers.typing``.

- Document your code. This project uses `sphinx`_ to generate static HTML docs. To build them, first make sure you have the required dependencies:

.. code-block:: bash
Expand DownExpand Up@@ -251,3 +253,5 @@ break the API classes. For example:
.. _`Google Python Style Guide`: http://google.github.io/styleguide/pyguide.html
.. _`Google Python Style Docstrings`: https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html
.. _AUTHORS.rst: ../AUTHORS.rst
.. _`MyPy`: https://mypy.readthedocs.io/en/stable/index.html
.. _`here`: https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html
2 changes: 1 addition & 1 deletion.github/workflows/test.yml
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -15,7 +15,7 @@ jobs:
runs-on: ${{matrix.os}}
strategy:
matrix:
python-version: [3.5, 3.6, 3.7, 3.8]
python-version: [3.6, 3.7, 3.8]
os: [ubuntu-latest, windows-latest]
include:
- os: ubuntu-latest
Expand Down
1 change: 1 addition & 0 deletions.gitignore
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -46,6 +46,7 @@ htmlcov/
.coverage.*
.cache
.pytest_cache
.mypy_cache
nosetests.xml
coverage.xml
*,cover
Expand Down
7 changes: 6 additions & 1 deletion.pre-commit-config.yaml
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,7 +7,7 @@ repos:
args:
- --diff
- repo: https://gitlab.com/pycqa/flake8
rev: 3.7.1
rev: 3.8.1
hooks:
- id: flake8
- repo: git://github.com/pre-commit/mirrors-pylint
Expand All@@ -18,3 +18,8 @@ repos:
args:
- --errors-only
- --disable=import-error
- repo: https://github.com/pre-commit/mirrors-mypy
rev: 'v0.770'
hooks:
- id: mypy
files: ^telegram/.*\.py$
6 changes: 6 additions & 0 deletionsMakefile
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,6 +6,7 @@ PYTEST := pytest
PEP257 := pep257
PEP8 := flake8
YAPF := yapf
MYPY := mypy
PIP := pip

clean:
Expand All@@ -28,6 +29,9 @@ yapf:
lint:
$(PYLINT) -E telegram --disable=no-name-in-module,import-error

mypy:
$(MYPY) -p telegram

test:
$(PYTEST) -v

Expand All@@ -41,6 +45,7 @@ help:
@echo "- pep8 Check style with flake8"
@echo "- lint Check style with pylint"
@echo "- yapf Check style with yapf"
@echo "- mypy Check type hinting with mypy"
@echo "- test Run tests using pytest"
@echo
@echo "Available variables:"
Expand All@@ -49,4 +54,5 @@ help:
@echo "- PEP257 default: $(PEP257)"
@echo "- PEP8 default: $(PEP8)"
@echo "- YAPF default: $(YAPF)"
@echo "- MYPY default: $(MYPY)"
@echo "- PIP default: $(PIP)"
2 changes: 1 addition & 1 deletionREADME.rst
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -83,7 +83,7 @@ Introduction

This library provides a pure Python interface for the
`Telegram Bot API <https://core.telegram.org/bots/api>`_.
It's compatible with Python versions 3.5+. PTB might also work on `PyPy <http://pypy.org/>`_, though there have been a lot of issues before. Hence, PyPy is not officially supported.
It's compatible with Python versions 3.6+. PTB might also work on `PyPy <http://pypy.org/>`_, though there have been a lot of issues before. Hence, PyPy is not officially supported.

In addition to the pure API implementation, this library features a number of high-level classes to
make the development of bots easy and straightforward. These classes are contained in the
Expand Down
1 change: 1 addition & 0 deletionsdocs/source/telegram.utils.rst
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,3 +6,4 @@ telegram.utils package
telegram.utils.helpers
telegram.utils.promise
telegram.utils.request
telegram.utils.types
6 changes: 6 additions & 0 deletionsdocs/source/telegram.utils.types.rst
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
telegram.utils.types Module
===========================

.. automodule:: telegram.utils.types
:members:
:show-inheritance:
1 change: 1 addition & 0 deletionsrequirements-dev.txt
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,6 +3,7 @@ pep257
pylint
flaky
yapf
mypy==0.770
pre-commit
beautifulsoup4
pytest==4.2.0
Expand Down
1 change: 1 addition & 0 deletionsrequirements.txt
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,3 +2,4 @@ certifi
tornado>=5.1
cryptography
decorator>=4.4.0
APScheduler==3.6.3
19 changes: 19 additions & 0 deletionssetup.cfg
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -40,3 +40,22 @@ omit =
telegram/__main__.py
telegram/vendor/*

[coverage:report]
exclude_lines =
if TYPE_CHECKING:

[mypy]
warn_unused_ignores = True
warn_unused_configs = True
disallow_untyped_defs = True
disallow_incomplete_defs = True
disallow_untyped_decorators = True
show_error_codes = True

[mypy-telegram.vendor.*]
ignore_errors = True

# Disable strict optional for telegram objects with class methods
# We don't want to clutter the code with 'if self.bot is None: raise RuntimeError()'
[mypy-telegram.callbackquery,telegram.chat,telegram.message,telegram.user,telegram.files.*,telegram.inline.inlinequery,telegram.payment.precheckoutquery,telegram.payment.shippingquery,telegram.passport.passportdata,telegram.passport.credentials,telegram.passport.passportfile,telegram.ext.filters]
strict_optional = False
1 change: 0 additions & 1 deletionsetup.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -61,7 +61,6 @@ def requirements():
'Topic :: Internet',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
Expand Down
2 changes: 1 addition & 1 deletiontelegram/__init__.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -104,7 +104,6 @@
from .update import Update
from .files.inputmedia import (InputMedia, InputMediaVideo, InputMediaPhoto, InputMediaAnimation,
InputMediaAudio, InputMediaDocument)
from .bot import Bot
from .constants import (MAX_MESSAGE_LENGTH, MAX_CAPTION_LENGTH, SUPPORTED_WEBHOOK_PORTS,
MAX_FILESIZE_DOWNLOAD, MAX_FILESIZE_UPLOAD,
MAX_MESSAGES_PER_SECOND_PER_CHAT, MAX_MESSAGES_PER_SECOND,
Expand All@@ -124,6 +123,7 @@
SecureData,
FileCredentials,
TelegramDecryptionError)
from .bot import Bot
from .version import __version__ # noqa: F401

__author__ = 'devs@python-telegram-bot.org'
Expand Down
9 changes: 5 additions & 4 deletionstelegram/__main__.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,11 +21,12 @@

import certifi

from typing import Optional

from . import __version__ as telegram_ver


def _git_revision():
def _git_revision() -> Optional[str]:
try:
output = subprocess.check_output(["git", "describe", "--long", "--tags"],
stderr=subprocess.STDOUT)
Expand All@@ -34,15 +35,15 @@ def _git_revision():
return output.decode().strip()


def print_ver_info():
def print_ver_info() -> None:
git_revision = _git_revision()
print('python-telegram-bot {}'.format(telegram_ver) + (' ({})'.format(git_revision)
if git_revision else ''))
print('certifi {}'.format(certifi.__version__))
print('certifi {}'.format(certifi.__version__)) # type: ignore[attr-defined]
print('Python {}'.format(sys.version.replace('\n', ' ')))


def main():
def main() -> None:
print_ver_info()


Expand Down
60 changes: 48 additions & 12 deletionstelegram/base.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,34 +17,64 @@
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""Base class for Telegram Objects."""

try:
import ujson as json
except ImportError:
import json
import json # type: ignore[no-redef]

import warnings

from telegram.utils.types import JSONDict
from typing import Tuple, Any, Optional, Type, TypeVar, TYPE_CHECKING, List

if TYPE_CHECKING:
from telegram import Bot

TO = TypeVar('TO', bound='TelegramObject', covariant=True)


class TelegramObject:
"""Base class for most telegram objects."""

_id_attrs = ()
# def __init__(self, *args: Any, **kwargs: Any):
# pass

_id_attrs: Tuple[Any, ...] = ()

def __str__(self):
def __str__(self) -> str:
return str(self.to_dict())

def __getitem__(self, item):
def __getitem__(self, item: str) -> Any:
return self.__dict__[item]

@staticmethod
def parse_data(data: Optional[JSONDict]) -> Optional[JSONDict]:
if not data:
return None
return data.copy()

@classmethod
def de_json(cls, data, bot):
def de_json(cls: Type[TO], data: Optional[JSONDict], bot: 'Bot') -> Optional[TO]:
data = cls.parse_data(data)

if not data:
return None

data = data.copy()
if cls == TelegramObject:
return cls()
else:
return cls(bot=bot, **data) # type: ignore[call-arg]

return data
@classmethod
def de_list(cls: Type[TO],
data: Optional[List[JSONDict]],
bot: 'Bot') -> List[Optional[TO]]:
if not data:
return []

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

def to_json(self):
def to_json(self) -> str:
"""
Returns:
:obj:`str`
Expand All@@ -53,7 +83,7 @@ def to_json(self):

return json.dumps(self.to_dict())

def to_dict(self):
def to_dict(self) -> JSONDict:
data = dict()

for key in iter(self.__dict__):
Expand All@@ -71,12 +101,18 @@ def to_dict(self):
data['from'] = data.pop('from_user', None)
return data

def __eq__(self, other):
def __eq__(self, other: object) -> bool:
if isinstance(other, self.__class__):
if self._id_attrs == ():
warnings.warn("Objects of type {} can not be meaningfully tested for "
"equivalence.".format(self.__class__.__name__))
if other._id_attrs == ():
warnings.warn("Objects of type {} can not be meaningfully tested for "
"equivalence.".format(other.__class__.__name__))
return self._id_attrs == other._id_attrs
return super().__eq__(other) # pylint: disable=no-member

def __hash__(self):
def __hash__(self) -> int:
if self._id_attrs:
return hash((self.__class__, self._id_attrs)) # pylint: disable=no-member
return super().__hash__()
Loading

[8]ページ先頭

©2009-2025 Movatter.jp