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

Commit

Permalink
YAPF Formatter
Browse files Browse the repository at this point in the history
  • Loading branch information
YAPF Formatter committed Dec 29, 2021
1 parent c72598a commit a711bef
Show file tree
Hide file tree
Showing 14 changed files with 129 additions and 60 deletions.
10 changes: 6 additions & 4 deletions examples/config-files/config_bot_allowed_interactive.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
4 changes: 3 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
import setuptools; setuptools.setup()
import setuptools

setuptools.setup()
56 changes: 38 additions & 18 deletions simplematrixbotlib/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ class Api:
creds : simplematrixbotlib.Creds
"""

def __init__(self, creds):
"""
Initializes the simplematrixbotlib.Api class.
Expand All @@ -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'):
Expand Down Expand Up @@ -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'])
})


4 changes: 3 additions & 1 deletion simplematrixbotlib/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ class Creds:
The password for the bot to connect with.
"""

def __init__(self,
homeserver,
username=None,
Expand Down Expand Up @@ -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):
"""
Expand Down
20 changes: 12 additions & 8 deletions simplematrixbotlib/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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)
Expand Down
3 changes: 2 additions & 1 deletion simplematrixbotlib/callbacks.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ class Callbacks:
...
"""

def __init__(self, async_client, bot):
self.async_client = async_client
self.bot = bot
Expand All @@ -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],
Expand Down
26 changes: 15 additions & 11 deletions simplematrixbotlib/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]:
Expand All @@ -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
Expand All @@ -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)

Expand Down
2 changes: 2 additions & 0 deletions simplematrixbotlib/listener.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
3 changes: 2 additions & 1 deletion simplematrixbotlib/match.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@

class Match:
"""
Class with methods to filter events
...
"""

def __init__(self, room, event, bot) -> None:
"""
Initializes the simplematrixbotlib.Match class.
Expand Down Expand Up @@ -85,6 +85,7 @@ class MessageMatch(Match):
...
"""

def __init__(self, room, event, bot, prefix="") -> None:
"""
Initializes the simplematrixbotlib.MessageMatch class.
Expand Down
3 changes: 2 additions & 1 deletion tests/api/test_api.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import pytest
import simplematrixbotlib as botlib


def test_check_valid_homeserver():

creds = botlib.Creds("https://example.com", "user", "pass")
Expand All @@ -23,4 +24,4 @@ def test_check_valid_homeserver():
if 'LoginError: M_FORBIDDEN Invalid password' in str(e):
pass
else:
raise e
raise e
20 changes: 14 additions & 6 deletions tests/config/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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'}
Expand All @@ -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'}
Expand Down
Loading

0 comments on commit a711bef

Please sign in to comment.