forked from slackapi/bolt-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodels.py
More file actions
260 lines (224 loc) · 7.5 KB
/
models.py
File metadata and controls
260 lines (224 loc) · 7.5 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
# ----------------------
# Database tables
# ----------------------
from django.db import models
class SlackBot(models.Model):
client_id = models.TextField(null=False)
app_id = models.TextField(null=False)
enterprise_id = models.TextField(null=True)
enterprise_name = models.TextField(null=True)
team_id = models.TextField(null=True)
team_name = models.TextField(null=True)
bot_token = models.TextField(null=True)
bot_id = models.TextField(null=True)
bot_user_id = models.TextField(null=True)
bot_scopes = models.TextField(null=True)
is_enterprise_install = models.BooleanField(null=True)
installed_at = models.DateTimeField(null=False)
class Meta:
indexes = [
models.Index(
fields=["client_id", "enterprise_id", "team_id", "installed_at"]
),
]
class SlackInstallation(models.Model):
client_id = models.TextField(null=False)
app_id = models.TextField(null=False)
enterprise_id = models.TextField(null=True)
enterprise_name = models.TextField(null=True)
enterprise_url = models.TextField(null=True)
team_id = models.TextField(null=True)
team_name = models.TextField(null=True)
bot_token = models.TextField(null=True)
bot_id = models.TextField(null=True)
bot_user_id = models.TextField(null=True)
bot_scopes = models.TextField(null=True)
user_id = models.TextField(null=False)
user_token = models.TextField(null=True)
user_scopes = models.TextField(null=True)
incoming_webhook_url = models.TextField(null=True)
incoming_webhook_channel = models.TextField(null=True)
incoming_webhook_channel_id = models.TextField(null=True)
incoming_webhook_configuration_url = models.TextField(null=True)
is_enterprise_install = models.BooleanField(null=True)
token_type = models.TextField(null=True)
installed_at = models.DateTimeField(null=False)
class Meta:
indexes = [
models.Index(
fields=[
"client_id",
"enterprise_id",
"team_id",
"user_id",
"installed_at",
]
),
]
class SlackOAuthState(models.Model):
state = models.TextField(null=False)
expire_at = models.DateTimeField(null=False)
# ----------------------
# Bolt store implementations
# ----------------------
from logging import Logger
from typing import Optional
from uuid import uuid4
from django.db.models import F
from django.utils import timezone
from slack_sdk.oauth import InstallationStore, OAuthStateStore
from slack_sdk.oauth.installation_store import Bot, Installation
class DjangoInstallationStore(InstallationStore):
client_id: str
def __init__(
self,
client_id: str,
logger: Logger,
):
self.client_id = client_id
self._logger = logger
@property
def logger(self) -> Logger:
return self._logger
def save(self, installation: Installation):
i = installation.to_dict()
i["client_id"] = self.client_id
SlackInstallation(**i).save()
b = installation.to_bot().to_dict()
b["client_id"] = self.client_id
SlackBot(**b).save()
def find_bot(
self,
*,
enterprise_id: Optional[str],
team_id: Optional[str],
is_enterprise_install: Optional[bool] = False,
) -> Optional[Bot]:
e_id = enterprise_id or None
t_id = team_id or None
if is_enterprise_install:
t_id = None
rows = (
SlackBot.objects.filter(enterprise_id=e_id)
.filter(team_id=t_id)
.order_by(F("installed_at").desc())[:1]
)
if len(rows) > 0:
b = rows[0]
return Bot(
app_id=b.app_id,
enterprise_id=b.enterprise_id,
team_id=b.team_id,
bot_token=b.bot_token,
bot_id=b.bot_id,
bot_user_id=b.bot_user_id,
bot_scopes=b.bot_scopes,
installed_at=b.installed_at.timestamp(),
)
return None
def find_installation(
self,
*,
enterprise_id: Optional[str],
team_id: Optional[str],
user_id: Optional[str] = None,
is_enterprise_install: Optional[bool] = False,
) -> Optional[Installation]:
e_id = enterprise_id or None
t_id = team_id or None
if is_enterprise_install:
t_id = None
if user_id is None:
rows = (
SlackInstallation.objects.filter(enterprise_id=e_id)
.filter(team_id=t_id)
.order_by(F("installed_at").desc())[:1]
)
else:
rows = (
SlackInstallation.objects.filter(enterprise_id=e_id)
.filter(team_id=t_id)
.filter(user_id=user_id)
.order_by(F("installed_at").desc())[:1]
)
if len(rows) > 0:
i = rows[0]
return Installation(
app_id=i.app_id,
enterprise_id=i.enterprise_id,
team_id=i.team_id,
bot_token=i.bot_token,
bot_id=i.bot_id,
bot_user_id=i.bot_user_id,
bot_scopes=i.bot_scopes,
user_id=i.user_id,
user_token=i.user_token,
user_scopes=i.user_scopes,
incoming_webhook_url=i.incoming_webhook_url,
incoming_webhook_channel_id=i.incoming_webhook_channel_id,
incoming_webhook_configuration_url=i.incoming_webhook_configuration_url,
installed_at=i.installed_at.timestamp(),
)
return None
class DjangoOAuthStateStore(OAuthStateStore):
expiration_seconds: int
def __init__(
self,
expiration_seconds: int,
logger: Logger,
):
self.expiration_seconds = expiration_seconds
self._logger = logger
@property
def logger(self) -> Logger:
return self._logger
def issue(self) -> str:
state: str = str(uuid4())
expire_at = timezone.now() + timezone.timedelta(seconds=self.expiration_seconds)
row = SlackOAuthState(state=state, expire_at=expire_at)
row.save()
return state
def consume(self, state: str) -> bool:
rows = SlackOAuthState.objects.filter(state=state).filter(
expire_at__gte=timezone.now()
)
if len(rows) > 0:
for row in rows:
row.delete()
return True
return False
# ----------------------
# Slack App
# ----------------------
import logging
import os
from slack_bolt import App
from slack_bolt.oauth.oauth_settings import OAuthSettings
logger = logging.getLogger(__name__)
client_id, client_secret, signing_secret = (
os.environ["SLACK_CLIENT_ID"],
os.environ["SLACK_CLIENT_SECRET"],
os.environ["SLACK_SIGNING_SECRET"],
)
app = App(
signing_secret=signing_secret,
installation_store=DjangoInstallationStore(
client_id=client_id,
logger=logger,
),
oauth_settings=OAuthSettings(
client_id=client_id,
client_secret=client_secret,
state_store=DjangoOAuthStateStore(
expiration_seconds=120,
logger=logger,
),
),
)
@app.event("app_mention")
def event_test(body, say, logger):
logger.info(body)
say("What's up?")
@app.command("/hello-bolt-python")
def command(ack):
ack("This is a Django app!")