refactoring and cleaning up

main
parent cd038d5086
commit 6fc794fea1

@ -3,4 +3,4 @@
# W503 line break before binary operator
# W504 line break after binary operator
#ignore = E501,W503,W504
exclude = tests
exclude = tests,bullit.py

1
.gitignore vendored

@ -144,6 +144,7 @@ credentials.json
config.json
notflixbot.json
notflixbot.log
bullit.py
nio_store/
**/*-old.py
**/*-old

@ -11,7 +11,8 @@
},
"cmd_prefixes": {
"!c": "cmd"
"!c": "cmd",
"%key_sync": "key_sync"
},
"autotrust": false,

@ -26,7 +26,7 @@ def get_args():
return get_parser().parse_args()
# @logger.catch
@logger.catch
def main():
try:
args = get_args()

@ -73,7 +73,7 @@ class MatrixClient:
logger.debug(f"connecting to '{self.config.homeserver}'")
self._callbacks()
await self._set_creds()
await self._wrangle_keys()
await self._key_sync()
if self.config.avatar:
await self._avatar()
@ -135,7 +135,7 @@ class MatrixClient:
self.nio.add_event_callback(self._cb_message, (RoomMessageText,))
self.nio.add_response_callback(self._cb_sync, SyncResponse)
async def _wrangle_keys(self):
async def _key_sync(self, room=None, event=None):
if self.nio.should_upload_keys:
resp_upload = await self.nio.keys_upload()
logger.info(f"uploaded keys: {resp_upload}")
@ -151,6 +151,9 @@ class MatrixClient:
resp_claim = await self.nio.keys_claim(user) # noqa
logger.warning("claimed keys for: '{user}'")
if room is not None and event is not None:
await self.send_msg(room.room_id, "key sync: `ok`")
async def _login(self, passwd):
try:
resp = await self.nio.login(
@ -250,27 +253,33 @@ class MatrixClient:
logger.debug(f"room: {room_id}, user_id: {user_id}, msg: '{msg}'")
# "".split(" ")[0] -> ""
cmdmsg = event.body.split(' ')
prefix = cmdmsg[0]
if prefix in self.config.cmd_prefixes:
cmd = self.config.cmd_prefixes[prefix]
response = await self._cmd_respond(user_id, cmd, cmdmsg, room_id)
await self.send_msg(room_id, response)
cmd = event.body.strip().split(' ')
prefix = cmd[0]
else:
response = await self._phrase_respond(user_id, event.body, room_id)
if response is not None:
await self.send_msg(room_id, response)
handler_name = self.config.cmd_prefixes.get(prefix, None)
if handler_name == "key_sync":
await self._key_sync(room, event)
elif handler_name is not None:
await self._cmd_respond(room, event, handler_name)
async def _phrase_respond(self, user_id, msg, room_id):
if msg == "are you alive?":
return "no im a `robot`"
else:
return None
async def _cmd_respond(self, user_id, cmd, msg, room_id):
return f"user_id: `{user_id}`, cmd: `{cmd}`, msg: `{msg}`"
await self._phrase_respond(room, event)
async def _phrase_respond(self, room, event):
phrases = {
'are you alive?': 'no im a `robot`'
}
msg = event.body.strip()
response = phrases.get(msg, None)
if response is not None:
await self.send_msg(room.room_id, response)
async def _cmd_respond(self, room, event, handler_name):
h = handler_name
user_id = event.sender
msg = event.body
response = f"user_id: `{user_id}`, handler_name: {h}, msg: `{msg}`"
await self.send_msg(room.room_id, response)
async def send_msg(self, room, msg):
# msgtypes:

@ -20,7 +20,7 @@ def get_imdb_id_from_url(url):
imdb_id = path_parts[2]
return imdb_id
else:
raise ImdbError("not imdb url")
raise ImdbError("not an imdb url")
class TheMovieDB:
@ -39,15 +39,12 @@ class TheMovieDB:
r.raise_for_status()
j = r.json()
try:
return self.parse_tvdb(j)
except TvdbError:
info = self.parse_tvdb(j)
if info is None:
err = f"no results in tv or movies for '{imdb_id}'"
logger.error(err)
return err
except TvdbError as e:
logger.info(e)
return str(e)
raise TvdbError(err)
return info
def parse_tvdb(self, j):
if j['movie_results']:
@ -62,20 +59,23 @@ class TheMovieDB:
'release_date': m['release_date'],
'release_year': m['release_date'].split('-')[0],
'title': m['title'],
'original_title': m.get('original_title', ""),
'tmdb_id': str(m['id']),
'vote_average': m['vote_average']
}
elif j['tv_results']:
raise NotImplementedError("currenlty this only works for movies")
logger.warning("tv show requested")
raise NotImplementedError("currently this only works for movies")
else:
raise TvdbError("no result in tv or movies")
return None
class NotflixMatrixClient(MatrixClient):
async def _cmd_respond(self, user_id, cmd, msg, room_id):
url = msg[1].strip()
async def _cmd_respond(self, room, event, handler_name):
try:
cmd = event.body.strip().split(' ')
url = cmd[1].strip()
imdb_id = get_imdb_id_from_url(url)
tvdbapi = TheMovieDB(self.config.notflixbot['themoviedb_api_key'])
info = tvdbapi.search_imdb_id(imdb_id)
@ -96,7 +96,13 @@ class NotflixMatrixClient(MatrixClient):
# },
# ignore_unverified_devices=False
# )
return f"{info['title']} ({info['release_year']}) | [poster]({info['poster']})" # noqa
resp = f"{info['title']} ({info['release_year']}) | [poster]({info['poster']})" # noqa
await self.send_msg(room.room_id, resp)
except IndexError:
err = f"invalid command: '{cmd}'"
logger.error(err)
await self.send_msg(room.room_id, err)
except ImdbError:
return f"url fail: `{url}`"
except (ImdbError, TvdbError, NotImplementedError) as e:
await self.send_msg(room.room_id, f"error: {str(e)}")

@ -18,6 +18,7 @@ flake8 = "^4.0.1"
[tool.poetry.scripts]
notflixbot = "notflixbot.main:main"
bullit = "notflixbot.bullit:main"
[build-system]
requires = ["poetry-core>=1.0.0"]

@ -31,7 +31,7 @@ def test_config_file_sample_json():
assert len(conf['log']) == 4
assert conf['cmd_prefixes']["!c"] == "cmd"
assert len(conf['cmd_prefixes']) == 1
assert len(conf['cmd_prefixes']) == 2
assert conf['autotrust'] == False
assert conf['credentials_path'] == "credentials-sample.json"
assert conf['storage_path'] == "/var/lib/notflixbot/store"
@ -48,7 +48,7 @@ def test_config_parser():
assert conf.device_name == "sample"
assert conf.avatar is None
assert conf.cmd_prefixes["!c"] == "cmd"
assert len(conf.cmd_prefixes) == 1
assert len(conf.cmd_prefixes) == 2
assert conf.autotrust is False
assert conf.credentials_path == "credentials-sample.json"
assert conf.storage_path == "/var/lib/notflixbot/store"

Loading…
Cancel
Save