0
# Event Handling
1
2
Event listener registration and management using PyEE's event emitter pattern. The SlackEventAdapter inherits from BaseEventEmitter, providing comprehensive event handling capabilities for processing various Slack event types.
3
4
## Capabilities
5
6
### Event Listener Registration
7
8
Register callback functions to handle specific Slack event types using the decorator pattern or direct method calls.
9
10
```python { .api }
11
def on(self, event_type: str, callback: callable):
12
"""
13
Register an event listener for a specific event type.
14
15
Parameters:
16
- event_type: str - The Slack event type to listen for (e.g., "message", "reaction_added")
17
- callback: callable - Function to call when the event occurs
18
19
Returns:
20
The callback function (for use as decorator)
21
"""
22
```
23
24
### Event Emission
25
26
Emit events to registered listeners (primarily used internally for error handling).
27
28
```python { .api }
29
def emit(self, event_type: str, *args):
30
"""
31
Emit an event to all registered listeners.
32
33
Parameters:
34
- event_type: str - The event type to emit
35
- *args: Arguments to pass to event listeners
36
37
Returns:
38
None
39
"""
40
```
41
42
## Common Slack Event Types
43
44
The adapter can listen for any Slack event type. Common event types include:
45
46
- `"message"` - Messages posted in channels
47
- `"reaction_added"` - Emoji reactions added to messages
48
- `"reaction_removed"` - Emoji reactions removed from messages
49
- `"app_mention"` - App mentioned in messages
50
- `"team_join"` - New team members join
51
- `"user_change"` - User profile changes
52
- `"channel_created"` - New channels created
53
- `"error"` - Internal errors (signature verification failures, etc.)
54
55
## Event Data Structure
56
57
All Slack events (except "error") receive event data with this structure:
58
59
```python
60
{
61
"token": "verification_token", # Legacy verification token
62
"team_id": "T1234567890", # Slack team ID
63
"api_app_id": "A1234567890", # Slack app ID
64
"event": { # The actual event data
65
"type": "message", # Event type
66
"channel": "C1234567890", # Channel ID
67
"user": "U1234567890", # User ID
68
"text": "Hello world!", # Message content (for message events)
69
"ts": "1234567890.123456", # Timestamp
70
# ... other event-specific fields
71
},
72
"type": "event_callback", # Always "event_callback" for events
73
"event_id": "Ev1234567890", # Unique event ID
74
"event_time": 1234567890 # Event timestamp
75
}
76
```
77
78
## Usage Examples
79
80
### Decorator Pattern
81
82
```python
83
from slackeventsapi import SlackEventAdapter
84
85
slack_events_adapter = SlackEventAdapter(signing_secret="your_secret")
86
87
@slack_events_adapter.on("message")
88
def handle_message(event_data):
89
event = event_data["event"]
90
if event.get("subtype") is None: # Ignore special message subtypes
91
user = event["user"]
92
text = event["text"]
93
channel = event["channel"]
94
print(f"Message from {user} in {channel}: {text}")
95
96
@slack_events_adapter.on("reaction_added")
97
def handle_reaction(event_data):
98
event = event_data["event"]
99
emoji = event["reaction"]
100
user = event["user"]
101
print(f"User {user} added reaction: {emoji}")
102
```
103
104
### Direct Method Registration
105
106
```python
107
from slackeventsapi import SlackEventAdapter
108
109
slack_events_adapter = SlackEventAdapter(signing_secret="your_secret")
110
111
def app_mention_handler(event_data):
112
event = event_data["event"]
113
text = event["text"]
114
channel = event["channel"]
115
print(f"App mentioned in {channel}: {text}")
116
117
# Register handler directly
118
slack_events_adapter.on("app_mention", app_mention_handler)
119
```
120
121
### Error Handling
122
123
```python
124
from slackeventsapi import SlackEventAdapter
125
from slackeventsapi.server import SlackEventAdapterException
126
127
slack_events_adapter = SlackEventAdapter(signing_secret="your_secret")
128
129
@slack_events_adapter.on("error")
130
def error_handler(error):
131
if isinstance(error, SlackEventAdapterException):
132
print(f"Slack Events API Error: {error}")
133
if "Invalid request signature" in str(error):
134
print("Check your signing secret configuration")
135
elif "Invalid request timestamp" in str(error):
136
print("Request timestamp is too old (>5 minutes)")
137
else:
138
print(f"Unknown error: {error}")
139
```
140
141
### Multiple Event Types
142
143
```python
144
from slackeventsapi import SlackEventAdapter
145
146
slack_events_adapter = SlackEventAdapter(signing_secret="your_secret")
147
148
def universal_handler(event_data):
149
event_type = event_data["event"]["type"]
150
print(f"Received event: {event_type}")
151
152
# Register same handler for multiple event types
153
slack_events_adapter.on("message", universal_handler)
154
slack_events_adapter.on("reaction_added", universal_handler)
155
slack_events_adapter.on("app_mention", universal_handler)
156
```
157
158
### Conditional Event Processing
159
160
```python
161
from slackeventsapi import SlackEventAdapter
162
163
slack_events_adapter = SlackEventAdapter(signing_secret="your_secret")
164
165
@slack_events_adapter.on("message")
166
def handle_greetings(event_data):
167
event = event_data["event"]
168
169
# Only process direct messages (no subtype) containing "hi"
170
if (event.get("subtype") is None and
171
event.get("channel_type") == "im" and
172
"hi" in event.get("text", "").lower()):
173
174
user = event["user"]
175
print(f"Greeting from user {user}")
176
```