-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlibrary_usage.py
More file actions
373 lines (291 loc) Β· 12.9 KB
/
library_usage.py
File metadata and controls
373 lines (291 loc) Β· 12.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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
#!/usr/bin/env python3
"""
TicketQ Library Usage Examples
This file demonstrates how to use TicketQ as a Python library for programmatic
access to ticketing systems across different platforms.
Prerequisites:
- Install TicketQ: pip install "ticketq[cli]"
- Install adapter: pip install ticketq-zendesk
- Configure adapter: tq configure --adapter zendesk
"""
from datetime import datetime
from typing import List
import logging
from ticketq import TicketQLibrary
from ticketq.lib.models import LibraryTicket
from ticketq.models.exceptions import (
AuthenticationError,
NetworkError,
ConfigurationError,
PluginError,
TicketQError
)
# Configure logging to see progress messages
logging.basicConfig(level=logging.INFO)
def basic_usage():
"""Basic library usage example."""
print("=" * 60)
print("BASIC LIBRARY USAGE")
print("=" * 60)
try:
# Initialize with auto-detected adapter
print("π Initializing TicketQ library...")
tq = TicketQLibrary.from_config()
# Get adapter information
adapter_info = tq.get_adapter_info()
print(f"β
Using {adapter_info['display_name']} adapter v{adapter_info['version']}")
# Test connection
print("π Testing connection...")
if tq.test_connection():
print("β
Connection successful!")
else:
print("β Connection failed!")
return
# Get current user
user = tq.get_current_user()
if user:
print(f"π€ Authenticated as: {user.name} ({user.email})")
# Get basic ticket list
print("\nπ Fetching open tickets...")
tickets = tq.get_tickets(status="open")
print(f"Found {len(tickets)} open tickets")
# Display first few tickets
for i, ticket in enumerate(tickets[:3]):
print(f" #{ticket.id}: {ticket.title[:50]}...")
print(f" Status: {ticket.status}, Team: {ticket.team_name or 'Unassigned'}")
print(f" Age: {ticket.days_since_created} days")
if len(tickets) > 3:
print(f" ... and {len(tickets) - 3} more tickets")
except Exception as e:
print(f"β Error: {e}")
def advanced_filtering():
"""Advanced filtering and sorting examples."""
print("\n" + "=" * 60)
print("ADVANCED FILTERING & SORTING")
print("=" * 60)
try:
tq = TicketQLibrary.from_config()
# Multiple status filtering
print("π Getting tickets with multiple statuses...")
tickets = tq.get_tickets(status=["open", "pending"])
print(f"Found {len(tickets)} open/pending tickets")
# Assignee-only filtering
print("\nπ Getting your assigned tickets...")
my_tickets = tq.get_tickets(assignee_only=True)
print(f"Found {len(my_tickets)} tickets assigned to you")
# Group/team filtering
print("\nπ Getting tickets by team...")
groups = tq.get_groups()
if groups:
first_group = groups[0]
print(f"Filtering by team: {first_group.name}")
team_tickets = tq.get_tickets(groups=[first_group.name])
print(f"Found {len(team_tickets)} tickets for {first_group.name}")
# Sorting examples
print("\nπ Sorting examples...")
# Sort by staleness (most urgent first)
stale_tickets = tq.get_tickets(
status=["open", "pending"],
sort_by="days_updated"
)
print(f"Tickets sorted by staleness: {len(stale_tickets)}")
if stale_tickets:
stalest = stale_tickets[0]
print(f" Most stale: #{stalest.id} ({stalest.days_since_updated} days since update)")
# Sort by creation date (newest first)
recent_tickets = tq.get_tickets(sort_by="created_at")
print(f"Tickets sorted by creation date: {len(recent_tickets)}")
if recent_tickets:
newest = recent_tickets[0]
print(f" Newest: #{newest.id} (created {newest.days_since_created} days ago)")
except Exception as e:
print(f"β Error: {e}")
def search_functionality():
"""Search functionality example."""
print("\n" + "=" * 60)
print("SEARCH FUNCTIONALITY")
print("=" * 60)
try:
tq = TicketQLibrary.from_config()
# Search for tickets (adapter-specific query format)
print("π Searching tickets...")
# Note: Search query format depends on the adapter
# For Zendesk: can use Zendesk search syntax
# For Jira: would use JQL syntax
# For ServiceNow: would use ServiceNow query syntax
adapter_info = tq.get_adapter_info()
if adapter_info['name'] == 'zendesk':
# Example Zendesk search
search_results = tq.search_tickets("type:ticket status:open")
print(f"Found {len(search_results)} tickets from search")
# Display search results
for ticket in search_results[:3]:
print(f" #{ticket.id}: {ticket.title[:50]}...")
else:
print(f"Search syntax for {adapter_info['name']} adapter not shown in this example")
except Exception as e:
print(f"β Search error: {e}")
def csv_export_examples():
"""CSV export functionality examples."""
print("\n" + "=" * 60)
print("CSV EXPORT EXAMPLES")
print("=" * 60)
try:
tq = TicketQLibrary.from_config()
# Get tickets for export
tickets = tq.get_tickets(status=["open", "pending"], sort_by="days_updated")
if not tickets:
print("No tickets found for export")
return
print(f"π Exporting {len(tickets)} tickets...")
# Basic export with full descriptions
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
csv_file = f"tickets_export_{timestamp}.csv"
tq.export_to_csv(tickets, csv_file, include_full_description=True)
print(f"β
Full export saved to: {csv_file}")
# Export with truncated descriptions (faster processing)
csv_file_short = f"tickets_summary_{timestamp}.csv"
tq.export_to_csv(tickets, csv_file_short, include_full_description=False)
print(f"β
Summary export saved to: {csv_file_short}")
print(f"\nπ Export includes these columns:")
print(" β’ Ticket ID, Title, Status, Team Name")
print(" β’ Description (full or truncated)")
print(" β’ Created/Updated dates and age calculations")
print(" β’ Direct link to ticket in source system")
print(" β’ Adapter name for multi-system exports")
except Exception as e:
print(f"β Export error: {e}")
def error_handling_examples():
"""Comprehensive error handling examples."""
print("\n" + "=" * 60)
print("ERROR HANDLING EXAMPLES")
print("=" * 60)
# Example 1: Configuration errors
print("π§ͺ Testing configuration error handling...")
try:
# Try to use non-existent adapter
tq = TicketQLibrary.from_config(adapter_name="nonexistent")
except ConfigurationError as e:
print(f"β
Caught ConfigurationError: {e.message}")
if e.suggestions:
print(" Suggestions:", ", ".join(e.suggestions[:2]))
except PluginError as e:
print(f"β
Caught PluginError: {e.message}")
# Example 2: Connection testing with error handling
print("\nπ§ͺ Testing connection error handling...")
try:
tq = TicketQLibrary.from_config()
# Test various operations with error handling
tickets = tq.get_tickets()
print(f"β
Successfully retrieved {len(tickets)} tickets")
except AuthenticationError as e:
print(f"β Authentication failed: {e.message}")
print(" π‘ Tip: Check your API credentials with 'tq configure --test'")
except NetworkError as e:
print(f"β Network error: {e.message}")
print(" π‘ Tip: Check your internet connection and firewall settings")
except TicketQError as e:
print(f"β TicketQ error: {e.message}")
if e.suggestions:
print(" Suggestions:")
for suggestion in e.suggestions:
print(f" β’ {suggestion}")
except Exception as e:
print(f"β Unexpected error: {e}")
def progress_callback_example():
"""Progress callback functionality example."""
print("\n" + "=" * 60)
print("PROGRESS CALLBACK EXAMPLE")
print("=" * 60)
def progress_callback(message: str) -> None:
"""Custom progress callback with timestamp."""
timestamp = datetime.now().strftime("%H:%M:%S")
print(f"[{timestamp}] π {message}")
try:
# Initialize with progress callback
tq = TicketQLibrary.from_config(progress_callback=progress_callback)
print("π Operations will now show progress...")
# Operations will show progress via callback
tickets = tq.get_tickets(status=["open", "pending"])
if tickets:
# Export will also show progress
tq.export_to_csv(tickets[:5], "progress_example.csv")
except Exception as e:
print(f"β Error: {e}")
def multi_adapter_example():
"""Example of using multiple adapters (when available)."""
print("\n" + "=" * 60)
print("MULTI-ADAPTER EXAMPLE")
print("=" * 60)
# This example shows how you would work with multiple adapters
# when additional adapter packages are installed
adapters_to_try = ["zendesk", "jira", "servicenow"]
all_tickets: List[LibraryTicket] = []
for adapter_name in adapters_to_try:
try:
print(f"π Trying {adapter_name} adapter...")
tq = TicketQLibrary.from_config(adapter_name=adapter_name)
adapter_info = tq.get_adapter_info()
print(f"β
Connected to {adapter_info['display_name']}")
# Get tickets from this adapter
tickets = tq.get_tickets(status="open")
print(f" Found {len(tickets)} open tickets")
# Add to combined list
all_tickets.extend(tickets)
except (ConfigurationError, PluginError):
print(f"βοΈ {adapter_name} adapter not configured or not installed")
except Exception as e:
print(f"β Error with {adapter_name}: {e}")
if all_tickets:
print(f"\nπ Total tickets across all systems: {len(all_tickets)}")
# Group by adapter
by_adapter = {}
for ticket in all_tickets:
adapter = ticket.adapter_name
if adapter not in by_adapter:
by_adapter[adapter] = []
by_adapter[adapter].append(ticket)
for adapter, tickets in by_adapter.items():
print(f" {adapter}: {len(tickets)} tickets")
# Export combined results
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
combined_export = f"all_systems_tickets_{timestamp}.csv"
# Use any adapter for export (they all have the same export method)
if all_tickets:
tq = TicketQLibrary.from_config()
tq.export_to_csv(all_tickets, combined_export)
print(f"β
Combined export saved to: {combined_export}")
else:
print("βΉοΈ No tickets found across any configured adapters")
def main():
"""Run all examples."""
print("π« TicketQ Library Usage Examples")
print("=================================")
print("This script demonstrates various ways to use TicketQ as a Python library.")
print("Make sure you have configured at least one adapter before running!")
print()
try:
# Run all examples
basic_usage()
advanced_filtering()
search_functionality()
csv_export_examples()
progress_callback_example()
multi_adapter_example()
error_handling_examples()
print("\n" + "=" * 60)
print("β
ALL EXAMPLES COMPLETED")
print("=" * 60)
print("π‘ Next steps:")
print(" β’ Modify these examples for your specific use case")
print(" β’ Integrate TicketQ into your automation scripts")
print(" β’ Build web applications using the library API")
print(" β’ Check the README.md for more documentation")
except Exception as e:
print(f"\nβ Example execution failed: {e}")
print("π‘ Make sure you have:")
print(" 1. Installed TicketQ: pip install 'ticketq[cli]'")
print(" 2. Installed an adapter: pip install ticketq-zendesk")
print(" 3. Configured the adapter: tq configure --adapter zendesk")
if __name__ == "__main__":
main()