pyupgrade: Reformat with --py36-plus.

This includes mainly fixes of string literals using f-strings or
.format(...), as well as unpacking of list comprehensions.
This commit is contained in:
PIG208 2021-05-28 19:19:40 +08:00 committed by Tim Abbott
parent e27ac0ddbe
commit 9ce7c52a10
78 changed files with 356 additions and 389 deletions

View file

@ -90,11 +90,11 @@ except ImportError:
except (ImportError, AssertionError):
if version is not None:
print(
"{name}>={version} is not installed.".format(name=module_name, version=version),
f"{module_name}>={version} is not installed.",
file=sys.stderr,
)
else:
print("{name} is not installed.".format(name=module_name), file=sys.stderr)
print(f"{module_name} is not installed.", file=sys.stderr)
sys.exit(1)
check_dependency_manually("zulip")

View file

@ -73,7 +73,7 @@ class BaremetricsHandler:
if content == ["list-commands"]:
response = "**Available Commands:** \n"
for command, description in zip(self.commands, self.descriptions):
response += " - {} : {}\n".format(command, description)
response += f" - {command} : {description}\n"
bot_handler.send_reply(message, response)
return
@ -148,7 +148,7 @@ class BaremetricsHandler:
return response
def get_plans(self, source_id: str) -> str:
url = "https://api.baremetrics.com/v1/{}/plans".format(source_id)
url = f"https://api.baremetrics.com/v1/{source_id}/plans"
plans_response = requests.get(url, headers=self.auth_header)
plans_data = plans_response.json()
@ -174,7 +174,7 @@ class BaremetricsHandler:
return "\n".join(response)
def get_customers(self, source_id: str) -> str:
url = "https://api.baremetrics.com/v1/{}/customers".format(source_id)
url = f"https://api.baremetrics.com/v1/{source_id}/customers"
customers_response = requests.get(url, headers=self.auth_header)
customers_data = customers_response.json()
@ -203,7 +203,7 @@ class BaremetricsHandler:
return "\n".join(response)
def get_subscriptions(self, source_id: str) -> str:
url = "https://api.baremetrics.com/v1/{}/subscriptions".format(source_id)
url = f"https://api.baremetrics.com/v1/{source_id}/subscriptions"
subscriptions_response = requests.get(url, headers=self.auth_header)
subscriptions_data = subscriptions_response.json()
@ -250,7 +250,7 @@ class BaremetricsHandler:
"interval_count": int(parameters[6]),
} # type: Any
url = "https://api.baremetrics.com/v1/{}/plans".format(parameters[0])
url = f"https://api.baremetrics.com/v1/{parameters[0]}/plans"
create_plan_response = requests.post(url, data=data_header, headers=self.auth_header)
if "error" not in create_plan_response.json():
return "Plan Created."

View file

@ -70,7 +70,7 @@ at syntax by: @mention-botname help"
r.status_code
) # Occures in case of unprocessable entity
else:
datapoint_link = "https://www.beeminder.com/{}/{}".format(username, goalname)
datapoint_link = f"https://www.beeminder.com/{username}/{goalname}"
return "[Datapoint]({}) created.".format(
datapoint_link
) # Handles the case of successful datapoint creation

View file

