Skip to content
This repository was archived by the owner on May 22, 2024. It is now read-only.

Commit a711bef

Browse files
author
YAPF Formatter
committed
YAPF Formatter
1 parent c72598a commit a711bef

File tree

14 files changed

+129
-60
lines changed

14 files changed

+129
-60
lines changed

examples/config-files/config_bot_allowed_interactive.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -42,13 +42,15 @@ async def echo(room, message):
4242

4343
if match.command("allow"):
4444
bot.config.add_allowlist(set(match.args()))
45-
await bot.api.send_text_message(room.room_id,
46-
f'allowing {", ".join(arg for arg in match.args())}')
45+
await bot.api.send_text_message(
46+
room.room_id,
47+
f'allowing {", ".join(arg for arg in match.args())}')
4748

4849
if match.command("disallow"):
4950
bot.config.remove_allowlist(set(match.args()))
50-
await bot.api.send_text_message(room.room_id,
51-
f'disallowing {", ".join(arg for arg in match.args())}')
51+
await bot.api.send_text_message(
52+
room.room_id,
53+
f'disallowing {", ".join(arg for arg in match.args())}')
5254

5355

5456
bot.run()

setup.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,3 @@
1-
import setuptools; setuptools.setup()
1+
import setuptools
2+
3+
setuptools.setup()

simplematrixbotlib/api.py

Lines changed: 38 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ class Api:
2222
creds : simplematrixbotlib.Creds
2323
2424
"""
25+
2526
def __init__(self, creds):
2627
"""
2728
Initializes the simplematrixbotlib.Api class.
@@ -43,44 +44,63 @@ async def login(self):
4344
raise ValueError("Missing homeserver")
4445
if not self.creds.username:
4546
raise ValueError("Missing Username")
46-
if not (self.creds.password or self.creds.login_token or self.creds.access_token):
47-
raise ValueError("Missing password, login token, access token. Either password, login token or access token must be provided")
47+
if not (self.creds.password or self.creds.login_token
48+
or self.creds.access_token):
49+
raise ValueError(
50+
"Missing password, login token, access token. Either password, login token or access token must be provided"
51+
)
4852

49-
self.async_client = AsyncClient(homeserver=self.creds.homeserver, user=self.creds.username, device_id=self.creds.device_id)
53+
self.async_client = AsyncClient(homeserver=self.creds.homeserver,
54+
user=self.creds.username,
55+
device_id=self.creds.device_id)
5056

5157
if self.creds.password:
52-
resp = await self.async_client.login(password=self.creds.password, device_name=self.creds.device_name)
58+
resp = await self.async_client.login(
59+
password=self.creds.password,
60+
device_name=self.creds.device_name)
5361

5462
elif self.creds.access_token:
5563
self.async_client.access_token = self.creds.access_token
5664

5765
async with aiohttp.ClientSession() as session:
58-
async with session.get(f'{self.creds.homeserver}/_matrix/client/r0/account/whoami?access_token={self.creds.access_token}') as response:
59-
device_id = ast.literal_eval((await response.text()).replace(":false,", ":\"false\","))['device_id']
60-
user_id = ast.literal_eval((await response.text()).replace(":false,", ":\"false\","))['user_id']
61-
66+
async with session.get(
67+
f'{self.creds.homeserver}/_matrix/client/r0/account/whoami?access_token={self.creds.access_token}'
68+
) as response:
69+
device_id = ast.literal_eval(
70+
(await
71+
response.text()).replace(":false,",
72+
":\"false\","))['device_id']
73+
user_id = ast.literal_eval(
74+
(await
75+
response.text()).replace(":false,",
76+
":\"false\","))['user_id']
77+
6278
self.async_client.device_id, self.creds.device_id = device_id, device_id
6379
self.async_client.user_id, self.creds.user_id = user_id, user_id
6480
resp = None
6581

6682
elif self.creds.login_token:
67-
resp = await self.async_client.login(token=self.creds.login_token, device_name=self.creds.device_name)
68-
83+
resp = await self.async_client.login(
84+
token=self.creds.login_token,
85+
device_name=self.creds.device_name)
86+
6987
if isinstance(resp, nio.responses.LoginError):
7088
raise Exception(resp)
71-
89+
7290
async def check_valid_homeserver(self, homeserver: str) -> bool:
73-
if not (homeserver.startswith('http://') or homeserver.startswith('https://')):
91+
if not (homeserver.startswith('http://')
92+
or homeserver.startswith('https://')):
7493
return False
75-
94+
7695
async with aiohttp.ClientSession() as session:
7796
try:
78-
async with session.get(f'{homeserver}/_matrix/client/versions') as response:
97+
async with session.get(
98+
f'{homeserver}/_matrix/client/versions') as response:
7999
if response.status == 200:
80100
return True
81101
except aiohttp.client_exceptions.ClientConnectorError:
82102
return False
83-
103+
84104
return False
85105

86106
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'):
184204
"format":
185205
"org.matrix.custom.html",
186206
"formatted_body":
187-
markdown.markdown(message, extensions=['nl2br'])
207+
markdown.markdown(
208+
message,
209+
extensions=['nl2br'])
188210
})
189-
190-

simplematrixbotlib/auth.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ class Creds:
1919
The password for the bot to connect with.
2020
2121
"""
22+
2223
def __init__(self,
2324
homeserver,
2425
username=None,
@@ -67,7 +68,8 @@ def __init__(self,
6768
elif self.access_token:
6869
self._key = fw.key_from_pass(self.access_token)
6970
else:
70-
raise ValueError("password or login_token or access_token is required")
71+
raise ValueError(
72+
"password or login_token or access_token is required")
7173

7274
def session_read_file(self):
7375
"""

