- Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathexample.py
More file actions
Latest commit
218 lines (171 loc) · 7.9 KB
/
Copy pathexample.py
File metadata and controls
218 lines (171 loc) · 7.9 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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
#!/usr/bin/env python3
"""
Example usage of the Wasender API SDK
This example demonstrates:
1. Sending a text message
2. Getting all contacts
Set the following environment variables before running:
- WASENDER_API_KEY: Your Wasender API key
- WASENDER_ACCESS_TOKEN: Your personal access token (optional)
Usage:
python example.py
"""
importos
importasyncio
fromwasenderapiimportcreate_sync_wasender, create_async_wasender
fromwasenderapi.modelsimportRetryConfig
fromwasenderapi.errorsimportWasenderAPIError
defget_api_credentials():
"""Get API credentials from environment variables."""
api_key=os.getenv('WASENDER_API_KEY')
access_token=os.getenv('WASENDER_ACCESS_TOKEN')
ifnotapi_key:
raiseValueError(
"WASENDER_API_KEY environment variable is required. "
"Please set it to your Wasender API key."
)
returnapi_key, access_token
defsync_example():
"""Example using the synchronous client."""
print("=== Synchronous Client Example ===")
try:
# Get credentials from environment
api_key, access_token=get_api_credentials()
# Create sync client with retry configuration
retry_config=RetryConfig(enabled=True, max_retries=3)
client=create_sync_wasender(
api_key=api_key,
personal_access_token=access_token,
retry_options=retry_config
)
# Example 1: Send a text message
print("\n1. Sending text message...")
try:
# Replace with an actual phone number for testing
phone_number="+1234567890"# Update this with a real number
message_text="Hello from Wasender API SDK! 🚀"
result=client.send_text(
to=phone_number,
text_body=message_text
)
print(f"✅ Message sent successfully!")
print(f" Status: {result.response.message}")
# Show rate limit info
ifresult.rate_limit:
print(f" Rate limit: {result.rate_limit.remaining}/{result.rate_limit.limit} remaining")
exceptWasenderAPIErrorase:
print(f"❌ Failed to send message: {e.message}")
ife.status_code==429:
print(f" Rate limited. Retry after: {e.retry_after} seconds")
elife.error_details:
print(f" Error details: {e.error_details}")
# Example 2: Get all contacts
print("\n2. Getting contacts...")
try:
contacts_result=client.get_contacts()
print(f"✅ Retrieved contacts successfully!")
print(f" Total contacts: {len(contacts_result.response.data)}")
# Show first few contacts
fori, contactinenumerate(contacts_result.response.data[:3]):
contact_name=contact.nameor"Unknown"
contact_id=contact.idor"No ID"
print(f" Contact {i+1}: {contact_name} ({contact_id})")
iflen(contacts_result.response.data) >3:
print(f" ... and {len(contacts_result.response.data) -3} more")
exceptWasenderAPIErrorase:
print(f"❌ Failed to get contacts: {e.message}")
ife.status_code==401:
print(" Check your API key and access token")
elife.error_details:
print(f" Error details: {e.error_details}")
exceptValueErrorase:
print(f"❌ Configuration error: {e}")
exceptExceptionase:
print(f"❌ Unexpected error: {e}")
asyncdefasync_example():
"""Example using the asynchronous client."""
print("\n=== Asynchronous Client Example ===")
try:
# Get credentials from environment
api_key, access_token=get_api_credentials()
# Create async client with retry configuration
retry_config=RetryConfig(enabled=True, max_retries=3)
asyncwithcreate_async_wasender(
api_key=api_key,
personal_access_token=access_token,
retry_options=retry_config
) asclient:
# Example 1: Send a text message
print("\n1. Sending text message (async)...")
try:
# Replace with an actual phone number for testing
phone_number="+1234567890"# Update this with a real number
message_text="Hello from Wasender API SDK (async)! 🚀"
result=awaitclient.send_text(
to=phone_number,
text_body=message_text
)
print(f"✅ Message sent successfully!")
print(f" Status: {result.response.message}")
# Show rate limit info
ifresult.rate_limit:
print(f" Rate limit: {result.rate_limit.remaining}/{result.rate_limit.limit} remaining")
exceptWasenderAPIErrorase:
print(f"❌ Failed to send message: {e.message}")
ife.status_code==429:
print(f" Rate limited. Retry after: {e.retry_after} seconds")
elife.error_details:
print(f" Error details: {e.error_details}")
# Example 2: Get all contacts
print("\n2. Getting contacts (async)...")
try:
contacts_result=awaitclient.get_contacts()
print(f"✅ Retrieved contacts successfully!")
print(f" Total contacts: {len(contacts_result.response.data)}")
# Show first few contacts
fori, contactinenumerate(contacts_result.response.data[:3]):
contact_name=contact.nameor"Unknown"
contact_id=contact.idor"No ID"
print(f" Contact {i+1}: {contact_name} ({contact_id})")
iflen(contacts_result.response.data) >3:
print(f" ... and {len(contacts_result.response.data) -3} more")
exceptWasenderAPIErrorase:
print(f"❌ Failed to get contacts: {e.message}")
ife.status_code==401:
print(" Check your API key and access token")
elife.error_details:
print(f" Error details: {e.error_details}")
exceptValueErrorase:
print(f"❌ Configuration error: {e}")
exceptExceptionase:
print(f"❌ Unexpected error: {e}")
defmain():
"""Main function to run both sync and async examples."""
print("Wasender API SDK Example")
print("="*40)
# Check if environment variables are set
api_key=os.getenv('WASENDER_API_KEY')
ifnotapi_key:
print("❌ Environment variable WASENDER_API_KEY is not set!")
print("\nTo run this example, please set the required environment variables:")
print(" WASENDER_API_KEY=your_api_key_here")
print(" WASENDER_ACCESS_TOKEN=your_access_token_here # Optional")
print("\nExample:")
print(" export WASENDER_API_KEY=wsk_...")
print(" export WASENDER_ACCESS_TOKEN=pat_...")
print(" python example.py")
return
print(f"✅ API Key found: {api_key[:10]}...")
access_token=os.getenv('WASENDER_ACCESS_TOKEN')
ifaccess_token:
print(f"✅ Access Token found: {access_token[:10]}...")
else:
print("ℹ️ Access Token not provided (optional)")
# Run synchronous example
sync_example()
# Run asynchronous example
asyncio.run(async_example())
print("\n"+"="*40)
print("Examples completed!")
if__name__=="__main__":
main()