0
# Events
1
2
Event system module providing GitHub webhook event handling, event parsing, and sample event management for testing and development.
3
4
## Capabilities
5
6
### Event Handling
7
8
Base functionality for working with GitHub webhook events.
9
10
```python { .api }
11
class GhEvent:
12
"""
13
Base class for GitHub webhook events.
14
"""
15
```
16
17
### Sample Event Management
18
19
Functions for managing sample events for testing and development.
20
21
```python { .api }
22
def load_sample_events():
23
"""
24
Load sample GitHub events from storage.
25
26
Returns:
27
Sample event data for testing
28
"""
29
30
def save_sample_events():
31
"""
32
Save sample GitHub events to storage.
33
"""
34
```
35
36
### Extended API Methods
37
38
Additional methods added to GhApi for event-related operations.
39
40
```python { .api }
41
def list_events(self, per_page=30, page=1, **kwargs):
42
"""
43
Fetch public events for repo network, org, user, or all.
44
45
Parameters:
46
- per_page: int, number of events per page
47
- page: int, page number
48
- username: str, filter by username
49
- org: str, filter by organization
50
- owner: str, repository owner (requires repo)
51
- repo: str, repository name (requires owner)
52
53
Returns:
54
List of event objects with integer IDs
55
"""
56
57
def list_events_parallel(self, per_page=30, n_pages=8, **kwargs):
58
"""
59
Fetch events in parallel for better performance.
60
61
Parameters:
62
- per_page: int, number of events per page
63
- n_pages: int, number of pages to fetch in parallel
64
- username: str, filter by username
65
- org: str, filter by organization
66
- owner: str, repository owner (requires repo)
67
- repo: str, repository name (requires owner)
68
69
Returns:
70
List of event objects with integer IDs
71
"""
72
```
73
74
### Event Type Classes
75
76
Specific event classes for different GitHub webhook event types.
77
78
```python { .api }
79
class PageBuildEvent(GhEvent):
80
"""Page build event - triggered when GitHub Pages site is built."""
81
82
class ContentReferenceEvent(GhEvent):
83
"""Content reference event - triggered when content is referenced."""
84
85
class RepositoryImportEvent(GhEvent):
86
"""Repository import event - triggered during repository imports."""
87
88
class CreateEvent(GhEvent):
89
"""Create event - triggered when branch or tag is created."""
90
91
class WorkflowRunEvent(GhEvent):
92
"""Workflow run event - triggered by GitHub Actions workflow runs."""
93
94
class DeleteEvent(GhEvent):
95
"""Delete event - triggered when branch or tag is deleted."""
96
97
class OrganizationEvent(GhEvent):
98
"""Organization event - triggered by organization changes."""
99
100
class SponsorshipEvent(GhEvent):
101
"""Sponsorship event - triggered by GitHub Sponsors activity."""
102
103
class ProjectColumnEvent(GhEvent):
104
"""Project column event - triggered by project column changes."""
105
106
class PushEvent(GhEvent):
107
"""Push event - triggered by git pushes to repository."""
108
109
class ContextEvent(GhEvent):
110
"""Context event - triggered by context changes."""
111
112
class MilestoneEvent(GhEvent):
113
"""Milestone event - triggered by milestone changes."""
114
115
class ProjectCardEvent(GhEvent):
116
"""Project card event - triggered by project card changes."""
117
118
class ProjectEvent(GhEvent):
119
"""Project event - triggered by project changes."""
120
121
class PackageEvent(GhEvent):
122
"""Package event - triggered by GitHub Packages activity."""
123
124
class PullRequestEvent(GhEvent):
125
"""Pull request event - triggered by pull request activity."""
126
127
class RepositoryDispatchEvent(GhEvent):
128
"""Repository dispatch event - triggered by repository dispatch."""
129
130
class TeamAddEvent(GhEvent):
131
"""Team add event - triggered when team is added to repository."""
132
133
class WorkflowDispatchEvent(GhEvent):
134
"""Workflow dispatch event - triggered by manual workflow dispatch."""
135
136
class MemberEvent(GhEvent):
137
"""Member event - triggered by repository collaborator changes."""
138
139
class MetaEvent(GhEvent):
140
"""Meta event - triggered by repository metadata changes."""
141
142
class CodeScanningAlertEvent(GhEvent):
143
"""Code scanning alert event - triggered by code scanning alerts."""
144
145
class PublicEvent(GhEvent):
146
"""Public event - triggered when repository is made public."""
147
148
class NeedsEvent(GhEvent):
149
"""Needs event - triggered by workflow needs changes."""
150
151
class CheckRunEvent(GhEvent):
152
"""Check run event - triggered by check run activity."""
153
154
class SecurityAdvisoryEvent(GhEvent):
155
"""Security advisory event - triggered by security advisories."""
156
157
class PullRequestReviewCommentEvent(GhEvent):
158
"""Pull request review comment event - triggered by PR review comments."""
159
160
class OrgBlockEvent(GhEvent):
161
"""Organization block event - triggered by organization blocks."""
162
163
class CommitCommentEvent(GhEvent):
164
"""Commit comment event - triggered by commit comments."""
165
166
class WatchEvent(GhEvent):
167
"""Watch event - triggered when repository is starred."""
168
169
class MarketplacePurchaseEvent(GhEvent):
170
"""Marketplace purchase event - triggered by GitHub Marketplace purchases."""
171
172
class StarEvent(GhEvent):
173
"""Star event - triggered when repository is starred/unstarred."""
174
175
class InstallationRepositoriesEvent(GhEvent):
176
"""Installation repositories event - triggered by GitHub App installations."""
177
178
class CheckSuiteEvent(GhEvent):
179
"""Check suite event - triggered by check suite activity."""
180
181
class GithubAppAuthorizationEvent(GhEvent):
182
"""GitHub App authorization event - triggered by app authorization."""
183
184
class TeamEvent(GhEvent):
185
"""Team event - triggered by team changes."""
186
187
class StatusEvent(GhEvent):
188
"""Status event - triggered by commit status changes."""
189
190
class RepositoryVulnerabilityAlertEvent(GhEvent):
191
"""Repository vulnerability alert event - triggered by vulnerability alerts."""
192
193
class PullRequestReviewEvent(GhEvent):
194
"""Pull request review event - triggered by PR reviews."""
195
196
class LabelEvent(GhEvent):
197
"""Label event - triggered by label changes."""
198
199
class InstallationEvent(GhEvent):
200
"""Installation event - triggered by GitHub App installations."""
201
202
class ReleaseEvent(GhEvent):
203
"""Release event - triggered by release activity."""
204
205
class IssuesEvent(GhEvent):
206
"""Issues event - triggered by issue activity."""
207
208
class RepositoryEvent(GhEvent):
209
"""Repository event - triggered by repository changes."""
210
211
class GollumEvent(GhEvent):
212
"""Gollum event - triggered by wiki page changes."""
213
214
class MembershipEvent(GhEvent):
215
"""Membership event - triggered by organization membership changes."""
216
217
class DeploymentEvent(GhEvent):
218
"""Deployment event - triggered by deployment activity."""
219
220
class DeployKeyEvent(GhEvent):
221
"""Deploy key event - triggered by deploy key changes."""
222
223
class IssueCommentEvent(GhEvent):
224
"""Issue comment event - triggered by issue comments."""
225
226
class PingEvent(GhEvent):
227
"""Ping event - triggered by webhook ping."""
228
229
class DeploymentStatusEvent(GhEvent):
230
"""Deployment status event - triggered by deployment status changes."""
231
232
class ForkEvent(GhEvent):
233
"""Fork event - triggered when repository is forked."""
234
235
class ScheduleEvent(GhEvent):
236
"""Schedule event - triggered by scheduled workflows."""
237
```
238
239
### Event Utilities
240
241
Utilities for working with GitHub events.
242
243
```python { .api }
244
evt_emojis: dict # Emoji mappings for event types
245
described_evts: dict # Event descriptions
246
```
247
248
## Usage Examples
249
250
### Listing Public Events
251
252
```python
253
from ghapi.all import GhApi
254
255
api = GhApi(token='your_token')
256
257
# List all public events
258
events = api.list_events(per_page=50)
259
for event in events:
260
print(f"{event.type}: {event.actor.login} on {event.repo.name}")
261
262
# List events for specific user
263
user_events = api.list_events(username='octocat', per_page=25)
264
for event in user_events:
265
print(f"{event.created_at}: {event.type}")
266
267
# List events for organization
268
org_events = api.list_events(org='github', per_page=30)
269
for event in org_events:
270
print(f"{event.type} in {event.repo.name} by {event.actor.login}")
271
272
# List events for repository network
273
repo_events = api.list_events(owner='octocat', repo='Hello-World')
274
for event in repo_events:
275
print(f"{event.type}: {event.created_at}")
276
```
277
278
### Event Type Identification
279
280
```python
281
from ghapi.all import GhApi, Event
282
283
api = GhApi(token='your_token')
284
285
events = api.list_events(per_page=100)
286
event_counts = {}
287
288
for event in events:
289
event_type = event.type
290
event_counts[event_type] = event_counts.get(event_type, 0) + 1
291
292
# Handle specific event types
293
if event_type == 'PushEvent':
294
print(f"Push to {event.repo.name}: {len(event.payload.commits)} commits")
295
elif event_type == 'PullRequestEvent':
296
action = event.payload.action
297
pr = event.payload.pull_request
298
print(f"PR {action}: #{pr.number} - {pr.title}")
299
elif event_type == 'IssuesEvent':
300
action = event.payload.action
301
issue = event.payload.issue
302
print(f"Issue {action}: #{issue.number} - {issue.title}")
303
elif event_type == 'WatchEvent':
304
print(f"{event.actor.login} starred {event.repo.name}")
305
elif event_type == 'ForkEvent':
306
print(f"{event.actor.login} forked {event.repo.name}")
307
308
print("Event type counts:")
309
for event_type, count in sorted(event_counts.items()):
310
print(f" {event_type}: {count}")
311
```
312
313
### Working with Event Payloads
314
315
```python
316
from ghapi.all import GhApi
317
318
api = GhApi(token='your_token')
319
320
# Get events and examine payloads
321
events = api.list_events(owner='octocat', repo='Hello-World', per_page=20)
322
323
for event in events:
324
print(f"\\n--- {event.type} Event ---")
325
print(f"Actor: {event.actor.login}")
326
print(f"Repository: {event.repo.name}")
327
print(f"Created: {event.created_at}")
328
329
# Examine payload based on event type
330
payload = event.payload
331
332
if event.type == 'PushEvent':
333
print(f"Ref: {payload.ref}")
334
print(f"Commits: {len(payload.commits)}")
335
for commit in payload.commits[:3]: # Show first 3 commits
336
print(f" - {commit.sha[:8]}: {commit.message.split('\\n')[0]}")
337
338
elif event.type == 'PullRequestEvent':
339
pr = payload.pull_request
340
print(f"Action: {payload.action}")
341
print(f"PR #{pr.number}: {pr.title}")
342
print(f"State: {pr.state}")
343
print(f"Author: {pr.user.login}")
344
345
elif event.type == 'IssuesEvent':
346
issue = payload.issue
347
print(f"Action: {payload.action}")
348
print(f"Issue #{issue.number}: {issue.title}")
349
print(f"State: {issue.state}")
350
print(f"Labels: {[label.name for label in issue.labels]}")
351
352
elif event.type == 'CreateEvent':
353
print(f"Ref type: {payload.ref_type}")
354
print(f"Ref: {payload.ref}")
355
print(f"Description: {payload.description}")
356
357
elif event.type == 'ReleaseEvent':
358
release = payload.release
359
print(f"Action: {payload.action}")
360
print(f"Release: {release.tag_name}")
361
print(f"Name: {release.name}")
362
print(f"Draft: {release.draft}")
363
print(f"Prerelease: {release.prerelease}")
364
```
365
366
### Event Filtering and Analysis
367
368
```python
369
from ghapi.all import GhApi
370
from datetime import datetime, timedelta
371
from collections import defaultdict
372
373
api = GhApi(token='your_token')
374
375
# Analyze events for a specific timeframe
376
events = api.list_events(username='octocat', per_page=100)
377
378
# Filter events from last week
379
week_ago = datetime.now() - timedelta(days=7)
380
recent_events = []
381
382
for event in events:
383
event_date = datetime.fromisoformat(event.created_at.replace('Z', '+00:00'))
384
if event_date >= week_ago:
385
recent_events.append(event)
386
387
print(f"Events in last 7 days: {len(recent_events)}")
388
389
# Analyze activity patterns
390
activity_by_repo = defaultdict(int)
391
activity_by_type = defaultdict(int)
392
activity_by_day = defaultdict(int)
393
394
for event in recent_events:
395
activity_by_repo[event.repo.name] += 1
396
activity_by_type[event.type] += 1
397
398
event_date = datetime.fromisoformat(event.created_at.replace('Z', '+00:00'))
399
day_key = event_date.strftime('%Y-%m-%d')
400
activity_by_day[day_key] += 1
401
402
print("\\nMost active repositories:")
403
for repo, count in sorted(activity_by_repo.items(), key=lambda x: x[1], reverse=True)[:5]:
404
print(f" {repo}: {count} events")
405
406
print("\\nEvent type breakdown:")
407
for event_type, count in sorted(activity_by_type.items(), key=lambda x: x[1], reverse=True):
408
print(f" {event_type}: {count}")
409
410
print("\\nDaily activity:")
411
for day, count in sorted(activity_by_day.items()):
412
print(f" {day}: {count} events")
413
```
414
415
### Sample Event Management
416
417
```python
418
from ghapi.all import load_sample_events, save_sample_events
419
420
# Load sample events for testing
421
sample_events = load_sample_events()
422
if sample_events:
423
print(f"Loaded {len(sample_events)} sample events")
424
425
# Use sample events for testing webhook handlers
426
for event in sample_events[:5]:
427
print(f"Sample {event.get('type', 'unknown')} event")
428
429
# Save current events as samples for future testing
430
from ghapi.all import GhApi
431
432
api = GhApi(token='your_token')
433
current_events = api.list_events(per_page=50)
434
435
# Convert to sample format and save
436
save_sample_events()
437
print("Saved current events as samples")
438
```
439
440
### Event-Driven Automation
441
442
```python
443
from ghapi.all import GhApi
444
445
def process_repository_events(owner, repo, event_handler):
446
"""Process events for a repository with custom handler."""
447
api = GhApi(token='your_token')
448
449
events = api.list_events(owner=owner, repo=repo, per_page=50)
450
451
for event in events:
452
try:
453
event_handler(event)
454
except Exception as e:
455
print(f"Error processing {event.type} event: {e}")
456
457
def my_event_handler(event):
458
"""Custom event handler function."""
459
if event.type == 'PushEvent':
460
print(f"New push to {event.payload.ref} with {len(event.payload.commits)} commits")
461
462
# Check for specific files in commits
463
for commit in event.payload.commits:
464
if any('requirements.txt' in file for file in commit.added + commit.modified):
465
print(f" Dependencies changed in commit {commit.sha[:8]}")
466
467
elif event.type == 'PullRequestEvent' and event.payload.action == 'opened':
468
pr = event.payload.pull_request
469
print(f"New PR opened: #{pr.number} - {pr.title}")
470
471
# Check if PR needs review
472
if 'WIP' not in pr.title and not pr.draft:
473
print(f" PR #{pr.number} ready for review")
474
475
elif event.type == 'IssuesEvent' and event.payload.action == 'opened':
476
issue = event.payload.issue
477
print(f"New issue opened: #{issue.number} - {issue.title}")
478
479
# Check for bug reports
480
if 'bug' in [label.name.lower() for label in issue.labels]:
481
print(f" Bug report detected: #{issue.number}")
482
483
# Process events for a repository
484
process_repository_events('octocat', 'Hello-World', my_event_handler)
485
```