simplematrixbotlib/bot.py

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,8 @@ class Bot:
1717
An instance of the simplematrixbotlib.Api class.
1818
1919
"""
20-
def __init__(self, creds, config = None):
20+
21+
def __init__(self, creds, config=None):
2122
"""
2223
Initializes the simplematrixbotlib.Bot class.
2324
@@ -39,26 +40,29 @@ def __init__(self, creds, config = None):
3940
async def main(self):
4041

4142
self.creds.session_read_file()
42-
43+
4344
if not (await self.api.check_valid_homeserver(self.creds.homeserver)):
4445
raise ValueError("Invalid Homeserver")
4546

4647
await self.api.login()
47-
48-
self.async_client = self.api.async_client
4948

49+
self.async_client = self.api.async_client
5050

51-
resp = await self.async_client.sync(timeout=65536,
52-
full_state=False) #Ignore prior messages
51+
resp = await self.async_client.sync(timeout=65536, full_state=False
52+
) #Ignore prior messages
5353

5454
if isinstance(resp, SyncResponse):
55-
print(f"Connected to {self.async_client.homeserver} as {self.async_client.user_id} ({self.async_client.device_id})")
55+
print(
56+
f"Connected to {self.async_client.homeserver} as {self.async_client.user_id} ({self.async_client.device_id})"
57+
)
5658

5759
self.creds.session_write_file()
5860

5961
if self._need_allow_homeserver_users:
6062
# allow (only) users from our own homeserver by default
61-
hs: str = self.api.async_client.user_id[self.api.async_client.user_id.index(":")+1:].replace('.', '\\.')
63+
hs: str = self.api.async_client.user_id[self.api.async_client.
64+
user_id.index(":") +
65+
1:].replace('.', '\\.')
6266
self.config.allowlist = set([f"(.+):{hs}"])
6367

6468
self.callbacks = botlib.Callbacks(self.async_client, self)

simplematrixbotlib/callbacks.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ class Callbacks:
88
...
99
1010
"""
11+
1112
def __init__(self, async_client, bot):
1213
self.async_client = async_client
1314
self.bot = bot
@@ -19,7 +20,7 @@ async def setup_callbacks(self):
1920
"""
2021
if self.bot.config.join_on_invite:
2122
self.async_client.add_event_callback(self.invite_callback,
22-
InviteMemberEvent)
23+
InviteMemberEvent)
2324

2425
for event_listener in self.bot.listener._registry:
2526
self.async_client.add_event_callback(event_listener[0],

simplematrixbotlib/config.py

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,12 @@
33
import re
44
from typing import Set
55

6+
67
@dataclass
78
class Config:
89
_join_on_invite: bool = True
9-
_allowlist: Set[re.Pattern] = field(default_factory=set) #TODO: default to bot's homeserver
10+
_allowlist: Set[re.Pattern] = field(
11+
default_factory=set) #TODO: default to bot's homeserver
1012
_blocklist: Set[re.Pattern] = field(default_factory=set)
1113

1214
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]:
1517
try:
1618
tmp = re.compile(v)
1719
except re.error:
18-
print(f"{v} is not a valid regular expression. Ignoring your list update.")
20+
print(
21+
f"{v} is not a valid regular expression. Ignoring your list update."
22+
)
1923
return
2024
new_list.add(tmp)
2125
return new_list
@@ -35,15 +39,15 @@ def load_toml(self, file_path: str) -> None:
3539
self._load_config_dict(config_dict)
3640

3741
def save_toml(self, file_path: str) -> None:
38-
tmp = {'simplematrixbotlib':
39-
{'config':
40-
{
41-
'join_on_invite': self._join_on_invite,
42-
'allowlist': [l.pattern for l in self._allowlist],
43-
'blocklist': [l.pattern for l in self._blocklist]
44-
}
45-
}
46-
}
42+
tmp = {
43+
'simplematrixbotlib': {
44+
'config': {
45+
'join_on_invite': self._join_on_invite,
46+
'allowlist': [l.pattern for l in self._allowlist],
47+
'blocklist': [l.pattern for l in self._blocklist]
48+
}
49+
}
50+
}
4751
with open(file_path, 'w') as file:
4852
toml.dump(tmp, file)
4953

simplematrixbotlib/listener.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,14 @@
22

33

44
class Listener:
5+
56
def __init__(self, bot):
67
self._bot = bot
78
self._registry = []
89
self._startup_registry = []
910

1011
def on_custom_event(self, event):
12+
1113
def wrapper(func):
1214
if [func, event] in self._registry:
1315
func()

simplematrixbotlib/match.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
1-
21
class Match:
32
"""
43
Class with methods to filter events
54
65
...
76
87
"""
8+
99
def __init__(self, room, event, bot) -> None:
1010
"""
1111
Initializes the simplematrixbotlib.Match class.
@@ -85,6 +85,7 @@ class MessageMatch(Match):
8585
...
8686
8787
"""
88+
8889
def __init__(self, room, event, bot, prefix="") -> None:
8990
"""
9091
Initializes the simplematrixbotlib.MessageMatch class.

tests/api/test_api.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import pytest
22
import simplematrixbotlib as botlib
33

4+
45
def test_check_valid_homeserver():
56

67
creds = botlib.Creds("https://example.com", "user", "pass")
@@ -23,4 +24,4 @@ def test_check_valid_homeserver():
2324
if 'LoginError: M_FORBIDDEN Invalid password' in str(e):
2425
pass
2526
else:
26-
raise e
27+
raise e

0 commit comments

Comments
 (0)