@ -376,7 +376,7 @@ def make_draw_response(reason: str) -> str:
Returns: The draw response string.
"""
return "It's a draw because of {}!".format(reason)
return f"It's a draw because of {reason}!"
def make_loss_response(board: chess.Board, reason: str) -> str:
@ -525,7 +525,7 @@ def make_str(board: chess.Board, is_white_on_bottom: bool) -> str:
replaced_and_guided_str if is_white_on_bottom else replaced_and_guided_str[::-1]
)
trimmed_str = trim_whitespace_before_newline(properly_flipped_str)
monospaced_str = "```\n{}\n```".format(trimmed_str)
monospaced_str = f"```\n{trimmed_str}\n```"
return monospaced_str

View file

@ -51,7 +51,7 @@ class DefineHandler:
if not to_define_lower:
return self.EMPTY_WORD_REQUEST_ERROR_MESSAGE
else:
response = "**{}**:\n".format(to_define)
response = f"**{to_define}**:\n"
try:
# Use OwlBot API to fetch definition.

View file

@ -36,7 +36,7 @@ def get_bot_result(message_content: str, config: Dict[str, str], sender_id: str)
return res_json["result"]["fulfillment"]["speech"]
except Exception as e:
logging.exception(str(e))
return "Error. {}.".format(str(e))
return f"Error. {str(e)}."
class DialogFlowHandler:

View file

@ -117,7 +117,7 @@ def syntax_help(cmd_name: str) -> str:
cmd = cmd_name + " " + arg_syntax
else:
cmd = cmd_name
return "syntax: {}".format(cmd)
return f"syntax: {cmd}"
def dbx_help(client: Any, cmd_name: str) -> str:
@ -197,7 +197,7 @@ def dbx_read(client: Any, fn: str) -> str:
try:
result = client.files_download(fn)
msg = "**{}** :\n{}".format(result[0].name, result[1].text)
msg = f"**{result[0].name}** :\n{result[1].text}"
except Exception:
msg = (
"Please provide a correct file path\nUsage: `read <filename>` to read content of a file"

View file

@ -27,14 +27,14 @@ class FileUploaderHandler:
path = Path(os.path.expanduser(content))
if not path.is_file():
bot_handler.send_reply(message, "File `{}` not found".format(content))
bot_handler.send_reply(message, f"File `{content}` not found")
return
path = path.resolve()
upload = bot_handler.upload_file_from_path(str(path))
if upload["result"] != "success":
msg = upload["msg"]
bot_handler.send_reply(message, "Failed to upload `{}` file: {}".format(path, msg))
bot_handler.send_reply(message, f"Failed to upload `{path}` file: {msg}")
return
uploaded_file_reply = "[{}]({})".format(path.name, upload["uri"])

View file

@ -52,7 +52,7 @@ class FollowupHandler:
def get_bot_followup_response(self, message: Dict[str, str]) -> str:
original_content = message["content"]
original_sender = message["sender_email"]
temp_content = "from %s: " % (original_sender,)
temp_content = f"from {original_sender}: "
new_content = temp_content + original_content
return new_content

View file

@ -35,7 +35,7 @@ class FrontHandler:
def help(self, bot_handler: BotHandler) -> str:
response = ""
for command, description in self.COMMANDS:
response += "`{}` {}\n".format(command, description)
response += f"`{command}` {description}\n"
return response

View file

@ -78,9 +78,9 @@ class TestFrontBot(BotTestCase, DefaultTests):
def _test_command_error(self, command_name: str, command_arg: Optional[str] = None) -> None:
bot_command = command_name
if command_arg:
bot_command += " {}".format(command_arg)
bot_command += f" {command_arg}"
with self.mock_config_info({"api_key": "TEST"}):
with self.mock_http_conversation("{}_error".format(command_name)):
with self.mock_http_conversation(f"{command_name}_error"):
self.verify_reply(bot_command, "Something went wrong.")

View file

@ -1,6 +1,5 @@
from typing import Any, Dict, List
from mock import patch
from unittest.mock import patch
from zulip_bots.game_handler import GameInstance
from zulip_bots.test_lib import BotTestCase, DefaultTests
@ -66,8 +65,8 @@ class TestGameHandlerBot(BotTestCase, DefaultTests):
if bot is None:
bot, bot_handler = self._get_handlers()
message = {
"sender_email": "{}@example.com".format(name),
"sender_full_name": "{}".format(name),
"sender_email": f"{name}@example.com",
"sender_full_name": f"{name}",
}
bot.add_user_to_cache(message)
return bot

View file

@ -42,8 +42,8 @@ class GithubHandler:
status = details["state"].title()
message_string = (
"**[{owner}/{repo}#{id}]".format(owner=owner, repo=repo, id=number),
"({link}) - {title}**\n".format(title=title, link=link),
f"**[{owner}/{repo}#{number}]",
f"({link}) - {title}**\n",
"Created by **[{author}](https://github.com/{author})**\n".format(author=author),
"Status - **{status}**\n```quote\n{description}\n```".format(
status=status, description=description

View file

@ -32,7 +32,7 @@ def google_search(keywords: str) -> List[Dict[str, str]]:
if a.text.strip() == "Cached" and "webcache.googleusercontent.com" in a["href"]:
continue
# a.text: The name of the page
result = {"url": "https://www.google.com{}".format(link), "name": a.text}
result = {"url": f"https://www.google.com{link}", "name": a.text}
results.append(result)
return results
@ -61,7 +61,7 @@ def get_google_result(search_keywords: str) -> str:
return "Found Result: [{}]({})".format(results[0]["name"], results[0]["url"])
except Exception as e:
logging.exception(str(e))
return "Error: Search failed. {}.".format(e)
return f"Error: Search failed. {e}."
class GoogleSearchHandler:

View file

@ -107,12 +107,12 @@ def get_translate_bot_response(message_content, config_file, author, all_languag
text_to_translate, config_file["key"], target_language, source_language
)
except requests.exceptions.ConnectionError as conn_err:
return "Could not connect to Google Translate. {}.".format(conn_err)
return f"Could not connect to Google Translate. {conn_err}."
except TranslateError as tr_err:
return "Translate Error. {}.".format(tr_err)
return f"Translate Error. {tr_err}."
except Exception as err:
return "Error. {}.".format(err)
return "{} (from {})".format(translated_text, author)
return f"Error. {err}."
return f"{translated_text} (from {author})"
handler_class = GoogleTranslateHandler

View file

@ -64,12 +64,12 @@ def api_list_team() -> List[Dict[str, str]]:
def api_show_team(hash_id: str) -> Dict[str, str]:
return make_API_request("/teams/{}".format(hash_id))
return make_API_request(f"/teams/{hash_id}")
# NOTE: This function is not currently used
def api_show_users(hash_id: str) -> Any:
return make_API_request("/teams/{}/members".format(hash_id))
return make_API_request(f"/teams/{hash_id}/members")
def api_list_entries(team_id: Optional[str] = None) -> List[Dict[str, Any]]:
@ -105,7 +105,7 @@ def team_info(team_name: str) -> str:
def entries_list(team_name: str) -> str:
if team_name:
data = api_list_entries(get_team_hash(team_name))
response = "Entries for {}:".format(team_name)
response = f"Entries for {team_name}:"
else:
data = api_list_entries()
response = "Entries for all teams:"

View file

@ -39,7 +39,7 @@ class IncidentHandler:
bot_response = "Invalid answer format"
bot_handler.send_reply(message, bot_response)
return
bot_response = "Incident %s\n status = %s" % (ticket_id, answer)
bot_response = f"Incident {ticket_id}\n status = {answer}"
bot_handler.send_reply(message, bot_response)
else:
bot_response = 'type "new <description>" for a new incident'
@ -125,15 +125,13 @@ def format_incident_for_widget(ticket_id: str, incident: Dict[str, Any]) -> str:
def format_incident_for_markdown(ticket_id: str, incident: Dict[str, Any]) -> str:
answer_list = "\n".join(
[
"* **{code}** {answer}".format(
code=code,
answer=ANSWERS[code],
)
for code in "1234"
]
"* **{code}** {answer}".format(
code=code,
answer=ANSWERS[code],
)
for code in "1234"
)
how_to_respond = """**reply**: answer {ticket_id} <code>""".format(ticket_id=ticket_id)
how_to_respond = f"""**reply**: answer {ticket_id} <code>"""
content = """
Incident: {incident}

View file

@ -183,7 +183,7 @@ class JiraHandler:
UNKNOWN_VAL = "*unknown*"
jira_response = requests.get(
self.domain_with_protocol
+ "/rest/api/2/search?jql={}&fields=key,summary,status".format(jql_query),
+ f"/rest/api/2/search?jql={jql_query}&fields=key,summary,status",
headers={"Authorization": self.auth},
).json()
@ -194,7 +194,7 @@ class JiraHandler:
if errors:
response = "Oh no! Jira raised an error:\n > " + ", ".join(errors)
else:
response = "*Found {} results*\n\n".format(results)
response = f"*Found {results} results*\n\n"
for issue in jira_response.get("issues", []):
fields = issue.get("fields", {})
summary = fields.get("summary", UNKNOWN_VAL)
@ -314,12 +314,12 @@ class JiraHandler:
response = "Issue *" + key + "* was edited! " + url
elif search_match:
search_term = search_match.group("search_term")
search_results = self.jql_search("summary ~ {}".format(search_term))
response = '**Search results for "{}"**\n\n{}'.format(search_term, search_results)
search_results = self.jql_search(f"summary ~ {search_term}")
response = f'**Search results for "{search_term}"**\n\n{search_results}'
elif jql_match:
jql_query = jql_match.group("jql_query")
search_results = self.jql_search(jql_query)
response = '**Search results for "{}"**\n\n{}'.format(jql_query, search_results)
response = f'**Search results for "{jql_query}"**\n\n{search_results}'
elif help_match:
response = HELP_RESPONSE
else:

View file

@ -197,5 +197,5 @@ def check_win(topic_name, merels_storage):
win = mechanics.who_won(topic_name, merels_storage)
if win != "None":
merels.remove_game(topic_name)
return "{} wins the game!".format(win)
return f"{win} wins the game!"
return ""

View file

@ -278,7 +278,7 @@ def create_room(topic_name, merels_storage):
if merels.create_new_game(topic_name):
response = ""
response += "A room has been created in {0}. Starting game now.\n".format(topic_name)
response += f"A room has been created in {topic_name}. Starting game now.\n"
response += display_game(topic_name, merels_storage)
return response
@ -404,7 +404,7 @@ def put_man(topic_name, v, h, merels_storage):
data.hill_uid,
data.take_mode,
)
return "Put a man to ({}, {}) for {}.".format(v, h, data.turn)
return f"Put a man to ({v}, {h}) for {data.turn}."
else:
raise BadMoveException("Failed: That's not a legal put. Please try again.")
@ -448,7 +448,7 @@ def take_man(topic_name, v, h, merels_storage):
data.hill_uid,
data.take_mode,
)
return "Taken a man from ({}, {}) for {}.".format(v, h, data.turn)
return f"Taken a man from ({v}, {h}) for {data.turn}."
else:
raise BadMoveException("Failed: That's not a legal take. Please try again.")

View file

@ -44,7 +44,7 @@ class MerelsModel:
if self.storage.get(self.topic) == '["X", 0, 0, "NNNNNNNNNNNNNNNNNNNNNNNN", "", 0]':
self.storage.put(
self.topic,
'["{}", 0, 0, "NNNNNNNNNNNNNNNNNNNNNNNN", "", 0]'.format(self.token[player_number]),
f'["{self.token[player_number]}", 0, 0, "NNNNNNNNNNNNNNNNNNNNNNNN", "", 0]',
)
self.current_board, same_player_move = game.beat(move, self.topic, self.storage)
if same_player_move != "":

View file

