slackwright 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
slackwright/forms.py ADDED
@@ -0,0 +1,999 @@
1
+ """Block Kit forms that an agent designs and Slack users fill in.
2
+
3
+ An agent writes a :class:`FormSpec`. :class:`Runtime` posts it as a
4
+ message, either with an "Open form" button (``mode='modal'``) or with
5
+ the inputs in the message (``mode='inline'``), and handles the Slack
6
+ interactions. When a user submits valid answers, the runtime calls the
7
+ bot's ``on_submit`` callback with a :class:`Submission`.
8
+
9
+ The button listener does its work after ``ack()``. The modal listener
10
+ reads and claims the form in the store before ``ack()``, because the
11
+ ``ack()`` response can carry ``response_action``, so those store calls
12
+ count against Slack's 3-second limit. The message update and
13
+ ``on_submit`` run after ``ack()``. Bolt sends the acknowledgement
14
+ first when ``process_before_response`` is ``False`` (the default), so
15
+ that slow work does not pass the limit.
16
+
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import collections.abc
22
+ import dataclasses
23
+ import logging
24
+ import re
25
+ import secrets
26
+ import time
27
+ import typing
28
+
29
+ import aiohttp
30
+ import pydantic
31
+ from slack_sdk import errors
32
+
33
+ from slackwright import blocks as block_specs
34
+ from slackwright import inflight, render
35
+
36
+ LOGGER = logging.getLogger(__name__)
37
+
38
+ ACTION_OPEN = 'slackwright:open'
39
+ ACTION_SUBMIT = 'slackwright:submit'
40
+ CALLBACK_ID = 'slackwright:form'
41
+ ACTION_PATTERN = re.compile(r'^slackwright:(?:open|submit)$')
42
+
43
+ DEFAULT_TTL = 7 * 24 * 60 * 60
44
+ """Seconds that a form can be answered."""
45
+
46
+ MAX_FIELDS = 40
47
+ CREATED_BY = 'Form created by the assistant'
48
+
49
+ _VALUE = 'value'
50
+ """The ``action_id`` of every input element."""
51
+
52
+ _SECRET_WORDS = re.compile(
53
+ r'\b(?:passwords?|passcodes?|passphrases?|tokens?|api[ _-]?keys?|'
54
+ r'secrets?|credentials?|private[ _-]?keys?|ssn|social security|'
55
+ r'credit[ _-]?cards?|card numbers?|cvv|cvc)\b',
56
+ re.IGNORECASE,
57
+ )
58
+ _EMAIL = re.compile(r'^[^@\s]+@[^@\s]+\.[^@\s]+$')
59
+ _USER_ID = r'^[UW][A-Z0-9]+$'
60
+ _CHANNEL_ID = r'^[CDG][A-Z0-9]+$'
61
+
62
+ _Option = typing.Annotated[str, pydantic.Field(min_length=1, max_length=75)]
63
+ _Placeholder = typing.Annotated[
64
+ str | None,
65
+ pydantic.Field(max_length=150, description='Grey text in the input.'),
66
+ ]
67
+
68
+
69
+ _plain = block_specs.plain_text
70
+
71
+
72
+ def _options(options: list[str]) -> list[dict[str, typing.Any]]:
73
+ return [{'text': _plain(o), 'value': o} for o in options]
74
+
75
+
76
+ class _Field(pydantic.BaseModel):
77
+ model_config = pydantic.ConfigDict(extra='forbid')
78
+
79
+ id: str = pydantic.Field(
80
+ pattern=r'^[a-z][a-z0-9_]{0,49}$',
81
+ description='Unique field ID: lower-case letters, digits, and _.',
82
+ )
83
+ label: str = pydantic.Field(
84
+ min_length=1, max_length=2000, description='The question.'
85
+ )
86
+ required: bool = pydantic.Field(
87
+ default=True, description='True if the user must answer.'
88
+ )
89
+ hint: str | None = pydantic.Field(
90
+ default=None, max_length=2000, description='Help text below it.'
91
+ )
92
+
93
+ def texts(self) -> list[str]:
94
+ """Return the texts that the user reads, for the secret check."""
95
+ texts = [self.label, self.hint, getattr(self, 'placeholder', None)]
96
+ return [text for text in texts if text]
97
+
98
+ def block(self) -> dict[str, typing.Any]:
99
+ """Return the Block Kit ``input`` block for this field."""
100
+ block: dict[str, typing.Any] = {
101
+ 'type': 'input',
102
+ 'block_id': self.id,
103
+ 'label': _plain(self.label),
104
+ 'optional': not self.required,
105
+ 'element': {'action_id': _VALUE, **self.element()},
106
+ }
107
+ if self.hint:
108
+ block['hint'] = _plain(self.hint)
109
+ return block
110
+
111
+ def element(self) -> dict[str, typing.Any]:
112
+ raise NotImplementedError
113
+
114
+ def convert(self, state: dict[str, typing.Any]) -> typing.Any:
115
+ """Return the typed answer from a ``state.values`` entry.
116
+
117
+ Raises :class:`ValueError` with a message for the user.
118
+
119
+ """
120
+ value = self.read(state)
121
+ if value in (None, '', []):
122
+ if self.required:
123
+ raise ValueError('This field is required.')
124
+ return [] if isinstance(value, list) else None
125
+ return self.check(value)
126
+
127
+ def read(self, state: dict[str, typing.Any]) -> typing.Any:
128
+ return state.get('value')
129
+
130
+ def check(self, value: typing.Any) -> typing.Any:
131
+ return value
132
+
133
+
134
+ class TextField(_Field):
135
+ """Free text, on one line or more."""
136
+
137
+ type: typing.Literal['text']
138
+ multiline: bool = pydantic.Field(
139
+ default=False, description='True for a large text box.'
140
+ )
141
+ min_length: int | None = pydantic.Field(
142
+ default=None, ge=0, le=3000, description='Minimum characters.'
143
+ )
144
+ max_length: int | None = pydantic.Field(
145
+ default=None, ge=1, le=3000, description='Maximum characters.'
146
+ )
147
+ placeholder: _Placeholder = None
148
+ initial: str | None = pydantic.Field(
149
+ default=None, max_length=3000, description='Text filled in first.'
150
+ )
151
+
152
+ def element(self) -> dict[str, typing.Any]:
153
+ element: dict[str, typing.Any] = {
154
+ 'type': 'plain_text_input',
155
+ 'multiline': self.multiline,
156
+ }
157
+ if self.min_length is not None:
158
+ element['min_length'] = self.min_length
159
+ if self.max_length is not None:
160
+ element['max_length'] = self.max_length
161
+ if self.placeholder:
162
+ element['placeholder'] = _plain(self.placeholder)
163
+ if self.initial:
164
+ element['initial_value'] = self.initial
165
+ return element
166
+
167
+ def check(self, value: typing.Any) -> typing.Any:
168
+ text = str(value)
169
+ if self.min_length is not None and len(text) < self.min_length:
170
+ raise ValueError(f'Use at least {self.min_length} characters.')
171
+ if self.max_length is not None and len(text) > self.max_length:
172
+ raise ValueError(f'Use at most {self.max_length} characters.')
173
+ return text
174
+
175
+
176
+ class NumberField(_Field):
177
+ """A number, with optional limits."""
178
+
179
+ type: typing.Literal['number']
180
+ decimal: bool = pydantic.Field(
181
+ default=False, description='True to allow decimals.'
182
+ )
183
+ min: float | None = pydantic.Field(default=None, description='Minimum.')
184
+ max: float | None = pydantic.Field(default=None, description='Maximum.')
185
+ placeholder: _Placeholder = None
186
+ initial: float | None = pydantic.Field(
187
+ default=None, description='Number filled in first.'
188
+ )
189
+
190
+ def element(self) -> dict[str, typing.Any]:
191
+ element: dict[str, typing.Any] = {
192
+ 'type': 'number_input',
193
+ 'is_decimal_allowed': self.decimal,
194
+ }
195
+ for key, value in (
196
+ ('min_value', self.min),
197
+ ('max_value', self.max),
198
+ ('initial_value', self.initial),
199
+ ):
200
+ if value is not None:
201
+ element[key] = _number_text(value)
202
+ if self.placeholder:
203
+ element['placeholder'] = _plain(self.placeholder)
204
+ return element
205
+
206
+ def check(self, value: typing.Any) -> typing.Any:
207
+ try:
208
+ number = float(value) if self.decimal else int(value)
209
+ except (TypeError, ValueError):
210
+ kind = 'a number' if self.decimal else 'a whole number'
211
+ raise ValueError(f'Enter {kind}.') from None
212
+ if self.min is not None and number < self.min:
213
+ raise ValueError(f'Enter {_number_text(self.min)} or more.')
214
+ if self.max is not None and number > self.max:
215
+ raise ValueError(f'Enter {_number_text(self.max)} or less.')
216
+ return number
217
+
218
+
219
+ class AddressField(_Field):
220
+ """An email address or a web URL."""
221
+
222
+ type: typing.Literal['email', 'url']
223
+ placeholder: _Placeholder = None
224
+ initial: str | None = pydantic.Field(
225
+ default=None, max_length=3000, description='Value filled in first.'
226
+ )
227
+
228
+ def element(self) -> dict[str, typing.Any]:
229
+ kind = 'email_text_input' if self.type == 'email' else 'url_text_input'
230
+ element: dict[str, typing.Any] = {'type': kind}
231
+ if self.placeholder:
232
+ element['placeholder'] = _plain(self.placeholder)
233
+ if self.initial:
234
+ element['initial_value'] = self.initial
235
+ return element
236
+
237
+ def check(self, value: typing.Any) -> typing.Any:
238
+ text = str(value).strip()
239
+ if self.type == 'email' and not _EMAIL.match(text):
240
+ raise ValueError('Enter an email address.')
241
+ if self.type == 'url' and not text.startswith(('https://', 'http://')):
242
+ raise ValueError('Enter a URL that starts with https://.')
243
+ return text
244
+
245
+
246
+ class DateTimeField(_Field):
247
+ """A date (YYYY-MM-DD) or a time of day (HH:MM, 24-hour)."""
248
+
249
+ type: typing.Literal['date', 'time']
250
+ placeholder: _Placeholder = None
251
+ initial: str | None = pydantic.Field(
252
+ default=None,
253
+ description='YYYY-MM-DD for a date, HH:MM for a time.',
254
+ )
255
+
256
+ @pydantic.model_validator(mode='after')
257
+ def _check_initial(self) -> DateTimeField:
258
+ if self.initial and not re.match(self._pattern(), self.initial):
259
+ raise ValueError(f'initial must match {self._format()}')
260
+ return self
261
+
262
+ def element(self) -> dict[str, typing.Any]:
263
+ element: dict[str, typing.Any] = {
264
+ 'type': 'datepicker' if self.type == 'date' else 'timepicker'
265
+ }
266
+ if self.placeholder:
267
+ element['placeholder'] = _plain(self.placeholder)
268
+ if self.initial:
269
+ key = 'initial_date' if self.type == 'date' else 'initial_time'
270
+ element[key] = self.initial
271
+ return element
272
+
273
+ def read(self, state: dict[str, typing.Any]) -> typing.Any:
274
+ key = 'selected_date' if self.type == 'date' else 'selected_time'
275
+ return state.get(key)
276
+
277
+ def check(self, value: typing.Any) -> typing.Any:
278
+ if not re.match(self._pattern(), str(value)):
279
+ raise ValueError(f'Use the format {self._format()}.')
280
+ return str(value)
281
+
282
+ def _pattern(self) -> str:
283
+ if self.type == 'date':
284
+ return r'^\d{4}-\d{2}-\d{2}$'
285
+ return r'^\d{2}:\d{2}$'
286
+
287
+ def _format(self) -> str:
288
+ return 'YYYY-MM-DD' if self.type == 'date' else 'HH:MM'
289
+
290
+
291
+ class ChoiceField(_Field):
292
+ """A choice from a list: one (select, radio) or many (multi_select,
293
+ checkboxes)."""
294
+
295
+ type: typing.Literal['select', 'multi_select', 'radio', 'checkboxes']
296
+ options: list[_Option] = pydantic.Field(
297
+ min_length=1,
298
+ max_length=100,
299
+ description=(
300
+ 'The choices, max 75 characters each. Max 100 for select and '
301
+ 'multi_select, 10 for radio and checkboxes.'
302
+ ),
303
+ )
304
+ max_selected: int | None = pydantic.Field(
305
+ default=None, ge=1, description='multi_select only: most choices.'
306
+ )
307
+ placeholder: _Placeholder = None
308
+ initial: str | list[str] | None = pydantic.Field(
309
+ default=None,
310
+ description=(
311
+ 'Choice selected first: one option for select and radio, a '
312
+ 'list of options for multi_select and checkboxes.'
313
+ ),
314
+ )
315
+
316
+ @property
317
+ def multiple(self) -> bool:
318
+ return self.type in ('multi_select', 'checkboxes')
319
+
320
+ @pydantic.model_validator(mode='after')
321
+ def _check_choices(self) -> ChoiceField:
322
+ if len(set(self.options)) != len(self.options):
323
+ raise ValueError('options must be unique')
324
+ if self.type in ('radio', 'checkboxes') and len(self.options) > 10:
325
+ raise ValueError(f'{self.type} allows at most 10 options')
326
+ if self.max_selected is not None and self.type != 'multi_select':
327
+ raise ValueError('max_selected is only for multi_select')
328
+ if self.initial is None:
329
+ return self
330
+ if self.multiple != isinstance(self.initial, list):
331
+ kind = 'a list of options' if self.multiple else 'one option'
332
+ raise ValueError(f'initial must be {kind} for {self.type}')
333
+ chosen = (
334
+ self.initial if isinstance(self.initial, list) else [self.initial]
335
+ )
336
+ if not set(chosen) <= set(self.options):
337
+ raise ValueError('initial must be one of the options')
338
+ return self
339
+
340
+ def element(self) -> dict[str, typing.Any]:
341
+ kind = {
342
+ 'select': 'static_select',
343
+ 'multi_select': 'multi_static_select',
344
+ 'radio': 'radio_buttons',
345
+ 'checkboxes': 'checkboxes',
346
+ }[self.type]
347
+ element: dict[str, typing.Any] = {
348
+ 'type': kind,
349
+ 'options': _options(self.options),
350
+ }
351
+ if self.max_selected is not None:
352
+ element['max_selected_items'] = self.max_selected
353
+ if self.placeholder and self.type in ('select', 'multi_select'):
354
+ element['placeholder'] = _plain(self.placeholder)
355
+ if isinstance(self.initial, list) and self.initial:
356
+ element['initial_options'] = _options(self.initial)
357
+ elif isinstance(self.initial, str):
358
+ element['initial_option'] = _options([self.initial])[0]
359
+ return element
360
+
361
+ def read(self, state: dict[str, typing.Any]) -> typing.Any:
362
+ if self.multiple:
363
+ return [o['value'] for o in state.get('selected_options') or []]
364
+ return (state.get('selected_option') or {}).get('value')
365
+
366
+ def check(self, value: typing.Any) -> typing.Any:
367
+ chosen = value if isinstance(value, list) else [value]
368
+ if not set(chosen) <= set(self.options):
369
+ raise ValueError('Choose from the options.')
370
+ if self.max_selected is not None and len(chosen) > self.max_selected:
371
+ raise ValueError(f'Choose at most {self.max_selected}.')
372
+ return value
373
+
374
+
375
+ class PickerField(_Field):
376
+ """Slack users or channels: one (user, channel) or many (users,
377
+ channels)."""
378
+
379
+ type: typing.Literal['user', 'users', 'channel', 'channels']
380
+ placeholder: _Placeholder = None
381
+ initial: str | list[str] | None = pydantic.Field(
382
+ default=None,
383
+ description=(
384
+ 'Selected first: a user ID (U...) or channel ID (C...), or a '
385
+ 'list of IDs for users and channels.'
386
+ ),
387
+ )
388
+
389
+ @property
390
+ def multiple(self) -> bool:
391
+ return self.type in ('users', 'channels')
392
+
393
+ @pydantic.model_validator(mode='after')
394
+ def _check_initial(self) -> PickerField:
395
+ if self.initial is None:
396
+ return self
397
+ if self.multiple != isinstance(self.initial, list):
398
+ kind = 'a list of IDs' if self.multiple else 'one ID'
399
+ raise ValueError(f'initial must be {kind} for {self.type}')
400
+ pattern = _USER_ID if self.type.startswith('user') else _CHANNEL_ID
401
+ ids = (
402
+ self.initial if isinstance(self.initial, list) else [self.initial]
403
+ )
404
+ if not all(re.match(pattern, value) for value in ids):
405
+ raise ValueError(f'initial has an ID that is not a {self.type}')
406
+ return self
407
+
408
+ def element(self) -> dict[str, typing.Any]:
409
+ kind, initial_key = {
410
+ 'user': ('users_select', 'initial_user'),
411
+ 'users': ('multi_users_select', 'initial_users'),
412
+ 'channel': ('conversations_select', 'initial_conversation'),
413
+ 'channels': (
414
+ 'multi_conversations_select',
415
+ 'initial_conversations',
416
+ ),
417
+ }[self.type]
418
+ element: dict[str, typing.Any] = {'type': kind}
419
+ if self.placeholder:
420
+ element['placeholder'] = _plain(self.placeholder)
421
+ if self.initial:
422
+ element[initial_key] = self.initial
423
+ return element
424
+
425
+ def read(self, state: dict[str, typing.Any]) -> typing.Any:
426
+ key = {
427
+ 'user': 'selected_user',
428
+ 'users': 'selected_users',
429
+ 'channel': 'selected_conversation',
430
+ 'channels': 'selected_conversations',
431
+ }[self.type]
432
+ return state.get(key) or ([] if self.multiple else None)
433
+
434
+
435
+ FieldSpec = typing.Annotated[
436
+ TextField
437
+ | NumberField
438
+ | AddressField
439
+ | DateTimeField
440
+ | ChoiceField
441
+ | PickerField,
442
+ pydantic.Field(discriminator='type'),
443
+ ]
444
+
445
+
446
+ class FormSpec(pydantic.BaseModel):
447
+ """A form that an agent designs."""
448
+
449
+ model_config = pydantic.ConfigDict(extra='forbid')
450
+
451
+ title: str = pydantic.Field(
452
+ min_length=1, max_length=24, description='Short title, max 24.'
453
+ )
454
+ intro: str | None = pydantic.Field(
455
+ default=None,
456
+ max_length=2000,
457
+ description='Markdown above the fields: why you ask.',
458
+ )
459
+ fields: list[FieldSpec] = pydantic.Field(
460
+ min_length=1,
461
+ max_length=MAX_FIELDS,
462
+ description=f'The questions, top to bottom. Max {MAX_FIELDS}.',
463
+ )
464
+ submit_label: str = pydantic.Field(
465
+ default='Submit',
466
+ min_length=1,
467
+ max_length=24,
468
+ description='Text of the submit button.',
469
+ )
470
+ mode: typing.Literal['modal', 'inline'] = pydantic.Field(
471
+ default='modal',
472
+ description=(
473
+ 'modal: the message has an "Open form" button that opens a '
474
+ 'dialog. inline: the inputs are in the message. Use inline '
475
+ 'for 1 to 3 short questions.'
476
+ ),
477
+ )
478
+ respondents: (
479
+ typing.Literal['requester', 'anyone']
480
+ | typing.Annotated[
481
+ list[typing.Annotated[str, pydantic.Field(pattern=_USER_ID)]],
482
+ pydantic.Field(min_length=1, max_length=50),
483
+ ]
484
+ ) = pydantic.Field(
485
+ default='requester',
486
+ description=(
487
+ 'Who can answer: requester (the user you act for), anyone '
488
+ 'in the channel, or a list of user IDs.'
489
+ ),
490
+ )
491
+ single_submission: bool = pydantic.Field(
492
+ default=True,
493
+ description=(
494
+ 'True: the form closes after one answer. False: each '
495
+ 'respondent can answer once.'
496
+ ),
497
+ )
498
+
499
+ @pydantic.model_validator(mode='after')
500
+ def _check_fields(self) -> FormSpec:
501
+ ids = [field.id for field in self.fields]
502
+ if len(set(ids)) != len(ids):
503
+ raise ValueError('field IDs must be unique')
504
+ texts = [self.title, self.intro or '', self.submit_label] + [
505
+ text for field in self.fields for text in field.texts()
506
+ ]
507
+ for text in texts:
508
+ if match := _SECRET_WORDS.search(text):
509
+ raise ValueError(
510
+ f'forms cannot ask for secrets ({match.group(0)!r}); '
511
+ 'ask users to never share passwords, tokens, or keys'
512
+ )
513
+ return self
514
+
515
+
516
+ class FormRecord(pydantic.BaseModel):
517
+ """A posted form, as a :class:`FormStore` keeps it."""
518
+
519
+ form_id: str
520
+ spec: FormSpec
521
+ channel_id: str
522
+ thread_ts: str | None
523
+ message_ts: str | None = None
524
+ requester: str
525
+ created_at: float
526
+
527
+ def allows(self, user_id: str) -> bool:
528
+ """Return ``True`` if ``user_id`` can answer this form."""
529
+ respondents = self.spec.respondents
530
+ if respondents == 'anyone':
531
+ return True
532
+ if respondents == 'requester':
533
+ return user_id == self.requester
534
+ return user_id in respondents
535
+
536
+ def claim_key(self, user_id: str) -> str:
537
+ if self.spec.single_submission:
538
+ return self.form_id
539
+ return f'{self.form_id}:{user_id}'
540
+
541
+
542
+ class FormStore(typing.Protocol):
543
+ """Keeps posted forms between the post and the answers.
544
+
545
+ ``claim`` must be atomic: of two calls with the same key, only one
546
+ returns ``True`` until ``ttl`` seconds pass.
547
+
548
+ """
549
+
550
+ async def put(self, record: FormRecord, ttl: int) -> None: ...
551
+
552
+ async def get(self, form_id: str) -> FormRecord | None: ...
553
+
554
+ async def claim(self, key: str, ttl: int) -> bool: ...
555
+
556
+
557
+ class MemoryFormStore:
558
+ """A :class:`FormStore` in process memory.
559
+
560
+ For tests and bots with one process. Forms are lost when the
561
+ process stops.
562
+
563
+ """
564
+
565
+ def __init__(self) -> None:
566
+ self._records: dict[str, tuple[str, float]] = {}
567
+ self._claims: dict[str, float] = {}
568
+
569
+ async def put(self, record: FormRecord, ttl: int) -> None:
570
+ self._records[record.form_id] = (
571
+ record.model_dump_json(),
572
+ time.monotonic() + ttl,
573
+ )
574
+
575
+ async def get(self, form_id: str) -> FormRecord | None:
576
+ data, expires = self._records.get(form_id, ('', 0.0))
577
+ if expires <= time.monotonic():
578
+ self._records.pop(form_id, None)
579
+ return None
580
+ return FormRecord.model_validate_json(data)
581
+
582
+ async def claim(self, key: str, ttl: int) -> bool:
583
+ now = time.monotonic()
584
+ if self._claims.get(key, 0.0) > now:
585
+ return False
586
+ self._claims[key] = now + ttl
587
+ return True
588
+
589
+
590
+ @dataclasses.dataclass(frozen=True)
591
+ class Submission:
592
+ """Valid answers to a form.
593
+
594
+ ``values`` maps each field ID to its answer: ``str`` for text,
595
+ email, url, date (YYYY-MM-DD), time (HH:MM), select, radio, user,
596
+ and channel; ``int`` or ``float`` for number; ``list[str]`` for
597
+ multi_select, checkboxes, users, and channels; ``None`` (or an
598
+ empty list) for an optional field with no answer.
599
+
600
+ The values are untrusted user input. Give them to an agent as
601
+ data, not as instructions.
602
+
603
+ """
604
+
605
+ form_id: str
606
+ spec: FormSpec
607
+ values: dict[str, typing.Any]
608
+ user_id: str
609
+ channel_id: str
610
+ thread_ts: str | None
611
+
612
+
613
+ OnSubmit = collections.abc.Callable[
614
+ [Submission], collections.abc.Awaitable[None]
615
+ ]
616
+ Ack = collections.abc.Callable[..., collections.abc.Awaitable[typing.Any]]
617
+
618
+
619
+ class Runtime:
620
+ """Post forms and handle their Slack interactions.
621
+
622
+ Args:
623
+ store: Where posted forms are kept until they are answered.
624
+ on_submit: ``async on_submit(submission)``, called once for
625
+ each valid submission.
626
+ ttl: Seconds that a form can be answered.
627
+
628
+ """
629
+
630
+ def __init__(
631
+ self,
632
+ store: FormStore,
633
+ on_submit: OnSubmit,
634
+ *,
635
+ ttl: int = DEFAULT_TTL,
636
+ ) -> None:
637
+ self._store = store
638
+ self._on_submit = on_submit
639
+ self._ttl = ttl
640
+
641
+ def register(self, app: typing.Any) -> None:
642
+ """Add the form listeners to a Bolt ``AsyncApp``."""
643
+ app.action(ACTION_PATTERN)(self.handle_action)
644
+ app.view(CALLBACK_ID)(self.handle_view)
645
+
646
+ async def post(
647
+ self,
648
+ slack: typing.Any,
649
+ spec: FormSpec,
650
+ *,
651
+ channel_id: str,
652
+ thread_ts: str | None,
653
+ requester: str,
654
+ ) -> FormRecord:
655
+ """Post ``spec`` as a message and store it. Return the record."""
656
+ record = FormRecord(
657
+ form_id=secrets.token_urlsafe(12),
658
+ spec=spec,
659
+ channel_id=channel_id,
660
+ thread_ts=thread_ts,
661
+ requester=requester,
662
+ created_at=time.time(),
663
+ )
664
+ # Store before posting, so that a fast click finds the form.
665
+ await self._store.put(record, self._ttl)
666
+ response = await slack.chat_postMessage(
667
+ channel=channel_id,
668
+ thread_ts=thread_ts,
669
+ blocks=_message_blocks(record),
670
+ text=f'Form: {spec.title}',
671
+ )
672
+ record.message_ts = response['ts']
673
+ await self._store.put(record, self._ttl)
674
+ return record
675
+
676
+ async def handle_action(
677
+ self, ack: Ack, body: dict[str, typing.Any], client: typing.Any
678
+ ) -> None:
679
+ """Bolt listener for the open and submit buttons."""
680
+ await ack()
681
+ action = body['actions'][0]
682
+ user_id = body['user']['id']
683
+ record = await self._store.get(action.get('value', ''))
684
+ if record is None:
685
+ await _expire_message(client, body, user_id)
686
+ return
687
+ if not record.allows(user_id):
688
+ await _ephemeral(
689
+ client, record, user_id, 'You cannot answer this form.'
690
+ )
691
+ return
692
+ if action['action_id'] == ACTION_OPEN:
693
+ if record.spec.mode == 'modal':
694
+ await client.views_open(
695
+ trigger_id=body['trigger_id'], view=_modal(record)
696
+ )
697
+ return
698
+ if record.spec.mode != 'inline':
699
+ return
700
+ values, problems = _parse(record.spec, body.get('state') or {})
701
+ if problems:
702
+ lines = [
703
+ f'• {_label(record.spec, field_id)}: {message}'
704
+ for field_id, message in problems.items()
705
+ ]
706
+ await _ephemeral(
707
+ client,
708
+ record,
709
+ user_id,
710
+ 'Your answers were not sent:\n' + '\n'.join(lines),
711
+ )
712
+ return
713
+ if not await self._store.claim(record.claim_key(user_id), self._ttl):
714
+ await _ephemeral(
715
+ client, record, user_id, 'This form was already answered.'
716
+ )
717
+ return
718
+ await self._finish(client, record, user_id, values)
719
+
720
+ async def handle_view(
721
+ self, ack: Ack, body: dict[str, typing.Any], client: typing.Any
722
+ ) -> None:
723
+ """Bolt listener for the modal submission."""
724
+ view = body['view']
725
+ user_id = body['user']['id']
726
+ first = _first_input(view)
727
+ record = await self._store.get(view.get('private_metadata', ''))
728
+ if record is None:
729
+ await ack(
730
+ response_action='errors',
731
+ errors={first: 'This form has expired.'},
732
+ )
733
+ return
734
+ if not record.allows(user_id):
735
+ await ack(
736
+ response_action='errors',
737
+ errors={first: 'You cannot answer this form.'},
738
+ )
739
+ return
740
+ values, problems = _parse(record.spec, view.get('state') or {})
741
+ if problems:
742
+ await ack(response_action='errors', errors=problems)
743
+ return
744
+ if not await self._store.claim(record.claim_key(user_id), self._ttl):
745
+ await ack(
746
+ response_action='update',
747
+ view=_notice(record.spec, 'This form was already answered.'),
748
+ )
749
+ return
750
+ await ack()
751
+ await self._finish(client, record, user_id, values)
752
+
753
+ async def _finish(
754
+ self,
755
+ client: typing.Any,
756
+ record: FormRecord,
757
+ user_id: str,
758
+ values: dict[str, typing.Any],
759
+ ) -> None:
760
+ async with inflight.track():
761
+ if record.spec.single_submission and record.message_ts:
762
+ try:
763
+ await client.chat_update(
764
+ channel=record.channel_id,
765
+ ts=record.message_ts,
766
+ blocks=_answered_blocks(record, user_id, values),
767
+ text=f'Form: {record.spec.title} (answered)',
768
+ )
769
+ except (
770
+ errors.SlackApiError,
771
+ aiohttp.ClientError,
772
+ TimeoutError,
773
+ ) as error:
774
+ # The update is cosmetic. Deliver the answers anyway.
775
+ LOGGER.warning(
776
+ 'Could not update form %s: %r', record.form_id, error
777
+ )
778
+ elif record.spec.mode == 'inline':
779
+ await _ephemeral(
780
+ client, record, user_id, 'Thanks. Your answers were sent.'
781
+ )
782
+ submission = Submission(
783
+ form_id=record.form_id,
784
+ spec=record.spec,
785
+ values=values,
786
+ user_id=user_id,
787
+ channel_id=record.channel_id,
788
+ thread_ts=record.thread_ts,
789
+ )
790
+ # ponytail: the claim stays held after a failure, so the
791
+ # user cannot submit again; add FormStore.release for retry.
792
+ try:
793
+ await self._on_submit(submission)
794
+ except Exception:
795
+ LOGGER.exception(
796
+ 'on_submit failed for form %s', record.form_id
797
+ )
798
+ await _ephemeral(
799
+ client,
800
+ record,
801
+ user_id,
802
+ 'Your answers were received, but processing failed.',
803
+ )
804
+
805
+
806
+ def _parse(
807
+ spec: FormSpec, state: dict[str, typing.Any]
808
+ ) -> tuple[dict[str, typing.Any], dict[str, str]]:
809
+ """Return ``(values, problems)`` from a payload's ``state``."""
810
+ entries = state.get('values') or {}
811
+ values: dict[str, typing.Any] = {}
812
+ problems: dict[str, str] = {}
813
+ for field in spec.fields:
814
+ entry = (entries.get(field.id) or {}).get(_VALUE) or {}
815
+ try:
816
+ values[field.id] = field.convert(entry)
817
+ except ValueError as error:
818
+ problems[field.id] = str(error)
819
+ return values, problems
820
+
821
+
822
+ def _message_blocks(record: FormRecord) -> list[dict[str, typing.Any]]:
823
+ spec = record.spec
824
+ blocks: list[dict[str, typing.Any]] = [
825
+ {'type': 'header', 'text': _plain(spec.title)}
826
+ ]
827
+ if spec.intro:
828
+ blocks.append({'type': 'markdown', 'text': spec.intro})
829
+ if spec.mode == 'inline':
830
+ blocks += [field.block() for field in spec.fields]
831
+ blocks.append(_context(CREATED_BY))
832
+ action, label = (
833
+ (ACTION_SUBMIT, spec.submit_label)
834
+ if spec.mode == 'inline'
835
+ else (ACTION_OPEN, 'Open form')
836
+ )
837
+ blocks.append(
838
+ {
839
+ 'type': 'actions',
840
+ 'elements': [
841
+ {
842
+ 'type': 'button',
843
+ 'action_id': action,
844
+ 'text': _plain(label),
845
+ 'style': 'primary',
846
+ 'value': record.form_id,
847
+ }
848
+ ],
849
+ }
850
+ )
851
+ return blocks
852
+
853
+
854
+ def _modal(record: FormRecord) -> dict[str, typing.Any]:
855
+ spec = record.spec
856
+ blocks: list[dict[str, typing.Any]] = []
857
+ if spec.intro:
858
+ blocks.append(
859
+ {
860
+ 'type': 'section',
861
+ 'text': {
862
+ 'type': 'mrkdwn',
863
+ 'text': render.to_mrkdwn(spec.intro)[
864
+ : block_specs.TEXT_OBJECT_LIMIT
865
+ ],
866
+ },
867
+ }
868
+ )
869
+ blocks.append(_context(CREATED_BY))
870
+ blocks += [field.block() for field in spec.fields]
871
+ return {
872
+ 'type': 'modal',
873
+ 'callback_id': CALLBACK_ID,
874
+ 'private_metadata': record.form_id,
875
+ 'title': _plain(spec.title),
876
+ 'submit': _plain(spec.submit_label),
877
+ 'close': _plain('Cancel'),
878
+ 'blocks': blocks,
879
+ }
880
+
881
+
882
+ def _notice(spec: FormSpec, text: str) -> dict[str, typing.Any]:
883
+ return {
884
+ 'type': 'modal',
885
+ 'title': _plain(spec.title),
886
+ 'close': _plain('Close'),
887
+ 'blocks': [{'type': 'section', 'text': _plain(text)}],
888
+ }
889
+
890
+
891
+ def _answered_blocks(
892
+ record: FormRecord, user_id: str, values: dict[str, typing.Any]
893
+ ) -> list[dict[str, typing.Any]]:
894
+ blocks: list[dict[str, typing.Any]] = [
895
+ {'type': 'header', 'text': _plain(record.spec.title)}
896
+ ]
897
+ if record.spec.mode == 'inline':
898
+ # plain_text shows no links, formatting, or mentions, so user
899
+ # answers cannot speak in the voice of the bot.
900
+ blocks.extend(
901
+ {
902
+ 'type': 'section',
903
+ 'text': _plain(
904
+ f'{field.label}\n{_display(values.get(field.id))}'[
905
+ : block_specs.TEXT_OBJECT_LIMIT
906
+ ]
907
+ ),
908
+ }
909
+ for field in record.spec.fields
910
+ )
911
+ blocks.append(_context(f'Answered by <@{user_id}>'))
912
+ return blocks
913
+
914
+
915
+ def _display(value: typing.Any) -> str:
916
+ if value in (None, '', []):
917
+ return '-'
918
+ if isinstance(value, list):
919
+ return ', '.join(str(item) for item in value)
920
+ return str(value)
921
+
922
+
923
+ def _context(text: str) -> dict[str, typing.Any]:
924
+ return {'type': 'context', 'elements': [{'type': 'mrkdwn', 'text': text}]}
925
+
926
+
927
+ def _label(spec: FormSpec, field_id: str) -> str:
928
+ return next(f.label for f in spec.fields if f.id == field_id)
929
+
930
+
931
+ def _first_input(view: dict[str, typing.Any]) -> str:
932
+ return next(
933
+ (
934
+ block['block_id']
935
+ for block in view.get('blocks') or []
936
+ if block.get('type') == 'input'
937
+ ),
938
+ '',
939
+ )
940
+
941
+
942
+ def _number_text(value: float) -> str:
943
+ return str(int(value)) if float(value).is_integer() else str(value)
944
+
945
+
946
+ async def _ephemeral(
947
+ client: typing.Any, record: FormRecord, user_id: str, text: str
948
+ ) -> None:
949
+ await _tell(client, record.channel_id, record.thread_ts, user_id, text)
950
+
951
+
952
+ async def _tell(
953
+ client: typing.Any,
954
+ channel_id: str,
955
+ thread_ts: str | None,
956
+ user_id: str,
957
+ text: str,
958
+ ) -> None:
959
+ """Send ``user_id`` an ephemeral message. Log a Slack error."""
960
+ try:
961
+ await client.chat_postEphemeral(
962
+ channel=channel_id, user=user_id, thread_ts=thread_ts, text=text
963
+ )
964
+ except errors.SlackApiError as error:
965
+ LOGGER.warning(
966
+ 'Could not tell %s about a form: %s',
967
+ user_id,
968
+ error.response.get('error'),
969
+ )
970
+
971
+
972
+ async def _expire_message(
973
+ client: typing.Any, body: dict[str, typing.Any], user_id: str
974
+ ) -> None:
975
+ """Tell the user that the form expired and mark the message."""
976
+ channel_id = (body.get('channel') or {}).get('id')
977
+ message = body.get('message') or {}
978
+ if not channel_id:
979
+ return
980
+ expired = 'This form has expired.'
981
+ await _tell(client, channel_id, message.get('thread_ts'), user_id, expired)
982
+ if not message.get('ts'):
983
+ return
984
+ kept = [
985
+ block
986
+ for block in message.get('blocks') or []
987
+ if block.get('type') not in ('actions', 'input')
988
+ ]
989
+ try:
990
+ await client.chat_update(
991
+ channel=channel_id,
992
+ ts=message['ts'],
993
+ blocks=[*kept, _context(expired)],
994
+ text=expired,
995
+ )
996
+ except errors.SlackApiError as error:
997
+ LOGGER.warning(
998
+ 'Could not mark an expired form: %s', error.response.get('error')
999
+ )