Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Spond.get_messages: add max_chats parameter (default 100) and populate Spond.messages. #146

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,9 @@ Optional parameters allow filtering by start and end datetimes, group and subgro
### get_person()
Get a member's details.

### get_messages()
Get all your messages.
### get_messages(max_chats=100)
Get chats, limited to 100 by default.
Optional parameter allows more events to be returned.

### send_message(text, user=None, group_uid=None, chat_id=None)
Send a message with content `text`.
Expand Down
37 changes: 22 additions & 15 deletions manual_test_functions.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""Use Spond 'get' functions to summarise available data.

Intended as a simple end-to-end test for assurance when making changes, where there are s
Intended as a simple end-to-end test for assurance when making changes, where there are
gaps in test suite coverage.

Doesn't yet use `get_person(user)` or any `send_`, `update_` methods."""
Expand All @@ -13,6 +13,10 @@

DUMMY_ID = "DUMMY_ID"

MAX_EVENTS = 10
MAX_CHATS = 10
MAX_TRANSACTIONS = 10


async def main() -> None:
s = spond.Spond(username=username, password=password)
Expand All @@ -27,19 +31,19 @@ async def main() -> None:

# EVENTS

print("\nGetting up to 10 events...")
events = await s.get_events(max_events=10)
print(f"\nGetting up to {MAX_EVENTS} events...")
events = await s.get_events(max_events=MAX_EVENTS)
print(f"{len(events)} events:")
for i, event in enumerate(events):
print(f"[{i}] {_event_summary(event)}")

# MESSAGES
# CHATS (MESSAGES)

print("\nGetting up to 10 messages...")
messages = await s.get_messages()
print(f"{len(messages)} messages:")
for i, message in enumerate(messages):
print(f"[{i}] {_message_summary(message)}")
print(f"\nGetting up to {MAX_CHATS} chats...")
chats = await s.get_messages(max_chats=MAX_CHATS)
print(f"{len(chats)} chats:")
for i, chat in enumerate(chats):
print(f"[{i}] {_chat_summary(chat)}")

# ATTENDANCE EXPORT

Expand All @@ -56,8 +60,10 @@ async def main() -> None:

# SPOND CLUB
sc = club.SpondClub(username=username, password=password)
print("\nGetting up to 10 transactions...")
transactions = await sc.get_transactions(club_id=club_id, max_items=10)
print(f"\nGetting up to {MAX_TRANSACTIONS} transactions...")
transactions = await sc.get_transactions(
club_id=club_id, max_items=MAX_TRANSACTIONS
)
print(f"{len(transactions)} transactions:")
for i, t in enumerate(transactions):
print(f"[{i}] {_transaction_summary(t)}")
Expand All @@ -76,11 +82,12 @@ def _event_summary(event) -> str:
)


def _message_summary(message) -> str:
def _chat_summary(chat) -> str:
msg_text = chat["message"].get("text", "")
return (
f"id='{message['id']}', "
f"timestamp='{message['message']['timestamp']}', "
f"text={_abbreviate(message['message']['text'] if message['message'].get('text') else '', length=64)}, "
f"id='{chat['id']}', "
f"timestamp='{chat['message']['timestamp']}', "
f"text={_abbreviate(msg_text, length=64)}"
)


Expand Down
53 changes: 39 additions & 14 deletions spond/spond.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ def __init__(self, username: str, password: str) -> None:
self.auth = None
self.groups = None
self.events = None
self.messages = None

async def login_chat(self) -> None:
api_chat_url = f"{self.api_url}chat"
Expand All @@ -32,15 +33,16 @@ async def login_chat(self) -> None:
self.auth = result["auth"]

@_SpondBase.require_authentication
async def get_groups(self) -> list[dict]:
async def get_groups(self) -> Optional[list[dict]]:
"""
Get all groups.
Subject to authenticated user's access.
Retrieve all groups, subject to authenticated user's access.

Returns
-------
list of dict
Groups; each group is a dict.
list[dict] or None
A list of groups, each represented as a dictionary, or None if no groups
are available.

"""
url = f"{self.api_url}groups/"
async with self.clientsession.get(url, headers=self.auth_headers) as r:
Expand Down Expand Up @@ -116,12 +118,34 @@ async def get_person(self, user: str) -> dict:
raise KeyError(errmsg)

@_SpondBase.require_authentication
async def get_messages(self) -> list[dict]:
async def get_messages(self, max_chats: int = 100) -> Optional[list[dict]]:
"""
Retrieve messages (chats).

Parameters
----------
max_chats : int, optional
Set a limit on the number of chats returned.
For performance reasons, defaults to 100.
Uses `max` API parameter.

Returns
-------
list[dict] or None
A list of chats, each represented as a dictionary, or None if no chats
are available.

"""
if not self.auth:
await self.login_chat()
url = f"{self.chat_url}/chats/?max=10"
async with self.clientsession.get(url, headers={"auth": self.auth}) as r:
return await r.json()
url = f"{self.chat_url}/chats/"
async with self.clientsession.get(
url,
headers={"auth": self.auth},
params={"max": str(max_chats)},
) as r:
self.messages = await r.json()
return self.messages

@_SpondBase.require_authentication
async def _continue_chat(self, chat_id: str, text: str):
Expand Down Expand Up @@ -216,10 +240,9 @@ async def get_events(
max_start: Optional[datetime] = None,
min_start: Optional[datetime] = None,
max_events: int = 100,
) -> list[dict]:
) -> Optional[list[dict]]:
"""
Get events.
Subject to authenticated user's access.
Retrieve events.

Parameters
----------
Expand Down Expand Up @@ -255,8 +278,10 @@ async def get_events(

Returns
-------
list of dict
Events; each event is a dict.
list[dict] or None
A list of events, each represented as a dictionary, or None if no events
are available.

"""
url = f"{self.api_url}sponds/"
params = {
Expand Down