Use F-Strings Where Possible (#2222)

This commit is contained in:
Bibo-Joshi 2020-11-23 22:09:29 +01:00 committed by GitHub
parent df6d5f0840
commit 58b9882021
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
40 changed files with 145 additions and 173 deletions

View file

@ -50,7 +50,7 @@ def facts_to_str(user_data: Dict[str, str]) -> str:
facts = list() facts = list()
for key, value in user_data.items(): for key, value in user_data.items():
facts.append('{} - {}'.format(key, value)) facts.append(f'{key} - {value}')
return "\n".join(facts).join(['\n', '\n']) return "\n".join(facts).join(['\n', '\n'])
@ -68,9 +68,7 @@ def start(update: Update, context: CallbackContext) -> int:
def regular_choice(update: Update, context: CallbackContext) -> int: def regular_choice(update: Update, context: CallbackContext) -> int:
text = update.message.text text = update.message.text
context.user_data['choice'] = text context.user_data['choice'] = text
update.message.reply_text( update.message.reply_text(f'Your {text.lower()}? Yes, I would love to hear about that!')
'Your {}? Yes, I would love to hear about that!'.format(text.lower())
)
return TYPING_REPLY return TYPING_REPLY
@ -92,8 +90,8 @@ def received_information(update: Update, context: CallbackContext) -> int:
update.message.reply_text( update.message.reply_text(
"Neat! Just so you know, this is what you already told me:" "Neat! Just so you know, this is what you already told me:"
"{} You can tell me more, or change your opinion" f"{facts_to_str(user_data)} You can tell me more, or change your opinion"
" on something.".format(facts_to_str(user_data)), " on something.",
reply_markup=markup, reply_markup=markup,
) )
@ -106,7 +104,7 @@ def done(update: Update, context: CallbackContext) -> int:
del user_data['choice'] del user_data['choice']
update.message.reply_text( update.message.reply_text(
"I learned these facts about you:" "{}" "Until next time!".format(facts_to_str(user_data)) f"I learned these facts about you: {facts_to_str(user_data)} Until next time!"
) )
user_data.clear() user_data.clear()

View file

@ -66,7 +66,7 @@ def deep_linked_level_2(update: Update, context: CallbackContext) -> None:
"""Reached through the SO_COOL payload""" """Reached through the SO_COOL payload"""
bot = context.bot bot = context.bot
url = helpers.create_deep_linked_url(bot.get_me().username, USING_ENTITIES) url = helpers.create_deep_linked_url(bot.get_me().username, USING_ENTITIES)
text = "You can also mask the deep-linked URLs as links: " "[▶️ CLICK HERE]({}).".format(url) text = f"You can also mask the deep-linked URLs as links: [▶️ CLICK HERE]({url})."
update.message.reply_text(text, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True) update.message.reply_text(text, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True)
@ -74,7 +74,7 @@ def deep_linked_level_3(update: Update, context: CallbackContext) -> None:
"""Reached through the USING_ENTITIES payload""" """Reached through the USING_ENTITIES payload"""
payload = context.args payload = context.args
update.message.reply_text( update.message.reply_text(
"Congratulations! This is as deep as it gets 👏🏻\n\n" "The payload was: {}".format(payload) f"Congratulations! This is as deep as it gets 👏🏻\n\nThe payload was: {payload}"
) )

View file

@ -42,16 +42,12 @@ def error_handler(update: Update, context: CallbackContext) -> None:
# Build the message with some markup and additional information about what happened. # Build the message with some markup and additional information about what happened.
# You might need to add some logic to deal with messages longer than the 4096 character limit. # You might need to add some logic to deal with messages longer than the 4096 character limit.
message = ( message = (
'An exception was raised while handling an update\n' f'An exception was raised while handling an update\n'
'<pre>update = {}</pre>\n\n' f'<pre>update = {html.escape(json.dumps(update.to_dict(), indent=2, ensure_ascii=False))}'
'<pre>context.chat_data = {}</pre>\n\n' '</pre>\n\n'
'<pre>context.user_data = {}</pre>\n\n' f'<pre>context.chat_data = {html.escape(str(context.chat_data))}</pre>\n\n'
'<pre>{}</pre>' f'<pre>context.user_data = {html.escape(str(context.user_data))}</pre>\n\n'
).format( f'<pre>{html.escape(tb_string)}</pre>'
html.escape(json.dumps(update.to_dict(), indent=2, ensure_ascii=False)),
html.escape(str(context.chat_data)),
html.escape(str(context.user_data)),
html.escape(tb_string),
) )
# Finally, send the message # Finally, send the message
@ -66,7 +62,7 @@ def bad_command(update: Update, context: CallbackContext) -> None:
def start(update: Update, context: CallbackContext) -> None: def start(update: Update, context: CallbackContext) -> None:
update.effective_message.reply_html( update.effective_message.reply_html(
'Use /bad_command to cause an error.\n' 'Use /bad_command to cause an error.\n'
'Your chat id is <code>{}</code>.'.format(update.effective_chat.id) f'Your chat id is <code>{update.effective_chat.id}</code>.'
) )

View file

@ -52,14 +52,14 @@ def inlinequery(update: Update, context: CallbackContext) -> None:
id=uuid4(), id=uuid4(),
title="Bold", title="Bold",
input_message_content=InputTextMessageContent( input_message_content=InputTextMessageContent(
"*{}*".format(escape_markdown(query)), parse_mode=ParseMode.MARKDOWN f"*{escape_markdown(query)}*", parse_mode=ParseMode.MARKDOWN
), ),
), ),
InlineQueryResultArticle( InlineQueryResultArticle(
id=uuid4(), id=uuid4(),
title="Italic", title="Italic",
input_message_content=InputTextMessageContent( input_message_content=InputTextMessageContent(
"_{}_".format(escape_markdown(query)), parse_mode=ParseMode.MARKDOWN f"_{escape_markdown(query)}_", parse_mode=ParseMode.MARKDOWN
), ),
), ),
] ]

View file

@ -39,7 +39,7 @@ def button(update: Update, context: CallbackContext) -> None:
# Some clients may have trouble otherwise. See https://core.telegram.org/bots/api#callbackquery # Some clients may have trouble otherwise. See https://core.telegram.org/bots/api#callbackquery
query.answer() query.answer()
query.edit_message_text(text="Selected option: {}".format(query.data)) query.edit_message_text(text=f"Selected option: {query.data}")
def help_command(update: Update, context: CallbackContext) -> None: def help_command(update: Update, context: CallbackContext) -> None:

View file

@ -128,15 +128,13 @@ def show_data(update: Update, context: CallbackContext) -> None:
text = '' text = ''
if level == SELF: if level == SELF:
for person in user_data[level]: for person in user_data[level]:
text += '\nName: {}, Age: {}'.format(person.get(NAME, '-'), person.get(AGE, '-')) text += f"\nName: {person.get(NAME, '-')}, Age: {person.get(AGE, '-')}"
else: else:
male, female = _name_switcher(level) male, female = _name_switcher(level)
for person in user_data[level]: for person in user_data[level]:
gender = female if person[GENDER] == FEMALE else male gender = female if person[GENDER] == FEMALE else male
text += '\n{}: Name: {}, Age: {}'.format( text += f"\n{gender}: Name: {person.get(NAME, '-')}, Age: {person.get(AGE, '-')}"
gender, person.get(NAME, '-'), person.get(AGE, '-')
)
return text return text
user_data = context.user_data user_data = context.user_data
@ -341,9 +339,7 @@ def main():
entry_points=[CallbackQueryHandler(select_level, pattern='^' + str(ADDING_MEMBER) + '$')], entry_points=[CallbackQueryHandler(select_level, pattern='^' + str(ADDING_MEMBER) + '$')],
states={ states={
SELECTING_LEVEL: [ SELECTING_LEVEL: [
CallbackQueryHandler( CallbackQueryHandler(select_gender, pattern=f'^{PARENTS}$|^{CHILDREN}$')
select_gender, pattern='^{}$|^{}$'.format(str(PARENTS), str(CHILDREN))
)
], ],
SELECTING_GENDER: [description_conv], SELECTING_GENDER: [description_conv],
}, },

