-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpractical_example.py
More file actions
168 lines (126 loc) · 5.24 KB
/
practical_example.py
File metadata and controls
168 lines (126 loc) · 5.24 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
#!/usr/bin/env python3
"""
GetResponse API - Practical Contact Management Example
=====================================================
This script demonstrates practical usage of the GetResponseClient
for adding and removing contacts from campaigns.
Features demonstrated:
- Adding contacts to specific campaigns
- Removing contacts by email
- Error handling and validation
- Batch operations
Author: Agent Zero
Date: 2025-11-06
"""
import os
from getresponse_client import GetResponseClient
def add_contact_example(client, campaign_id):
"""Example of adding a contact to a campaign."""
# Example contact data
contact_data = {
'email': 'test.user@example.com',
'name': 'Test User',
'campaign_id': campaign_id
}
try:
print(f"\n➕ Adding contact: {contact_data['email']}")
result = client.add_contact(
email=contact_data['email'],
campaign_id=contact_data['campaign_id'],
name=contact_data['name']
)
print(f"✅ Contact added successfully!")
print(f" Contact ID: {result.get('contactId', 'N/A')}")
return result
except ValueError as e:
print(f"❌ Failed to add contact: {e}")
return None
def remove_contact_example(client, email):
"""Example of removing a contact by email."""
try:
print(f"\n➖ Removing contact: {email}")
# First, check if contact exists
contact = client.get_contact_by_email(email)
if contact:
print(f" Found contact: {contact.get('name', 'No Name')}")
# Remove the contact
success = client.remove_contact_by_email(email)
if success:
print("✅ Contact removed successfully!")
else:
print("❌ Failed to remove contact")
else:
print("⚠️ Contact not found, nothing to remove")
except ValueError as e:
print(f"❌ Error removing contact: {e}")
def batch_operations_example(client, campaign_id):
"""Example of batch contact operations."""
# Example batch of contacts
contacts_batch = [
{'email': 'user1@example.com', 'name': 'User One'},
{'email': 'user2@example.com', 'name': 'User Two'},
{'email': 'user3@example.com', 'name': 'User Three'}
]
print(f"\n🔄 Processing batch of {len(contacts_batch)} contacts")
added_contacts = []
for contact in contacts_batch:
try:
result = client.add_contact(
email=contact['email'],
campaign_id=campaign_id,
name=contact['name']
)
print(f"✅ Added: {contact['email']}")
added_contacts.append(contact['email'])
except ValueError as e:
print(f"❌ Failed to add {contact['email']}: {e}")
return added_contacts
def main():
"""Main function demonstrating practical usage."""
try:
# Initialize client
client = GetResponseClient()
print("🔧 GetResponse Practical Examples")
print("=" * 50)
# Test connection
if not client.test_connection():
print("❌ Connection failed. Please check your API key.")
return
print("✅ Connection successful!")
# Get campaigns to work with
campaigns = client.get_campaigns()
if not campaigns:
print("❌ No campaigns found in your account.")
return
# Use the first campaign for examples
campaign = campaigns[0]
campaign_id = campaign['campaignId']
print(f"\n🎯 Using campaign: {campaign['name']} (ID: {campaign_id})")
# Example 1: Add a contact
added_contact = add_contact_example(client, campaign_id)
# Example 2: Remove the contact we just added (if successful)
if added_contact:
remove_contact_example(client, 'test.user@example.com')
# Example 3: Batch operations (commented out to prevent accidental execution)
# print("\n💡 Uncomment the batch_operations_example call to test batch operations")
# added_emails = batch_operations_example(client, campaign_id)
#
# # Clean up batch contacts
# if added_emails:
# print(f"\n🧹 Cleaning up {len(added_emails)} test contacts...")
# for email in added_emails:
# remove_contact_example(client, email)
print("\n" + "=" * 50)
print("🎉 Practical examples completed!")
print("\n📝 Usage Tips:")
print("• Always handle exceptions when making API calls")
print("• Validate email addresses before adding")
print("• Use get_campaigns() to find the right campaign IDs")
print("• Implement rate limiting for batch operations")
except ValueError as e:
print(f"\n❌ Setup Error: {e}")
print("\n🔧 Please ensure you have:")
print("1. Created a .env file with GETRESPONSE_API_KEY")
print("2. Installed requirements: pip install -r requirements.txt")
if __name__ == "__main__":
main()