ruff: Fix N801 Class name should use CapWords convention.
Signed-off-by: Anders Kaseorg <anders@zulip.com>
This commit is contained in:
parent
272c63bfd3
commit
2c4e7069ad
2 changed files with 29 additions and 29 deletions
|
@ -35,15 +35,15 @@ ZULIP_MESSAGE_TEMPLATE: str = "**{username}** [{uid}]: {message}"
|
||||||
MATRIX_MESSAGE_TEMPLATE: str = "<{username} ({uid})> {message}"
|
MATRIX_MESSAGE_TEMPLATE: str = "<{username} ({uid})> {message}"
|
||||||
|
|
||||||
|
|
||||||
class Bridge_ConfigException(Exception):
|
class BridgeConfigException(Exception):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
class Bridge_FatalMatrixException(Exception):
|
class BridgeFatalMatrixException(Exception):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
class Bridge_FatalZulipException(Exception):
|
class BridgeFatalZulipException(Exception):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
@ -86,7 +86,7 @@ class MatrixToZulip:
|
||||||
# the new messages and not with all the old ones.
|
# the new messages and not with all the old ones.
|
||||||
sync_response: Union[SyncResponse, SyncError] = await matrix_client.sync()
|
sync_response: Union[SyncResponse, SyncError] = await matrix_client.sync()
|
||||||
if isinstance(sync_response, nio.SyncError):
|
if isinstance(sync_response, nio.SyncError):
|
||||||
raise Bridge_FatalMatrixException(sync_response.message)
|
raise BridgeFatalMatrixException(sync_response.message)
|
||||||
|
|
||||||
return matrix_to_zulip
|
return matrix_to_zulip
|
||||||
|
|
||||||
|
@ -117,10 +117,10 @@ class MatrixToZulip:
|
||||||
)
|
)
|
||||||
except Exception as exception:
|
except Exception as exception:
|
||||||
# Generally raised when user is forbidden
|
# Generally raised when user is forbidden
|
||||||
raise Bridge_FatalZulipException(exception)
|
raise BridgeFatalZulipException(exception)
|
||||||
if result["result"] != "success":
|
if result["result"] != "success":
|
||||||
# Generally raised when API key is invalid
|
# Generally raised when API key is invalid
|
||||||
raise Bridge_FatalZulipException(result["msg"])
|
raise BridgeFatalZulipException(result["msg"])
|
||||||
|
|
||||||
# Update the bot's read marker in order to show the other users which
|
# Update the bot's read marker in order to show the other users which
|
||||||
# messages are already processed by the bot.
|
# messages are already processed by the bot.
|
||||||
|
@ -194,14 +194,14 @@ class MatrixToZulip:
|
||||||
for room_id in self.matrix_config["bridges"]:
|
for room_id in self.matrix_config["bridges"]:
|
||||||
result: Union[JoinResponse, JoinError] = await self.matrix_client.join(room_id)
|
result: Union[JoinResponse, JoinError] = await self.matrix_client.join(room_id)
|
||||||
if isinstance(result, nio.JoinError):
|
if isinstance(result, nio.JoinError):
|
||||||
raise Bridge_FatalMatrixException(str(result))
|
raise BridgeFatalMatrixException(str(result))
|
||||||
|
|
||||||
async def matrix_login(self) -> None:
|
async def matrix_login(self) -> None:
|
||||||
result: Union[LoginResponse, LoginError] = await self.matrix_client.login(
|
result: Union[LoginResponse, LoginError] = await self.matrix_client.login(
|
||||||
self.matrix_config["password"]
|
self.matrix_config["password"]
|
||||||
)
|
)
|
||||||
if isinstance(result, nio.LoginError):
|
if isinstance(result, nio.LoginError):
|
||||||
raise Bridge_FatalMatrixException(str(result))
|
raise BridgeFatalMatrixException(str(result))
|
||||||
|
|
||||||
async def run(self) -> None:
|
async def run(self) -> None:
|
||||||
print("Starting message handler on Matrix client")
|
print("Starting message handler on Matrix client")
|
||||||
|
@ -230,7 +230,7 @@ class ZulipToMatrix:
|
||||||
# Precompute the url of the Zulip server, needed later.
|
# Precompute the url of the Zulip server, needed later.
|
||||||
result: Dict[str, Any] = self.zulip_client.get_server_settings()
|
result: Dict[str, Any] = self.zulip_client.get_server_settings()
|
||||||
if result["result"] != "success":
|
if result["result"] != "success":
|
||||||
raise Bridge_FatalZulipException("cannot get server settings")
|
raise BridgeFatalZulipException("cannot get server settings")
|
||||||
self.server_url: str = result["realm_uri"]
|
self.server_url: str = result["realm_uri"]
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
|
@ -250,7 +250,7 @@ class ZulipToMatrix:
|
||||||
self.matrix_client.room_send(**kwargs), self.loop
|
self.matrix_client.room_send(**kwargs), self.loop
|
||||||
).result()
|
).result()
|
||||||
if isinstance(result, nio.RoomSendError):
|
if isinstance(result, nio.RoomSendError):
|
||||||
raise Bridge_FatalMatrixException(str(result))
|
raise BridgeFatalMatrixException(str(result))
|
||||||
|
|
||||||
def _zulip_to_matrix(self, msg: Dict[str, Any]) -> None:
|
def _zulip_to_matrix(self, msg: Dict[str, Any]) -> None:
|
||||||
logging.debug("_zulip_to_matrix; msg: %s", msg)
|
logging.debug("_zulip_to_matrix; msg: %s", msg)
|
||||||
|
@ -303,12 +303,12 @@ class ZulipToMatrix:
|
||||||
for stream, _ in self.zulip_config["bridges"]:
|
for stream, _ in self.zulip_config["bridges"]:
|
||||||
result: Dict[str, Any] = self.zulip_client.get_stream_id(stream)
|
result: Dict[str, Any] = self.zulip_client.get_stream_id(stream)
|
||||||
if result["result"] == "error":
|
if result["result"] == "error":
|
||||||
raise Bridge_FatalZulipException(f"cannot access stream '{stream}': {result}")
|
raise BridgeFatalZulipException(f"cannot access stream '{stream}': {result}")
|
||||||
if result["result"] != "success":
|
if result["result"] != "success":
|
||||||
raise Bridge_FatalZulipException(f"cannot checkout stream id for stream '{stream}'")
|
raise BridgeFatalZulipException(f"cannot checkout stream id for stream '{stream}'")
|
||||||
result = self.zulip_client.add_subscriptions(streams=[{"name": stream}])
|
result = self.zulip_client.add_subscriptions(streams=[{"name": stream}])
|
||||||
if result["result"] != "success":
|
if result["result"] != "success":
|
||||||
raise Bridge_FatalZulipException(f"cannot subscribe to stream '{stream}': {result}")
|
raise BridgeFatalZulipException(f"cannot subscribe to stream '{stream}': {result}")
|
||||||
|
|
||||||
def get_matrix_room_for_zulip_message(self, msg: Dict[str, Any]) -> Optional[str]:
|
def get_matrix_room_for_zulip_message(self, msg: Dict[str, Any]) -> Optional[str]:
|
||||||
"""Check whether we want to process the given message.
|
"""Check whether we want to process the given message.
|
||||||
|
@ -459,10 +459,10 @@ def read_configuration(config_file: str) -> Dict[str, Dict[str, Any]]:
|
||||||
try:
|
try:
|
||||||
config.read(config_file)
|
config.read(config_file)
|
||||||
except configparser.Error as exception:
|
except configparser.Error as exception:
|
||||||
raise Bridge_ConfigException(str(exception))
|
raise BridgeConfigException(str(exception))
|
||||||
|
|
||||||
if set(config.sections()) < {"matrix", "zulip"}:
|
if set(config.sections()) < {"matrix", "zulip"}:
|
||||||
raise Bridge_ConfigException("Please ensure the configuration has zulip & matrix sections.")
|
raise BridgeConfigException("Please ensure the configuration has zulip & matrix sections.")
|
||||||
|
|
||||||
result: Dict[str, Dict[str, Any]] = {"matrix": {}, "zulip": {}}
|
result: Dict[str, Dict[str, Any]] = {"matrix": {}, "zulip": {}}
|
||||||
# For Matrix: create a mapping with the Matrix room_ids as keys and
|
# For Matrix: create a mapping with the Matrix room_ids as keys and
|
||||||
|
@ -484,7 +484,7 @@ def read_configuration(config_file: str) -> Dict[str, Dict[str, Any]]:
|
||||||
|
|
||||||
if section.startswith("additional_bridge"):
|
if section.startswith("additional_bridge"):
|
||||||
if section_keys != bridge_key_set:
|
if section_keys != bridge_key_set:
|
||||||
raise Bridge_ConfigException(
|
raise BridgeConfigException(
|
||||||
f"Please ensure the bridge configuration section {section} contain the following keys: {bridge_key_set}."
|
f"Please ensure the bridge configuration section {section} contain the following keys: {bridge_key_set}."
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -493,7 +493,7 @@ def read_configuration(config_file: str) -> Dict[str, Dict[str, Any]]:
|
||||||
result["matrix"]["bridges"][section_config["room_id"]] = zulip_target
|
result["matrix"]["bridges"][section_config["room_id"]] = zulip_target
|
||||||
elif section == "matrix":
|
elif section == "matrix":
|
||||||
if section_keys != matrix_full_key_set:
|
if section_keys != matrix_full_key_set:
|
||||||
raise Bridge_ConfigException(
|
raise BridgeConfigException(
|
||||||
"Please ensure the matrix configuration section contains the following keys: %s."
|
"Please ensure the matrix configuration section contains the following keys: %s."
|
||||||
% str(matrix_full_key_set)
|
% str(matrix_full_key_set)
|
||||||
)
|
)
|
||||||
|
@ -505,10 +505,10 @@ def read_configuration(config_file: str) -> Dict[str, Dict[str, Any]]:
|
||||||
|
|
||||||
# Verify the format of the Matrix user ID.
|
# Verify the format of the Matrix user ID.
|
||||||
if re.fullmatch(r"@[^:]+:.+", result["matrix"]["mxid"]) is None:
|
if re.fullmatch(r"@[^:]+:.+", result["matrix"]["mxid"]) is None:
|
||||||
raise Bridge_ConfigException("Malformatted mxid.")
|
raise BridgeConfigException("Malformatted mxid.")
|
||||||
elif section == "zulip":
|
elif section == "zulip":
|
||||||
if section_keys != zulip_full_key_set:
|
if section_keys != zulip_full_key_set:
|
||||||
raise Bridge_ConfigException(
|
raise BridgeConfigException(
|
||||||
"Please ensure the zulip configuration section contains the following keys: %s."
|
"Please ensure the zulip configuration section contains the following keys: %s."
|
||||||
% str(zulip_full_key_set)
|
% str(zulip_full_key_set)
|
||||||
)
|
)
|
||||||
|
@ -555,9 +555,9 @@ async def run(zulip_config: Dict[str, Any], matrix_config: Dict[str, Any], no_no
|
||||||
|
|
||||||
await asyncio.gather(matrix_to_zulip.run(), zulip_to_matrix.run())
|
await asyncio.gather(matrix_to_zulip.run(), zulip_to_matrix.run())
|
||||||
|
|
||||||
except Bridge_FatalMatrixException as exception:
|
except BridgeFatalMatrixException as exception:
|
||||||
sys.exit(f"Matrix bridge error: {exception}")
|
sys.exit(f"Matrix bridge error: {exception}")
|
||||||
except Bridge_FatalZulipException as exception:
|
except BridgeFatalZulipException as exception:
|
||||||
sys.exit(f"Zulip bridge error: {exception}")
|
sys.exit(f"Zulip bridge error: {exception}")
|
||||||
except zulip.ZulipError as exception:
|
except zulip.ZulipError as exception:
|
||||||
sys.exit(f"Zulip error: {exception}")
|
sys.exit(f"Zulip error: {exception}")
|
||||||
|
@ -571,7 +571,7 @@ async def run(zulip_config: Dict[str, Any], matrix_config: Dict[str, Any], no_no
|
||||||
|
|
||||||
def write_sample_config(target_path: str, zuliprc: Optional[str]) -> None:
|
def write_sample_config(target_path: str, zuliprc: Optional[str]) -> None:
|
||||||
if os.path.exists(target_path):
|
if os.path.exists(target_path):
|
||||||
raise Bridge_ConfigException(f"Path '{target_path}' exists; not overwriting existing file.")
|
raise BridgeConfigException(f"Path '{target_path}' exists; not overwriting existing file.")
|
||||||
|
|
||||||
sample_dict: OrderedDict[str, OrderedDict[str, str]] = OrderedDict(
|
sample_dict: OrderedDict[str, OrderedDict[str, str]] = OrderedDict(
|
||||||
(
|
(
|
||||||
|
@ -613,20 +613,20 @@ def write_sample_config(target_path: str, zuliprc: Optional[str]) -> None:
|
||||||
|
|
||||||
if zuliprc is not None:
|
if zuliprc is not None:
|
||||||
if not os.path.exists(zuliprc):
|
if not os.path.exists(zuliprc):
|
||||||
raise Bridge_ConfigException(f"Zuliprc file '{zuliprc}' does not exist.")
|
raise BridgeConfigException(f"Zuliprc file '{zuliprc}' does not exist.")
|
||||||
|
|
||||||
zuliprc_config: configparser.ConfigParser = configparser.ConfigParser()
|
zuliprc_config: configparser.ConfigParser = configparser.ConfigParser()
|
||||||
try:
|
try:
|
||||||
zuliprc_config.read(zuliprc)
|
zuliprc_config.read(zuliprc)
|
||||||
except configparser.Error as exception:
|
except configparser.Error as exception:
|
||||||
raise Bridge_ConfigException(str(exception))
|
raise BridgeConfigException(str(exception))
|
||||||
|
|
||||||
try:
|
try:
|
||||||
sample_dict["zulip"]["email"] = zuliprc_config["api"]["email"]
|
sample_dict["zulip"]["email"] = zuliprc_config["api"]["email"]
|
||||||
sample_dict["zulip"]["site"] = zuliprc_config["api"]["site"]
|
sample_dict["zulip"]["site"] = zuliprc_config["api"]["site"]
|
||||||
sample_dict["zulip"]["api_key"] = zuliprc_config["api"]["key"]
|
sample_dict["zulip"]["api_key"] = zuliprc_config["api"]["key"]
|
||||||
except KeyError as exception:
|
except KeyError as exception:
|
||||||
raise Bridge_ConfigException("You provided an invalid zuliprc file: " + str(exception))
|
raise BridgeConfigException("You provided an invalid zuliprc file: " + str(exception))
|
||||||
|
|
||||||
sample: configparser.ConfigParser = configparser.ConfigParser()
|
sample: configparser.ConfigParser = configparser.ConfigParser()
|
||||||
sample.read_dict(sample_dict)
|
sample.read_dict(sample_dict)
|
||||||
|
@ -648,7 +648,7 @@ def main() -> None:
|
||||||
if options.sample_config:
|
if options.sample_config:
|
||||||
try:
|
try:
|
||||||
write_sample_config(options.sample_config, options.zuliprc)
|
write_sample_config(options.sample_config, options.zuliprc)
|
||||||
except Bridge_ConfigException as exception:
|
except BridgeConfigException as exception:
|
||||||
print(f"Could not write sample config: {exception}")
|
print(f"Could not write sample config: {exception}")
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
if options.zuliprc is None:
|
if options.zuliprc is None:
|
||||||
|
@ -667,7 +667,7 @@ def main() -> None:
|
||||||
|
|
||||||
try:
|
try:
|
||||||
config: Dict[str, Dict[str, Any]] = read_configuration(options.config)
|
config: Dict[str, Dict[str, Any]] = read_configuration(options.config)
|
||||||
except Bridge_ConfigException as exception:
|
except BridgeConfigException as exception:
|
||||||
print(f"Could not parse config file: {exception}")
|
print(f"Could not parse config file: {exception}")
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
|
|
|
@ -256,7 +256,7 @@ class TicTacToeMessageHandler:
|
||||||
return "Welcome to tic-tac-toe!To make a move, type @-mention `move <number>` or `<number>`"
|
return "Welcome to tic-tac-toe!To make a move, type @-mention `move <number>` or `<number>`"
|
||||||
|
|
||||||
|
|
||||||
class ticTacToeHandler(GameAdapter):
|
class TicTacToeHandler(GameAdapter):
|
||||||
"""
|
"""
|
||||||
You can play tic-tac-toe! Make sure your message starts with
|
You can play tic-tac-toe! Make sure your message starts with
|
||||||
"@mention-bot".
|
"@mention-bot".
|
||||||
|
@ -304,4 +304,4 @@ def coords_from_command(cmd: str) -> str:
|
||||||
return cmd
|
return cmd
|
||||||
|
|
||||||
|
|
||||||
handler_class = ticTacToeHandler
|
handler_class = TicTacToeHandler
|
||||||
|
|
Loading…
Add table
Reference in a new issue