diff --git a/tools/deploy b/tools/deploy index 1a63ebb4a..dd70a19d1 100755 --- a/tools/deploy +++ b/tools/deploy @@ -55,11 +55,11 @@ def pack(options: argparse.Namespace) -> None: zip_file.write(options.config, "zuliprc") # Pack the config file for the botfarm. bot_config = textwrap.dedent( - """\ + f"""\ [deploy] - bot={} + bot={options.main} zuliprc=zuliprc - """.format(options.main) + """ ) zip_file.writestr("config.ini", bot_config) zip_file.close() diff --git a/tools/provision b/tools/provision index 77de61790..8b7cf45c9 100755 --- a/tools/provision +++ b/tools/provision @@ -58,12 +58,10 @@ the Python version this command is executed with.""" return_code = subprocess.call([options.python_interpreter, "-m", "venv", venv_dir]) except OSError: print( - "{red}Installation with venv failed. Probable errors are: " + f"{red}Installation with venv failed. Probable errors are: " "You are on Ubuntu and you haven't installed python3-venv," "or you are running an unsupported python version" - "or python is not installed properly{end_format}".format( - red=red, end_format=end_format - ) + f"or python is not installed properly{end_format}" ) sys.exit(1) raise diff --git a/zulip/integrations/bridge_with_irc/irc-mirror.py b/zulip/integrations/bridge_with_irc/irc-mirror.py index 2f30a13fa..222ff082a 100755 --- a/zulip/integrations/bridge_with_irc/irc-mirror.py +++ b/zulip/integrations/bridge_with_irc/irc-mirror.py @@ -47,7 +47,7 @@ traceback.print_exc() print( "You have unsatisfied dependencies. Install all missing dependencies with " - "{} --provision".format(sys.argv[0]) + f"{sys.argv[0]} --provision" ) sys.exit(1) diff --git a/zulip/integrations/bridge_with_irc/irc_mirror_backend.py b/zulip/integrations/bridge_with_irc/irc_mirror_backend.py index a3d2fd7b8..fb9e26b35 100644 --- a/zulip/integrations/bridge_with_irc/irc_mirror_backend.py +++ b/zulip/integrations/bridge_with_irc/irc_mirror_backend.py @@ -51,8 +51,7 @@ def check_subscription_or_die(self) -> None: subs = [s["name"] for s in resp["subscriptions"]] if self.stream not in subs: print( - "The bot is not yet subscribed to stream '%s'. Please subscribe the bot to the stream first." - % (self.stream,) + f"The bot is not yet subscribed to stream '{self.stream}'. Please subscribe the bot to the stream first." ) exit(1) diff --git a/zulip/integrations/bridge_with_matrix/matrix_bridge.py b/zulip/integrations/bridge_with_matrix/matrix_bridge.py index 6b7e68db3..c6a191310 100644 --- a/zulip/integrations/bridge_with_matrix/matrix_bridge.py +++ b/zulip/integrations/bridge_with_matrix/matrix_bridge.py @@ -91,7 +91,7 @@ async def create( return matrix_to_zulip async def _matrix_to_zulip(self, room: nio.MatrixRoom, event: nio.Event) -> None: - logging.debug("_matrix_to_zulip; room %s, event: %s" % (str(room.room_id), str(event))) + logging.debug(f"_matrix_to_zulip; room {room.room_id}, event: {event}") # We do this to identify the messages generated from Zulip -> Matrix # and we make sure we don't forward it again to the Zulip stream. @@ -253,7 +253,7 @@ def _matrix_send(self, **kwargs: Any) -> None: raise Bridge_FatalMatrixException(str(result)) def _zulip_to_matrix(self, msg: Dict[str, Any]) -> None: - logging.debug("_zulip_to_matrix; msg: %s" % (str(msg),)) + logging.debug(f"_zulip_to_matrix; msg: {msg}") room_id: Optional[str] = self.get_matrix_room_for_zulip_message(msg) if room_id is None: @@ -485,8 +485,7 @@ def read_configuration(config_file: str) -> Dict[str, Dict[str, Any]]: if section.startswith("additional_bridge"): if section_keys != bridge_key_set: raise Bridge_ConfigException( - "Please ensure the bridge configuration section %s contain the following keys: %s." - % (section, str(bridge_key_set)) + f"Please ensure the bridge configuration section {section} contain the following keys: {bridge_key_set}." ) zulip_target = (section_config["stream"], section_config["topic"]) @@ -519,7 +518,7 @@ def read_configuration(config_file: str) -> Dict[str, Dict[str, Any]]: for key in zulip_bridge_key_set: first_bridge[key] = section_config[key] else: - logging.warning("Unknown section %s" % (section,)) + logging.warning(f"Unknown section {section}") # Add the "first_bridge" to the bridges. zulip_target = (first_bridge["stream"], first_bridge["topic"]) diff --git a/zulip/integrations/bridge_with_matrix/test_matrix.py b/zulip/integrations/bridge_with_matrix/test_matrix.py index ca1488aea..087d07b34 100644 --- a/zulip/integrations/bridge_with_matrix/test_matrix.py +++ b/zulip/integrations/bridge_with_matrix/test_matrix.py @@ -118,11 +118,7 @@ def test_write_sample_config_from_zuliprc(self) -> None: ) self.assertEqual( output_lines, - [ - "Wrote sample configuration to '{}' using zuliprc file '{}'".format( - path, zuliprc_path - ) - ], + [f"Wrote sample configuration to '{path}' using zuliprc file '{zuliprc_path}'"], ) with open(path) as sample_file: @@ -143,11 +139,7 @@ def test_detect_zuliprc_does_not_exist(self) -> None: ) self.assertEqual( output_lines, - [ - "Could not write sample config: Zuliprc file '{}' does not exist.".format( - zuliprc_path - ) - ], + [f"Could not write sample config: Zuliprc file '{zuliprc_path}' does not exist."], ) def test_parse_multiple_bridges(self) -> None: diff --git a/zulip/integrations/codebase/zulip_codebase_mirror b/zulip/integrations/codebase/zulip_codebase_mirror index 88264ca8e..c2bd4e58b 100755 --- a/zulip/integrations/codebase/zulip_codebase_mirror +++ b/zulip/integrations/codebase/zulip_codebase_mirror @@ -147,10 +147,7 @@ def handle_event(event: Dict[str, Any]) -> None: if assignee is None: assignee = "no one" subject = f"#{num}: {name}" - content = ( - """%s created a new ticket [#%s](%s) priority **%s** assigned to %s:\n\n~~~ quote\n %s""" - % (actor_name, num, url, priority, assignee, name) - ) + content = f"""{actor_name} created a new ticket [#{num}]({url}) priority **{priority}** assigned to {assignee}:\n\n~~~ quote\n {name}""" elif event_type == "ticketing_note": stream = config.ZULIP_TICKETS_STREAM_NAME @@ -173,10 +170,7 @@ def handle_event(event: Dict[str, Any]) -> None: if "status_id" in changes: status_change = changes.get("status_id") - content += "Status changed from **{}** to **{}**\n\n".format( - status_change[0], - status_change[1], - ) + content += f"Status changed from **{status_change[0]}** to **{status_change[1]}**\n\n" elif event_type == "ticketing_milestone": stream = config.ZULIP_TICKETS_STREAM_NAME @@ -199,12 +193,7 @@ def handle_event(event: Dict[str, Any]) -> None: url = make_url(f"projects/{project_link}/repositories/{repo_link}/commit/{commit}") subject = f"{actor_name} commented on {commit}" - content = "{} commented on [{}]({}):\n\n~~~ quote\n{}".format( - actor_name, - commit, - url, - comment, - ) + content = f"{actor_name} commented on [{commit}]({url}):\n\n~~~ quote\n{comment}" else: # Otherwise, this is a Discussion item, and handle it subj = raw_props.get("subject") @@ -233,8 +222,7 @@ def handle_event(event: Dict[str, Any]) -> None: ) end_ref_url = make_url(f"projects/{project_link}/repositories/{repo_link}/commit/{end_ref}") between_url = make_url( - "projects/%s/repositories/%s/compare/%s...%s" - % (project_link, repo_link, start_ref, end_ref) + f"projects/{project_link}/repositories/{repo_link}/compare/{start_ref}...{end_ref}" ) subject = f"Deployment to {environment}" @@ -294,7 +282,7 @@ def run_mirror() -> None: else: since = datetime.fromtimestamp(float(timestamp), tz=pytz.utc) except (ValueError, OSError) as e: - logging.warn(f"Could not open resume file: {str(e)}") + logging.warn(f"Could not open resume file: {e}") since = default_since() try: diff --git a/zulip/integrations/hg/zulip_changegroup.py b/zulip/integrations/hg/zulip_changegroup.py index 519e186e8..ab98d533b 100755 --- a/zulip/integrations/hg/zulip_changegroup.py +++ b/zulip/integrations/hg/zulip_changegroup.py @@ -30,18 +30,12 @@ def format_summary_line( if web_url: shortlog_base_url = web_url.rstrip("/") + "/shortlog/" - summary_url = "{shortlog}{tip}?revcount={revcount}".format( - shortlog=shortlog_base_url, tip=tip - 1, revcount=revcount - ) - formatted_commit_count = "[{revcount} commit{s}]({url})".format( - revcount=revcount, s=plural, url=summary_url - ) + summary_url = f"{shortlog_base_url}{tip - 1}?revcount={revcount}" + formatted_commit_count = f"[{revcount} commit{plural}]({summary_url})" else: formatted_commit_count = f"{revcount} commit{plural}" - return "**{user}** pushed {commits} to **{branch}** (`{tip}:{node}`):\n\n".format( - user=user, commits=formatted_commit_count, branch=branch, tip=tip, node=node[:12] - ) + return f"**{user}** pushed {formatted_commit_count} to **{branch}** (`{tip}:{node[:12]}`):\n\n" def format_commit_lines(web_url: str, repo: repo, base: int, tip: int) -> str: diff --git a/zulip/integrations/perforce/zulip_change-commit.py b/zulip/integrations/perforce/zulip_change-commit.py index 0ca830798..38e39ee6c 100755 --- a/zulip/integrations/perforce/zulip_change-commit.py +++ b/zulip/integrations/perforce/zulip_change-commit.py @@ -77,7 +77,7 @@ if p4web is not None: # linkify the change number - change = "[{change}]({p4web}/{change}?ac=10)".format(p4web=p4web, change=change) + change = f"[{change}]({p4web}/{change}?ac=10)" message = """**{user}** committed revision @{change} to `{path}`. diff --git a/zulip/integrations/rss/rss-bot b/zulip/integrations/rss/rss-bot index 4a592f1d0..a5833209c 100755 --- a/zulip/integrations/rss/rss-bot +++ b/zulip/integrations/rss/rss-bot @@ -177,12 +177,7 @@ def send_zulip(entry: Any, feed_name: str) -> Dict[str, Any]: if opts.unwrap: body = unwrap_text(body) - content = "**[{}]({})**\n{}\n{}".format( - entry.title, - entry.link, - strip_tags(body), - entry.link, - ) + content = f"**[{entry.title}]({entry.link})**\n{strip_tags(body)}\n{entry.link}" if opts.math: content = content.replace("$", "$$") diff --git a/zulip/integrations/trello/zulip_trello.py b/zulip/integrations/trello/zulip_trello.py index e7a58de0c..08aeadd7d 100755 --- a/zulip/integrations/trello/zulip_trello.py +++ b/zulip/integrations/trello/zulip_trello.py @@ -122,7 +122,7 @@ def main() -> None: parser.add_argument( "--trello-board-id", required=True, - help=("The Trello board short ID. Can usually be found " "in the URL of the Trello board."), + help=("The Trello board short ID. Can usually be found in the URL of the Trello board."), ) parser.add_argument( "--trello-api-key", diff --git a/zulip/integrations/zephyr/check-mirroring b/zulip/integrations/zephyr/check-mirroring index d5f9dff56..63e715b92 100755 --- a/zulip/integrations/zephyr/check-mirroring +++ b/zulip/integrations/zephyr/check-mirroring @@ -250,8 +250,7 @@ for key, (stream, test) in zhkeys.items(): server_failure_again = send_zephyr(zwrite_args, str(new_key)) if server_failure_again: logging.error( - "Zephyr server failure twice in a row on keys %s and %s! Aborting." - % (key, new_key) + f"Zephyr server failure twice in a row on keys {key} and {new_key}! Aborting." ) print_status_and_exit(1) else: diff --git a/zulip/integrations/zephyr/zephyr_mirror_backend.py b/zulip/integrations/zephyr/zephyr_mirror_backend.py index 8ce1b3476..7c244e85a 100755 --- a/zulip/integrations/zephyr/zephyr_mirror_backend.py +++ b/zulip/integrations/zephyr/zephyr_mirror_backend.py @@ -160,7 +160,7 @@ def send_zulip(zulip_client: zulip.Client, zeph: ZephyrDict) -> Dict[str, Any]: message["content"] = unwrap_lines(zeph["content"]) if options.test_mode and options.site == DEFAULT_SITE: - logger.debug(f"Message is: {str(message)}") + logger.debug(f"Message is: {message}") return {"result": "success"} return zulip_client.send_message(message) @@ -669,8 +669,9 @@ def zephyr_to_zulip(options: optparse.Values) -> None: if "instance" in zeph: zeph["subject"] = zeph["instance"] logger.info( - "sending saved message to %s from %s..." - % (zeph.get("stream", zeph.get("recipient")), zeph["sender"]) + "sending saved message to {} from {}...".format( + zeph.get("stream", zeph.get("recipient")), zeph["sender"] + ) ) send_zulip(zulip_client, zeph) except Exception: @@ -793,9 +794,7 @@ def forward_to_zephyr(message: Dict[str, Any], zulip_client: zulip.Client) -> No # Forward messages sent to '(instance "WHITESPACE")' back to the # appropriate WHITESPACE instance for bidirectional mirroring instance = match_whitespace_instance.group(1) - elif instance == f"instance {zephyr_class}" or instance == "test instance {}".format( - zephyr_class, - ): + elif instance == f"instance {zephyr_class}" or instance == f"test instance {zephyr_class}": # Forward messages to e.g. -c -i white-magic back from the # place we forward them to if instance.startswith("test"): @@ -833,7 +832,7 @@ def forward_to_zephyr(message: Dict[str, Any], zulip_client: zulip.Client) -> No if result is None: send_error_zulip( zulip_client, - """%s + f"""{support_heading} Your Zulip-Zephyr mirror bot was unable to forward that last message \ from Zulip to Zephyr because you were sending to a zcrypted Zephyr \ @@ -841,8 +840,7 @@ class and your mirroring bot does not have access to the relevant \ key (perhaps because your AFS tokens expired). That means that while \ Zulip users (like you) received it, Zephyr users did not. -%s""" - % (support_heading, support_closing), +{support_closing}""", ) return @@ -860,15 +858,14 @@ class and your mirroring bot does not have access to the relevant \ elif code == 0: send_error_zulip( zulip_client, - """%s + f"""{support_heading} Your last message was successfully mirrored to zephyr, but zwrite \ returned the following warning: -%s +{stderr} -%s""" - % (support_heading, stderr, support_closing), +{support_closing}""", ) return elif code != 0 and ( @@ -883,7 +880,7 @@ class and your mirroring bot does not have access to the relevant \ return send_error_zulip( zulip_client, - """%s + f"""{support_heading} Your last message was forwarded from Zulip to Zephyr unauthenticated, \ because your Kerberos tickets have expired. It was sent successfully, \ @@ -891,8 +888,7 @@ class and your mirroring bot does not have access to the relevant \ are running the Zulip-Zephyr mirroring bot, so we can send \ authenticated Zephyr messages for you again. -%s""" - % (support_heading, support_closing), +{support_closing}""", ) return @@ -901,16 +897,15 @@ class and your mirroring bot does not have access to the relevant \ # but regardless, we should just notify the user. send_error_zulip( zulip_client, - """%s + f"""{support_heading} Your Zulip-Zephyr mirror bot was unable to forward that last message \ from Zulip to Zephyr. That means that while Zulip users (like you) \ received it, Zephyr users did not. The error message from zwrite was: -%s +{stderr} -%s""" - % (support_heading, stderr, support_closing), +{support_closing}""", ) return @@ -1281,11 +1276,10 @@ def die_gracefully(signal: int, frame: Optional[FrameType]) -> None: "\n" + "\n".join( textwrap.wrap( - """\ + f"""\ Could not find API key file. -You need to either place your api key file at %s, +You need to either place your api key file at {options.api_key_file}, or specify the --api-key-file option.""" - % (options.api_key_file,) ) ) ) diff --git a/zulip/tests/test_default_arguments.py b/zulip/tests/test_default_arguments.py index bc076af7d..c4f0e0b04 100755 --- a/zulip/tests/test_default_arguments.py +++ b/zulip/tests/test_default_arguments.py @@ -41,9 +41,7 @@ def test_config_path_with_tilde(self, mock_os_path_exists: bool) -> None: expanded_test_path = os.path.abspath(os.path.expanduser(test_path)) self.assertEqual( str(cm.exception), - "api_key or email not specified and " "file {} does not exist".format( - expanded_test_path - ), + f"api_key or email not specified and file {expanded_test_path} does not exist", ) diff --git a/zulip/zulip/__init__.py b/zulip/zulip/__init__.py index c8074774d..40b7a9544 100644 --- a/zulip/zulip/__init__.py +++ b/zulip/zulip/__init__.py @@ -417,8 +417,8 @@ def __init__( if insecure is None: raise ZulipError( "The ZULIP_ALLOW_INSECURE environment " - "variable is set to '{}', it must be " - "'true' or 'false'".format(insecure_setting) + f"variable is set to '{insecure_setting}', it must be " + "'true' or 'false'" ) if config_file is None: config_file = get_default_config_filename() @@ -448,10 +448,8 @@ def __init__( if insecure is None: raise ZulipError( - "insecure is set to '{}', it must be " - "'true' or 'false' if it is used in {}".format( - insecure_setting, config_file - ) + f"insecure is set to '{insecure_setting}', it must be " + f"'true' or 'false' if it is used in {config_file}" ) elif None in (api_key, email): @@ -498,8 +496,7 @@ def __init__( if client_cert is None: if client_cert_key is not None: raise ConfigNotFoundError( - "client cert key '%s' specified, but no client cert public part provided" - % (client_cert_key,) + f"client cert key '{client_cert_key}' specified, but no client cert public part provided" ) else: # we have a client cert if not os.path.isfile(client_cert): @@ -561,11 +558,7 @@ def get_user_agent(self) -> str: elif vendor == "Darwin": vendor_version = platform.mac_ver()[0] - return "{client_name} ({vendor}; {vendor_version})".format( - client_name=self.client_name, - vendor=vendor, - vendor_version=vendor_version, - ) + return f"{self.client_name} ({vendor}; {vendor_version})" def do_api_query( self, @@ -615,8 +608,7 @@ def error_retry(error_string: str) -> bool: if self.verbose: if not query_state["had_error_retry"]: sys.stdout.write( - "zulip API(%s): connection error%s -- retrying." - % ( + "zulip API({}): connection error{} -- retrying.".format( url.split(API_VERSTRING, 2)[0], error_string, ) @@ -1403,7 +1395,7 @@ def get_subscriptions(self, request: Optional[Dict[str, Any]] = None) -> Dict[st def list_subscriptions(self, request: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: logger.warning( - "list_subscriptions() is deprecated." " Please use get_subscriptions() instead." + "list_subscriptions() is deprecated. Please use get_subscriptions() instead." ) return self.get_subscriptions(request) @@ -1707,7 +1699,7 @@ def move_topic( if message_id is None: if propagate_mode != "change_all": raise AttributeError( - "A message_id must be provided if " 'propagate_mode isn\'t "change_all"' + 'A message_id must be provided if propagate_mode isn\'t "change_all"' ) # ask the server for the latest message ID in the topic. diff --git a/zulip/zulip/cli.py b/zulip/zulip/cli.py index a1ec761aa..632d84cff 100755 --- a/zulip/zulip/cli.py +++ b/zulip/zulip/cli.py @@ -84,8 +84,9 @@ def send_message(recipients: List[str], stream: str, subject: str, message: str) if message_data["type"] == "stream": log.info( - 'Sending message to stream "%s", subject "%s"... ' - % (message_data["to"], message_data["subject"]) + 'Sending message to stream "{}", subject "{}"... '.format( + message_data["to"], message_data["subject"] + ) ) else: log.info("Sending message to %s... " % message_data["to"]) diff --git a/zulip/zulip/send.py b/zulip/zulip/send.py index fc580483e..d7fe85a79 100755 --- a/zulip/zulip/send.py +++ b/zulip/zulip/send.py @@ -18,8 +18,9 @@ def do_send_message(client: zulip.Client, message_data: Dict[str, Any]) -> bool: if message_data["type"] == "stream": log.info( - 'Sending message to stream "%s", subject "%s"... ' - % (message_data["to"], message_data["subject"]) + 'Sending message to stream "{}", subject "{}"... '.format( + message_data["to"], message_data["subject"] + ) ) else: log.info("Sending message to {}... ".format(message_data["to"])) diff --git a/zulip_bots/zulip_bots/bots/baremetrics/baremetrics.py b/zulip_bots/zulip_bots/bots/baremetrics/baremetrics.py index 3ef62a122..13aa067a0 100644 --- a/zulip_bots/zulip_bots/bots/baremetrics/baremetrics.py +++ b/zulip_bots/zulip_bots/bots/baremetrics/baremetrics.py @@ -142,7 +142,7 @@ def get_sources(self) -> str: response = "**Listing sources:** \n" for index, source in enumerate(sources_data): response += ( - "{_count}.ID: {id}\n" "Provider: {provider}\n" "Provider ID: {provider_id}\n\n" + "{_count}.ID: {id}\nProvider: {provider}\nProvider ID: {provider_id}\n\n" ).format(_count=index + 1, **source) return response @@ -154,15 +154,7 @@ def get_plans(self, source_id: str) -> str: plans_data = plans_response.json() plans_data = plans_data["plans"] - template = "\n".join( - [ - "{_count}.Name: {name}", - "Active: {active}", - "Interval: {interval}", - "Interval Count: {interval_count}", - "Amounts:", - ] - ) + template = "{_count}.Name: {name}\nActive: {active}\nInterval: {interval}\nInterval Count: {interval_count}\nAmounts:" response = ["**Listing plans:**"] for index, plan in enumerate(plans_data): response += ( @@ -181,17 +173,7 @@ def get_customers(self, source_id: str) -> str: customers_data = customers_data["customers"] # FIXME BUG here? mismatch of name and display name? - template = "\n".join( - [ - "{_count}.Name: {display_name}", - "Display Name: {name}", - "OID: {oid}", - "Active: {is_active}", - "Email: {email}", - "Notes: {notes}", - "Current Plans:", - ] - ) + template = "{_count}.Name: {display_name}\nDisplay Name: {name}\nOID: {oid}\nActive: {is_active}\nEmail: {email}\nNotes: {notes}\nCurrent Plans:" response = ["**Listing customers:**"] for index, customer in enumerate(customers_data): response += ( @@ -209,17 +191,7 @@ def get_subscriptions(self, source_id: str) -> str: subscriptions_data = subscriptions_response.json() subscriptions_data = subscriptions_data["subscriptions"] - template = "\n".join( - [ - "{_count}.Customer Name: {name}", - "Customer Display Name: {display_name}", - "Customer OID: {oid}", - "Customer Email: {email}", - "Active: {_active}", - "Plan Name: {_plan_name}", - "Plan Amounts:", - ] - ) + template = "{_count}.Customer Name: {name}\nCustomer Display Name: {display_name}\nCustomer OID: {oid}\nCustomer Email: {email}\nActive: {_active}\nPlan Name: {_plan_name}\nPlan Amounts:" response = ["**Listing subscriptions:**"] for index, subscription in enumerate(subscriptions_data): response += ( diff --git a/zulip_bots/zulip_bots/bots/beeminder/beeminder.py b/zulip_bots/zulip_bots/bots/beeminder/beeminder.py index d15c79658..a0be21ae9 100644 --- a/zulip_bots/zulip_bots/bots/beeminder/beeminder.py +++ b/zulip_bots/zulip_bots/bots/beeminder/beeminder.py @@ -26,9 +26,7 @@ def get_beeminder_response(message_content: str, config_info: Dict[str, str]) -> if message_content == "" or message_content == "help": return help_message - url = "https://www.beeminder.com/api/v1/users/{}/goals/{}/datapoints.json".format( - username, goalname - ) + url = f"https://www.beeminder.com/api/v1/users/{username}/goals/{goalname}/datapoints.json" message_pieces = message_content.split(",") for i in range(len(message_pieces)): message_pieces[i] = message_pieces[i].strip() @@ -66,13 +64,11 @@ def get_beeminder_response(message_content: str, config_info: Dict[str, str]) -> if r.status_code == 401: # Handles case of invalid key and missing key return "Error. Check your key!" else: - return "Error occured : {}".format( - r.status_code - ) # Occures in case of unprocessable entity + return f"Error occured : {r.status_code}" # Occures in case of unprocessable entity else: datapoint_link = f"https://www.beeminder.com/{username}/{goalname}" - return "[Datapoint]({}) created.".format( - datapoint_link + return ( + f"[Datapoint]({datapoint_link}) created." ) # Handles the case of successful datapoint creation except ConnectionError as e: logging.exception(str(e)) diff --git a/zulip_bots/zulip_bots/bots/chessbot/chessbot.py b/zulip_bots/zulip_bots/bots/chessbot/chessbot.py index fb5a0e5e9..e6c48cb8f 100644 --- a/zulip_bots/zulip_bots/bots/chessbot/chessbot.py +++ b/zulip_bots/zulip_bots/bots/chessbot/chessbot.py @@ -401,7 +401,7 @@ def make_loss_response(board: chess.Board, reason: str) -> str: Returns: The loss response string. """ - return ("*{}* {}. **{}** wins!\n\n" "{}").format( + return ("*{}* {}. **{}** wins!\n\n{}").format( "White" if board.turn else "Black", reason, "Black" if board.turn else "White", @@ -418,7 +418,7 @@ def make_not_legal_response(board: chess.Board, move_san: str) -> str: Returns: The not-legal-move response string. """ - return ("Sorry, the move *{}* isn't legal.\n\n" "{}" "\n\n\n" "{}").format( + return ("Sorry, the move *{}* isn't legal.\n\n{}\n\n\n{}").format( move_san, make_str(board, board.turn), make_footer() ) diff --git a/zulip_bots/zulip_bots/bots/connect_four/test_connect_four.py b/zulip_bots/zulip_bots/bots/connect_four/test_connect_four.py index 491b260cb..285ba91b7 100644 --- a/zulip_bots/zulip_bots/bots/connect_four/test_connect_four.py +++ b/zulip_bots/zulip_bots/bots/connect_four/test_connect_four.py @@ -73,7 +73,7 @@ def test_static_responses(self) -> None: def test_game_message_handler_responses(self) -> None: board = ( ":one: :two: :three: :four: :five: :six: :seven:\n\n" - + "\ + "\ :white_circle: :white_circle: :white_circle: :white_circle: \ :white_circle: :white_circle: :white_circle: \n\n\ :white_circle: :white_circle: :white_circle: :white_circle: \ diff --git a/zulip_bots/zulip_bots/bots/converter/converter.py b/zulip_bots/zulip_bots/bots/converter/converter.py index 9e23f0742..625776676 100644 --- a/zulip_bots/zulip_bots/bots/converter/converter.py +++ b/zulip_bots/zulip_bots/bots/converter/converter.py @@ -124,9 +124,7 @@ def get_bot_converter_response(message: Dict[str, str], bot_handler: BotHandler) number_res = round_to(number_res, 7) results.append( - "{} {} = {} {}".format( - number, words[convert_index + 2], number_res, words[convert_index + 3] - ) + f"{number} {words[convert_index + 2]} = {number_res} {words[convert_index + 3]}" ) else: diff --git a/zulip_bots/zulip_bots/bots/dialogflow/dialogflow.py b/zulip_bots/zulip_bots/bots/dialogflow/dialogflow.py index 592180ba0..16ea544d6 100644 --- a/zulip_bots/zulip_bots/bots/dialogflow/dialogflow.py +++ b/zulip_bots/zulip_bots/bots/dialogflow/dialogflow.py @@ -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 f"Error. {str(e)}." + return f"Error. {e}." class DialogFlowHandler: diff --git a/zulip_bots/zulip_bots/bots/giphy/giphy.py b/zulip_bots/zulip_bots/bots/giphy/giphy.py index a0a5a421e..d0e0c73e0 100644 --- a/zulip_bots/zulip_bots/bots/giphy/giphy.py +++ b/zulip_bots/zulip_bots/bots/giphy/giphy.py @@ -96,10 +96,10 @@ def get_bot_giphy_response( "let's try again later! :grin:" ) except GiphyNoResultException: - return 'Sorry, I don\'t have a GIF for "%s"! ' ":astonished:" % (keyword,) + return f'Sorry, I don\'t have a GIF for "{keyword}"! :astonished:' return ( - "[Click to enlarge](%s)" - "[](/static/images/interactive-bot/giphy/powered-by-giphy.png)" % (gif_url,) + f"[Click to enlarge]({gif_url})" + "[](/static/images/interactive-bot/giphy/powered-by-giphy.png)" ) diff --git a/zulip_bots/zulip_bots/bots/github_detail/github_detail.py b/zulip_bots/zulip_bots/bots/github_detail/github_detail.py index 726e50be0..071094ff8 100644 --- a/zulip_bots/zulip_bots/bots/github_detail/github_detail.py +++ b/zulip_bots/zulip_bots/bots/github_detail/github_detail.py @@ -27,7 +27,7 @@ def usage(self) -> str: "To reference an issue or pull request usename mention the bot then " "anytime in the message type its id, for example:\n" "@**Github detail** #3212 zulip#3212 zulip/zulip#3212\n" - "The default owner is {} and the default repo is {}.".format(self.owner, self.repo) + f"The default owner is {self.owner} and the default repo is {self.repo}." ) def format_message(self, details: Dict[str, Any]) -> str: @@ -44,10 +44,8 @@ def format_message(self, details: Dict[str, Any]) -> str: message_string = ( 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 - ), + f"Created by **[{author}](https://github.com/{author})**\n", + f"Status - **{status}**\n```quote\n{description}\n```", ) return "".join(message_string) @@ -100,9 +98,7 @@ def handle_message(self, message: Dict[str, str], bot_handler: BotHandler) -> No bot_messages.append(self.format_message(details)) else: bot_messages.append( - "Failed to find issue/pr: {owner}/{repo}#{id}".format( - owner=owner, repo=repo, id=issue_pr.group(3) - ) + f"Failed to find issue/pr: {owner}/{repo}#{issue_pr.group(3)}" ) else: bot_messages.append("Failed to detect owner and repository name.") diff --git a/zulip_bots/zulip_bots/bots/idonethis/idonethis.py b/zulip_bots/zulip_bots/bots/idonethis/idonethis.py index a84346f34..443841a66 100644 --- a/zulip_bots/zulip_bots/bots/idonethis/idonethis.py +++ b/zulip_bots/zulip_bots/bots/idonethis/idonethis.py @@ -97,9 +97,7 @@ def get_team_hash(team_name: str) -> str: def team_info(team_name: str) -> str: data = api_show_team(get_team_hash(team_name)) - return "\n".join(["Team Name: {name}", "ID: `{hash_id}`", "Created at: {created_at}"]).format( - **data - ) + return "Team Name: {name}\nID: `{hash_id}`\nCreated at: {created_at}".format(**data) def entries_list(team_name: str) -> str: @@ -110,17 +108,9 @@ def entries_list(team_name: str) -> str: data = api_list_entries() response = "Entries for all teams:" for entry in data: - response += "\n".join( - [ - "", - " * {body_formatted}", - " * Created at: {created_at}", - " * Status: {status}", - " * User: {username}", - " * Team: {teamname}", - " * ID: {hash_id}", - ] - ).format(username=entry["user"]["full_name"], teamname=entry["team"]["name"], **entry) + response += "\n * {body_formatted}\n * Created at: {created_at}\n * Status: {status}\n * User: {username}\n * Team: {teamname}\n * ID: {hash_id}".format( + username=entry["user"]["full_name"], teamname=entry["team"]["name"], **entry + ) return response diff --git a/zulip_bots/zulip_bots/bots/incident/incident.py b/zulip_bots/zulip_bots/bots/incident/incident.py index d773c5d89..6ff1ab05d 100644 --- a/zulip_bots/zulip_bots/bots/incident/incident.py +++ b/zulip_bots/zulip_bots/bots/incident/incident.py @@ -124,26 +124,15 @@ def get_choice(code: str) -> Dict[str, 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" - ) + answer_list = "\n".join(f"* **{code}** {ANSWERS[code]}" for code in "1234") how_to_respond = f"""**reply**: answer {ticket_id} """ - content = """ + content = f""" Incident: {incident} -Q: {question} +Q: {QUESTION} {answer_list} -{how_to_respond}""".format( - question=QUESTION, - answer_list=answer_list, - how_to_respond=how_to_respond, - incident=incident, - ) +{how_to_respond}""" return content diff --git a/zulip_bots/zulip_bots/bots/jira/jira.py b/zulip_bots/zulip_bots/bots/jira/jira.py index 7c3c81cf3..9d68fe53b 100644 --- a/zulip_bots/zulip_bots/bots/jira/jira.py +++ b/zulip_bots/zulip_bots/bots/jira/jira.py @@ -242,24 +242,14 @@ def handle_message(self, message: Dict[str, str], bot_handler: BotHandler) -> No response = "Oh no! Jira raised an error:\n > " + ", ".join(errors) else: response = ( - "**Issue *[{}]({})*: {}**\n\n" - " - Type: *{}*\n" + f"**Issue *[{key}]({url})*: {summary}**\n\n" + f" - Type: *{type_name}*\n" " - Description:\n" - " > {}\n" - " - Creator: *{}*\n" - " - Project: *{}*\n" - " - Priority: *{}*\n" - " - Status: *{}*\n" - ).format( - key, - url, - summary, - type_name, - description, - creator_name, - project_name, - priority_name, - status_name, + f" > {description}\n" + f" - Creator: *{creator_name}*\n" + f" - Project: *{project_name}*\n" + f" - Priority: *{priority_name}*\n" + f" - Status: *{status_name}*\n" ) elif create_match: jira_response = requests.post( diff --git a/zulip_bots/zulip_bots/bots/merels/libraries/game.py b/zulip_bots/zulip_bots/bots/merels/libraries/game.py index 8cc3b2d6d..4798fcbfb 100644 --- a/zulip_bots/zulip_bots/bots/merels/libraries/game.py +++ b/zulip_bots/zulip_bots/bots/merels/libraries/game.py @@ -19,7 +19,7 @@ def getInfo(): :return: Info on how to start the game """ - return "To start a game, mention me and add `create`. A game will start " "in that topic. " + return "To start a game, mention me and add `create`. A game will start in that topic. " def getHelp(): @@ -70,7 +70,7 @@ def beat(message, topic_name, merels_storage): p2 = [int(x) for x in match.group(3).split(",")] if mechanics.get_take_status(topic_name, merels_storage) == 1: - raise BadMoveException("Take is required to proceed." " Please try again.\n") + raise BadMoveException("Take is required to proceed. Please try again.\n") responses += mechanics.move_man(topic_name, p1, p2, merels_storage) + "\n" no_moves = after_event_checkup(responses, topic_name, merels_storage) @@ -98,7 +98,7 @@ def beat(message, topic_name, merels_storage): responses = "" if mechanics.get_take_status(topic_name, merels_storage) == 1: - raise BadMoveException("Take is required to proceed." " Please try again.\n") + raise BadMoveException("Take is required to proceed. Please try again.\n") responses += mechanics.put_man(topic_name, p1[0], p1[1], merels_storage) + "\n" no_moves = after_event_checkup(responses, topic_name, merels_storage) @@ -162,7 +162,7 @@ def check_any_moves(topic_name, merels_storage): """ if not mechanics.can_make_any_move(topic_name, merels_storage): mechanics.update_change_turn(topic_name, merels_storage) - return "Cannot make any move on the grid. Switching to " "previous player.\n" + return "Cannot make any move on the grid. Switching to previous player.\n" return "" diff --git a/zulip_bots/zulip_bots/bots/merels/libraries/mechanics.py b/zulip_bots/zulip_bots/bots/merels/libraries/mechanics.py index a95e1aaa2..3093f882d 100644 --- a/zulip_bots/zulip_bots/bots/merels/libraries/mechanics.py +++ b/zulip_bots/zulip_bots/bots/merels/libraries/mechanics.py @@ -284,8 +284,8 @@ def create_room(topic_name, merels_storage): return response else: return ( - "Failed: Cannot create an already existing game in {}. " - "Please finish the game first.".format(topic_name) + f"Failed: Cannot create an already existing game in {topic_name}. " + "Please finish the game first." ) @@ -309,9 +309,9 @@ def display_game(topic_name, merels_storage): take = "No" response += interface.graph_grid(data.grid()) + "\n" - response += """Phase {}. Take mode: {}. -X taken: {}, O taken: {}. - """.format(data.get_phase(), take, data.x_taken, data.o_taken) + response += f"""Phase {data.get_phase()}. Take mode: {take}. +X taken: {data.x_taken}, O taken: {data.o_taken}. + """ return response @@ -362,9 +362,7 @@ def move_man(topic_name, p1, p2, merels_storage): data.hill_uid, data.take_mode, ) - return "Moved a man from ({}, {}) -> ({}, {}) for {}.".format( - p1[0], p1[1], p2[0], p2[1], data.turn - ) + return f"Moved a man from ({p1[0]}, {p1[1]}) -> ({p2[0]}, {p2[1]}) for {data.turn}." else: raise BadMoveException("Failed: That's not a legal move. Please try again.") diff --git a/zulip_bots/zulip_bots/bots/merels/test_merels.py b/zulip_bots/zulip_bots/bots/merels/test_merels.py index eefe8b013..b6e2b7062 100644 --- a/zulip_bots/zulip_bots/bots/merels/test_merels.py +++ b/zulip_bots/zulip_bots/bots/merels/test_merels.py @@ -15,7 +15,7 @@ def test_no_command(self): ) res = self.get_response(message) self.assertEqual( - res["content"], "You are not in a game at the moment." " Type `help` for help." + res["content"], "You are not in a game at the moment. Type `help` for help." ) # FIXME: Add tests for computer moves diff --git a/zulip_bots/zulip_bots/bots/monkeytestit/lib/parse.py b/zulip_bots/zulip_bots/bots/monkeytestit/lib/parse.py index 9866f484c..e4403bfd3 100644 --- a/zulip_bots/zulip_bots/bots/monkeytestit/lib/parse.py +++ b/zulip_bots/zulip_bots/bots/monkeytestit/lib/parse.py @@ -22,7 +22,7 @@ def execute(message: str, apikey: str) -> str: len_params = len(params) if len_params < 2: - return failed("You **must** provide at least an URL to perform a " "check.") + return failed("You **must** provide at least an URL to perform a check.") options = { "secret": apikey, @@ -65,7 +65,7 @@ def execute(message: str, apikey: str) -> str: # the user needs to modify the asset_count. There are probably ways # to counteract this, but I think this is more fast to run. else: - return "Unknown command. Available commands: `check " "[params]`" + return "Unknown command. Available commands: `check [params]`" def failed(message: str) -> str: diff --git a/zulip_bots/zulip_bots/bots/tictactoe/tictactoe.py b/zulip_bots/zulip_bots/bots/tictactoe/tictactoe.py index b9e807449..f3b1ffc03 100644 --- a/zulip_bots/zulip_bots/bots/tictactoe/tictactoe.py +++ b/zulip_bots/zulip_bots/bots/tictactoe/tictactoe.py @@ -253,9 +253,7 @@ def alert_move_message(self, original_player: str, move_info: str) -> str: return f"{original_player} put a token at {move_info}" def game_start_message(self) -> str: - return ( - "Welcome to tic-tac-toe!" "To make a move, type @-mention `move ` or ``" - ) + return "Welcome to tic-tac-toe!To make a move, type @-mention `move ` or ``" class ticTacToeHandler(GameAdapter): diff --git a/zulip_bots/zulip_bots/bots/trello/test_trello.py b/zulip_bots/zulip_bots/bots/trello/test_trello.py index 9559a343c..4cb0832c3 100644 --- a/zulip_bots/zulip_bots/bots/trello/test_trello.py +++ b/zulip_bots/zulip_bots/bots/trello/test_trello.py @@ -83,7 +83,7 @@ def test_get_all_lists_command(self) -> None: with self.mock_http_conversation("get_lists"): self.verify_reply( "get-all-lists TEST", - ("**Lists:**\n" "1. TEST_A\n" " * TEST_1\n" "2. TEST_B\n" " * TEST_2"), + ("**Lists:**\n1. TEST_A\n * TEST_1\n2. TEST_B\n * TEST_2"), ) def test_command_exceptions(self) -> None: diff --git a/zulip_bots/zulip_bots/bots/trivia_quiz/test_trivia_quiz.py b/zulip_bots/zulip_bots/bots/trivia_quiz/test_trivia_quiz.py index 9df9839d7..a1913b0fc 100644 --- a/zulip_bots/zulip_bots/bots/trivia_quiz/test_trivia_quiz.py +++ b/zulip_bots/zulip_bots/bots/trivia_quiz/test_trivia_quiz.py @@ -22,11 +22,11 @@ class TestTriviaQuizBot(BotTestCase, DefaultTests): new_question_response = ( "\nQ: Which class of animals are newts members of?\n\n" - + "* **A** Amphibian\n" - + "* **B** Fish\n" - + "* **C** Reptiles\n" - + "* **D** Mammals\n" - + "**reply**: answer Q001 " + "* **A** Amphibian\n" + "* **B** Fish\n" + "* **C** Reptiles\n" + "* **D** Mammals\n" + "**reply**: answer Q001 " ) def get_test_quiz(self) -> Tuple[Dict[str, Any], Any]: diff --git a/zulip_bots/zulip_bots/bots/trivia_quiz/trivia_quiz.py b/zulip_bots/zulip_bots/bots/trivia_quiz/trivia_quiz.py index 302ecbd09..ebb8b9b2d 100644 --- a/zulip_bots/zulip_bots/bots/trivia_quiz/trivia_quiz.py +++ b/zulip_bots/zulip_bots/bots/trivia_quiz/trivia_quiz.py @@ -189,24 +189,14 @@ def get_choice(letter: str) -> Dict[str, str]: 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" - ) + answer_list = "\n".join(f"* **{letter}** {answers[letter]}" for letter in "ABCD") how_to_respond = f"""**reply**: answer {quiz_id} """ - content = """ + content = f""" Q: {question} {answer_list} -{how_to_respond}""".format( - question=question, - answer_list=answer_list, - how_to_respond=how_to_respond, - ) +{how_to_respond}""" return content diff --git a/zulip_bots/zulip_bots/bots/xkcd/xkcd.py b/zulip_bots/zulip_bots/bots/xkcd/xkcd.py index ee1b607ce..09cd44ab1 100644 --- a/zulip_bots/zulip_bots/bots/xkcd/xkcd.py +++ b/zulip_bots/zulip_bots/bots/xkcd/xkcd.py @@ -62,11 +62,11 @@ def get_xkcd_bot_response(message: Dict[str, str], quoted_name: str) -> str: commands_help = ( "%s" - "\n* `{0} help` to show this help message." - "\n* `{0} latest` to fetch the latest comic strip from xkcd." - "\n* `{0} random` to fetch a random comic strip from xkcd." - "\n* `{0} ` to fetch a comic strip based on `` " - "e.g `{0} 1234`.".format(quoted_name) + f"\n* `{quoted_name} help` to show this help message." + f"\n* `{quoted_name} latest` to fetch the latest comic strip from xkcd." + f"\n* `{quoted_name} random` to fetch a random comic strip from xkcd." + f"\n* `{quoted_name} ` to fetch a comic strip based on `` " + f"e.g `{quoted_name} 1234`." ) try: diff --git a/zulip_bots/zulip_bots/bots/youtube/test_youtube.py b/zulip_bots/zulip_bots/bots/youtube/test_youtube.py index d003d545a..4bfcee0a6 100644 --- a/zulip_bots/zulip_bots/bots/youtube/test_youtube.py +++ b/zulip_bots/zulip_bots/bots/youtube/test_youtube.py @@ -108,5 +108,5 @@ def test_connection_error(self) -> None: "requests.get", side_effect=ConnectionError() ), patch("logging.exception"): self.verify_reply( - "Wow !", "Uh-Oh, couldn't process the request " "right now.\nPlease again later" + "Wow !", "Uh-Oh, couldn't process the request right now.\nPlease again later" ) diff --git a/zulip_bots/zulip_bots/bots/youtube/youtube.py b/zulip_bots/zulip_bots/bots/youtube/youtube.py index 646fbf767..3d1a5cbca 100644 --- a/zulip_bots/zulip_bots/bots/youtube/youtube.py +++ b/zulip_bots/zulip_bots/bots/youtube/youtube.py @@ -37,7 +37,7 @@ def initialize(self, bot_handler: BotHandler) -> None: assert e.response is not None if e.response.json()["error"]["errors"][0]["reason"] == "keyInvalid": bot_handler.quit( - "Invalid key." "Follow the instructions in doc.md for setting API key." + "Invalid key.Follow the instructions in doc.md for setting API key." ) else: raise @@ -112,7 +112,7 @@ def get_bot_response( return YoutubeHandler.help_content except (ConnectionError, HTTPError): - return "Uh-Oh, couldn't process the request " "right now.\nPlease again later" + return "Uh-Oh, couldn't process the request right now.\nPlease again later" reply = "Here is what I found for `" + query + "` : " @@ -123,8 +123,7 @@ def get_bot_response( elif len(video_list) == 1: return ( reply - + "\n%s - [Watch now](https://www.youtube.com/watch?v=%s)" - % (video_list[0][0], video_list[0][1]) + + f"\n{video_list[0][0]} - [Watch now](https://www.youtube.com/watch?v={video_list[0][1]})" ).strip() for title, id in video_list: diff --git a/zulip_bots/zulip_bots/game_handler.py b/zulip_bots/zulip_bots/game_handler.py index 39516288f..9b420469e 100644 --- a/zulip_bots/zulip_bots/game_handler.py +++ b/zulip_bots/zulip_bots/game_handler.py @@ -80,12 +80,12 @@ def add_user_statistics(self, user: str, values: Dict[str, int]) -> None: self.put_user_cache() def help_message(self) -> str: - return """** {} Bot Help:** -*Preface all commands with @**{}*** + return f"""** {self.game_name} Bot Help:** +*Preface all commands with @**{self.get_bot_username()}*** * To start a game in a stream (*recommended*), type `start game` * To start a game against another player, type -`start game with @`{} +`start game with @`{self.play_with_computer_help()} * To play game with the current number of players, type `play game` * To quit a game at any time, type @@ -100,23 +100,18 @@ def help_message(self) -> str: `cancel game` * To see rules of this game, type `rules` -{}""".format( - self.game_name, - self.get_bot_username(), - self.play_with_computer_help(), - self.move_help_message, - ) +{self.move_help_message}""" def help_message_single_player(self) -> str: - return """** {} Bot Help:** -*Preface all commands with @**{}*** + return f"""** {self.game_name} Bot Help:** +*Preface all commands with @**{self.get_bot_username()}*** * To start a game in a stream, type `start game` * To quit a game at any time, type `quit` * To see rules of this game, type `rules` -{}""".format(self.game_name, self.get_bot_username(), self.move_help_message) +{self.move_help_message}""" def get_commands(self) -> Dict[str, str]: action = self.help_message_single_player() @@ -359,9 +354,7 @@ def create_game_lobby(self, message: Dict[str, Any], users: List[str] = []) -> N if len(users) + 1 < self.min_players: self.send_reply( message, - "You must have at least {} players to play.\nGame cancelled.".format( - self.min_players - ), + f"You must have at least {self.min_players} players to play.\nGame cancelled.", ) return if len(users) + 1 > self.max_players: @@ -538,19 +531,16 @@ def start_game(self, game_id: str) -> None: self.instances[game_id] = GameInstance(self, False, subject, game_id, players, stream) self.broadcast( game_id, - f"The game has started in #{stream} {self.instances[game_id].subject}" - + "\n" + f"The game has started in #{stream} {self.instances[game_id].subject}\n" + self.get_formatted_game_object(game_id), ) del self.invites[game_id] self.instances[game_id].start() def get_formatted_game_object(self, game_id: str) -> str: - object = """> **Game `{}`** -> {} -> {}/{} players""".format( - game_id, self.game_name, self.get_number_of_players(game_id), self.max_players - ) + object = f"""> **Game `{game_id}`** +> {self.game_name} +> {self.get_number_of_players(game_id)}/{self.max_players} players""" if game_id in self.instances.keys(): instance = self.instances[game_id] if not self.is_single_player: @@ -631,18 +621,16 @@ def parse_message(self, message: Dict[str, Any]) -> None: return self.send_reply( message, - "Join your game using the link below!\n\n{}".format( - self.get_formatted_game_object(game_id) - ), + f"Join your game using the link below!\n\n{self.get_formatted_game_object(game_id)}", ) return if game["subject"] != message["subject"] or game["stream"] != message["display_recipient"]: if game_id not in self.pending_subject_changes: self.send_reply( message, - "Your current game is not in this subject. \n\ + f"Your current game is not in this subject. \n\ To move subjects, send your message again, otherwise join the game using the link below.\n\n\ -{}".format(self.get_formatted_game_object(game_id)), +{self.get_formatted_game_object(game_id)}", ) self.pending_subject_changes.append(game_id) return @@ -950,9 +938,7 @@ def make_move(self, content: str, is_computer: bool) -> None: if not is_computer: self.current_messages.append( self.gameAdapter.gameMessageHandler.alert_move_message( - "**{}**".format( - self.gameAdapter.get_username_by_email(self.players[self.turn]) - ), + f"**{self.gameAdapter.get_username_by_email(self.players[self.turn])}**", content, ) ) @@ -973,9 +959,7 @@ def same_player_turn(self, content: str, message: str, is_computer: bool) -> Non if not is_computer: self.current_messages.append( self.gameAdapter.gameMessageHandler.alert_move_message( - "**{}**".format( - self.gameAdapter.get_username_by_email(self.players[self.turn]) - ), + f"**{self.gameAdapter.get_username_by_email(self.players[self.turn])}**", content, ) ) diff --git a/zulip_bots/zulip_bots/lib.py b/zulip_bots/zulip_bots/lib.py index f651716a9..895ba6691 100644 --- a/zulip_bots/zulip_bots/lib.py +++ b/zulip_bots/zulip_bots/lib.py @@ -145,7 +145,7 @@ 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(f"Error updating state: {str(response)}") + raise StateHandlerError(f"Error updating state: {response}") def get(self, key: str) -> Any: if key in self.state_: @@ -222,21 +222,21 @@ def __init__( user_profile = client.get_profile() except ZulipError as e: print( - """ - ERROR: {} + f""" + ERROR: {e} Have you not started the server? Or did you mis-specify the URL? - """.format(e) + """ ) sys.exit(1) if user_profile.get("result") == "error": msg = user_profile.get("msg", "unknown") print( + f""" + ERROR: {msg} """ - ERROR: {} - """.format(msg) ) sys.exit(1) @@ -323,18 +323,18 @@ def get_config_info(self, bot_name: str, optional: bool = False) -> Dict[str, st if bot_name not in self.bot_config_file: print( - """ + f""" WARNING! - {} does not adhere to the + {self.bot_config_file} does not adhere to the file naming convention, and it could be a sign that you passed in the wrong third-party configuration file. - The suggested name is {}.conf + The suggested name is {bot_name}.conf We will proceed anyway. - """.format(self.bot_config_file, bot_name) + """ ) # We expect the caller to pass in None if the user does @@ -368,8 +368,8 @@ def open(self, filepath: str) -> IO[str]: return open(abs_filepath) else: raise PermissionError( - 'Cannot open file "{}". Bots may only access ' - "files in their local directory.".format(abs_filepath) + f'Cannot open file "{abs_filepath}". Bots may only access ' + "files in their local directory." ) def quit(self, message: str = "") -> None: diff --git a/zulip_bots/zulip_bots/run.py b/zulip_bots/zulip_bots/run.py index e26922318..d58563218 100755 --- a/zulip_bots/zulip_bots/run.py +++ b/zulip_bots/zulip_bots/run.py @@ -103,12 +103,11 @@ def exit_gracefully_if_bot_config_file_does_not_exist(bot_config_file: Optional[ if not os.path.exists(bot_config_file): print( - """ - ERROR: %s does not exist. + f""" + ERROR: {bot_config_file} does not exist. You probably just specified the wrong file location here. """ - % (bot_config_file,) ) sys.exit(1) diff --git a/zulip_bots/zulip_bots/test_file_utils.py b/zulip_bots/zulip_bots/test_file_utils.py index 3fbdaf970..46d849ceb 100644 --- a/zulip_bots/zulip_bots/test_file_utils.py +++ b/zulip_bots/zulip_bots/test_file_utils.py @@ -19,7 +19,7 @@ def get_bot_message_handler(bot_name: str) -> Any: # handler class. Eventually, we want bot's handler classes to # inherit from a common prototype specifying the handle_message # function. - lib_module: Any = import_module("zulip_bots.bots.{bot}.{bot}".format(bot=bot_name)) + lib_module: Any = import_module(f"zulip_bots.bots.{bot_name}.{bot_name}") return lib_module.handler_class() diff --git a/zulip_botserver/tests/test_server.py b/zulip_botserver/tests/test_server.py index d01b20504..ec068f874 100644 --- a/zulip_botserver/tests/test_server.py +++ b/zulip_botserver/tests/test_server.py @@ -273,8 +273,8 @@ def test_load_lib_modules(self) -> None: # load invalid file path with self.assertRaisesRegex( SystemExit, - 'Error: Bot "{}/zulip_bots/zulip_bots/bots/helloworld.py" doesn\'t exist. ' - "Please make sure you have set up the botserverrc file correctly.".format(root_dir), + f'Error: Bot "{root_dir}/zulip_bots/zulip_bots/bots/helloworld.py" doesn\'t exist. ' + "Please make sure you have set up the botserverrc file correctly.", ): path = Path( root_dir, "zulip_bots/zulip_bots/bots/{bot}.py".format(bot="helloworld") diff --git a/zulip_botserver/zulip_botserver/server.py b/zulip_botserver/zulip_botserver/server.py index 08f1d233d..60314a3e5 100644 --- a/zulip_botserver/zulip_botserver/server.py +++ b/zulip_botserver/zulip_botserver/server.py @@ -90,9 +90,7 @@ def read_config_file( bot_section = parser.sections()[0] bots_config[bot_name] = read_config_section(parser, bot_section) logging.warning( - "First bot name in the config list was changed from '{}' to '{}'".format( - bot_section, bot_name - ) + f"First bot name in the config list was changed from '{bot_section}' to '{bot_name}'" ) ignored_sections = parser.sections()[1:] @@ -118,7 +116,7 @@ def load_lib_modules(available_bots: List[str]) -> Dict[str, ModuleType]: if bot.endswith(".py") and os.path.isfile(bot): lib_module = import_module_from_source(bot, "custom_bot_module") else: - module_name = "zulip_bots.bots.{bot}.{bot}".format(bot=bot) + module_name = f"zulip_bots.bots.{bot}.{bot}" lib_module = import_module(module_name) bots_lib_module[bot] = lib_module except ImportError: