Skip to content

[REFACTOR]: Enum constants #2708

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

Merged
merged 19 commits into from
Oct 19, 2021
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 2 additions & 0 deletions .github/pull_request_template.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ Hey! You're PRing? Cool! Please have a look at the below checklist. It's here to
* If relevant:

- [ ] Added new constants at `telegram.constants` and shortcuts to them as class variables
- [ ] Link new and existing constants in docstrings instead of hard coded number and strings
- [ ] Add new message types to `Message.effective_attachment`
- [ ] Added new handlers for new update types
- [ ] Added new filters for new message (sub)types
- [ ] Added or updated documentation for the changed class(es) and/or method(s)
Expand Down
64 changes: 61 additions & 3 deletions docs/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,18 @@
# serve to show the default.
import sys
import os
# import telegram
from enum import Enum
from typing import Tuple

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
from docutils.nodes import Element
from sphinx.application import Sphinx
from sphinx.domains.python import PyXRefRole
from sphinx.environment import BuildEnvironment
from sphinx.util import logging

sys.path.insert(0, os.path.abspath('../..'))

# -- General configuration ------------------------------------------------
Expand Down Expand Up @@ -45,7 +52,7 @@
source_suffix = '.rst'

# The encoding of source files.
#source_encoding = 'utf-8-sig'
# source_encoding = 'utf-8-sig'

# The master toctree document.
master_doc = 'index'
Expand Down Expand Up @@ -299,11 +306,62 @@

# -- script stuff --------------------------------------------------------

# get the sphinx(!) logger
# Makes sure logs render in red and also plays nicely with e.g. the `nitpicky` option.
sphinx_logger = logging.getLogger(__name__)

CONSTANTS_ROLE = 'tg-const'
import telegram # We need this so that the `eval` below works


class TGConstXRefRole(PyXRefRole):
"""This is a bit of Sphinx magic. We add a new role type called tg-const that allows us to
reference values from the `telegram.constants.module` while using the actual value as title
of the link.

Example:

:tg-const:`telegram.constants.MessageLimit.TEXT_LENGTH` renders as `4096` but links to the
constant.
"""
def process_link(self, env: BuildEnvironment, refnode: Element,
has_explicit_title: bool, title: str, target: str) -> Tuple[str, str]:
title, target = super().process_link(env, refnode, has_explicit_title, title, target)
try:
# We use `eval` to get the value of the expression. Maybe there are better ways to
# do this via importlib or so, but it does the job for now
value = eval(target)
# Maybe we need a better check if the target is actually from tg.constants
# for now checking if it's an Enum suffices since those are used nowhere else in PTB
if isinstance(value, Enum):
# Special casing for file size limits
if isinstance(value, telegram.constants.FileSizeLimit):
return f'{int(value.value / 1e6)} MB', target
return repr(value.value), target
sphinx_logger.warning(
f'%s:%d: WARNING: Did not convert reference %s. :{CONSTANTS_ROLE}: is not supposed'
' to be used with this type of target.',
refnode.source,
refnode.line,
refnode.rawsource,
)
return title, target
except Exception as exc:
sphinx_logger.exception(
f'%s:%d: WARNING: Did not convert reference %s due to an exception.',
refnode.source,
refnode.line,
refnode.rawsource,
exc_info=exc
)
return title, target


def autodoc_skip_member(app, what, name, obj, skip, options):
pass


def setup(app):
def setup(app: Sphinx):
app.add_css_file("dark.css")
app.connect('autodoc-skip-member', autodoc_skip_member)
app.add_role_to_domain('py', CONSTANTS_ROLE, TGConstXRefRole())
8 changes: 0 additions & 8 deletions docs/source/telegram.chataction.rst

This file was deleted.

8 changes: 0 additions & 8 deletions docs/source/telegram.ext.utils.stack.rst

This file was deleted.

8 changes: 0 additions & 8 deletions docs/source/telegram.parsemode.rst

This file was deleted.

