-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_client.py
More file actions
201 lines (173 loc) · 6.43 KB
/
example_client.py
File metadata and controls
201 lines (173 loc) · 6.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
"""Example client demonstrating notification service integration."""
import asyncio
import aiohttp
from typing import Optional
class NotificationClient:
"""Simple client for notification service."""
def __init__(self, base_url: str = "http://localhost:8002", api_token: Optional[str] = None):
"""Initialize client.
Args:
base_url: Notification service URL
api_token: API authentication token
"""
self.base_url = base_url.rstrip("/")
self.api_token = api_token
self.headers = {}
if api_token:
self.headers["X-API-Token"] = api_token
async def send_sms(self, notification_id: str, phone: str, message: str, priority: str = "medium") -> dict:
"""Send SMS notification.
Args:
notification_id: Unique notification ID
phone: Phone number in E.164 format
message: SMS message text
priority: Priority level (immediate/high/medium/low)
Returns:
API response dict
"""
async with aiohttp.ClientSession() as session:
async with session.post(
f"{self.base_url}/commands/add-notifications",
json={
"notifications": [{
"id": notification_id,
"type": "sms",
"priority": priority,
"payload": {
"phone": phone,
"message": message
}
}]
},
headers=self.headers
) as resp:
resp.raise_for_status()
return await resp.json()
async def send_push(
self,
notification_id: str,
title: str,
body: str,
device_tokens: Optional[list] = None,
topic: Optional[str] = None,
priority: str = "medium",
data: Optional[dict] = None
) -> dict:
"""Send push notification.
Args:
notification_id: Unique notification ID
title: Notification title
body: Notification body text
device_tokens: List of device tokens (for direct targeting)
topic: Topic name (for broadcast)
priority: Priority level
data: Additional data payload
Returns:
API response dict
"""
payload = {
"title": title,
"body": body
}
if device_tokens:
payload["device_tokens"] = device_tokens
if topic:
payload["topic"] = topic
if data:
payload["data"] = data
async with aiohttp.ClientSession() as session:
async with session.post(
f"{self.base_url}/commands/add-notifications",
json={
"notifications": [{
"id": notification_id,
"type": "push",
"priority": priority,
"payload": payload
}]
},
headers=self.headers
) as resp:
resp.raise_for_status()
return await resp.json()
async def trigger_send(self) -> dict:
"""Trigger immediate send cycle."""
async with aiohttp.ClientSession() as session:
async with session.post(
f"{self.base_url}/commands/run-now",
headers=self.headers
) as resp:
resp.raise_for_status()
return await resp.json()
async def list_notifications(self) -> dict:
"""List all notifications."""
async with aiohttp.ClientSession() as session:
async with session.get(
f"{self.base_url}/notifications",
headers=self.headers
) as resp:
resp.raise_for_status()
return await resp.json()
async def check_status(self) -> dict:
"""Check service health."""
async with aiohttp.ClientSession() as session:
async with session.get(
f"{self.base_url}/status",
headers=self.headers
) as resp:
resp.raise_for_status()
return await resp.json()
async def main():
"""Example usage."""
# Initialize client
client = NotificationClient(
base_url="http://localhost:8002",
api_token="your-secret-token" # Match your config.ini
)
# Check service status
print("Checking service status...")
status = await client.check_status()
print(f"Status: {status}")
# Send SMS
print("\nSending SMS...")
sms_result = await client.send_sms(
notification_id="example-sms-001",
phone="+393331234567",
message="Hello! This is a test SMS from the notification service.",
priority="high"
)
print(f"SMS Result: {sms_result}")
# Send push notification to specific devices
print("\nSending push notification to devices...")
push_result = await client.send_push(
notification_id="example-push-001",
title="Test Notification",
body="This is a test push notification",
device_tokens=["mock-token-1", "mock-token-2"],
priority="medium",
data={"type": "test", "timestamp": "2025-01-01T00:00:00Z"}
)
print(f"Push Result: {push_result}")
# Broadcast to topic
print("\nSending broadcast notification...")
broadcast_result = await client.send_push(
notification_id="example-broadcast-001",
title="Important Update",
body="New version available!",
topic="all-users",
priority="low"
)
print(f"Broadcast Result: {broadcast_result}")
# Trigger immediate processing
print("\nTriggering immediate send...")
await client.trigger_send()
# Wait a moment for processing
await asyncio.sleep(1)
# List notifications
print("\nListing notifications...")
notifications = await client.list_notifications()
print(f"Found {len(notifications.get('notifications', []))} notifications")
for notif in notifications.get("notifications", [])[:5]:
print(f" - {notif['id']}: {notif['type']} (sent: {notif.get('sent_ts') is not None})")
if __name__ == "__main__":
asyncio.run(main())