From a711bef741f2347143770af7ca3807cbc18cbb44 Mon Sep 17 00:00:00 2001 From: YAPF Formatter Date: Wed, 29 Dec 2021 14:34:45 +0000 Subject: [PATCH] YAPF Formatter --- .../config_bot_allowed_interactive.py | 10 ++-- setup.py | 4 +- simplematrixbotlib/api.py | 56 +++++++++++++------ simplematrixbotlib/auth.py | 4 +- simplematrixbotlib/bot.py | 20 ++++--- simplematrixbotlib/callbacks.py | 3 +- simplematrixbotlib/config.py | 26 +++++---- simplematrixbotlib/listener.py | 2 + simplematrixbotlib/match.py | 3 +- tests/api/test_api.py | 3 +- tests/config/test_config.py | 20 +++++-- tests/listener/test_listener.py | 22 +++++--- tests/match/test_match.py | 9 ++- tests/match/test_messagematch.py | 7 +++ 14 files changed, 129 insertions(+), 60 deletions(-) diff --git a/examples/config-files/config_bot_allowed_interactive.py b/examples/config-files/config_bot_allowed_interactive.py index 0ac2976..fd3836e 100644 --- a/examples/config-files/config_bot_allowed_interactive.py +++ b/examples/config-files/config_bot_allowed_interactive.py @@ -42,13 +42,15 @@ async def echo(room, message): if match.command("allow"): bot.config.add_allowlist(set(match.args())) - await bot.api.send_text_message(room.room_id, - f'allowing {", ".join(arg for arg in match.args())}') + await bot.api.send_text_message( + room.room_id, + f'allowing {", ".join(arg for arg in match.args())}') if match.command("disallow"): bot.config.remove_allowlist(set(match.args())) - await bot.api.send_text_message(room.room_id, - f'disallowing {", ".join(arg for arg in match.args())}') + await bot.api.send_text_message( + room.room_id, + f'disallowing {", ".join(arg for arg in match.args())}') bot.run() diff --git a/setup.py b/setup.py index aebead1..55f7451 100644 --- a/setup.py +++ b/setup.py @@ -1 +1,3 @@ -import setuptools; setuptools.setup() \ No newline at end of file +import setuptools + +setuptools.setup() diff --git a/simplematrixbotlib/api.py b/simplematrixbotlib/api.py index cedb53e..bc22b8a 100644 --- a/simplematrixbotlib/api.py +++ b/simplematrixbotlib/api.py @@ -22,6 +22,7 @@ class Api: creds : simplematrixbotlib.Creds """ + def __init__(self, creds): """ Initializes the simplematrixbotlib.Api class. @@ -43,44 +44,63 @@ async def login(self): raise ValueError("Missing homeserver") if not self.creds.username: raise ValueError("Missing Username") - if not (self.creds.password or self.creds.login_token or self.creds.access_token): - raise ValueError("Missing password, login token, access token. Either password, login token or access token must be provided") + if not (self.creds.password or self.creds.login_token + or self.creds.access_token): + raise ValueError( + "Missing password, login token, access token. Either password, login token or access token must be provided" + ) - self.async_client = AsyncClient(homeserver=self.creds.homeserver, user=self.creds.username, device_id=self.creds.device_id) + self.async_client = AsyncClient(homeserver=self.creds.homeserver, + user=self.creds.username, + device_id=self.creds.device_id) if self.creds.password: - resp = await self.async_client.login(password=self.creds.password, device_name=self.creds.device_name) + resp = await self.async_client.login( + password=self.creds.password, + device_name=self.creds.device_name) elif self.creds.access_token: self.async_client.access_token = self.creds.access_token async with aiohttp.ClientSession() as session: - async with session.get(f'{self.creds.homeserver}/_matrix/client/r0/account/whoami?access_token={self.creds.access_token}') as response: - device_id = ast.literal_eval((await response.text()).replace(":false,", ":\"false\","))['device_id'] - user_id = ast.literal_eval((await response.text()).replace(":false,", ":\"false\","))['user_id'] - + async with session.get( + f'{self.creds.homeserver}/_matrix/client/r0/account/whoami?access_token={self.creds.access_token}' + ) as response: + device_id = ast.literal_eval( + (await + response.text()).replace(":false,", + ":\"false\","))['device_id'] + user_id = ast.literal_eval( + (await + response.text()).replace(":false,", + ":\"false\","))['user_id'] + self.async_client.device_id, self.creds.device_id = device_id, device_id self.async_client.user_id, self.creds.user_id = user_id, user_id resp = None elif self.creds.login_token: - resp = await self.async_client.login(token=self.creds.login_token, device_name=self.creds.device_name) - + resp = await self.async_client.login( + token=self.creds.login_token, + device_name=self.creds.device_name) + if isinstance(resp, nio.responses.LoginError): raise Exception(resp) - + async def check_valid_homeserver(self, homeserver: str) -> bool: - if not (homeserver.startswith('http://') or homeserver.startswith('https://')): + if not (homeserver.startswith('http://') + or homeserver.startswith('https://')): return False - + async with aiohttp.ClientSession() as session: try: - async with session.get(f'{homeserver}/_matrix/client/versions') as response: + async with session.get( + f'{homeserver}/_matrix/client/versions') as response: if response.status == 200: return True except aiohttp.client_exceptions.ClientConnectorError: return False - + return False async def send_text_message(self, room_id, message, msgtype='m.text'): @@ -184,7 +204,7 @@ async def send_markdown_message(self, room_id, message, msgtype='m.text'): "format": "org.matrix.custom.html", "formatted_body": - markdown.markdown(message, extensions=['nl2br']) + markdown.markdown( + message, + extensions=['nl2br']) }) - - diff --git a/simplematrixbotlib/auth.py b/simplematrixbotlib/auth.py index eb6d2da..77f760b 100644 --- a/simplematrixbotlib/auth.py +++ b/simplematrixbotlib/auth.py @@ -19,6 +19,7 @@ class Creds: The password for the bot to connect with. """ + def __init__(self, homeserver, username=None, @@ -67,7 +68,8 @@ def __init__(self, elif self.access_token: self._key = fw.key_from_pass(self.access_token) else: - raise ValueError("password or login_token or access_token is required") + raise ValueError( + "password or login_token or access_token is required") def session_read_file(self): """ diff --git a/simplematrixbotlib/bot.py b/simplematrixbotlib/bot.py index 2c0e252..3aa5fdd 100644 --- a/simplematrixbotlib/bot.py +++ b/simplematrixbotlib/bot.py @@ -17,7 +17,8 @@ class Bot: An instance of the simplematrixbotlib.Api class. """ - def __init__(self, creds, config = None): + + def __init__(self, creds, config=None): """ Initializes the simplematrixbotlib.Bot class. @@ -39,26 +40,29 @@ def __init__(self, creds, config = None): async def main(self): self.creds.session_read_file() - + if not (await self.api.check_valid_homeserver(self.creds.homeserver)): raise ValueError("Invalid Homeserver") await self.api.login() - - self.async_client = self.api.async_client + self.async_client = self.api.async_client - resp = await self.async_client.sync(timeout=65536, - full_state=False) #Ignore prior messages + resp = await self.async_client.sync(timeout=65536, full_state=False + ) #Ignore prior messages if isinstance(resp, SyncResponse): - print(f"Connected to {self.async_client.homeserver} as {self.async_client.user_id} ({self.async_client.device_id})") + print( + f"Connected to {self.async_client.homeserver} as {self.async_client.user_id} ({self.async_client.device_id})" + ) self.creds.session_write_file() if self._need_allow_homeserver_users: # allow (only) users from our own homeserver by default - hs: str = self.api.async_client.user_id[self.api.async_client.user_id.index(":")+1:].replace('.', '\\.') + hs: str = self.api.async_client.user_id[self.api.async_client. + user_id.index(":") + + 1:].replace('.', '\\.') self.config.allowlist = set([f"(.+):{hs}"]) self.callbacks = botlib.Callbacks(self.async_client, self) diff --git a/simplematrixbotlib/callbacks.py b/simplematrixbotlib/callbacks.py index 4ce7066..c9c49dc 100644 --- a/simplematrixbotlib/callbacks.py +++ b/simplematrixbotlib/callbacks.py @@ -8,6 +8,7 @@ class Callbacks: ... """ + def __init__(self, async_client, bot): self.async_client = async_client self.bot = bot @@ -19,7 +20,7 @@ async def setup_callbacks(self): """ if self.bot.config.join_on_invite: self.async_client.add_event_callback(self.invite_callback, - InviteMemberEvent) + InviteMemberEvent) for event_listener in self.bot.listener._registry: self.async_client.add_event_callback(event_listener[0], diff --git a/simplematrixbotlib/config.py b/simplematrixbotlib/config.py index 02a489f..0500e38 100644 --- a/simplematrixbotlib/config.py +++ b/simplematrixbotlib/config.py @@ -3,10 +3,12 @@ import re from typing import Set + @dataclass class Config: _join_on_invite: bool = True - _allowlist: Set[re.Pattern] = field(default_factory=set) #TODO: default to bot's homeserver + _allowlist: Set[re.Pattern] = field( + default_factory=set) #TODO: default to bot's homeserver _blocklist: Set[re.Pattern] = field(default_factory=set) def _check_set_regex(self, value: Set[str]) -> Set[re.Pattern]: @@ -15,7 +17,9 @@ def _check_set_regex(self, value: Set[str]) -> Set[re.Pattern]: try: tmp = re.compile(v) except re.error: - print(f"{v} is not a valid regular expression. Ignoring your list update.") + print( + f"{v} is not a valid regular expression. Ignoring your list update." + ) return new_list.add(tmp) return new_list @@ -35,15 +39,15 @@ def load_toml(self, file_path: str) -> None: self._load_config_dict(config_dict) def save_toml(self, file_path: str) -> None: - tmp = {'simplematrixbotlib': - {'config': - { - 'join_on_invite': self._join_on_invite, - 'allowlist': [l.pattern for l in self._allowlist], - 'blocklist': [l.pattern for l in self._blocklist] - } - } - } + tmp = { + 'simplematrixbotlib': { + 'config': { + 'join_on_invite': self._join_on_invite, + 'allowlist': [l.pattern for l in self._allowlist], + 'blocklist': [l.pattern for l in self._blocklist] + } + } + } with open(file_path, 'w') as file: toml.dump(tmp, file) diff --git a/simplematrixbotlib/listener.py b/simplematrixbotlib/listener.py index 06038d4..b4632af 100644 --- a/simplematrixbotlib/listener.py +++ b/simplematrixbotlib/listener.py @@ -2,12 +2,14 @@ class Listener: + def __init__(self, bot): self._bot = bot self._registry = [] self._startup_registry = [] def on_custom_event(self, event): + def wrapper(func): if [func, event] in self._registry: func() diff --git a/simplematrixbotlib/match.py b/simplematrixbotlib/match.py index bb1a952..835b3a8 100644 --- a/simplematrixbotlib/match.py +++ b/simplematrixbotlib/match.py @@ -1,4 +1,3 @@ - class Match: """ Class with methods to filter events @@ -6,6 +5,7 @@ class Match: ... """ + def __init__(self, room, event, bot) -> None: """ Initializes the simplematrixbotlib.Match class. @@ -85,6 +85,7 @@ class MessageMatch(Match): ... """ + def __init__(self, room, event, bot, prefix="") -> None: """ Initializes the simplematrixbotlib.MessageMatch class. diff --git a/tests/api/test_api.py b/tests/api/test_api.py index 13b0e87..f646b75 100644 --- a/tests/api/test_api.py +++ b/tests/api/test_api.py @@ -1,6 +1,7 @@ import pytest import simplematrixbotlib as botlib + def test_check_valid_homeserver(): creds = botlib.Creds("https://example.com", "user", "pass") @@ -23,4 +24,4 @@ def test_check_valid_homeserver(): if 'LoginError: M_FORBIDDEN Invalid password' in str(e): pass else: - raise e \ No newline at end of file + raise e diff --git a/tests/config/test_config.py b/tests/config/test_config.py index 0a061a6..ac42796 100644 --- a/tests/config/test_config.py +++ b/tests/config/test_config.py @@ -4,7 +4,9 @@ import os.path import re -sample_config_path = os.path.join(pathlib.Path(__file__).parent, 'sample_config_files') +sample_config_path = os.path.join( + pathlib.Path(__file__).parent, 'sample_config_files') + def test_defaults(): config = botlib.Config() @@ -13,13 +15,16 @@ def test_defaults(): assert config.allowlist == set() assert config.blocklist == set() + def test_read_toml(): config = botlib.Config() config.load_toml(os.path.join(sample_config_path, 'config1.toml')) assert not config.join_on_invite - assert set(config.allowlist) == set(map(re.compile, ['.*:example\\.org', '@test:matrix\\.org'])) - assert set(config.blocklist) == set(map(re.compile, ['@test2:example\\.org'])) - + assert set(config.allowlist) == set( + map(re.compile, ['.*:example\\.org', '@test:matrix\\.org'])) + assert set(config.blocklist) == set( + map(re.compile, ['@test2:example\\.org'])) + config = botlib.Config() config.load_toml(os.path.join(sample_config_path, 'config2.toml')) assert config.join_on_invite @@ -35,6 +40,7 @@ def test_read_toml(): # TODO: test botlib.Bot() constructor creating a default Config + def test_manual_set(): config = botlib.Config() config.join_on_invite = True @@ -47,7 +53,8 @@ def test_manual_set(): config.allowlist = {'.*:example\\.org'} assert re.compile('.*:example\\.org') in config.allowlist config.add_allowlist({'@test:matrix\\.org'}) - assert config.allowlist == set(map(re.compile, ['.*:example\\.org', '@test:matrix\\.org'])) + assert config.allowlist == set( + map(re.compile, ['.*:example\\.org', '@test:matrix\\.org'])) config.remove_allowlist({'.*:example\\.org'}) assert config.allowlist == set(map(re.compile, ['@test:matrix\\.org'])) config.allowlist = {'*:example\\.org'} @@ -56,7 +63,8 @@ def test_manual_set(): config.blocklist = {'.*:example\\.org'} assert re.compile('.*:example\\.org') in config.blocklist config.add_blocklist({'@test:matrix\\.org'}) - assert config.blocklist == set(map(re.compile, ['.*:example\\.org', '@test:matrix\\.org'])) + assert config.blocklist == set( + map(re.compile, ['.*:example\\.org', '@test:matrix\\.org'])) config.remove_blocklist({'.*:example\\.org'}) assert config.blocklist == set(map(re.compile, ['@test:matrix\\.org'])) config.blocklist = {'*:example\\.org'} diff --git a/tests/listener/test_listener.py b/tests/listener/test_listener.py index 83c5857..32447dd 100644 --- a/tests/listener/test_listener.py +++ b/tests/listener/test_listener.py @@ -9,46 +9,54 @@ listener = Listener(mock_bot) + def test_init(): assert isinstance(listener._bot, mock.MagicMock) assert listener._registry == [] assert listener._startup_registry == [] + def test_on_custom_event(): + @listener.on_custom_event(mock_event) def example(): return "example" - + def check(): for func_event in listener._registry: if func_event[0]() == "example" and func_event[1] == mock_event: return True return False - + assert check() == True + def test_on_message_event(): + @listener.on_message_event def example2(): return "example2" - + def check(): for func_event in listener._registry: - if func_event[0]() == "example2" and func_event[1] == RoomMessageText: + if func_event[0]( + ) == "example2" and func_event[1] == RoomMessageText: return True return False - + assert check() == True + def test_on_startup(): + @listener.on_startup def example3(): return "example3" - + def check(): for func in listener._startup_registry: if func() == "example3": return True return False - assert check() \ No newline at end of file + assert check() diff --git a/tests/match/test_match.py b/tests/match/test_match.py index a4ceae3..23f862e 100644 --- a/tests/match/test_match.py +++ b/tests/match/test_match.py @@ -15,17 +15,23 @@ match_config = Match(mock_room, mock_event, mock_bot) match_config._bot.config = Config() -match_config._bot.config.load_toml(os.path.join(pathlib.Path(__file__).parent.parent, 'config', 'sample_config_files', 'config1.toml')) +match_config._bot.config.load_toml( + os.path.join( + pathlib.Path(__file__).parent.parent, 'config', 'sample_config_files', + 'config1.toml')) + def test_init(): assert isinstance(match.room, mock.MagicMock) assert isinstance(match.event, mock.MagicMock) assert isinstance(match._bot, mock.MagicMock) + def test_is_from_userid(): assert match.is_from_userid("123") assert not match.is_from_userid("456") + def test_allow_block(): match_config.event.sender = "@test:example.org" assert match_config.is_from_allowed_user() @@ -39,5 +45,6 @@ def test_allow_block(): match_config.event.sender = "@test2:matrix.org" assert not match_config.is_from_allowed_user() + def test_is_not_from_this_bot(): assert match.is_not_from_this_bot() diff --git a/tests/match/test_messagematch.py b/tests/match/test_messagematch.py index adfda4c..e33c940 100644 --- a/tests/match/test_messagematch.py +++ b/tests/match/test_messagematch.py @@ -19,10 +19,12 @@ match3 = MessageMatch(mock_room, mock_event, mock_bot, prefix2) match4 = MessageMatch(mock_room, mock_event2, mock_bot, prefix) + def test_init(): assert issubclass(MessageMatch, Match) assert match._prefix == prefix + def test_command(): assert match.command() == "help" assert match.command("help") == True @@ -30,24 +32,29 @@ def test_command(): assert match2.command() == "p!help" assert match2.command("p!help") == True + def test_prefix(): assert match.prefix() == True assert match3.prefix() == False assert match2.prefix() == True + def test_args(): assert match.args() == ["example"] assert match4.args() == [] + def test_contains(): assert match.contains("!h") == True assert match.contains("lp exam") == True assert match.contains("nothing") == False + match = MessageMatch(mock_room, mock_event, mock_bot, prefix) + def test_init(): assert issubclass(MessageMatch, Match) assert match._prefix == prefix