2 changes: 0 additions & 2 deletions docs/source/telegram.rst
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ telegram package
telegram.botcommandscopechatmember
telegram.callbackquery
telegram.chat
telegram.chataction
telegram.chatinvitelink
telegram.chatlocation
telegram.chatmember
Expand Down Expand Up @@ -52,7 +51,6 @@ telegram package
telegram.messageautodeletetimerchanged
telegram.messageid
telegram.messageentity
telegram.parsemode
telegram.photosize
telegram.poll
telegram.pollanswer
Expand Down
3 changes: 2 additions & 1 deletion examples/chatmemberbot.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@
import logging
from typing import Tuple, Optional

from telegram import Update, Chat, ChatMember, ParseMode, ChatMemberUpdated
from telegram import Update, Chat, ChatMember, ChatMemberUpdated
from telegram.constants import ParseMode
from telegram.ext import (
CommandHandler,
ChatMemberHandler,
Expand Down
5 changes: 3 additions & 2 deletions examples/contexttypesbot.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
from collections import defaultdict
from typing import DefaultDict, Optional, Set

from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup, ParseMode
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.constants import ParseMode
from telegram.ext import (
CommandHandler,
CallbackContext,
Expand Down Expand Up @@ -57,7 +58,7 @@ def message_clicks(self) -> Optional[int]:
def message_clicks(self, value: int) -> None:
"""Allow to change the count"""
if not self._message_id:
raise RuntimeError('There is no message associated with this context obejct.')
raise RuntimeError('There is no message associated with this context object.')
self.chat_data.clicks_per_message[self._message_id] = value

@classmethod
Expand Down
3 changes: 2 additions & 1 deletion examples/deeplinking.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@

import logging

from telegram import ParseMode, InlineKeyboardMarkup, InlineKeyboardButton, Update, helpers
from telegram import InlineKeyboardMarkup, InlineKeyboardButton, Update, helpers
from telegram.constants import ParseMode
from telegram.ext import (
CommandHandler,
CallbackQueryHandler,
Expand Down
3 changes: 2 additions & 1 deletion examples/errorhandlerbot.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
import logging
import traceback

from telegram import Update, ParseMode
from telegram import Update
from telegram.constants import ParseMode
from telegram.ext import CommandHandler, Updater, CallbackContext

# Enable logging
Expand Down
3 changes: 2 additions & 1 deletion examples/inlinebot.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@
import logging
from uuid import uuid4

from telegram import InlineQueryResultArticle, ParseMode, InputTextMessageContent, Update
from telegram import InlineQueryResultArticle, InputTextMessageContent, Update
from telegram.constants import ParseMode
from telegram.helpers import escape_markdown
from telegram.ext import Updater, InlineQueryHandler, CommandHandler, CallbackContext

Expand Down
2 changes: 1 addition & 1 deletion examples/pollbot.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,13 @@

from telegram import (
Poll,
ParseMode,
KeyboardButton,
KeyboardButtonPollType,
ReplyKeyboardMarkup,
ReplyKeyboardRemove,
Update,
)
from telegram.constants import ParseMode
from telegram.ext import (
CommandHandler,
PollAnswerHandler,
Expand Down
5 changes: 1 addition & 4 deletions telegram/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@
from ._files.location import Location
from ._files.venue import Venue
from ._files.videonote import VideoNote
from ._chataction import ChatAction
from ._dice import Dice
from ._userprofilephotos import UserProfilePhotos
from ._keyboardbuttonpolltype import KeyboardButtonPollType
Expand All @@ -58,7 +57,6 @@
from ._forcereply import ForceReply
from ._files.inputfile import InputFile
from ._files.file import File
from ._parsemode import ParseMode
from ._messageentity import MessageEntity
from ._messageid import MessageId
from ._games.game import Game
Expand Down Expand Up @@ -168,6 +166,7 @@
'Animation',
'Audio',
'Bot',
'bot_api_version',
'BotCommand',
'BotCommandScope',
'BotCommandScopeAllChatAdministrators',
Expand All @@ -180,7 +179,6 @@
'CallbackGame',
'CallbackQuery',
'Chat',
'ChatAction',
'ChatInviteLink',
'ChatLocation',
'ChatMember',
Expand Down Expand Up @@ -256,7 +254,6 @@
'MessageEntity',
'MessageId',
'OrderInfo',
'ParseMode',
'PassportData',
'PassportElementError',
'PassportElementErrorDataField',
Expand Down
Loading