@ -60,8 +60,8 @@ class TestMerelsBot(BotTestCase, DefaultTests):
if bot is None:
bot, bot_handler = self._get_handlers()
message = {
"sender_email": "{}@example.com".format(name),
"sender_full_name": "{}".format(name),
"sender_email": f"{name}@example.com",
"sender_full_name": f"{name}",
}
bot.add_user_to_cache(message)
return bot

View file

@ -25,15 +25,15 @@ def compose(results: Dict) -> str:
response = ""
response += "{}\n".format(print_status(results))
response += f"{print_status(results)}\n"
if "success" in response.lower():
response += "{}".format(print_test_id(results))
response += f"{print_test_id(results)}"
return response
response += "{}\n".format(print_enabled_checkers(results))
response += "{}\n".format(print_failures_checkers(results))
response += "{}".format(print_more_info_url(results))
response += f"{print_enabled_checkers(results)}\n"
response += f"{print_failures_checkers(results)}\n"
response += f"{print_more_info_url(results)}"
return response
@ -81,11 +81,11 @@ def print_failures_checkers(results: Dict) -> str:
] # [('seo', 3), ..]
failures_checkers_messages = [
"{} ({})".format(fail_checker[0], fail_checker[1]) for fail_checker in failures_checkers
f"{fail_checker[0]} ({fail_checker[1]})" for fail_checker in failures_checkers
]
failures_checkers_message = ", ".join(failures_checkers_messages)
return "Failures from checkers: {}".format(failures_checkers_message)
return f"Failures from checkers: {failures_checkers_message}"
def get_enabled_checkers(results: Dict) -> List:

View file

