diff options
author | 2020-10-10 13:12:51 +0100 | |
---|---|---|
committer | 2020-10-10 13:12:51 +0100 | |
commit | 6b7322c4e43fb28da05b6ddcc39d1de4e718f223 (patch) | |
tree | ff7db8ed7ba47e660c2a5f327cfd2a3ecb720fca /pydis_site/apps/api/models/bot | |
parent | Merge pull request #378 from RohanJnr/user_endpoint (diff) | |
parent | Merge remote-tracking branch 'upstream/master' into feat/397-398-metricity-db... (diff) |
Merge pull request #409 from dementati/feat/397-398-metricity-db-and-api
Added metricity db connection and user bot API
Diffstat (limited to 'pydis_site/apps/api/models/bot')
-rw-r--r-- | pydis_site/apps/api/models/bot/metricity.py | 42 |
1 files changed, 42 insertions, 0 deletions
diff --git a/pydis_site/apps/api/models/bot/metricity.py b/pydis_site/apps/api/models/bot/metricity.py new file mode 100644 index 00000000..25b42fa2 --- /dev/null +++ b/pydis_site/apps/api/models/bot/metricity.py @@ -0,0 +1,42 @@ +from django.db import connections + + +class NotFound(Exception): + """Raised when an entity cannot be found.""" + + pass + + +class Metricity: + """Abstraction for a connection to the metricity database.""" + + def __init__(self): + self.cursor = connections['metricity'].cursor() + + def __enter__(self): + return self + + def __exit__(self, *_): + self.cursor.close() + + def user(self, user_id: str) -> dict: + """Query a user's data.""" + columns = ["verified_at"] + query = f"SELECT {','.join(columns)} FROM users WHERE id = '%s'" + self.cursor.execute(query, [user_id]) + values = self.cursor.fetchone() + + if not values: + raise NotFound() + + return dict(zip(columns, values)) + + def total_messages(self, user_id: str) -> int: + """Query total number of messages for a user.""" + self.cursor.execute("SELECT COUNT(*) FROM messages WHERE author_id = '%s'", [user_id]) + values = self.cursor.fetchone() + + if not values: + raise NotFound() + + return values[0] |