View file

@ -51,7 +51,7 @@ def facts_to_str(user_data):
facts = list() facts = list()
for key, value in user_data.items(): for key, value in user_data.items():
facts.append('{} - {}'.format(key, value)) facts.append(f'{key} - {value}')
return "\n".join(facts).join(['\n', '\n']) return "\n".join(facts).join(['\n', '\n'])
@ -60,9 +60,8 @@ def start(update: Update, context: CallbackContext) -> None:
reply_text = "Hi! My name is Doctor Botter." reply_text = "Hi! My name is Doctor Botter."
if context.user_data: if context.user_data:
reply_text += ( reply_text += (
" You already told me your {}. Why don't you tell me something more " f" You already told me your {', '.join(context.user_data.keys())}. Why don't you "
"about yourself? Or change anything I " f"tell me something more about yourself? Or change anything I already know."
"already know.".format(", ".join(context.user_data.keys()))
) )
else: else:
reply_text += ( reply_text += (
@ -78,11 +77,11 @@ def regular_choice(update: Update, context: CallbackContext) -> None:
text = update.message.text.lower() text = update.message.text.lower()
context.user_data['choice'] = text context.user_data['choice'] = text
if context.user_data.get(text): if context.user_data.get(text):
reply_text = 'Your {}, I already know the following ' 'about that: {}'.format( reply_text = (
text, context.user_data[text] f'Your {text}, I already know the following about that: {context.user_data[text]}'
) )
else: else:
reply_text = 'Your {}? Yes, I would love to hear about that!'.format(text) reply_text = f'Your {text}? Yes, I would love to hear about that!'
update.message.reply_text(reply_text) update.message.reply_text(reply_text)
return TYPING_REPLY return TYPING_REPLY
@ -104,9 +103,9 @@ def received_information(update: Update, context: CallbackContext) -> None:
update.message.reply_text( update.message.reply_text(
"Neat! Just so you know, this is what you already told me:" "Neat! Just so you know, this is what you already told me:"
"{}" f"{facts_to_str(context.user_data)}"
"You can tell me more, or change your opinion on " "You can tell me more, or change your opinion on "
"something.".format(facts_to_str(context.user_data)), "something.",
reply_markup=markup, reply_markup=markup,
) )
@ -115,7 +114,7 @@ def received_information(update: Update, context: CallbackContext) -> None:
def show_data(update: Update, context: CallbackContext) -> None: def show_data(update: Update, context: CallbackContext) -> None:
update.message.reply_text( update.message.reply_text(
"This is what you already told me:" "{}".format(facts_to_str(context.user_data)) f"This is what you already told me: {facts_to_str(context.user_data)}"
) )
@ -124,9 +123,7 @@ def done(update: Update, context: CallbackContext) -> None:
del context.user_data['choice'] del context.user_data['choice']
update.message.reply_text( update.message.reply_text(
"I learned these facts about you:" "I learned these facts about you:" f"{facts_to_str(context.user_data)}" "Until next time!"
"{}"
"Until next time!".format(facts_to_str(context.user_data))
) )
return ConversationHandler.END return ConversationHandler.END

View file

@ -84,7 +84,7 @@ def receive_poll_answer(update: Update, context: CallbackContext) -> None:
answer_string += questions[question_id] answer_string += questions[question_id]
context.bot.send_message( context.bot.send_message(
context.bot_data[poll_id]["chat_id"], context.bot_data[poll_id]["chat_id"],
"{} feels {}!".format(update.effective_user.mention_html(), answer_string), f"{update.effective_user.mention_html()} feels {answer_string}!",
parse_mode=ParseMode.HTML, parse_mode=ParseMode.HTML,
) )
context.bot_data[poll_id]["answers"] += 1 context.bot_data[poll_id]["answers"] += 1

View file

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

View file

@ -102,13 +102,13 @@ class TelegramObject:
if isinstance(other, self.__class__): if isinstance(other, self.__class__):
if self._id_attrs == (): if self._id_attrs == ():
warnings.warn( warnings.warn(
"Objects of type {} can not be meaningfully tested for " f"Objects of type {self.__class__.__name__} can not be meaningfully tested for"
"equivalence.".format(self.__class__.__name__) " equivalence."
) )
if other._id_attrs == (): if other._id_attrs == ():
warnings.warn( warnings.warn(
"Objects of type {} can not be meaningfully tested for " f"Objects of type {other.__class__.__name__} can not be meaningfully tested"
"equivalence.".format(other.__class__.__name__) " for equivalence."
) )
return self._id_attrs == other._id_attrs return self._id_attrs == other._id_attrs
return super().__eq__(other) # pylint: disable=no-member return super().__eq__(other) # pylint: disable=no-member

View file

@ -231,9 +231,7 @@ class Bot(TelegramObject):
else: else:
data = api_kwargs data = api_kwargs
return self.request.post( return self.request.post(f'{self.base_url}/{endpoint}', data=data, timeout=timeout)
'{}/{}'.format(self.base_url, endpoint), data=data, timeout=timeout
)
def _message( def _message(
self, self,
@ -321,7 +319,7 @@ class Bot(TelegramObject):
def link(self) -> str: def link(self) -> str:
""":obj:`str`: Convenience property. Returns the t.me link of the bot.""" """:obj:`str`: Convenience property. Returns the t.me link of the bot."""
return "https://t.me/{}".format(self.username) return f"https://t.me/{self.username}"
@property # type: ignore @property # type: ignore
@info @info
@ -355,7 +353,7 @@ class Bot(TelegramObject):
def name(self) -> str: def name(self) -> str:
""":obj:`str`: Bot's @username.""" """:obj:`str`: Bot's @username."""
return '@{}'.format(self.username) return f'@{self.username}'
@log @log
def get_me(self, timeout: int = None, api_kwargs: JSONDict = None) -> Optional[User]: def get_me(self, timeout: int = None, api_kwargs: JSONDict = None) -> Optional[User]:
@ -2010,9 +2008,7 @@ class Bot(TelegramObject):
result = self._post('getFile', data, timeout=timeout, api_kwargs=api_kwargs) result = self._post('getFile', data, timeout=timeout, api_kwargs=api_kwargs)
if result.get('file_path'): # type: ignore if result.get('file_path'): # type: ignore
result['file_path'] = '{}/{}'.format( # type: ignore result['file_path'] = f'{self.base_file_url}/{result["file_path"]}' # type: ignore
self.base_file_url, result['file_path'] # type: ignore
)
return File.de_json(result, self) # type: ignore return File.de_json(result, self) # type: ignore

View file

@ -148,7 +148,7 @@ class Chat(TelegramObject):
""":obj:`str`: Convenience property. If the chat has a :attr:`username`, returns a t.me """:obj:`str`: Convenience property. If the chat has a :attr:`username`, returns a t.me
link of the chat.""" link of the chat."""
if self.username: if self.username:
return "https://t.me/{}".format(self.username) return f"https://t.me/{self.username}"
return None return None
@property @property

View file

@ -93,7 +93,7 @@ class ChatMigrated(TelegramError):
""" """
def __init__(self, new_chat_id: int): def __init__(self, new_chat_id: int):
super().__init__('Group migrated to supergroup. New chat id: {}'.format(new_chat_id)) super().__init__(f'Group migrated to supergroup. New chat id: {new_chat_id}')
self.new_chat_id = new_chat_id self.new_chat_id = new_chat_id
def __reduce__(self) -> Tuple[type, Tuple[int]]: # type: ignore[override] def __reduce__(self) -> Tuple[type, Tuple[int]]: # type: ignore[override]
@ -108,7 +108,7 @@ class RetryAfter(TelegramError):
""" """
def __init__(self, retry_after: int): def __init__(self, retry_after: int):
super().__init__('Flood control exceeded. Retry in {} seconds'.format(float(retry_after))) super().__init__(f'Flood control exceeded. Retry in {float(retry_after)} seconds')
self.retry_after = float(retry_after) self.retry_after = float(retry_after)
def __reduce__(self) -> Tuple[type, Tuple[float]]: # type: ignore[override] def __reduce__(self) -> Tuple[type, Tuple[float]]: # type: ignore[override]

View file

@ -216,12 +216,10 @@ class Dispatcher:
return self.__exception_event return self.__exception_event
def _init_async_threads(self, base_name: str, workers: int) -> None: def _init_async_threads(self, base_name: str, workers: int) -> None:
base_name = '{}_'.format(base_name) if base_name else '' base_name = f'{base_name}_' if base_name else ''
for i in range(workers): for i in range(workers):
thread = Thread( thread = Thread(target=self._pooled, name=f'Bot:{self.bot.id}:worker:{base_name}{i}')
target=self._pooled, name='Bot:{}:worker:{}{}'.format(self.bot.id, base_name, i)
)
self.__async_threads.add(thread) self.__async_threads.add(thread)
thread.start() thread.start()
@ -243,7 +241,7 @@ class Dispatcher:
""" """
if cls.__singleton is not None: if cls.__singleton is not None:
return cls.__singleton() # type: ignore[return-value] # pylint: disable=not-callable return cls.__singleton() # type: ignore[return-value] # pylint: disable=not-callable
raise RuntimeError('{} not initialized or multiple instances exist'.format(cls.__name__)) raise RuntimeError(f'{cls.__name__} not initialized or multiple instances exist')
def _pooled(self) -> None: def _pooled(self) -> None:
thr_name = current_thread().getName() thr_name = current_thread().getName()
@ -484,14 +482,14 @@ class Dispatcher:
from .conversationhandler import ConversationHandler # pylint: disable=C0415 from .conversationhandler import ConversationHandler # pylint: disable=C0415
if not isinstance(handler, Handler): if not isinstance(handler, Handler):
raise TypeError('handler is not an instance of {}'.format(Handler.__name__)) raise TypeError(f'handler is not an instance of {Handler.__name__}')
if not isinstance(group, int): if not isinstance(group, int):
raise TypeError('group is not int') raise TypeError('group is not int')
if isinstance(handler, ConversationHandler) and handler.persistent and handler.name: if isinstance(handler, ConversationHandler) and handler.persistent and handler.name:
if not self.persistence: if not self.persistence:
raise ValueError( raise ValueError(
"ConversationHandler {} can not be persistent if dispatcher has no " f"ConversationHandler {handler.name} can not be persistent if dispatcher has "
"persistence".format(handler.name) f"no persistence"
) )
handler.persistence = self.persistence handler.persistence = self.persistence
handler.conversations = self.persistence.get_conversations(handler.name) handler.conversations = self.persistence.get_conversations(handler.name)

View file

@ -223,7 +223,7 @@ class InvertedFilter(UpdateFilter):
@property @property
def name(self) -> str: def name(self) -> str:
return "<inverted {}>".format(self.f) return f"<inverted {self.f}>"
@name.setter @name.setter
def name(self, name: str) -> NoReturn: def name(self, name: str) -> NoReturn:
@ -304,8 +304,9 @@ class MergedFilter(UpdateFilter):
@property @property
def name(self) -> str: def name(self) -> str:
return "<{} {} {}>".format( return (
self.base_filter, "and" if self.and_filter else "or", self.and_filter or self.or_filter f"<{self.base_filter} {'and' if self.and_filter else 'or'} "
f"{self.and_filter or self.or_filter}>"
) )
@name.setter @name.setter
@ -342,7 +343,7 @@ class XORFilter(UpdateFilter):
class _DiceEmoji(MessageFilter): class _DiceEmoji(MessageFilter):
def __init__(self, emoji: str = None, name: str = None): def __init__(self, emoji: str = None, name: str = None):
self.name = 'Filters.dice.{}'.format(name) if name else 'Filters.dice' self.name = f'Filters.dice.{name}' if name else 'Filters.dice'
self.emoji = emoji self.emoji = emoji
class _DiceValues(MessageFilter): class _DiceValues(MessageFilter):
@ -354,7 +355,7 @@ class _DiceEmoji(MessageFilter):
): ):
self.values = [values] if isinstance(values, int) else values self.values = [values] if isinstance(values, int) else values
self.emoji = emoji self.emoji = emoji
self.name = '{}({})'.format(name, values) self.name = f'{name}({values})'
def filter(self, message: Message) -> bool: def filter(self, message: Message) -> bool:
if message.dice and message.dice.value in self.values: if message.dice and message.dice.value in self.values:
@ -403,7 +404,7 @@ class Filters:
class _TextStrings(MessageFilter): class _TextStrings(MessageFilter):
def __init__(self, strings: Union[List[str], Tuple[str]]): def __init__(self, strings: Union[List[str], Tuple[str]]):
self.strings = strings self.strings = strings
self.name = 'Filters.text({})'.format(strings) self.name = f'Filters.text({strings})'
def filter(self, message: Message) -> bool: def filter(self, message: Message) -> bool:
if message.text: if message.text:
@ -454,7 +455,7 @@ class Filters:
class _CaptionStrings(MessageFilter): class _CaptionStrings(MessageFilter):
def __init__(self, strings: Union[List[str], Tuple[str]]): def __init__(self, strings: Union[List[str], Tuple[str]]):
self.strings = strings self.strings = strings
self.name = 'Filters.caption({})'.format(strings) self.name = f'Filters.caption({strings})'
def filter(self, message: Message) -> bool: def filter(self, message: Message) -> bool:
if message.caption: if message.caption:
@ -489,7 +490,7 @@ class Filters:
class _CommandOnlyStart(MessageFilter): class _CommandOnlyStart(MessageFilter):
def __init__(self, only_start: bool): def __init__(self, only_start: bool):
self.only_start = only_start self.only_start = only_start
self.name = 'Filters.command({})'.format(only_start) self.name = f'Filters.command({only_start})'
def filter(self, message: Message) -> bool: def filter(self, message: Message) -> bool:
return bool( return bool(
@ -566,7 +567,7 @@ class Filters:
pattern = re.compile(pattern) pattern = re.compile(pattern)
pattern = cast(Pattern, pattern) pattern = cast(Pattern, pattern)
self.pattern: Pattern = pattern self.pattern: Pattern = pattern
self.name = 'Filters.regex({})'.format(self.pattern) self.name = f'Filters.regex({self.pattern})'
def filter(self, message: Message) -> Optional[Dict[str, List[Match]]]: def filter(self, message: Message) -> Optional[Dict[str, List[Match]]]:
"""""" # remove method from docs """""" # remove method from docs
@ -601,7 +602,7 @@ class Filters:
pattern = re.compile(pattern) pattern = re.compile(pattern)
pattern = cast(Pattern, pattern) pattern = cast(Pattern, pattern)
self.pattern: Pattern = pattern self.pattern: Pattern = pattern
self.name = 'Filters.caption_regex ({})'.format(self.pattern) self.name = f'Filters.caption_regex({self.pattern})'
def filter(self, message: Message) -> Optional[Dict[str, List[Match]]]: def filter(self, message: Message) -> Optional[Dict[str, List[Match]]]:
"""""" # remove method from docs """""" # remove method from docs
@ -652,7 +653,7 @@ class Filters:
Args: Args:
category (str, optional): category of the media you want to filter""" category (str, optional): category of the media you want to filter"""
self.category = category self.category = category
self.name = "Filters.document.category('{}')".format(self.category) self.name = f"Filters.document.category('{self.category}')"
def filter(self, message: Message) -> bool: def filter(self, message: Message) -> bool:
"""""" # remove method from docs """""" # remove method from docs
@ -685,7 +686,7 @@ class Filters:
Args: Args:
mimetype (str, optional): mime_type of the media you want to filter""" mimetype (str, optional): mime_type of the media you want to filter"""
self.mimetype = mimetype self.mimetype = mimetype
self.name = "Filters.document.mime_type('{}')".format(self.mimetype) self.name = f"Filters.document.mime_type('{self.mimetype}')"
def filter(self, message: Message) -> bool: def filter(self, message: Message) -> bool:
"""""" # remove method from docs """""" # remove method from docs
@ -1108,7 +1109,7 @@ officedocument.wordprocessingml.document")``-
def __init__(self, entity_type: str): def __init__(self, entity_type: str):
self.entity_type = entity_type self.entity_type = entity_type
self.name = 'Filters.entity({})'.format(self.entity_type) self.name = f'Filters.entity({self.entity_type})'
def filter(self, message: Message) -> bool: def filter(self, message: Message) -> bool:
"""""" # remove method from docs """""" # remove method from docs
@ -1130,7 +1131,7 @@ officedocument.wordprocessingml.document")``-
def __init__(self, entity_type: str): def __init__(self, entity_type: str):
self.entity_type = entity_type self.entity_type = entity_type
self.name = 'Filters.caption_entity({})'.format(self.entity_type) self.name = f'Filters.caption_entity({self.entity_type})'
def filter(self, message: Message) -> bool: def filter(self, message: Message) -> bool:
"""""" # remove method from docs """""" # remove method from docs
@ -1902,7 +1903,7 @@ officedocument.wordprocessingml.document")``-
else: else:
lang = cast(List[str], lang) lang = cast(List[str], lang)
self.lang = lang self.lang = lang
self.name = 'Filters.language({})'.format(self.lang) self.name = f'Filters.language({self.lang})'
def filter(self, message: Message) -> bool: def filter(self, message: Message) -> bool:
"""""" # remove method from docs """""" # remove method from docs

View file

@ -89,7 +89,7 @@ class DelayQueue(threading.Thread):
self.__exit_req = False # flag to gently exit thread self.__exit_req = False # flag to gently exit thread
self.__class__._instcnt += 1 self.__class__._instcnt += 1
if name is None: if name is None:
name = '{}-{}'.format(self.__class__.__name__, self.__class__._instcnt) name = f'{self.__class__.__name__}-{self.__class__._instcnt}'
super().__init__(name=name) super().__init__(name=name)
self.daemon = False self.daemon = False
if autostart: # immediately start processing if autostart: # immediately start processing

View file

@ -111,9 +111,9 @@ class PicklePersistence(BasePersistence):
self.chat_data = defaultdict(dict) self.chat_data = defaultdict(dict)
self.bot_data = {} self.bot_data = {}
except pickle.UnpicklingError as exc: except pickle.UnpicklingError as exc:
raise TypeError("File {} does not contain valid pickle data".format(filename)) from exc raise TypeError(f"File {filename} does not contain valid pickle data") from exc
except Exception as exc: except Exception as exc:
raise TypeError("Something went wrong unpickling {}".format(filename)) from exc raise TypeError(f"Something went wrong unpickling {filename}") from exc
@staticmethod @staticmethod
def load_file(filename: str) -> Any: def load_file(filename: str) -> Any:
@ -123,9 +123,9 @@ class PicklePersistence(BasePersistence):
except IOError: except IOError:
return None return None
except pickle.UnpicklingError as exc: except pickle.UnpicklingError as exc:
raise TypeError("File {} does not contain valid pickle data".format(filename)) from exc raise TypeError(f"File {filename} does not contain valid pickle data") from exc
except Exception as exc: except Exception as exc:
raise TypeError("Something went wrong unpickling {}".format(filename)) from exc raise TypeError(f"Something went wrong unpickling {filename}") from exc
def dump_singlefile(self) -> None: def dump_singlefile(self) -> None:
with open(self.filename, "wb") as file: with open(self.filename, "wb") as file:
@ -151,7 +151,7 @@ class PicklePersistence(BasePersistence):
if self.user_data: if self.user_data:
pass pass
elif not self.single_file: elif not self.single_file:
filename = "{}_user_data".format(self.filename) filename = f"{self.filename}_user_data"
data = self.load_file(filename) data = self.load_file(filename)
if not data: if not data:
data = defaultdict(dict) data = defaultdict(dict)
@ -171,7 +171,7 @@ class PicklePersistence(BasePersistence):
if self.chat_data: if self.chat_data:
pass pass
elif not self.single_file: elif not self.single_file:
filename = "{}_chat_data".format(self.filename) filename = f"{self.filename}_chat_data"
data = self.load_file(filename) data = self.load_file(filename)
if not data: if not data:
data = defaultdict(dict) data = defaultdict(dict)
@ -191,7 +191,7 @@ class PicklePersistence(BasePersistence):
if self.bot_data: if self.bot_data:
pass pass
elif not self.single_file: elif not self.single_file:
filename = "{}_bot_data".format(self.filename) filename = f"{self.filename}_bot_data"
data = self.load_file(filename) data = self.load_file(filename)
if not data: if not data:
data = {} data = {}
@ -212,7 +212,7 @@ class PicklePersistence(BasePersistence):
if self.conversations: if self.conversations:
pass pass
elif not self.single_file: elif not self.single_file:
filename = "{}_conversations".format(self.filename) filename = f"{self.filename}_conversations"
data = self.load_file(filename) data = self.load_file(filename)
if not data: if not data:
data = {name: {}} data = {name: {}}
@ -239,7 +239,7 @@ class PicklePersistence(BasePersistence):
self.conversations[name][key] = new_state self.conversations[name][key] = new_state
if not self.on_flush: if not self.on_flush:
if not self.single_file: if not self.single_file:
filename = "{}_conversations".format(self.filename) filename = f"{self.filename}_conversations"
self.dump_file(filename, self.conversations) self.dump_file(filename, self.conversations)
else: else:
self.dump_singlefile() self.dump_singlefile()
@ -258,7 +258,7 @@ class PicklePersistence(BasePersistence):
self.user_data[user_id] = data self.user_data[user_id] = data
if not self.on_flush: if not self.on_flush:
if not self.single_file: if not self.single_file:
filename = "{}_user_data".format(self.filename) filename = f"{self.filename}_user_data"
self.dump_file(filename, self.user_data) self.dump_file(filename, self.user_data)
else: else:
self.dump_singlefile() self.dump_singlefile()
@ -277,7 +277,7 @@ class PicklePersistence(BasePersistence):
self.chat_data[chat_id] = data self.chat_data[chat_id] = data
if not self.on_flush: if not self.on_flush:
if not self.single_file: if not self.single_file:
filename = "{}_chat_data".format(self.filename) filename = f"{self.filename}_chat_data"
self.dump_file(filename, self.chat_data) self.dump_file(filename, self.chat_data)
else: else:
self.dump_singlefile() self.dump_singlefile()
@ -293,7 +293,7 @@ class PicklePersistence(BasePersistence):
self.bot_data = data.copy() self.bot_data = data.copy()
if not self.on_flush: if not self.on_flush:
if not self.single_file: if not self.single_file:
filename = "{}_bot_data".format(self.filename) filename = f"{self.filename}_bot_data"
self.dump_file(filename, self.bot_data) self.dump_file(filename, self.bot_data)
else: else:
self.dump_singlefile() self.dump_singlefile()
@ -305,10 +305,10 @@ class PicklePersistence(BasePersistence):
self.dump_singlefile() self.dump_singlefile()
else: else:
if self.user_data: if self.user_data:
self.dump_file("{}_user_data".format(self.filename), self.user_data) self.dump_file(f"{self.filename}_user_data", self.user_data)
if self.chat_data: if self.chat_data:
self.dump_file("{}_chat_data".format(self.filename), self.chat_data) self.dump_file(f"{self.filename}_chat_data", self.chat_data)
if self.bot_data: if self.bot_data:
self.dump_file("{}_bot_data".format(self.filename), self.bot_data) self.dump_file(f"{self.filename}_bot_data", self.bot_data)
if self.conversations: if self.conversations:
self.dump_file("{}_conversations".format(self.filename), self.conversations) self.dump_file(f"{self.filename}_conversations", self.conversations)

View file

@ -222,7 +222,7 @@ class Updater:
def _init_thread(self, target: Callable, name: str, *args: Any, **kwargs: Any) -> None: def _init_thread(self, target: Callable, name: str, *args: Any, **kwargs: Any) -> None:
thr = Thread( thr = Thread(
target=self._thread_wrapper, target=self._thread_wrapper,
name="Bot:{}:{}".format(self.bot.id, name), name=f"Bot:{self.bot.id}:{name}",
args=(target,) + args, args=(target,) + args,
kwargs=kwargs, kwargs=kwargs,
) )
@ -513,7 +513,7 @@ class Updater:
self.logger.debug('Updater thread started (webhook)') self.logger.debug('Updater thread started (webhook)')
use_ssl = cert is not None and key is not None use_ssl = cert is not None and key is not None
if not url_path.startswith('/'): if not url_path.startswith('/'):
url_path = '/{}'.format(url_path) url_path = f'/{url_path}'
# Create Tornado app instance # Create Tornado app instance
app = WebhookAppClass(url_path, self.bot, self.update_queue) app = WebhookAppClass(url_path, self.bot, self.update_queue)
@ -554,7 +554,7 @@ class Updater:
@staticmethod @staticmethod
def _gen_webhook_url(listen: str, port: int, url_path: str) -> str: def _gen_webhook_url(listen: str, port: int, url_path: str) -> str:
return 'https://{listen}:{port}{path}'.format(listen=listen, port=port, path=url_path) return f'https://{listen}:{port}{url_path}'
@no_type_check @no_type_check
def _bootstrap( def _bootstrap(

View file

@ -415,8 +415,8 @@ class Message(TelegramObject):
to_link = self.chat.username to_link = self.chat.username
else: else:
# Get rid of leading -100 for supergroups # Get rid of leading -100 for supergroups
to_link = "c/{}".format(str(self.chat.id)[4:]) to_link = f"c/{str(self.chat.id)[4:]}"
return "https://t.me/{}/{}".format(to_link, self.message_id) return f"https://t.me/{to_link}/{self.message_id}"
return None return None
@classmethod @classmethod
@ -1305,11 +1305,11 @@ class Message(TelegramObject):
) )
if entity.type == MessageEntity.TEXT_LINK: if entity.type == MessageEntity.TEXT_LINK:
insert = '<a href="{}">{}</a>'.format(entity.url, text) insert = f'<a href="{entity.url}">{text}</a>'
elif entity.type == MessageEntity.TEXT_MENTION and entity.user: elif entity.type == MessageEntity.TEXT_MENTION and entity.user:
insert = '<a href="tg://user?id={}">{}</a>'.format(entity.user.id, text) insert = f'<a href="tg://user?id={entity.user.id}">{text}</a>'
elif entity.type == MessageEntity.URL and urled: elif entity.type == MessageEntity.URL and urled:
insert = '<a href="{0}">{0}</a>'.format(text) insert = f'<a href="{text}">{text}</a>'
elif entity.type == MessageEntity.BOLD: elif entity.type == MessageEntity.BOLD:
insert = '<b>' + text + '</b>' insert = '<b>' + text + '</b>'
elif entity.type == MessageEntity.ITALIC: elif entity.type == MessageEntity.ITALIC:
@ -1318,9 +1318,7 @@ class Message(TelegramObject):
insert = '<code>' + text + '</code>' insert = '<code>' + text + '</code>'
elif entity.type == MessageEntity.PRE: elif entity.type == MessageEntity.PRE:
if entity.language: if entity.language:
insert = '<pre><code class="{}">{}</code></pre>'.format( insert = f'<pre><code class="{entity.language}">{text}</code></pre>'
entity.language, text
)
else: else:
insert = '<pre>' + text + '</pre>' insert = '<pre>' + text + '</pre>'
elif entity.type == MessageEntity.UNDERLINE: elif entity.type == MessageEntity.UNDERLINE:
@ -1480,15 +1478,15 @@ class Message(TelegramObject):
url = escape_markdown( url = escape_markdown(
entity.url, version=version, entity_type=MessageEntity.TEXT_LINK entity.url, version=version, entity_type=MessageEntity.TEXT_LINK
) )
insert = '[{}]({})'.format(text, url) insert = f'[{text}]({url})'
elif entity.type == MessageEntity.TEXT_MENTION and entity.user: elif entity.type == MessageEntity.TEXT_MENTION and entity.user:
insert = '[{}](tg://user?id={})'.format(text, entity.user.id) insert = f'[{text}](tg://user?id={entity.user.id})'
elif entity.type == MessageEntity.URL and urled: elif entity.type == MessageEntity.URL and urled:
if version == 1: if version == 1:
link = orig_text link = orig_text
else: else:
link = text link = text
insert = '[{}]({})'.format(link, orig_text) insert = f'[{link}]({orig_text})'
elif entity.type == MessageEntity.BOLD: elif entity.type == MessageEntity.BOLD:
insert = '*' + text + '*' insert = '*' + text + '*'
elif entity.type == MessageEntity.ITALIC: elif entity.type == MessageEntity.ITALIC:

View file

@ -45,7 +45,7 @@ class TelegramDecryptionError(TelegramError):
""" """
def __init__(self, message: Union[str, Exception]): def __init__(self, message: Union[str, Exception]):
super().__init__("TelegramDecryptionError: {}".format(message)) super().__init__(f"TelegramDecryptionError: {message}")
self._msg = str(message) self._msg = str(message)
def __reduce__(self) -> Tuple[type, Tuple[str]]: def __reduce__(self) -> Tuple[type, Tuple[str]]:
@ -91,7 +91,7 @@ def decrypt(secret, hash, data):
# If the newly calculated hash did not match the one telegram gave us # If the newly calculated hash did not match the one telegram gave us
if data_hash != hash: if data_hash != hash:
# Raise a error that is caught inside telegram.PassportData and transformed into a warning # Raise a error that is caught inside telegram.PassportData and transformed into a warning
raise TelegramDecryptionError("Hashes are not equal! {} != {}".format(data_hash, hash)) raise TelegramDecryptionError(f"Hashes are not equal! {data_hash} != {hash}")
# Return data without padding # Return data without padding
return data[data[0] :] return data[data[0] :]

View file

@ -101,7 +101,7 @@ class User(TelegramObject):
""":obj:`str`: Convenience property. If available, returns the user's :attr:`username` """:obj:`str`: Convenience property. If available, returns the user's :attr:`username`
prefixed with "@". If :attr:`username` is not available, returns :attr:`full_name`.""" prefixed with "@". If :attr:`username` is not available, returns :attr:`full_name`."""
if self.username: if self.username:
return '@{}'.format(self.username) return f'@{self.username}'
return self.full_name return self.full_name
@property @property
@ -119,7 +119,7 @@ class User(TelegramObject):
of the user.""" of the user."""
if self.username: if self.username:
return "https://t.me/{}".format(self.username) return f"https://t.me/{self.username}"
return None return None
@property @property

View file

@ -33,7 +33,7 @@ class TelegramDeprecationWarning(Warning):
def warn_deprecate_obj(old: str, new: str, stacklevel: int = 3) -> None: def warn_deprecate_obj(old: str, new: str, stacklevel: int = 3) -> None:
warnings.warn( warnings.warn(
'{} is being deprecated, please use {} from now on.'.format(old, new), f'{old} is being deprecated, please use {new} from now on.',
category=TelegramDeprecationWarning, category=TelegramDeprecationWarning,
stacklevel=stacklevel, stacklevel=stacklevel,
) )

View file

@ -80,7 +80,7 @@ def escape_markdown(text: str, version: int = 1, entity_type: str = None) -> str
else: else:
raise ValueError('Markdown version must be either 1 or 2!') raise ValueError('Markdown version must be either 1 or 2!')
return re.sub('([{}])'.format(re.escape(escape_chars)), r'\\\1', text) return re.sub(f'([{re.escape(escape_chars)}])', r'\\\1', text)
# -------- date/time related helpers -------- # -------- date/time related helpers --------
@ -178,7 +178,7 @@ def to_float_timestamp(
if isinstance(time_object, Number): if isinstance(time_object, Number):
return reference_timestamp + time_object return reference_timestamp + time_object
raise TypeError('Unable to convert {} object to timestamp'.format(type(time_object).__name__)) raise TypeError(f'Unable to convert {type(time_object).__name__} object to timestamp')
def to_timestamp( def to_timestamp(
@ -273,7 +273,7 @@ def effective_message_type(entity: 'MessageEntity') -> Optional[str]:
elif isinstance(entity, Update): elif isinstance(entity, Update):
message = entity.effective_message message = entity.effective_message
else: else:
raise TypeError("entity is not Message or Update (got: {})".format(type(entity))) raise TypeError(f"entity is not Message or Update (got: {type(entity)})")
for i in Message.MESSAGE_TYPES: for i in Message.MESSAGE_TYPES:
if getattr(message, i, None): if getattr(message, i, None):
@ -309,7 +309,7 @@ def create_deep_linked_url(bot_username: str, payload: str = None, group: bool =
if bot_username is None or len(bot_username) <= 3: if bot_username is None or len(bot_username) <= 3:
raise ValueError("You must provide a valid bot_username.") raise ValueError("You must provide a valid bot_username.")
base_url = 'https://t.me/{}'.format(bot_username) base_url = f'https://t.me/{bot_username}'
if not payload: if not payload:
return base_url return base_url
@ -327,7 +327,7 @@ def create_deep_linked_url(bot_username: str, payload: str = None, group: bool =
else: else:
key = 'start' key = 'start'
return '{}?{}={}'.format(base_url, key, payload) return f'{base_url}?{key}={payload}'
def encode_conversations_to_json(conversations: Dict[str, Dict[Tuple, Any]]) -> str: def encode_conversations_to_json(conversations: Dict[str, Dict[Tuple, Any]]) -> str:

View file

@ -255,7 +255,7 @@ class Request:
except urllib3.exceptions.HTTPError as error: except urllib3.exceptions.HTTPError as error:
# HTTPError must come last as its the base urllib3 exception class # HTTPError must come last as its the base urllib3 exception class
# TODO: do something smart here; for now just raise NetworkError # TODO: do something smart here; for now just raise NetworkError
raise NetworkError('urllib3 HTTPError {}'.format(error)) from error raise NetworkError(f'urllib3 HTTPError {error}') from error
if 200 <= resp.status <= 299: if 200 <= resp.status <= 299:
# 200-299 range are HTTP success statuses # 200-299 range are HTTP success statuses
@ -281,7 +281,7 @@ class Request:
) )
if resp.status == 502: if resp.status == 502:
raise NetworkError('Bad Gateway') raise NetworkError('Bad Gateway')
raise NetworkError('{} ({})'.format(message, resp.status)) raise NetworkError(f'{message} ({resp.status})')
def post(self, url: str, data: JSONDict, timeout: float = None) -> Union[JSONDict, bool]: def post(self, url: str, data: JSONDict, timeout: float = None) -> Union[JSONDict, bool]:
"""Request an URL. """Request an URL.

View file

@ -139,7 +139,7 @@ class WebhookServer:
class WebhookAppClass(tornado.web.Application): class WebhookAppClass(tornado.web.Application):
def __init__(self, webhook_path: str, bot: 'Bot', update_queue: Queue): def __init__(self, webhook_path: str, bot: 'Bot', update_queue: Queue):
self.shared_objects = {"bot": bot, "update_queue": update_queue} self.shared_objects = {"bot": bot, "update_queue": update_queue}
handlers = [(r"{}/?".format(webhook_path), WebhookHandler, self.shared_objects)] # noqa handlers = [(rf"{webhook_path}/?", WebhookHandler, self.shared_objects)] # noqa
tornado.web.Application.__init__(self, handlers) tornado.web.Application.__init__(self, handlers)
def log_request(self, handler: tornado.web.RequestHandler) -> None: def log_request(self, handler: tornado.web.RequestHandler) -> None:

View file

@ -87,7 +87,7 @@ def patient_request_wrapper(*args, **kwargs):
try: try:
return original_request_wrapper(*args, **kwargs) return original_request_wrapper(*args, **kwargs)
except RetryAfter as e: except RetryAfter as e:
pytest.xfail('Not waiting for flood control: {}'.format(e)) pytest.xfail(f'Not waiting for flood control: {e}')
Request._request_wrapper = patient_request_wrapper Request._request_wrapper = patient_request_wrapper

View file

@ -336,6 +336,6 @@ def expect_bad_request(func, message, reason):
return func() return func()
except BadRequest as e: except BadRequest as e:
if message in str(e): if message in str(e):
pytest.xfail('{}. {}'.format(reason, e)) pytest.xfail(f'{reason}. {e}')
else: else:
raise e raise e

View file

@ -26,7 +26,7 @@ def terminal_summary_wrapper(original, plugin_name):
text = fold_plugins[plugin_name] text = fold_plugins[plugin_name]
def pytest_terminal_summary(terminalreporter): def pytest_terminal_summary(terminalreporter):
terminalreporter.write('##[group] {}\n'.format(text)) terminalreporter.write(f'##[group] {text}\n')
original(terminalreporter) original(terminalreporter)
terminalreporter.write('##[endgroup]') terminalreporter.write('##[endgroup]')
@ -68,7 +68,7 @@ def pytest_runtest_protocol(item, nextitem):
if previous_name is None or previous_name != name: if previous_name is None or previous_name != name:
previous_name = name previous_name = name
terminal.write('\n##[group] {}'.format(name)) terminal.write(f'\n##[group] {name}')
yield yield

View file

@ -141,7 +141,7 @@ class TestBot:
assert get_me_bot.can_join_groups == bot.can_join_groups assert get_me_bot.can_join_groups == bot.can_join_groups
assert get_me_bot.can_read_all_group_messages == bot.can_read_all_group_messages assert get_me_bot.can_read_all_group_messages == bot.can_read_all_group_messages
assert get_me_bot.supports_inline_queries == bot.supports_inline_queries assert get_me_bot.supports_inline_queries == bot.supports_inline_queries
assert 'https://t.me/{}'.format(get_me_bot.username) == bot.link assert f'https://t.me/{get_me_bot.username}' == bot.link
assert commands == bot.commands assert commands == bot.commands
@flaky(3, 1) @flaky(3, 1)
@ -949,7 +949,7 @@ class TestBot:
chat = bot.get_chat(super_group_id) chat = bot.get_chat(super_group_id)
assert chat.type == 'supergroup' assert chat.type == 'supergroup'
assert chat.title == '>>> telegram.Bot(test) @{}'.format(bot.username) assert chat.title == f'>>> telegram.Bot(test) @{bot.username}'
assert chat.id == int(super_group_id) assert chat.id == int(super_group_id)
@flaky(3, 1) @flaky(3, 1)

View file

@ -91,7 +91,7 @@ class TestChat:
assert chat_dict['slow_mode_delay'] == chat.slow_mode_delay assert chat_dict['slow_mode_delay'] == chat.slow_mode_delay
def test_link(self, chat): def test_link(self, chat):
assert chat.link == 'https://t.me/{}'.format(chat.username) assert chat.link == f'https://t.me/{chat.username}'
chat.username = None chat.username = None
assert chat.link is None assert chat.link is None

View file

@ -158,7 +158,7 @@ class TestCommandHandler(BaseTest):
def ch_callback_args(self, bot, update, args): def ch_callback_args(self, bot, update, args):
if update.message.text == self.CMD: if update.message.text == self.CMD:
self.test_flag = len(args) == 0 self.test_flag = len(args) == 0
elif update.message.text == '{}@{}'.format(self.CMD, bot.username): elif update.message.text == f'{self.CMD}@{bot.username}':
self.test_flag = len(args) == 0 self.test_flag = len(args) == 0
else: else:
self.test_flag = args == ['one', 'two'] self.test_flag = args == ['one', 'two']
@ -175,8 +175,8 @@ class TestCommandHandler(BaseTest):
assert self.response(dp, make_command_update(command)) assert self.response(dp, make_command_update(command))
assert not is_match(handler, make_command_update(command[1:])) assert not is_match(handler, make_command_update(command[1:]))
assert not is_match(handler, make_command_update('/not{}'.format(command[1:]))) assert not is_match(handler, make_command_update(f'/not{command[1:]}'))
assert not is_match(handler, make_command_update('not {} at start'.format(command))) assert not is_match(handler, make_command_update(f'not {command} at start'))
@pytest.mark.parametrize( @pytest.mark.parametrize(
'cmd', 'cmd',
@ -227,7 +227,7 @@ class TestCommandHandler(BaseTest):
"""Test the passing of arguments alongside a command""" """Test the passing of arguments alongside a command"""
handler = self.make_default_handler(self.ch_callback_args, pass_args=True) handler = self.make_default_handler(self.ch_callback_args, pass_args=True)
dp.add_handler(handler) dp.add_handler(handler)
at_command = '{}@{}'.format(command, bot.username) at_command = f'{command}@{bot.username}'
assert self.response(dp, make_command_update(command)) assert self.response(dp, make_command_update(command))
assert self.response(dp, make_command_update(command + ' one two')) assert self.response(dp, make_command_update(command + ' one two'))
assert self.response(dp, make_command_update(at_command, bot=bot)) assert self.response(dp, make_command_update(at_command, bot=bot))
@ -344,7 +344,7 @@ class TestPrefixHandler(BaseTest):
assert self.response(dp, make_message_update(text)) assert self.response(dp, make_message_update(text))
assert not is_match(handler, make_message_update(command)) assert not is_match(handler, make_message_update(command))
assert not is_match(handler, make_message_update(prefix + 'notacommand')) assert not is_match(handler, make_message_update(prefix + 'notacommand'))
assert not is_match(handler, make_command_update('not {} at start'.format(text))) assert not is_match(handler, make_command_update(f'not {text} at start'))
def test_single_multi_prefixes_commands(self, prefixes, commands, prefix_message_update): def test_single_multi_prefixes_commands(self, prefixes, commands, prefix_message_update):
"""Test various combinations of prefixes and commands""" """Test various combinations of prefixes and commands"""

View file

@ -278,7 +278,7 @@ class TestConversationHandler:
assert list(value.keys())[0] == attr assert list(value.keys())[0] == attr
else: else:
assert getattr(ch, attr) == attr assert getattr(ch, attr) == attr
with pytest.raises(ValueError, match='You can not assign a new value to {}'.format(attr)): with pytest.raises(ValueError, match=f'You can not assign a new value to {attr}'):
setattr(ch, attr, True) setattr(ch, attr, True)
def test_immutable_per_message(self): def test_immutable_per_message(self):

View file

@ -678,7 +678,7 @@ class TestDispatcher:
thread_names = [thread.name for thread in getattr(dp2, '_Dispatcher__async_threads')] thread_names = [thread.name for thread in getattr(dp2, '_Dispatcher__async_threads')]
print(thread_names) print(thread_names)
for thread_name in thread_names: for thread_name in thread_names:
assert thread_name.startswith("Bot:{}:worker:".format(dp2.bot.id)) assert thread_name.startswith(f"Bot:{dp2.bot.id}:worker:")
def test_non_context_deprecation(self, dp): def test_non_context_deprecation(self, dp):
with pytest.warns(TelegramDeprecationWarning): with pytest.warns(TelegramDeprecationWarning):

View file

@ -183,16 +183,16 @@ class TestHelpers:
username = 'JamesTheMock' username = 'JamesTheMock'
payload = "hello" payload = "hello"
expected = "https://t.me/{}?start={}".format(username, payload) expected = f"https://t.me/{username}?start={payload}"
actual = helpers.create_deep_linked_url(username, payload) actual = helpers.create_deep_linked_url(username, payload)
assert expected == actual assert expected == actual
expected = "https://t.me/{}?startgroup={}".format(username, payload) expected = f"https://t.me/{username}?startgroup={payload}"
actual = helpers.create_deep_linked_url(username, payload, group=True) actual = helpers.create_deep_linked_url(username, payload, group=True)
assert expected == actual assert expected == actual
payload = "" payload = ""
expected = "https://t.me/{}".format(username) expected = f"https://t.me/{username}"
assert expected == helpers.create_deep_linked_url(username) assert expected == helpers.create_deep_linked_url(username)
assert expected == helpers.create_deep_linked_url(username, payload) assert expected == helpers.create_deep_linked_url(username, payload)
payload = None payload = None

View file

@ -350,7 +350,7 @@ class TestSendMediaGroup:
video_check = data[input_video.media.attach] == input_video.media.field_tuple video_check = data[input_video.media.attach] == input_video.media.field_tuple
thumb_check = data[input_video.thumb.attach] == input_video.thumb.field_tuple thumb_check = data[input_video.thumb.attach] == input_video.thumb.field_tuple
result = video_check and thumb_check result = video_check and thumb_check
raise (Exception('Test was {}'.format('successful' if result else 'failing'))) raise Exception(f"Test was {'successful' if result else 'failing'}")
monkeypatch.setattr('telegram.utils.request.Request._request_wrapper', test) monkeypatch.setattr('telegram.utils.request.Request._request_wrapper', test)
input_video = InputMediaVideo(video_file, thumb=photo_file) input_video = InputMediaVideo(video_file, thumb=photo_file)

View file

@ -579,9 +579,7 @@ class TestMessage:
def test_link_with_username(self, message, type): def test_link_with_username(self, message, type):
message.chat.username = 'username' message.chat.username = 'username'
message.chat.type = type message.chat.type = type
assert message.link == 'https://t.me/{}/{}'.format( assert message.link == f'https://t.me/{message.chat.username}/{message.message_id}'
message.chat.username, message.message_id
)
@pytest.mark.parametrize( @pytest.mark.parametrize(
'type, id', argvalues=[(Chat.CHANNEL, -1003), (Chat.SUPERGROUP, -1003)] 'type, id', argvalues=[(Chat.CHANNEL, -1003), (Chat.SUPERGROUP, -1003)]
@ -591,7 +589,7 @@ class TestMessage:
message.chat.id = id message.chat.id = id
message.chat.type = type message.chat.type = type
# The leading - for group ids/ -100 for supergroup ids isn't supposed to be in the link # The leading - for group ids/ -100 for supergroup ids isn't supposed to be in the link
assert message.link == 'https://t.me/c/{}/{}'.format(3, message.message_id) assert message.link == f'https://t.me/c/{3}/{message.message_id}'
@pytest.mark.parametrize('id, username', argvalues=[(None, 'username'), (-3, None)]) @pytest.mark.parametrize('id, username', argvalues=[(None, 'username'), (-3, None)])
def test_link_private_chats(self, message, id, username): def test_link_private_chats(self, message, id, username):

View file

@ -68,9 +68,7 @@ def check_method(h4):
checked = [] checked = []
for parameter in table: for parameter in table:
param = sig.parameters.get(parameter[0]) param = sig.parameters.get(parameter[0])
assert param is not None, "Parameter {} not found in {}".format( assert param is not None, f"Parameter {parameter[0]} not found in {method.__name__}"
parameter[0], method.__name__
)
# TODO: Check type via docstring # TODO: Check type via docstring
# TODO: Check if optional or required # TODO: Check if optional or required
checked.append(parameter[0]) checked.append(parameter[0])
@ -117,7 +115,7 @@ def check_object(h4):
continue continue
param = sig.parameters.get(field) param = sig.parameters.get(field)
assert param is not None, "Attribute {} not found in {}".format(field, obj.__name__) assert param is not None, f"Attribute {field} not found in {obj.__name__}"
# TODO: Check type via docstring # TODO: Check type via docstring
# TODO: Check if optional or required # TODO: Check if optional or required
checked.append(field) checked.append(field)

View file

@ -258,7 +258,7 @@ class TestSticker:
@pytest.fixture(scope='function') @pytest.fixture(scope='function')
def sticker_set(bot): def sticker_set(bot):
ss = bot.get_sticker_set('test_by_{}'.format(bot.username)) ss = bot.get_sticker_set(f'test_by_{bot.username}')
if len(ss.stickers) > 100: if len(ss.stickers) > 100:
try: try:
for i in range(1, 50): for i in range(1, 50):
@ -270,7 +270,7 @@ def sticker_set(bot):
@pytest.fixture(scope='function') @pytest.fixture(scope='function')
def animated_sticker_set(bot): def animated_sticker_set(bot):
ss = bot.get_sticker_set('animated_test_by_{}'.format(bot.username)) ss = bot.get_sticker_set(f'animated_test_by_{bot.username}')
if len(ss.stickers) > 100: if len(ss.stickers) > 100:
try: try:
for i in range(1, 50): for i in range(1, 50):
@ -295,7 +295,7 @@ class TestStickerSet:
name = 'NOTAREALNAME' name = 'NOTAREALNAME'
def test_de_json(self, bot, sticker): def test_de_json(self, bot, sticker):
name = 'test_by_{}'.format(bot.username) name = f'test_by_{bot.username}'
json_dict = { json_dict = {
'name': name, 'name': name,
'title': self.title, 'title': self.title,
@ -320,12 +320,12 @@ class TestStickerSet:
file = bot.upload_sticker_file(95205500, f) file = bot.upload_sticker_file(95205500, f)
assert file assert file
assert bot.add_sticker_to_set( assert bot.add_sticker_to_set(
chat_id, 'test_by_{}'.format(bot.username), png_sticker=file.file_id, emojis='😄' chat_id, f'test_by_{bot.username}', png_sticker=file.file_id, emojis='😄'
) )
# Also test with file input and mask # Also test with file input and mask
assert bot.add_sticker_to_set( assert bot.add_sticker_to_set(
chat_id, chat_id,
'test_by_{}'.format(bot.username), f'test_by_{bot.username}',
png_sticker=sticker_file, png_sticker=sticker_file,
emojis='😄', emojis='😄',
mask_position=MaskPosition(MaskPosition.EYES, -1, 1, 2), mask_position=MaskPosition(MaskPosition.EYES, -1, 1, 2),
@ -336,7 +336,7 @@ class TestStickerSet:
def test_bot_methods_1_tgs(self, bot, chat_id): def test_bot_methods_1_tgs(self, bot, chat_id):
assert bot.add_sticker_to_set( assert bot.add_sticker_to_set(
chat_id, chat_id,
'animated_test_by_{}'.format(bot.username), f'animated_test_by_{bot.username}',
tgs_sticker=open('tests/data/telegram_animated_sticker.tgs', 'rb'), tgs_sticker=open('tests/data/telegram_animated_sticker.tgs', 'rb'),
emojis='😄', emojis='😄',
) )
@ -368,7 +368,7 @@ class TestStickerSet:
def test_bot_methods_3_png(self, bot, chat_id, sticker_set_thumb_file): def test_bot_methods_3_png(self, bot, chat_id, sticker_set_thumb_file):
sleep(1) sleep(1)
assert bot.set_sticker_set_thumb( assert bot.set_sticker_set_thumb(
'test_by_{}'.format(bot.username), chat_id, sticker_set_thumb_file f'test_by_{bot.username}', chat_id, sticker_set_thumb_file
) )
@flaky(10, 1) @flaky(10, 1)
@ -376,13 +376,11 @@ class TestStickerSet:
def test_bot_methods_3_tgs(self, bot, chat_id, animated_sticker_file, animated_sticker_set): def test_bot_methods_3_tgs(self, bot, chat_id, animated_sticker_file, animated_sticker_set):
sleep(1) sleep(1)
assert bot.set_sticker_set_thumb( assert bot.set_sticker_set_thumb(
'animated_test_by_{}'.format(bot.username), chat_id, animated_sticker_file f'animated_test_by_{bot.username}', chat_id, animated_sticker_file
) )
file_id = animated_sticker_set.stickers[-1].file_id file_id = animated_sticker_set.stickers[-1].file_id
# also test with file input and mask # also test with file input and mask
assert bot.set_sticker_set_thumb( assert bot.set_sticker_set_thumb(f'animated_test_by_{bot.username}', chat_id, file_id)
'animated_test_by_{}'.format(bot.username), chat_id, file_id
)
@flaky(10, 1) @flaky(10, 1)
@pytest.mark.timeout(10) @pytest.mark.timeout(10)

View file

@ -134,7 +134,7 @@ class TestUpdater:
pprint.pprint([rec.getMessage() for rec in caplog.get_records('call')]) pprint.pprint([rec.getMessage() for rec in caplog.get_records('call')])
assert any( assert any(
'unhandled exception in Bot:{}:updater'.format(updater.bot.id) in rec.getMessage() f'unhandled exception in Bot:{updater.bot.id}:updater' in rec.getMessage()
for rec in caplog.get_records('call') for rec in caplog.get_records('call')
) )
@ -487,7 +487,7 @@ class TestUpdater:
if content_len is not None: if content_len is not None:
headers['content-length'] = str(content_len) headers['content-length'] = str(content_len)
url = 'http://{ip}:{port}/{path}'.format(ip=ip, port=port, path=url_path) url = f'http://{ip}:{port}/{url_path}'
req = Request(url, data=payload, headers=headers) req = Request(url, data=payload, headers=headers)
@ -512,7 +512,7 @@ class TestUpdater:
updater.idle() updater.idle()
rec = caplog.records[-2] rec = caplog.records[-2]
assert rec.getMessage().startswith('Received signal {}'.format(signal.SIGTERM)) assert rec.getMessage().startswith(f'Received signal {signal.SIGTERM}')
assert rec.levelname == 'INFO' assert rec.levelname == 'INFO'
rec = caplog.records[-1] rec = caplog.records[-1]

View file

@ -123,7 +123,7 @@ class TestUser:
assert user.full_name == u'first\u2022name' assert user.full_name == u'first\u2022name'
def test_link(self, user): def test_link(self, user):
assert user.link == 'https://t.me/{}'.format(user.username) assert user.link == f'https://t.me/{user.username}'
user.username = None user.username = None
assert user.link is None assert user.link is None