@ -57,17 +57,17 @@ def format_result(
output += "**[{}]({}{})**\n".format(record["Name"], login_url, record["Id"])
for key, value in record.items():
if key not in exclude_keys:
output += ">**{}**: {}\n".format(key, value)
output += f">**{key}**: {value}\n"
else:
for i, record in enumerate(result["records"]):
if rank_output:
output += "{}) ".format(i + 1)
output += f"{i + 1}) "
output += "**[{}]({}{})**\n".format(record["Name"], login_url, record["Id"])
added_keys = False
for key, value in record.items():
if key in force_keys or (show_all_keys and key not in exclude_keys):
added_keys = True
output += ">**{}**: {}\n".format(key, value)
output += f">**{key}**: {value}\n"
if added_keys:
output += "\n"
return output
@ -88,7 +88,7 @@ def query_salesforce(
limit = re_limit.search(raw_arg)
if limit:
limit_num = int(limit.group().rsplit(" ", 1)[1])
logging.info("Searching with limit {}".format(limit_num))
logging.info(f"Searching with limit {limit_num}")
query = default_query
if "query" in command.keys():
query = command["query"]
@ -170,14 +170,14 @@ class SalesforceHandler:
security_token=self.config_info["security_token"],
)
except simple_salesforce.exceptions.SalesforceAuthenticationFailed as err:
bot_handler.quit("Failed to log in to Salesforce. {} {}".format(err.code, err.message))
bot_handler.quit(f"Failed to log in to Salesforce. {err.code} {err.message}")
def handle_message(self, message: Dict[str, Any], bot_handler: BotHandler) -> None:
try:
bot_response = self.get_salesforce_response(message["content"])
bot_handler.send_reply(message, bot_response)
except Exception as e:
bot_handler.send_reply(message, "Error. {}.".format(e), bot_response)
bot_handler.send_reply(message, f"Error. {e}.", bot_response)
handler_class = SalesforceHandler

View file

@ -151,8 +151,8 @@ class TestTicTacToeBot(BotTestCase, DefaultTests):
if bot is None:
bot, bot_handler = self._get_handlers()
message = {
"sender_email": "{}@example.com".format(name),
"sender_full_name": "{}".format(name),
"sender_email": f"{name}@example.com",
"sender_full_name": f"{name}",
}
bot.add_user_to_cache(message)
return bot

View file

@ -241,14 +241,14 @@ class TicTacToeMessageHandler:
def parse_board(self, board: Any) -> str:
"""Takes the board as a nested list and returns a nice version for the user."""
return "".join([self.parse_row(r, r_num) for r_num, r in enumerate(board)])
return "".join(self.parse_row(r, r_num) for r_num, r in enumerate(board))
def get_player_color(self, turn: int) -> str:
return self.tokens[turn]
def alert_move_message(self, original_player: str, move_info: str) -> str:
move_info = move_info.replace("move ", "")
return "{} put a token at {}".format(original_player, move_info)
return f"{original_player} put a token at {move_info}"
def game_start_message(self) -> str:
return (
@ -299,7 +299,7 @@ def coords_from_command(cmd: str) -> str:
"""As there are various ways to input a coordinate (with/without parentheses, with/without spaces, etc.) the
input is stripped to just the numbers before being used in the program."""
cmd_num = int(cmd.replace("move ", "")) - 1
cmd = "{},{}".format((cmd_num % 3) + 1, (cmd_num // 3) + 1)
cmd = f"{(cmd_num % 3) + 1},{(cmd_num // 3) + 1}"
return cmd

View file

@ -30,7 +30,7 @@ class TrelloHandler:
def check_access_token(self, bot_handler: BotHandler) -> None:
test_query_response = requests.get(
"https://api.trello.com/1/members/{}/".format(self.user_name), params=self.auth_params
f"https://api.trello.com/1/members/{self.user_name}/", params=self.auth_params
)
if test_query_response.text == "invalid key":
@ -75,12 +75,12 @@ class TrelloHandler:
def get_all_supported_commands(self) -> str:
bot_response = "**Commands:** \n"
for index, (command, desc) in enumerate(supported_commands):
bot_response += "{}. **{}**: {}\n".format(index + 1, command, desc)
bot_response += f"{index + 1}. **{command}**: {desc}\n"
return bot_response
def get_all_boards(self) -> str:
get_board_ids_url = "https://api.trello.com/1/members/{}/".format(self.user_name)
get_board_ids_url = f"https://api.trello.com/1/members/{self.user_name}/"
board_ids_response = requests.get(get_board_ids_url, params=self.auth_params)
try:
@ -112,7 +112,7 @@ class TrelloHandler:
return INVALID_ARGUMENTS_ERROR_MESSAGE
board_id = content[1]
get_cards_url = "https://api.trello.com/1/boards/{}/cards".format(board_id)
get_cards_url = f"https://api.trello.com/1/boards/{board_id}/cards"
cards_response = requests.get(get_cards_url, params=self.auth_params)
try:
@ -133,7 +133,7 @@ class TrelloHandler:
return INVALID_ARGUMENTS_ERROR_MESSAGE
card_id = content[1]
get_checklists_url = "https://api.trello.com/1/cards/{}/checklists/".format(card_id)
get_checklists_url = f"https://api.trello.com/1/cards/{card_id}/checklists/"
checklists_response = requests.get(get_checklists_url, params=self.auth_params)
try:
@ -160,7 +160,7 @@ class TrelloHandler:
return INVALID_ARGUMENTS_ERROR_MESSAGE
board_id = content[1]
get_lists_url = "https://api.trello.com/1/boards/{}/lists".format(board_id)
get_lists_url = f"https://api.trello.com/1/boards/{board_id}/lists"
lists_response = requests.get(get_lists_url, params=self.auth_params)
try:

View file

@ -191,15 +191,13 @@ def format_quiz_for_markdown(quiz_id: str, quiz: Dict[str, Any]) -> str:
question = quiz["question"]
answers = quiz["answers"]
answer_list = "\n".join(
[
"* **{letter}** {answer}".format(
letter=letter,
answer=answers[letter],
)
for letter in "ABCD"
]
"* **{letter}** {answer}".format(
letter=letter,
answer=answers[letter],
)
for letter in "ABCD"
)
how_to_respond = """**reply**: answer {quiz_id} <letter>""".format(quiz_id=quiz_id)
how_to_respond = f"""**reply**: answer {quiz_id} <letter>"""
content = """
Q: {question}

View file

@ -48,7 +48,7 @@ class TwitpostBot:
status = self.post(" ".join(content[1:]))
screen_name = status["user"]["screen_name"]
id_str = status["id_str"]
bot_reply = "https://twitter.com/{}/status/{}".format(screen_name, id_str)
bot_reply = f"https://twitter.com/{screen_name}/status/{id_str}"
bot_reply = "Tweet Posted\n" + bot_reply
bot_handler.send_reply(message, bot_reply)

View file

@ -25,7 +25,7 @@ class VirtualFsHandler:
recipient = message["display_recipient"]
if isinstance(recipient, list): # If not a stream, then hash on list of emails
recipient = " ".join([x["email"] for x in recipient])
recipient = " ".join(x["email"] for x in recipient)
storage = bot_handler.storage
if not storage.contains(recipient):
@ -34,7 +34,7 @@ class VirtualFsHandler:
if sender not in fs["user_paths"]:
fs["user_paths"][sender] = "/"
fs, msg = fs_command(fs, sender, command)
prependix = "{}:\n".format(sender)
prependix = f"{sender}:\n"
msg = prependix + msg
storage.put(recipient, fs)
@ -170,7 +170,7 @@ def syntax_help(cmd_name: str) -> str:
cmd = cmd_name + " " + arg_syntax
else:
cmd = cmd_name
return "syntax: {}".format(cmd)
return f"syntax: {cmd}"
def fs_new() -> Dict[str, Any]:
@ -190,7 +190,7 @@ def fs_mkdir(fs: Dict[str, Any], user: str, fn: str) -> Tuple[Dict[str, Any], An
return fs, "ERROR: file already exists"
dir_path = os.path.dirname(path)
if not is_directory(fs, dir_path):
msg = "ERROR: {} is not a directory".format(dir_path)
msg = f"ERROR: {dir_path} is not a directory"
return fs, msg
new_fs = fs.copy()
new_dir = directory({path}.union(fs[dir_path]["fns"]))
@ -211,7 +211,7 @@ def fs_ls(fs: Dict[str, Any], user: str, fn: str) -> Tuple[Dict[str, Any], Any]:
msg = "ERROR: file does not exist"
return fs, msg
if not is_directory(fs, path):
return fs, "ERROR: {} is not a directory".format(path)
return fs, f"ERROR: {path} is not a directory"
fns = fs[path]["fns"]
if not fns:
return fs, "WARNING: directory is empty"
@ -233,7 +233,7 @@ def fs_rm(fs: Dict[str, Any], user: str, fn: str) -> Tuple[Dict[str, Any], Any]:
msg = "ERROR: file does not exist"
return fs, msg
if fs[path]["kind"] == "dir":
msg = "ERROR: {} is a directory, file required".format(nice_path(fs, path))
msg = f"ERROR: {nice_path(fs, path)} is a directory, file required"
return fs, msg
new_fs = fs.copy()
new_fs.pop(path)
@ -251,7 +251,7 @@ def fs_rmdir(fs: Dict[str, Any], user: str, fn: str) -> Tuple[Dict[str, Any], An
msg = "ERROR: directory does not exist"
return fs, msg
if fs[path]["kind"] == "text":
msg = "ERROR: {} is a file, directory required".format(nice_path(fs, path))
msg = f"ERROR: {nice_path(fs, path)} is a file, directory required"
return fs, msg
new_fs = fs.copy()
new_fs.pop(path)
@ -273,7 +273,7 @@ def fs_write(fs: Dict[str, Any], user: str, fn: str, content: str) -> Tuple[Dict
return fs, msg
dir_path = os.path.dirname(path)
if not is_directory(fs, dir_path):
msg = "ERROR: {} is not a directory".format(dir_path)
msg = f"ERROR: {dir_path} is not a directory"
return fs, msg
new_fs = fs.copy()
new_dir = directory({path}.union(fs[dir_path]["fns"]))
@ -291,7 +291,7 @@ def fs_read(fs: Dict[str, Any], user: str, fn: str) -> Tuple[Dict[str, Any], Any
msg = "ERROR: file does not exist"
return fs, msg
if fs[path]["kind"] == "dir":
msg = "ERROR: {} is a directory, file required".format(nice_path(fs, path))
msg = f"ERROR: {nice_path(fs, path)} is a directory, file required"
return fs, msg
val = fs[path]["content"]
return fs, val
@ -305,17 +305,17 @@ def fs_cd(fs: Dict[str, Any], user: str, fn: str) -> Tuple[Dict[str, Any], Any]:
msg = "ERROR: invalid path"
return fs, msg
if fs[path]["kind"] == "text":
msg = "ERROR: {} is a file, directory required".format(nice_path(fs, path))
msg = f"ERROR: {nice_path(fs, path)} is a file, directory required"
return fs, msg
fs["user_paths"][user] = path
return fs, "Current path: {}".format(nice_path(fs, path))
return fs, f"Current path: {nice_path(fs, path)}"
def make_path(fs: Dict[str, Any], user: str, leaf: str) -> List[str]:
if leaf == "/":
return ["/", ""]
if leaf.endswith("/"):
return ["", "ERROR: {} is not a valid name".format(leaf)]
return ["", f"ERROR: {leaf} is not a valid name"]
if leaf.startswith("/"):
return [leaf, ""]
path = fs["user_paths"][user]
@ -331,9 +331,9 @@ def nice_path(fs: Dict[str, Any], path: str) -> str:
if path not in fs:
return "ERROR: the current directory does not exist"
if fs[path]["kind"] == "text":
path_nice = "{}*{}*".format(path[: slash + 1], path[slash + 1 :])
path_nice = f"{path[: slash + 1]}*{path[slash + 1 :]}*"
elif path != "/":
path_nice = "{}/".format(path)
path_nice = f"{path}/"
return path_nice

View file

@ -79,19 +79,15 @@ def get_xkcd_bot_response(message: Dict[str, str], quoted_name: str) -> str:
elif command.isdigit():
fetched = fetch_xkcd_query(XkcdBotCommand.COMIC_ID, command)
else:
return commands_help % (
"xkcd bot only supports these commands, not `%s`:" % (command,),
)
return commands_help % (f"xkcd bot only supports these commands, not `{command}`:",)
except (requests.exceptions.ConnectionError, XkcdServerError):
logging.exception("Connection error occurred when trying to connect to xkcd server")
return "Sorry, I cannot process your request right now, please try again later!"
except XkcdNotFoundError:
logging.exception(
"XKCD server responded 404 when trying to fetch comic with id %s" % (command,)
)
return "Sorry, there is likely no xkcd comic strip with id: #%s" % (command,)
logging.exception(f"XKCD server responded 404 when trying to fetch comic with id {command}")
return f"Sorry, there is likely no xkcd comic strip with id: #{command}"
else:
return "#%s: **%s**\n[%s](%s)" % (
return "#{}: **{}**\n[{}]({})".format(
fetched["num"],
fetched["title"],
fetched["alt"],

View file

@ -130,7 +130,7 @@ def get_bot_response(
).strip()
for title, id in video_list:
reply = reply + "\n * %s - [Watch now](https://www.youtube.com/watch/%s)" % (title, id)
reply = reply + f"\n * {title} - [Watch now](https://www.youtube.com/watch/{id})"
# Using link https://www.youtube.com/watch/<id> to
# prevent showing multiple previews
return reply

View file

@ -229,7 +229,7 @@ class GameAdapter:
if sender not in self.user_cache.keys():
self.add_user_to_cache(message)
logging.info("Added {} to user cache".format(sender))
logging.info(f"Added {sender} to user cache")
if self.is_single_player:
if content.lower().startswith("start game with") or content.lower().startswith(
@ -300,7 +300,7 @@ class GameAdapter:
self.send_reply(message, self.help_message())
except Exception as e:
logging.exception(str(e))
self.bot_handler.send_reply(message, "Error {}.".format(e))
self.bot_handler.send_reply(message, f"Error {e}.")
def is_user_in_game(self, user_email: str) -> str:
for instance in self.instances.values():
@ -344,7 +344,7 @@ class GameAdapter:
self.send_reply(message, self.confirm_invitation_accepted(game_id))
self.broadcast(
game_id,
"@**{}** has accepted the invitation.".format(self.get_username_by_email(sender)),
f"@**{self.get_username_by_email(sender)}** has accepted the invitation.",
)
self.start_game_if_ready(game_id)
@ -365,7 +365,7 @@ class GameAdapter:
if len(users) + 1 > self.max_players:
self.send_reply(
message,
"The maximum number of players for this game is {}.".format(self.max_players),
f"The maximum number of players for this game is {self.max_players}.",
)
return
game_id = self.generate_game_id()
@ -411,7 +411,7 @@ class GameAdapter:
self.broadcast(game_id, "Wait... That's me!", include_private=True)
if message["type"] == "stream":
self.broadcast(
game_id, "@**{}** accept".format(self.get_bot_username()), include_private=False
game_id, f"@**{self.get_bot_username()}** accept", include_private=False
)
game_id = self.set_invite_by_user(self.email, True, {"type": "stream"})
self.start_game_if_ready(game_id)
@ -427,7 +427,7 @@ class GameAdapter:
self.send_reply(message, self.confirm_invitation_declined(game_id))
self.broadcast(
game_id,
"@**{}** has declined the invitation.".format(self.get_username_by_email(sender)),
f"@**{self.get_username_by_email(sender)}** has declined the invitation.",
)
if len(self.get_players(game_id, parameter="")) < self.min_players:
self.cancel_game(game_id)
@ -440,7 +440,7 @@ class GameAdapter:
if game_id == "":
self.send_reply(message, "You are not in a game. Type `help` for all commands.")
sender_name = self.get_username_by_email(sender)
self.cancel_game(game_id, reason="**{}** quit.".format(sender_name))
self.cancel_game(game_id, reason=f"**{sender_name}** quit.")
def command_join(self, message: Dict[str, Any], sender: str, content: str) -> None:
if not self.is_user_not_player(sender, message):
@ -472,7 +472,7 @@ class GameAdapter:
else:
self.send_reply(
message,
"Join {} more players to start the game".format(self.max_players - num_players),
f"Join {self.max_players - num_players} more players to start the game",
)
def command_leaderboard(self, message: Dict[str, Any], sender: str, content: str) -> None:
@ -483,9 +483,9 @@ class GameAdapter:
raw_headers = ["games_won", "games_drawn", "games_lost", "total_games"]
headers = ["Player"] + [key.replace("_", " ").title() for key in raw_headers]
response += " | ".join(headers)
response += "\n" + " | ".join([" --- " for header in headers])
response += "\n" + " | ".join(" --- " for header in headers)
for player, stat in top_stats:
response += "\n **{}** | ".format(self.get_username_by_email(player))
response += f"\n **{self.get_username_by_email(player)}** | "
values = [str(stat[key]) for key in raw_headers]
response += " | ".join(values)
self.send_reply(message, response)
@ -536,7 +536,7 @@ class GameAdapter:
self.instances[game_id] = GameInstance(self, False, subject, game_id, players, stream)
self.broadcast(
game_id,
"The game has started in #{} {}".format(stream, self.instances[game_id].subject)
f"The game has started in #{stream} {self.instances[game_id].subject}"
+ "\n"
+ self.get_formatted_game_object(game_id),
)
@ -564,7 +564,7 @@ class GameAdapter:
return
self.invites[game_id].update({user_email: "a"})
self.broadcast(
game_id, "@**{}** has joined the game".format(self.get_username_by_email(user_email))
game_id, f"@**{self.get_username_by_email(user_email)}** has joined the game"
)
self.start_game_if_ready(game_id)
@ -873,7 +873,7 @@ class GameInstance:
def get_player_text(self) -> str:
player_text = ""
for player in self.players:
player_text += " @**{}**".format(self.gameAdapter.get_username_by_email(player))
player_text += f" @**{self.gameAdapter.get_username_by_email(player)}**"
return player_text
def get_start_message(self) -> str:
@ -890,7 +890,7 @@ class GameInstance:
def handle_message(self, content: str, player_email: str) -> None:
if content == "forfeit":
player_name = self.gameAdapter.get_username_by_email(player_email)
self.broadcast("**{}** forfeited!".format(player_name))
self.broadcast(f"**{player_name}** forfeited!")
self.end_game("except:" + player_email)
return
if content == "draw":
@ -1032,7 +1032,7 @@ class GameInstance:
loser = winner.lstrip("except:")
else:
winner_name = self.gameAdapter.get_username_by_email(winner)
self.broadcast("**{}** won! :tada:".format(winner_name))
self.broadcast(f"**{winner_name}** won! :tada:")
for u in self.players:
values = {"total_games": 1, "games_won": 0, "games_lost": 0, "games_drawn": 0}
if loser == "":

View file

@ -139,13 +139,13 @@ class StateHandler:
self._client = client
self.marshal = lambda obj: json.dumps(obj)
self.demarshal = lambda obj: json.loads(obj)
self.state_ = dict()
self.state_: Dict[str, Any] = dict()
def put(self, key: str, value: Any) -> None:
self.state_[key] = self.marshal(value)
response = self._client.update_storage({"storage": {key: self.state_[key]}})
if response["result"] != "success":
raise StateHandlerError("Error updating state: {}".format(str(response)))
raise StateHandlerError(f"Error updating state: {str(response)}")
def get(self, key: str) -> Any:
if key in self.state_:
@ -423,8 +423,8 @@ def is_private_message_but_not_group_pm(
def display_config_file_errors(error_msg: str, config_file: str) -> None:
file_contents = open(config_file).read()
print("\nERROR: {} seems to be broken:\n\n{}".format(config_file, file_contents))
print("\nMore details here:\n\n{}\n".format(error_msg))
print(f"\nERROR: {config_file} seems to be broken:\n\n{file_contents}")
print(f"\nMore details here:\n\n{error_msg}\n")
def prepare_message_handler(bot: str, bot_handler: BotHandler, bot_lib_module: Any) -> Any:
@ -459,7 +459,7 @@ def run_message_handler_for_bot(
bot_details.update(getattr(lib_module.handler_class, "META", {}))
# Make sure you set up your ~/.zuliprc
client_name = "Zulip{}Bot".format(bot_name.capitalize())
client_name = f"Zulip{bot_name.capitalize()}Bot"
try:
client = Client(config_file=config_file, client=client_name)
@ -479,9 +479,7 @@ def run_message_handler_for_bot(
if hasattr(message_handler, "usage"):
print(message_handler.usage())
else:
print(
"WARNING: {} is missing usage handler, please add one eventually".format(bot_name)
)
print(f"WARNING: {bot_name} is missing usage handler, please add one eventually")
def handle_message(message: Dict[str, Any], flags: List[str]) -> None:
logging.info("waiting for next message")

View file

@ -21,7 +21,7 @@ def provision_bot(path_to_bot: str, force: bool) -> None:
req_path = os.path.join(path_to_bot, "requirements.txt")
if os.path.isfile(req_path):
bot_name = os.path.basename(path_to_bot)
logging.info("Installing dependencies for {}...".format(bot_name))
logging.info(f"Installing dependencies for {bot_name}...")
# pip install -r $BASEDIR/requirements.txt -t $BASEDIR/bot_dependencies --quiet
rcode = subprocess.call(["pip", "install", "-r", req_path])

View file

@ -63,7 +63,7 @@ def exit_gracefully_if_zulip_config_is_missing(config_file: Optional[str]) -> No
# but we'll catch those later.
return
else:
error_msg = "ERROR: %s does not exist." % (config_file,)
error_msg = f"ERROR: {config_file} does not exist."
else:
if zulip_env_vars_are_present():

View file

@ -33,15 +33,13 @@ class MockMessageServer:
return message
def add_reaction(self, reaction_data):
return dict(
result="success", msg="", uri="https://server/messages/{}/reactions".format(uuid4())
)
return dict(result="success", msg="", uri=f"https://server/messages/{uuid4()}/reactions")
def update(self, message):
self.messages[message["message_id"]] = message
def upload_file(self, file):
return dict(result="success", msg="", uri="https://server/user_uploads/{}".format(uuid4()))
return dict(result="success", msg="", uri=f"https://server/user_uploads/{uuid4()}")
class TerminalBotHandler:

View file

@ -44,7 +44,7 @@ def main():
if lib_module is None:
raise OSError
except OSError:
print("Could not find and import bot '{}'".format(bot_name))
print(f"Could not find and import bot '{bot_name}'")
sys.exit(1)
try:

View file

@ -27,7 +27,7 @@ def read_bot_fixture_data(bot_name: str, test_name: str) -> Dict[str, Any]:
base_path = os.path.realpath(
os.path.join(os.path.dirname(os.path.abspath(__file__)), "bots", bot_name, "fixtures")
)
http_data_path = os.path.join(base_path, "{}.json".format(test_name))
http_data_path = os.path.join(base_path, f"{test_name}.json")
with open(http_data_path, encoding="utf-8") as f:
content = f.read()
http_data = json.loads(content)