mirror of
https://github.com/python-telegram-bot/python-telegram-bot.git
synced 2024-12-28 23:38:31 +01:00
Use F-Strings Where Possible (#2222)
This commit is contained in:
parent
df6d5f0840
commit
58b9882021
40 changed files with 145 additions and 173 deletions
|
@ -50,7 +50,7 @@ def facts_to_str(user_data: Dict[str, str]) -> str:
|
|||
facts = list()
|
||||
|
||||
for key, value in user_data.items():
|
||||
facts.append('{} - {}'.format(key, value))
|
||||
facts.append(f'{key} - {value}')
|
||||
|
||||
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:
|
||||
text = update.message.text
|
||||
context.user_data['choice'] = text
|
||||
update.message.reply_text(
|
||||
'Your {}? Yes, I would love to hear about that!'.format(text.lower())
|
||||
)
|
||||
update.message.reply_text(f'Your {text.lower()}? Yes, I would love to hear about that!')
|
||||
|
||||
return TYPING_REPLY
|
||||
|
||||
|
@ -92,8 +90,8 @@ def received_information(update: Update, context: CallbackContext) -> int:
|
|||
|
||||
update.message.reply_text(
|
||||
"Neat! Just so you know, this is what you already told me:"
|
||||
"{} You can tell me more, or change your opinion"
|
||||
" on something.".format(facts_to_str(user_data)),
|
||||
f"{facts_to_str(user_data)} You can tell me more, or change your opinion"
|
||||
" on something.",
|
||||
reply_markup=markup,
|
||||
)
|
||||
|
||||
|
@ -106,7 +104,7 @@ def done(update: Update, context: CallbackContext) -> int:
|
|||
del user_data['choice']
|
||||
|
||||
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()
|
||||
|
|
|
@ -66,7 +66,7 @@ def deep_linked_level_2(update: Update, context: CallbackContext) -> None:
|
|||
"""Reached through the SO_COOL payload"""
|
||||
bot = context.bot
|
||||
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)
|
||||
|
||||
|
||||
|
@ -74,7 +74,7 @@ def deep_linked_level_3(update: Update, context: CallbackContext) -> None:
|
|||
"""Reached through the USING_ENTITIES payload"""
|
||||
payload = context.args
|
||||
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}"
|
||||
)
|
||||
|
||||
|
||||
|
|
|
@ -42,16 +42,12 @@ def error_handler(update: Update, context: CallbackContext) -> None:
|
|||
# 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.
|
||||
message = (
|
||||
'An exception was raised while handling an update\n'
|
||||
'<pre>update = {}</pre>\n\n'
|
||||
'<pre>context.chat_data = {}</pre>\n\n'
|
||||
'<pre>context.user_data = {}</pre>\n\n'
|
||||
'<pre>{}</pre>'
|
||||
).format(
|
||||
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),
|
||||
f'An exception was raised while handling an update\n'
|
||||
f'<pre>update = {html.escape(json.dumps(update.to_dict(), indent=2, ensure_ascii=False))}'
|
||||
'</pre>\n\n'
|
||||
f'<pre>context.chat_data = {html.escape(str(context.chat_data))}</pre>\n\n'
|
||||
f'<pre>context.user_data = {html.escape(str(context.user_data))}</pre>\n\n'
|
||||
f'<pre>{html.escape(tb_string)}</pre>'
|
||||
)
|
||||
|
||||
# Finally, send the message
|
||||
|
@ -66,7 +62,7 @@ def bad_command(update: Update, context: CallbackContext) -> None:
|
|||
def start(update: Update, context: CallbackContext) -> None:
|
||||
update.effective_message.reply_html(
|
||||
'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>.'
|
||||
)
|
||||
|
||||
|
||||
|
|
|
@ -52,14 +52,14 @@ def inlinequery(update: Update, context: CallbackContext) -> None:
|
|||
id=uuid4(),
|
||||
title="Bold",
|
||||
input_message_content=InputTextMessageContent(
|
||||
"*{}*".format(escape_markdown(query)), parse_mode=ParseMode.MARKDOWN
|
||||
f"*{escape_markdown(query)}*", parse_mode=ParseMode.MARKDOWN
|
||||
),
|
||||
),
|
||||
InlineQueryResultArticle(
|
||||
id=uuid4(),
|
||||
title="Italic",
|
||||
input_message_content=InputTextMessageContent(
|
||||
"_{}_".format(escape_markdown(query)), parse_mode=ParseMode.MARKDOWN
|
||||
f"_{escape_markdown(query)}_", parse_mode=ParseMode.MARKDOWN
|
||||
),
|
||||
),
|
||||
]
|
||||
|
|
|
@ -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
|
||||
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:
|
||||
|
|
|
@ -128,15 +128,13 @@ def show_data(update: Update, context: CallbackContext) -> None:
|
|||
text = ''
|
||||
if level == SELF:
|
||||
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:
|
||||
male, female = _name_switcher(level)
|
||||
|
||||
for person in user_data[level]:
|
||||
gender = female if person[GENDER] == FEMALE else male
|
||||
text += '\n{}: Name: {}, Age: {}'.format(
|
||||
gender, person.get(NAME, '-'), person.get(AGE, '-')
|
||||
)
|
||||
text += f"\n{gender}: Name: {person.get(NAME, '-')}, Age: {person.get(AGE, '-')}"
|
||||
return text
|
||||
|
||||
user_data = context.user_data
|
||||
|
@ -341,9 +339,7 @@ def main():
|
|||
entry_points=[CallbackQueryHandler(select_level, pattern='^' + str(ADDING_MEMBER) + '$')],
|
||||
states={
|
||||
SELECTING_LEVEL: [
|
||||
CallbackQueryHandler(
|
||||
select_gender, pattern='^{}$|^{}$'.format(str(PARENTS), str(CHILDREN))
|
||||
)
|
||||
CallbackQueryHandler(select_gender, pattern=f'^{PARENTS}$|^{CHILDREN}$')
|
||||
],
|
||||
SELECTING_GENDER: [description_conv],
|
||||
},
|
||||
|
|
|
@ -51,7 +51,7 @@ def facts_to_str(user_data):
|
|||
facts = list()
|
||||
|
||||
for key, value in user_data.items():
|
||||
facts.append('{} - {}'.format(key, value))
|
||||
facts.append(f'{key} - {value}')
|
||||
|
||||
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."
|
||||
if context.user_data:
|
||||
reply_text += (
|
||||
" You already told me your {}. Why don't you tell me something more "
|
||||
"about yourself? Or change anything I "
|
||||
"already know.".format(", ".join(context.user_data.keys()))
|
||||
f" You already told me your {', '.join(context.user_data.keys())}. Why don't you "
|
||||
f"tell me something more about yourself? Or change anything I already know."
|
||||
)
|
||||
else:
|
||||
reply_text += (
|
||||
|
@ -78,11 +77,11 @@ def regular_choice(update: Update, context: CallbackContext) -> None:
|
|||
text = update.message.text.lower()
|
||||
context.user_data['choice'] = text
|
||||
if context.user_data.get(text):
|
||||
reply_text = 'Your {}, I already know the following ' 'about that: {}'.format(
|
||||
text, context.user_data[text]
|
||||
reply_text = (
|
||||
f'Your {text}, I already know the following about that: {context.user_data[text]}'
|
||||
)
|
||||
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)
|
||||
|
||||
return TYPING_REPLY
|
||||
|
@ -104,9 +103,9 @@ def received_information(update: Update, context: CallbackContext) -> None:
|
|||
|
||||
update.message.reply_text(
|
||||
"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 "
|
||||
"something.".format(facts_to_str(context.user_data)),
|
||||
"something.",
|
||||
reply_markup=markup,
|
||||
)
|
||||
|
||||
|
@ -115,7 +114,7 @@ def received_information(update: Update, context: CallbackContext) -> None:
|
|||
|
||||
def show_data(update: Update, context: CallbackContext) -> None:
|
||||
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']
|
||||
|
||||
update.message.reply_text(
|
||||
"I learned these facts about you:"
|
||||
"{}"
|
||||
"Until next time!".format(facts_to_str(context.user_data))
|
||||
"I learned these facts about you:" f"{facts_to_str(context.user_data)}" "Until next time!"
|
||||
)
|
||||
return ConversationHandler.END
|
||||
|
||||
|
|
|
@ -84,7 +84,7 @@ def receive_poll_answer(update: Update, context: CallbackContext) -> None:
|
|||
answer_string += questions[question_id]
|
||||
context.bot.send_message(
|
||||
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,
|
||||
)
|
||||
context.bot_data[poll_id]["answers"] += 1
|
||||
|
|
|
@ -38,12 +38,10 @@ def _git_revision() -> Optional[str]:
|
|||
|
||||
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__)) # type: ignore[attr-defined]
|
||||
print('Python {}'.format(sys.version.replace('\n', ' ')))
|
||||
print(f'python-telegram-bot {telegram_ver}' + (f' ({git_revision})' if git_revision else ''))
|
||||
print(f'certifi {certifi.__version__}') # type: ignore[attr-defined]
|
||||
sys_version = sys.version.replace('\n', ' ')
|
||||
print(f'Python {sys_version}')
|
||||
|
||||
|
||||
def main() -> None:
|
||||
|
|
|
@ -102,13 +102,13 @@ class TelegramObject:
|
|||
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__)
|
||||
f"Objects of type {self.__class__.__name__} can not be meaningfully tested for"
|
||||
" equivalence."
|
||||
)
|
||||
if other._id_attrs == ():
|
||||
warnings.warn(
|
||||
"Objects of type {} can not be meaningfully tested for "
|
||||
"equivalence.".format(other.__class__.__name__)
|
||||
f"Objects of type {other.__class__.__name__} can not be meaningfully tested"
|
||||
" for equivalence."
|
||||
)
|
||||
return self._id_attrs == other._id_attrs
|
||||
return super().__eq__(other) # pylint: disable=no-member
|
||||
|
|
|
@ -231,9 +231,7 @@ class Bot(TelegramObject):
|
|||
else:
|
||||
data = api_kwargs
|
||||
|
||||
return self.request.post(
|
||||
'{}/{}'.format(self.base_url, endpoint), data=data, timeout=timeout
|
||||
)
|
||||
return self.request.post(f'{self.base_url}/{endpoint}', data=data, timeout=timeout)
|
||||
|
||||
def _message(
|
||||
self,
|
||||
|
@ -321,7 +319,7 @@ class Bot(TelegramObject):
|
|||
def link(self) -> str:
|
||||
""":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
|
||||
@info
|
||||
|
@ -355,7 +353,7 @@ class Bot(TelegramObject):
|
|||
def name(self) -> str:
|
||||
""":obj:`str`: Bot's @username."""
|
||||
|
||||
return '@{}'.format(self.username)
|
||||
return f'@{self.username}'
|
||||
|
||||
@log
|
||||
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)
|
||||
|
||||
if result.get('file_path'): # type: ignore
|
||||
result['file_path'] = '{}/{}'.format( # type: ignore
|
||||
self.base_file_url, result['file_path'] # type: ignore
|
||||
)
|
||||
result['file_path'] = f'{self.base_file_url}/{result["file_path"]}' # type: ignore
|
||||
|
||||
return File.de_json(result, self) # type: ignore
|
||||
|
||||
|
|
|
@ -148,7 +148,7 @@ class Chat(TelegramObject):
|
|||
""":obj:`str`: Convenience property. If the chat has a :attr:`username`, returns a t.me
|
||||
link of the chat."""
|
||||
if self.username:
|
||||
return "https://t.me/{}".format(self.username)
|
||||
return f"https://t.me/{self.username}"
|
||||
return None
|
||||
|
||||
@property
|
||||
|
|
|
@ -93,7 +93,7 @@ class ChatMigrated(TelegramError):
|
|||
"""
|
||||
|
||||
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
|
||||
|
||||
def __reduce__(self) -> Tuple[type, Tuple[int]]: # type: ignore[override]
|
||||
|
@ -108,7 +108,7 @@ class RetryAfter(TelegramError):
|
|||
"""
|
||||
|
||||
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)
|
||||
|
||||
def __reduce__(self) -> Tuple[type, Tuple[float]]: # type: ignore[override]
|
||||
|
|
|
@ -216,12 +216,10 @@ class Dispatcher:
|
|||
return self.__exception_event
|
||||
|
||||
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):
|
||||
thread = Thread(
|
||||
target=self._pooled, name='Bot:{}:worker:{}{}'.format(self.bot.id, base_name, i)
|
||||
)
|
||||
thread = Thread(target=self._pooled, name=f'Bot:{self.bot.id}:worker:{base_name}{i}')
|
||||
self.__async_threads.add(thread)
|
||||
thread.start()
|
||||
|
||||
|
@ -243,7 +241,7 @@ class Dispatcher:
|
|||
"""
|
||||
if cls.__singleton is not None:
|
||||
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:
|
||||
thr_name = current_thread().getName()
|
||||
|
@ -484,14 +482,14 @@ class Dispatcher:
|
|||
from .conversationhandler import ConversationHandler # pylint: disable=C0415
|
||||
|
||||
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):
|
||||
raise TypeError('group is not int')
|
||||
if isinstance(handler, ConversationHandler) and handler.persistent and handler.name:
|
||||
if not self.persistence:
|
||||
raise ValueError(
|
||||
"ConversationHandler {} can not be persistent if dispatcher has no "
|
||||
"persistence".format(handler.name)
|
||||
f"ConversationHandler {handler.name} can not be persistent if dispatcher has "
|
||||
f"no persistence"
|
||||
)
|
||||
handler.persistence = self.persistence
|
||||
handler.conversations = self.persistence.get_conversations(handler.name)
|
||||
|
|
|
@ -223,7 +223,7 @@ class InvertedFilter(UpdateFilter):
|
|||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
return "<inverted {}>".format(self.f)
|
||||
return f"<inverted {self.f}>"
|
||||
|
||||
@name.setter
|
||||
def name(self, name: str) -> NoReturn:
|
||||
|
@ -304,8 +304,9 @@ class MergedFilter(UpdateFilter):
|
|||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
return "<{} {} {}>".format(
|
||||
self.base_filter, "and" if self.and_filter else "or", self.and_filter or self.or_filter
|
||||
return (
|
||||
f"<{self.base_filter} {'and' if self.and_filter else 'or'} "
|
||||
f"{self.and_filter or self.or_filter}>"
|
||||
)
|
||||
|
||||
@name.setter
|
||||
|
@ -342,7 +343,7 @@ class XORFilter(UpdateFilter):
|
|||
|
||||
class _DiceEmoji(MessageFilter):
|
||||
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
|
||||
|
||||
class _DiceValues(MessageFilter):
|
||||
|
@ -354,7 +355,7 @@ class _DiceEmoji(MessageFilter):
|
|||
):
|
||||
self.values = [values] if isinstance(values, int) else values
|
||||
self.emoji = emoji
|
||||
self.name = '{}({})'.format(name, values)
|
||||
self.name = f'{name}({values})'
|
||||
|
||||
def filter(self, message: Message) -> bool:
|
||||
if message.dice and message.dice.value in self.values:
|
||||
|
@ -403,7 +404,7 @@ class Filters:
|
|||
class _TextStrings(MessageFilter):
|
||||
def __init__(self, strings: Union[List[str], Tuple[str]]):
|
||||
self.strings = strings
|
||||
self.name = 'Filters.text({})'.format(strings)
|
||||
self.name = f'Filters.text({strings})'
|
||||
|
||||
def filter(self, message: Message) -> bool:
|
||||
if message.text:
|
||||
|
@ -454,7 +455,7 @@ class Filters:
|
|||
class _CaptionStrings(MessageFilter):
|
||||
def __init__(self, strings: Union[List[str], Tuple[str]]):
|
||||
self.strings = strings
|
||||
self.name = 'Filters.caption({})'.format(strings)
|
||||
self.name = f'Filters.caption({strings})'
|
||||
|
||||
def filter(self, message: Message) -> bool:
|
||||
if message.caption:
|
||||
|
@ -489,7 +490,7 @@ class Filters:
|
|||
class _CommandOnlyStart(MessageFilter):
|
||||
def __init__(self, only_start: bool):
|
||||
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:
|
||||
return bool(
|
||||
|
@ -566,7 +567,7 @@ class Filters:
|
|||
pattern = re.compile(pattern)
|
||||
pattern = cast(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]]]:
|
||||
"""""" # remove method from docs
|
||||
|
@ -601,7 +602,7 @@ class Filters:
|
|||
pattern = re.compile(pattern)
|
||||
pattern = cast(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]]]:
|
||||
"""""" # remove method from docs
|
||||
|
@ -652,7 +653,7 @@ class Filters:
|
|||
Args:
|
||||
category (str, optional): category of the media you want to filter"""
|
||||
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:
|
||||
"""""" # remove method from docs
|
||||
|
@ -685,7 +686,7 @@ class Filters:
|
|||
Args:
|
||||
mimetype (str, optional): mime_type of the media you want to filter"""
|
||||
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:
|
||||
"""""" # remove method from docs
|
||||
|
@ -1108,7 +1109,7 @@ officedocument.wordprocessingml.document")``-
|
|||
|
||||
def __init__(self, entity_type: str):
|
||||
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:
|
||||
"""""" # remove method from docs
|
||||
|
@ -1130,7 +1131,7 @@ officedocument.wordprocessingml.document")``-
|
|||
|
||||
def __init__(self, entity_type: str):
|
||||
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:
|
||||
"""""" # remove method from docs
|
||||
|
@ -1902,7 +1903,7 @@ officedocument.wordprocessingml.document")``-
|
|||
else:
|
||||
lang = cast(List[str], lang)
|
||||
self.lang = lang
|
||||
self.name = 'Filters.language({})'.format(self.lang)
|
||||
self.name = f'Filters.language({self.lang})'
|
||||
|
||||
def filter(self, message: Message) -> bool:
|
||||
"""""" # remove method from docs
|
||||
|
|
|
@ -89,7 +89,7 @@ class DelayQueue(threading.Thread):
|
|||
self.__exit_req = False # flag to gently exit thread
|
||||
self.__class__._instcnt += 1
|
||||
if name is None:
|
||||
name = '{}-{}'.format(self.__class__.__name__, self.__class__._instcnt)
|
||||
name = f'{self.__class__.__name__}-{self.__class__._instcnt}'
|
||||
super().__init__(name=name)
|
||||
self.daemon = False
|
||||
if autostart: # immediately start processing
|
||||
|
|
|
@ -111,9 +111,9 @@ class PicklePersistence(BasePersistence):
|
|||
self.chat_data = defaultdict(dict)
|
||||
self.bot_data = {}
|
||||
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:
|
||||
raise TypeError("Something went wrong unpickling {}".format(filename)) from exc
|
||||
raise TypeError(f"Something went wrong unpickling {filename}") from exc
|
||||
|
||||
@staticmethod
|
||||
def load_file(filename: str) -> Any:
|
||||
|
@ -123,9 +123,9 @@ class PicklePersistence(BasePersistence):
|
|||
except IOError:
|
||||
return None
|
||||
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:
|
||||
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:
|
||||
with open(self.filename, "wb") as file:
|
||||
|
@ -151,7 +151,7 @@ class PicklePersistence(BasePersistence):
|
|||
if self.user_data:
|
||||
pass
|
||||
elif not self.single_file:
|
||||
filename = "{}_user_data".format(self.filename)
|
||||
filename = f"{self.filename}_user_data"
|
||||
data = self.load_file(filename)
|
||||
if not data:
|
||||
data = defaultdict(dict)
|
||||
|
@ -171,7 +171,7 @@ class PicklePersistence(BasePersistence):
|
|||
if self.chat_data:
|
||||
pass
|
||||
elif not self.single_file:
|
||||
filename = "{}_chat_data".format(self.filename)
|
||||
filename = f"{self.filename}_chat_data"
|
||||
data = self.load_file(filename)
|
||||
if not data:
|
||||
data = defaultdict(dict)
|
||||
|
@ -191,7 +191,7 @@ class PicklePersistence(BasePersistence):
|
|||
if self.bot_data:
|
||||
pass
|
||||
elif not self.single_file:
|
||||
filename = "{}_bot_data".format(self.filename)
|
||||
filename = f"{self.filename}_bot_data"
|
||||
data = self.load_file(filename)
|
||||
if not data:
|
||||
data = {}
|
||||
|
@ -212,7 +212,7 @@ class PicklePersistence(BasePersistence):
|
|||
if self.conversations:
|
||||
pass
|
||||
elif not self.single_file:
|
||||
filename = "{}_conversations".format(self.filename)
|
||||
filename = f"{self.filename}_conversations"
|
||||
data = self.load_file(filename)
|
||||
if not data:
|
||||
data = {name: {}}
|
||||
|
@ -239,7 +239,7 @@ class PicklePersistence(BasePersistence):
|
|||
self.conversations[name][key] = new_state
|
||||
if not self.on_flush:
|
||||
if not self.single_file:
|
||||
filename = "{}_conversations".format(self.filename)
|
||||
filename = f"{self.filename}_conversations"
|
||||
self.dump_file(filename, self.conversations)
|
||||
else:
|
||||
self.dump_singlefile()
|
||||
|
@ -258,7 +258,7 @@ class PicklePersistence(BasePersistence):
|
|||
self.user_data[user_id] = data
|
||||
if not self.on_flush:
|
||||
if not self.single_file:
|
||||
filename = "{}_user_data".format(self.filename)
|
||||
filename = f"{self.filename}_user_data"
|
||||
self.dump_file(filename, self.user_data)
|
||||
else:
|
||||
self.dump_singlefile()
|
||||
|
@ -277,7 +277,7 @@ class PicklePersistence(BasePersistence):
|
|||
self.chat_data[chat_id] = data
|
||||
if not self.on_flush:
|
||||
if not self.single_file:
|
||||
filename = "{}_chat_data".format(self.filename)
|
||||
filename = f"{self.filename}_chat_data"
|
||||
self.dump_file(filename, self.chat_data)
|
||||
else:
|
||||
self.dump_singlefile()
|
||||
|
@ -293,7 +293,7 @@ class PicklePersistence(BasePersistence):
|
|||
self.bot_data = data.copy()
|
||||
if not self.on_flush:
|
||||
if not self.single_file:
|
||||
filename = "{}_bot_data".format(self.filename)
|
||||
filename = f"{self.filename}_bot_data"
|
||||
self.dump_file(filename, self.bot_data)
|
||||
else:
|
||||
self.dump_singlefile()
|
||||
|
@ -305,10 +305,10 @@ class PicklePersistence(BasePersistence):
|
|||
self.dump_singlefile()
|
||||
else:
|
||||
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:
|
||||
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:
|
||||
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:
|
||||
self.dump_file("{}_conversations".format(self.filename), self.conversations)
|
||||
self.dump_file(f"{self.filename}_conversations", self.conversations)
|
||||
|
|
|
@ -222,7 +222,7 @@ class Updater:
|
|||
def _init_thread(self, target: Callable, name: str, *args: Any, **kwargs: Any) -> None:
|
||||
thr = Thread(
|
||||
target=self._thread_wrapper,
|
||||
name="Bot:{}:{}".format(self.bot.id, name),
|
||||
name=f"Bot:{self.bot.id}:{name}",
|
||||
args=(target,) + args,
|
||||
kwargs=kwargs,
|
||||
)
|
||||
|
@ -513,7 +513,7 @@ class Updater:
|
|||
self.logger.debug('Updater thread started (webhook)')
|
||||
use_ssl = cert is not None and key is not None
|
||||
if not url_path.startswith('/'):
|
||||
url_path = '/{}'.format(url_path)
|
||||
url_path = f'/{url_path}'
|
||||
|
||||
# Create Tornado app instance
|
||||
app = WebhookAppClass(url_path, self.bot, self.update_queue)
|
||||
|
@ -554,7 +554,7 @@ class Updater:
|
|||
|
||||
@staticmethod
|
||||
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
|
||||
def _bootstrap(
|
||||
|
|
|
@ -415,8 +415,8 @@ class Message(TelegramObject):
|
|||
to_link = self.chat.username
|
||||
else:
|
||||
# Get rid of leading -100 for supergroups
|
||||
to_link = "c/{}".format(str(self.chat.id)[4:])
|
||||
return "https://t.me/{}/{}".format(to_link, self.message_id)
|
||||
to_link = f"c/{str(self.chat.id)[4:]}"
|
||||
return f"https://t.me/{to_link}/{self.message_id}"
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
|
@ -1305,11 +1305,11 @@ class Message(TelegramObject):
|
|||
)
|
||||
|
||||
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:
|
||||
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:
|
||||
insert = '<a href="{0}">{0}</a>'.format(text)
|
||||
insert = f'<a href="{text}">{text}</a>'
|
||||
elif entity.type == MessageEntity.BOLD:
|
||||
insert = '<b>' + text + '</b>'
|
||||
elif entity.type == MessageEntity.ITALIC:
|
||||
|
@ -1318,9 +1318,7 @@ class Message(TelegramObject):
|
|||
insert = '<code>' + text + '</code>'
|
||||
elif entity.type == MessageEntity.PRE:
|
||||
if entity.language:
|
||||
insert = '<pre><code class="{}">{}</code></pre>'.format(
|
||||
entity.language, text
|
||||
)
|
||||
insert = f'<pre><code class="{entity.language}">{text}</code></pre>'
|
||||
else:
|
||||
insert = '<pre>' + text + '</pre>'
|
||||
elif entity.type == MessageEntity.UNDERLINE:
|
||||
|
@ -1480,15 +1478,15 @@ class Message(TelegramObject):
|
|||
url = escape_markdown(
|
||||
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:
|
||||
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:
|
||||
if version == 1:
|
||||
link = orig_text
|
||||
else:
|
||||
link = text
|
||||
insert = '[{}]({})'.format(link, orig_text)
|
||||
insert = f'[{link}]({orig_text})'
|
||||
elif entity.type == MessageEntity.BOLD:
|
||||
insert = '*' + text + '*'
|
||||
elif entity.type == MessageEntity.ITALIC:
|
||||
|
|
|
@ -45,7 +45,7 @@ class TelegramDecryptionError(TelegramError):
|
|||
"""
|
||||
|
||||
def __init__(self, message: Union[str, Exception]):
|
||||
super().__init__("TelegramDecryptionError: {}".format(message))
|
||||
super().__init__(f"TelegramDecryptionError: {message}")
|
||||
self._msg = str(message)
|
||||
|
||||
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 data_hash != hash:
|
||||
# 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[data[0] :]
|
||||
|
||||
|
|
|
@ -101,7 +101,7 @@ class User(TelegramObject):
|
|||
""":obj:`str`: Convenience property. If available, returns the user's :attr:`username`
|
||||
prefixed with "@". If :attr:`username` is not available, returns :attr:`full_name`."""
|
||||
if self.username:
|
||||
return '@{}'.format(self.username)
|
||||
return f'@{self.username}'
|
||||
return self.full_name
|
||||
|
||||
@property
|
||||
|
@ -119,7 +119,7 @@ class User(TelegramObject):
|
|||
of the user."""
|
||||
|
||||
if self.username:
|
||||
return "https://t.me/{}".format(self.username)
|
||||
return f"https://t.me/{self.username}"
|
||||
return None
|
||||
|
||||
@property
|
||||
|
|
|
@ -33,7 +33,7 @@ class TelegramDeprecationWarning(Warning):
|
|||
|
||||
def warn_deprecate_obj(old: str, new: str, stacklevel: int = 3) -> None:
|
||||
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,
|
||||
stacklevel=stacklevel,
|
||||
)
|
||||
|
|
|
@ -80,7 +80,7 @@ def escape_markdown(text: str, version: int = 1, entity_type: str = None) -> str
|
|||
else:
|
||||
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 --------
|
||||
|
@ -178,7 +178,7 @@ def to_float_timestamp(
|
|||
if isinstance(time_object, Number):
|
||||
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(
|
||||
|
@ -273,7 +273,7 @@ def effective_message_type(entity: 'MessageEntity') -> Optional[str]:
|
|||
elif isinstance(entity, Update):
|
||||
message = entity.effective_message
|
||||
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:
|
||||
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:
|
||||
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:
|
||||
return base_url
|
||||
|
||||
|
@ -327,7 +327,7 @@ def create_deep_linked_url(bot_username: str, payload: str = None, group: bool =
|
|||
else:
|
||||
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:
|
||||
|
|
|
@ -255,7 +255,7 @@ class Request:
|
|||
except urllib3.exceptions.HTTPError as error:
|
||||
# HTTPError must come last as its the base urllib3 exception class
|
||||
# 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:
|
||||
# 200-299 range are HTTP success statuses
|
||||
|
@ -281,7 +281,7 @@ class Request:
|
|||
)
|
||||
if resp.status == 502:
|
||||
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]:
|
||||
"""Request an URL.
|
||||
|
|
|
@ -139,7 +139,7 @@ class WebhookServer:
|
|||
class WebhookAppClass(tornado.web.Application):
|
||||
def __init__(self, webhook_path: str, bot: 'Bot', update_queue: 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)
|
||||
|
||||
def log_request(self, handler: tornado.web.RequestHandler) -> None:
|
||||
|
|
|
@ -87,7 +87,7 @@ def patient_request_wrapper(*args, **kwargs):
|
|||
try:
|
||||
return original_request_wrapper(*args, **kwargs)
|
||||
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
|
||||
|
|
|
@ -336,6 +336,6 @@ def expect_bad_request(func, message, reason):
|
|||
return func()
|
||||
except BadRequest as e:
|
||||
if message in str(e):
|
||||
pytest.xfail('{}. {}'.format(reason, e))
|
||||
pytest.xfail(f'{reason}. {e}')
|
||||
else:
|
||||
raise e
|
||||
|
|
|
@ -26,7 +26,7 @@ def terminal_summary_wrapper(original, plugin_name):
|
|||
text = fold_plugins[plugin_name]
|
||||
|
||||
def pytest_terminal_summary(terminalreporter):
|
||||
terminalreporter.write('##[group] {}\n'.format(text))
|
||||
terminalreporter.write(f'##[group] {text}\n')
|
||||
original(terminalreporter)
|
||||
terminalreporter.write('##[endgroup]')
|
||||
|
||||
|
@ -68,7 +68,7 @@ def pytest_runtest_protocol(item, nextitem):
|
|||
|
||||
if previous_name is None or previous_name != name:
|
||||
previous_name = name
|
||||
terminal.write('\n##[group] {}'.format(name))
|
||||
terminal.write(f'\n##[group] {name}')
|
||||
|
||||
yield
|
||||
|
||||
|
|
|
@ -141,7 +141,7 @@ class TestBot:
|
|||
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.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
|
||||
|
||||
@flaky(3, 1)
|
||||
|
@ -949,7 +949,7 @@ class TestBot:
|
|||
chat = bot.get_chat(super_group_id)
|
||||
|
||||
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)
|
||||
|
||||
@flaky(3, 1)
|
||||
|
|
|
@ -91,7 +91,7 @@ class TestChat:
|
|||
assert chat_dict['slow_mode_delay'] == chat.slow_mode_delay
|
||||
|
||||
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
|
||||
assert chat.link is None
|
||||
|
||||
|
|
|
@ -158,7 +158,7 @@ class TestCommandHandler(BaseTest):
|
|||
def ch_callback_args(self, bot, update, args):
|
||||
if update.message.text == self.CMD:
|
||||
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
|
||||
else:
|
||||
self.test_flag = args == ['one', 'two']
|
||||
|
@ -175,8 +175,8 @@ class TestCommandHandler(BaseTest):
|
|||
|
||||
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('/not{}'.format(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[1:]}'))
|
||||
assert not is_match(handler, make_command_update(f'not {command} at start'))
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
'cmd',
|
||||
|
@ -227,7 +227,7 @@ class TestCommandHandler(BaseTest):
|
|||
"""Test the passing of arguments alongside a command"""
|
||||
handler = self.make_default_handler(self.ch_callback_args, pass_args=True)
|
||||
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 + ' one two'))
|
||||
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 not is_match(handler, make_message_update(command))
|
||||
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):
|
||||
"""Test various combinations of prefixes and commands"""
|
||||
|
|
|
@ -278,7 +278,7 @@ class TestConversationHandler:
|
|||
assert list(value.keys())[0] == attr
|
||||
else:
|
||||
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)
|
||||
|
||||
def test_immutable_per_message(self):
|
||||
|
|
|
@ -678,7 +678,7 @@ class TestDispatcher:
|
|||
thread_names = [thread.name for thread in getattr(dp2, '_Dispatcher__async_threads')]
|
||||
print(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):
|
||||
with pytest.warns(TelegramDeprecationWarning):
|
||||
|
|
|
@ -183,16 +183,16 @@ class TestHelpers:
|
|||
username = 'JamesTheMock'
|
||||
|
||||
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)
|
||||
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)
|
||||
assert expected == actual
|
||||
|
||||
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, payload)
|
||||
payload = None
|
||||
|
|
|
@ -350,7 +350,7 @@ class TestSendMediaGroup:
|
|||
video_check = data[input_video.media.attach] == input_video.media.field_tuple
|
||||
thumb_check = data[input_video.thumb.attach] == input_video.thumb.field_tuple
|
||||
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)
|
||||
input_video = InputMediaVideo(video_file, thumb=photo_file)
|
||||
|
|
|
@ -579,9 +579,7 @@ class TestMessage:
|
|||
def test_link_with_username(self, message, type):
|
||||
message.chat.username = 'username'
|
||||
message.chat.type = type
|
||||
assert message.link == 'https://t.me/{}/{}'.format(
|
||||
message.chat.username, message.message_id
|
||||
)
|
||||
assert message.link == f'https://t.me/{message.chat.username}/{message.message_id}'
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
'type, id', argvalues=[(Chat.CHANNEL, -1003), (Chat.SUPERGROUP, -1003)]
|
||||
|
@ -591,7 +589,7 @@ class TestMessage:
|
|||
message.chat.id = id
|
||||
message.chat.type = type
|
||||
# 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)])
|
||||
def test_link_private_chats(self, message, id, username):
|
||||
|
|
|
@ -68,9 +68,7 @@ def check_method(h4):
|
|||
checked = []
|
||||
for parameter in table:
|
||||
param = sig.parameters.get(parameter[0])
|
||||
assert param is not None, "Parameter {} not found in {}".format(
|
||||
parameter[0], method.__name__
|
||||
)
|
||||
assert param is not None, f"Parameter {parameter[0]} not found in {method.__name__}"
|
||||
# TODO: Check type via docstring
|
||||
# TODO: Check if optional or required
|
||||
checked.append(parameter[0])
|
||||
|
@ -117,7 +115,7 @@ def check_object(h4):
|
|||
continue
|
||||
|
||||
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 if optional or required
|
||||
checked.append(field)
|
||||
|
|
|
@ -258,7 +258,7 @@ class TestSticker:
|
|||
|
||||
@pytest.fixture(scope='function')
|
||||
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:
|
||||
try:
|
||||
for i in range(1, 50):
|
||||
|
@ -270,7 +270,7 @@ def sticker_set(bot):
|
|||
|
||||
@pytest.fixture(scope='function')
|
||||
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:
|
||||
try:
|
||||
for i in range(1, 50):
|
||||
|
@ -295,7 +295,7 @@ class TestStickerSet:
|
|||
name = 'NOTAREALNAME'
|
||||
|
||||
def test_de_json(self, bot, sticker):
|
||||
name = 'test_by_{}'.format(bot.username)
|
||||
name = f'test_by_{bot.username}'
|
||||
json_dict = {
|
||||
'name': name,
|
||||
'title': self.title,
|
||||
|
@ -320,12 +320,12 @@ class TestStickerSet:
|
|||
file = bot.upload_sticker_file(95205500, f)
|
||||
assert file
|
||||
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
|
||||
assert bot.add_sticker_to_set(
|
||||
chat_id,
|
||||
'test_by_{}'.format(bot.username),
|
||||
f'test_by_{bot.username}',
|
||||
png_sticker=sticker_file,
|
||||
emojis='😄',
|
||||
mask_position=MaskPosition(MaskPosition.EYES, -1, 1, 2),
|
||||
|
@ -336,7 +336,7 @@ class TestStickerSet:
|
|||
def test_bot_methods_1_tgs(self, bot, chat_id):
|
||||
assert bot.add_sticker_to_set(
|
||||
chat_id,
|
||||
'animated_test_by_{}'.format(bot.username),
|
||||
f'animated_test_by_{bot.username}',
|
||||
tgs_sticker=open('tests/data/telegram_animated_sticker.tgs', 'rb'),
|
||||
emojis='😄',
|
||||
)
|
||||
|
@ -368,7 +368,7 @@ class TestStickerSet:
|
|||
def test_bot_methods_3_png(self, bot, chat_id, sticker_set_thumb_file):
|
||||
sleep(1)
|
||||
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)
|
||||
|
@ -376,13 +376,11 @@ class TestStickerSet:
|
|||
def test_bot_methods_3_tgs(self, bot, chat_id, animated_sticker_file, animated_sticker_set):
|
||||
sleep(1)
|
||||
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
|
||||
# also test with file input and mask
|
||||
assert bot.set_sticker_set_thumb(
|
||||
'animated_test_by_{}'.format(bot.username), chat_id, file_id
|
||||
)
|
||||
assert bot.set_sticker_set_thumb(f'animated_test_by_{bot.username}', chat_id, file_id)
|
||||
|
||||
@flaky(10, 1)
|
||||
@pytest.mark.timeout(10)
|
||||
|
|
|
@ -134,7 +134,7 @@ class TestUpdater:
|
|||
|
||||
pprint.pprint([rec.getMessage() for rec in caplog.get_records('call')])
|
||||
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')
|
||||
)
|
||||
|
||||
|
@ -487,7 +487,7 @@ class TestUpdater:
|
|||
if content_len is not None:
|
||||
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)
|
||||
|
||||
|
@ -512,7 +512,7 @@ class TestUpdater:
|
|||
updater.idle()
|
||||
|
||||
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'
|
||||
|
||||
rec = caplog.records[-1]
|
||||
|
|
|
@ -123,7 +123,7 @@ class TestUser:
|
|||
assert user.full_name == u'first\u2022name'
|
||||
|
||||
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
|
||||
assert user.link is None
|
||||
|
||||
|
|
Loading…
Reference in a new issue