ezytools 0.3.0__tar.gz → 0.4.0__tar.gz
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.
- {ezytools-0.3.0 → ezytools-0.4.0}/PKG-INFO +157 -44
- {ezytools-0.3.0 → ezytools-0.4.0}/README.md +156 -43
- {ezytools-0.3.0 → ezytools-0.4.0}/pyproject.toml +1 -1
- ezytools-0.4.0/src/ezytools/__init__.py +8 -0
- ezytools-0.4.0/src/ezytools/features.py +280 -0
- ezytools-0.4.0/tests/test_features.py +88 -0
- ezytools-0.3.0/src/ezytools/__init__.py +0 -5
- {ezytools-0.3.0 → ezytools-0.4.0}/LICENSE +0 -0
- {ezytools-0.3.0 → ezytools-0.4.0}/examples/yapper_bot.py +0 -0
- {ezytools-0.3.0 → ezytools-0.4.0}/src/ezytools/core.py +0 -0
- {ezytools-0.3.0 → ezytools-0.4.0}/tests/test_botkit.py +0 -0
- {ezytools-0.3.0 → ezytools-0.4.0}/tests/test_developer.py +0 -0
- {ezytools-0.3.0 → ezytools-0.4.0}/tests/test_voice.py +0 -0
- {ezytools-0.3.0 → ezytools-0.4.0}/tests/test_workflows.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: ezytools
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.4.0
|
|
4
4
|
Summary: A Python utility library for Yapper bot developers
|
|
5
5
|
License-Expression: LicenseRef-Proprietary
|
|
6
6
|
License-File: LICENSE
|
|
@@ -13,9 +13,156 @@ Build Yapper bots faster with reusable Python utilities for repetitive bot code.
|
|
|
13
13
|
Keep your command handlers and application logic; use Ezytools for argument
|
|
14
14
|
parsing, validation, moderation, role checks, embeds, and other common tasks.
|
|
15
15
|
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
16
|
+
Install with `python -m pip install .`. The package exports helpers from
|
|
17
|
+
`core.py` and `features.py`. Copying only `core.py` provides the older helpers;
|
|
18
|
+
install the package to use all 0.4.0 features.
|
|
19
|
+
|
|
20
|
+
## What's new
|
|
21
|
+
|
|
22
|
+
**0.4.0:** typed positional arguments, extended role and permission checks,
|
|
23
|
+
persistent server settings and moderation cases, interaction checks and explicit
|
|
24
|
+
acknowledgements, and structured error categories. Additional conveniences include
|
|
25
|
+
argument ranges/choices, resetting settings, and filtered, paginated case history.
|
|
26
|
+
Existing helpers retain their behavior, including `parse_duration` returning None
|
|
27
|
+
for invalid input. New typed parsing raises `ArgumentError` instead.
|
|
28
|
+
|
|
29
|
+
### 0.4.0 command building blocks
|
|
30
|
+
|
|
31
|
+
```python
|
|
32
|
+
import ezytools as e
|
|
33
|
+
|
|
34
|
+
store = e.ServerStore('bot.sqlite3', defaults={'prefix': '!'},
|
|
35
|
+
validators={'prefix': lambda value: isinstance(value, str) and bool(value)})
|
|
36
|
+
|
|
37
|
+
# Inside your own synchronous SDK command:
|
|
38
|
+
def warn_command(msg):
|
|
39
|
+
if not e.has_any_role(bot, msg.server_id, msg.author_id, ['staff', 'admin']):
|
|
40
|
+
return msg.reply('Staff only')
|
|
41
|
+
try:
|
|
42
|
+
values = e.parse_arguments(msg, [
|
|
43
|
+
e.Argument('target', 'user'),
|
|
44
|
+
e.Argument('reason', optional=True, default='No reason provided', rest=True),
|
|
45
|
+
])
|
|
46
|
+
except e.ArgumentError as error:
|
|
47
|
+
return msg.reply(str(error))
|
|
48
|
+
case = store.record_case(msg.server_id, 'warn', msg.author_id,
|
|
49
|
+
values['target'], values['reason'])
|
|
50
|
+
msg.reply(f"Recorded warning case #{case['case_id']}")
|
|
51
|
+
|
|
52
|
+
store.update_settings('server-id', prefix='?')
|
|
53
|
+
settings = store.settings('server-id')
|
|
54
|
+
history = store.list_cases('server-id', target='user-id', limit=10, offset=0)
|
|
55
|
+
# Call store.close() at application shutdown, or use it as a context manager.
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
`Argument` supports `str`, `int`, `float`, `bool`, `'user'`, `'channel'`, and
|
|
59
|
+
`'duration'` (seconds). Use `minimum`, `maximum`, and `choices` for validation.
|
|
60
|
+
Quoted phrases are preserved. Optional arguments follow required arguments;
|
|
61
|
+
only a final string argument may use `rest=True`. Defaults are already-typed
|
|
62
|
+
values. ID parsing validates syntax without fetching a member/channel.
|
|
63
|
+
|
|
64
|
+
`has_any_role`, `has_all_roles`, and `missing_roles` accept bot, server ID,
|
|
65
|
+
user ID, and a nonempty collection of role IDs. SDK failures propagate.
|
|
66
|
+
`is_server_owner(bot, msg)` remains available for an explicit ownership check.
|
|
67
|
+
`has_permissions(effective_permissions, ['kick'])` and `missing_permissions`
|
|
68
|
+
accept permission names or a mapping of names to literal booleans. Supply
|
|
69
|
+
effective permissions from your SDK; EzyTools does not guess permission flags
|
|
70
|
+
or treat an owner/admin role as an implicit bypass.
|
|
71
|
+
|
|
72
|
+
For button handlers, check ownership and expiry before handling an action:
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
decision = e.check_interaction(interaction, owner_id, expires_at=unix_expiry)
|
|
76
|
+
if decision != 'allowed':
|
|
77
|
+
e.acknowledge_interaction(interaction, 'Expired or owned by another user.')
|
|
78
|
+
else:
|
|
79
|
+
e.acknowledge_interaction(interaction) # SDK update(); acknowledge once
|
|
80
|
+
# Perform your own action.
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
`check_interaction` returns `allowed`, `expired`, or `not_owner` without sending
|
|
84
|
+
anything. Acknowledgement calls SDK `ephemeral(content)` or `update()`; callers
|
|
85
|
+
track whether an interaction has already been acknowledged. For page navigation,
|
|
86
|
+
the existing `ButtonPaginator` manages ownership and expiry automatically.
|
|
87
|
+
|
|
88
|
+
`classify_error(error)` returns `ErrorInfo` with `category`, `status`,
|
|
89
|
+
`retry_after`, and the unchanged `original` exception. Categories include
|
|
90
|
+
invalid_request, unauthorized, forbidden, not_found, conflict, rate_limited,
|
|
91
|
+
server_error, timeout, network, and unknown. No automatic retries occur.
|
|
92
|
+
|
|
93
|
+
SQLite storage isolates servers and allocates case IDs per server. Cases contain
|
|
94
|
+
action, moderator, target, reason, and a UTC timestamp. Recording is explicit;
|
|
95
|
+
after a moderation API action succeeds, call `record_case` if desired. The API
|
|
96
|
+
action and database write are separate operations. Settings validators return
|
|
97
|
+
True for accepted values; invalid changes leave saved settings intact.
|
|
98
|
+
`reset_settings(server_id)` removes overrides. Use one store per thread, a local
|
|
99
|
+
database path with an existing parent directory, and back up the database as
|
|
100
|
+
needed. Settings and history survive restarts; paginator sessions do not.
|
|
101
|
+
|
|
102
|
+
**0.3.1 — documentation update:** voice documentation is now near the top,
|
|
103
|
+
with navigation links below. No runtime behavior changed from 0.3.0.
|
|
104
|
+
|
|
105
|
+
**Added in 0.3.0:** 12 voice helpers for moving/disconnecting members,
|
|
106
|
+
bulk actions, voice membership lookups, and bot voice connections.
|
|
107
|
+
|
|
108
|
+
```shell
|
|
109
|
+
python -m pip install --upgrade ezytools
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
## Documentation
|
|
113
|
+
|
|
114
|
+
- [Voice shortcuts and examples](#voice-shortcuts)
|
|
115
|
+
- [Member, role, and channel workflows](#workflows)
|
|
116
|
+
- [Bot-building helpers](#bot-building)
|
|
117
|
+
- [Developer utilities](#developer-utilities)
|
|
118
|
+
- [Moderation utilities](#moderation-utilities)
|
|
119
|
+
- [License](https://github.com/Adecode-23/ezytools/blob/main/LICENSE)
|
|
120
|
+
|
|
121
|
+
<a id="voice-shortcuts"></a>
|
|
122
|
+
|
|
123
|
+
## Voice shortcuts
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
Requires a Yapper SDK exposing `voice`, `move_member`, `disconnect_member`,
|
|
127
|
+
`join_voice`, `leave_voice`, and (for audio) `connect_voice`.
|
|
128
|
+
Existing utilities remain available. Implementations stay in `src/ezytools/core.py`.
|
|
129
|
+
|
|
130
|
+
```python
|
|
131
|
+
import ezytools as e
|
|
132
|
+
|
|
133
|
+
members = e.voice_members(bot, server_id, channel_id)
|
|
134
|
+
count = e.voice_member_count(bot, server_id, channel_id)
|
|
135
|
+
current = e.member_voice_channel(bot, server_id, user_id) # ID or None
|
|
136
|
+
present = e.is_in_voice(bot, server_id, user_id)
|
|
137
|
+
snapshot = e.voice_channels(bot, server_id)
|
|
138
|
+
|
|
139
|
+
# Authorise the command user first (e.g. command_guard / require_roles).
|
|
140
|
+
e.move_member(bot, server_id, user_id, destination_channel_id)
|
|
141
|
+
e.disconnect_member(bot, server_id, user_id)
|
|
142
|
+
e.move_members(bot, server_id, [user_id, other_id], destination_channel_id)
|
|
143
|
+
e.disconnect_members(bot, server_id, [user_id, other_id])
|
|
144
|
+
|
|
145
|
+
# A ticket alone does not connect audio; do not log its secret fields.
|
|
146
|
+
ticket = e.join_voice(bot, server_id, channel_id)
|
|
147
|
+
e.leave_voice(bot, server_id)
|
|
148
|
+
|
|
149
|
+
# Inside an async function, with SDK audio dependencies installed:
|
|
150
|
+
call = await e.connect_voice(bot, server_id, channel_id)
|
|
151
|
+
try:
|
|
152
|
+
pass # Use the SDK call.source to supply audio frames.
|
|
153
|
+
finally:
|
|
154
|
+
await call.leave()
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
Moving requires a member already connected to voice; helpers cannot force
|
|
158
|
+
someone to join a call. Server permissions and SDK errors still apply.
|
|
159
|
+
Bulk actions validate all IDs first and deduplicate them; execution stops at
|
|
160
|
+
the first failure, leaving earlier successful actions applied. Respect platform
|
|
161
|
+
rate limits; there are no automatic retries or background moderation actions.
|
|
162
|
+
Voice snapshots can change between lookup and action. Audio connections require
|
|
163
|
+
the Yapper SDK's optional `livekit` and `cryptography` dependencies.
|
|
164
|
+
|
|
165
|
+
<a id="workflows"></a>
|
|
19
166
|
|
|
20
167
|
## Faster workflows inside your handlers
|
|
21
168
|
|
|
@@ -75,6 +222,8 @@ or expression evaluation; supplied mentions and Markdown stay active.
|
|
|
75
222
|
`msg.argv`. For strict quote validation with usage feedback, use
|
|
76
223
|
`command_arguments(msg, ...)` instead.
|
|
77
224
|
|
|
225
|
+
<a id="bot-building"></a>
|
|
226
|
+
|
|
78
227
|
## Yapper bot-building helpers
|
|
79
228
|
|
|
80
229
|
These helpers use the synchronous Yapper SDK's command, event, member, role,
|
|
@@ -149,6 +298,8 @@ Help reads the command list when invoked, so later commands appear automatically
|
|
|
149
298
|
`hidden=["internal"]` hides names from help only; guards enforce access.
|
|
150
299
|
See [the runnable example](examples/yapper_bot.py) for environment-based setup.
|
|
151
300
|
|
|
301
|
+
<a id="developer-utilities"></a>
|
|
302
|
+
|
|
152
303
|
## Developer utilities
|
|
153
304
|
|
|
154
305
|
Install the package from this checkout (Python 3.10+):
|
|
@@ -283,6 +434,8 @@ your-project/
|
|
|
283
434
|
import ezytools
|
|
284
435
|
```
|
|
285
436
|
|
|
437
|
+
<a id="moderation-utilities"></a>
|
|
438
|
+
|
|
286
439
|
## 🛡️ Moderation Utilities
|
|
287
440
|
|
|
288
441
|
Ezytools currently provides these moderation helpers:
|
|
@@ -453,43 +606,3 @@ More utilities can be added as the library develops.
|
|
|
453
606
|
|
|
454
607
|
|
|
455
608
|
|
|
456
|
-
## Voice shortcuts — 0.3.0
|
|
457
|
-
|
|
458
|
-
Requires a Yapper SDK exposing `voice`, `move_member`, `disconnect_member`,
|
|
459
|
-
`join_voice`, `leave_voice`, and (for audio) `connect_voice`.
|
|
460
|
-
Existing utilities remain available. Implementations stay in `src/ezytools/core.py`.
|
|
461
|
-
|
|
462
|
-
```python
|
|
463
|
-
import ezytools as e
|
|
464
|
-
|
|
465
|
-
members = e.voice_members(bot, server_id, channel_id)
|
|
466
|
-
count = e.voice_member_count(bot, server_id, channel_id)
|
|
467
|
-
current = e.member_voice_channel(bot, server_id, user_id) # ID or None
|
|
468
|
-
present = e.is_in_voice(bot, server_id, user_id)
|
|
469
|
-
snapshot = e.voice_channels(bot, server_id)
|
|
470
|
-
|
|
471
|
-
# Authorise the command user first (e.g. command_guard / require_roles).
|
|
472
|
-
e.move_member(bot, server_id, user_id, destination_channel_id)
|
|
473
|
-
e.disconnect_member(bot, server_id, user_id)
|
|
474
|
-
e.move_members(bot, server_id, [user_id, other_id], destination_channel_id)
|
|
475
|
-
e.disconnect_members(bot, server_id, [user_id, other_id])
|
|
476
|
-
|
|
477
|
-
# A ticket alone does not connect audio; do not log its secret fields.
|
|
478
|
-
ticket = e.join_voice(bot, server_id, channel_id)
|
|
479
|
-
e.leave_voice(bot, server_id)
|
|
480
|
-
|
|
481
|
-
# Inside an async function, with SDK audio dependencies installed:
|
|
482
|
-
call = await e.connect_voice(bot, server_id, channel_id)
|
|
483
|
-
try:
|
|
484
|
-
pass # Use the SDK call.source to supply audio frames.
|
|
485
|
-
finally:
|
|
486
|
-
await call.leave()
|
|
487
|
-
```
|
|
488
|
-
|
|
489
|
-
Moving requires a member already connected to voice; helpers cannot force
|
|
490
|
-
someone to join a call. Server permissions and SDK errors still apply.
|
|
491
|
-
Bulk actions validate all IDs first and deduplicate them; execution stops at
|
|
492
|
-
the first failure, leaving earlier successful actions applied. Respect platform
|
|
493
|
-
rate limits; there are no automatic retries or background moderation actions.
|
|
494
|
-
Voice snapshots can change between lookup and action. Audio connections require
|
|
495
|
-
the Yapper SDK's optional `livekit` and `cryptography` dependencies.
|
|
@@ -4,9 +4,156 @@ Build Yapper bots faster with reusable Python utilities for repetitive bot code.
|
|
|
4
4
|
Keep your command handlers and application logic; use Ezytools for argument
|
|
5
5
|
parsing, validation, moderation, role checks, embeds, and other common tasks.
|
|
6
6
|
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
7
|
+
Install with `python -m pip install .`. The package exports helpers from
|
|
8
|
+
`core.py` and `features.py`. Copying only `core.py` provides the older helpers;
|
|
9
|
+
install the package to use all 0.4.0 features.
|
|
10
|
+
|
|
11
|
+
## What's new
|
|
12
|
+
|
|
13
|
+
**0.4.0:** typed positional arguments, extended role and permission checks,
|
|
14
|
+
persistent server settings and moderation cases, interaction checks and explicit
|
|
15
|
+
acknowledgements, and structured error categories. Additional conveniences include
|
|
16
|
+
argument ranges/choices, resetting settings, and filtered, paginated case history.
|
|
17
|
+
Existing helpers retain their behavior, including `parse_duration` returning None
|
|
18
|
+
for invalid input. New typed parsing raises `ArgumentError` instead.
|
|
19
|
+
|
|
20
|
+
### 0.4.0 command building blocks
|
|
21
|
+
|
|
22
|
+
```python
|
|
23
|
+
import ezytools as e
|
|
24
|
+
|
|
25
|
+
store = e.ServerStore('bot.sqlite3', defaults={'prefix': '!'},
|
|
26
|
+
validators={'prefix': lambda value: isinstance(value, str) and bool(value)})
|
|
27
|
+
|
|
28
|
+
# Inside your own synchronous SDK command:
|
|
29
|
+
def warn_command(msg):
|
|
30
|
+
if not e.has_any_role(bot, msg.server_id, msg.author_id, ['staff', 'admin']):
|
|
31
|
+
return msg.reply('Staff only')
|
|
32
|
+
try:
|
|
33
|
+
values = e.parse_arguments(msg, [
|
|
34
|
+
e.Argument('target', 'user'),
|
|
35
|
+
e.Argument('reason', optional=True, default='No reason provided', rest=True),
|
|
36
|
+
])
|
|
37
|
+
except e.ArgumentError as error:
|
|
38
|
+
return msg.reply(str(error))
|
|
39
|
+
case = store.record_case(msg.server_id, 'warn', msg.author_id,
|
|
40
|
+
values['target'], values['reason'])
|
|
41
|
+
msg.reply(f"Recorded warning case #{case['case_id']}")
|
|
42
|
+
|
|
43
|
+
store.update_settings('server-id', prefix='?')
|
|
44
|
+
settings = store.settings('server-id')
|
|
45
|
+
history = store.list_cases('server-id', target='user-id', limit=10, offset=0)
|
|
46
|
+
# Call store.close() at application shutdown, or use it as a context manager.
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
`Argument` supports `str`, `int`, `float`, `bool`, `'user'`, `'channel'`, and
|
|
50
|
+
`'duration'` (seconds). Use `minimum`, `maximum`, and `choices` for validation.
|
|
51
|
+
Quoted phrases are preserved. Optional arguments follow required arguments;
|
|
52
|
+
only a final string argument may use `rest=True`. Defaults are already-typed
|
|
53
|
+
values. ID parsing validates syntax without fetching a member/channel.
|
|
54
|
+
|
|
55
|
+
`has_any_role`, `has_all_roles`, and `missing_roles` accept bot, server ID,
|
|
56
|
+
user ID, and a nonempty collection of role IDs. SDK failures propagate.
|
|
57
|
+
`is_server_owner(bot, msg)` remains available for an explicit ownership check.
|
|
58
|
+
`has_permissions(effective_permissions, ['kick'])` and `missing_permissions`
|
|
59
|
+
accept permission names or a mapping of names to literal booleans. Supply
|
|
60
|
+
effective permissions from your SDK; EzyTools does not guess permission flags
|
|
61
|
+
or treat an owner/admin role as an implicit bypass.
|
|
62
|
+
|
|
63
|
+
For button handlers, check ownership and expiry before handling an action:
|
|
64
|
+
|
|
65
|
+
```python
|
|
66
|
+
decision = e.check_interaction(interaction, owner_id, expires_at=unix_expiry)
|
|
67
|
+
if decision != 'allowed':
|
|
68
|
+
e.acknowledge_interaction(interaction, 'Expired or owned by another user.')
|
|
69
|
+
else:
|
|
70
|
+
e.acknowledge_interaction(interaction) # SDK update(); acknowledge once
|
|
71
|
+
# Perform your own action.
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
`check_interaction` returns `allowed`, `expired`, or `not_owner` without sending
|
|
75
|
+
anything. Acknowledgement calls SDK `ephemeral(content)` or `update()`; callers
|
|
76
|
+
track whether an interaction has already been acknowledged. For page navigation,
|
|
77
|
+
the existing `ButtonPaginator` manages ownership and expiry automatically.
|
|
78
|
+
|
|
79
|
+
`classify_error(error)` returns `ErrorInfo` with `category`, `status`,
|
|
80
|
+
`retry_after`, and the unchanged `original` exception. Categories include
|
|
81
|
+
invalid_request, unauthorized, forbidden, not_found, conflict, rate_limited,
|
|
82
|
+
server_error, timeout, network, and unknown. No automatic retries occur.
|
|
83
|
+
|
|
84
|
+
SQLite storage isolates servers and allocates case IDs per server. Cases contain
|
|
85
|
+
action, moderator, target, reason, and a UTC timestamp. Recording is explicit;
|
|
86
|
+
after a moderation API action succeeds, call `record_case` if desired. The API
|
|
87
|
+
action and database write are separate operations. Settings validators return
|
|
88
|
+
True for accepted values; invalid changes leave saved settings intact.
|
|
89
|
+
`reset_settings(server_id)` removes overrides. Use one store per thread, a local
|
|
90
|
+
database path with an existing parent directory, and back up the database as
|
|
91
|
+
needed. Settings and history survive restarts; paginator sessions do not.
|
|
92
|
+
|
|
93
|
+
**0.3.1 — documentation update:** voice documentation is now near the top,
|
|
94
|
+
with navigation links below. No runtime behavior changed from 0.3.0.
|
|
95
|
+
|
|
96
|
+
**Added in 0.3.0:** 12 voice helpers for moving/disconnecting members,
|
|
97
|
+
bulk actions, voice membership lookups, and bot voice connections.
|
|
98
|
+
|
|
99
|
+
```shell
|
|
100
|
+
python -m pip install --upgrade ezytools
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
## Documentation
|
|
104
|
+
|
|
105
|
+
- [Voice shortcuts and examples](#voice-shortcuts)
|
|
106
|
+
- [Member, role, and channel workflows](#workflows)
|
|
107
|
+
- [Bot-building helpers](#bot-building)
|
|
108
|
+
- [Developer utilities](#developer-utilities)
|
|
109
|
+
- [Moderation utilities](#moderation-utilities)
|
|
110
|
+
- [License](https://github.com/Adecode-23/ezytools/blob/main/LICENSE)
|
|
111
|
+
|
|
112
|
+
<a id="voice-shortcuts"></a>
|
|
113
|
+
|
|
114
|
+
## Voice shortcuts
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
Requires a Yapper SDK exposing `voice`, `move_member`, `disconnect_member`,
|
|
118
|
+
`join_voice`, `leave_voice`, and (for audio) `connect_voice`.
|
|
119
|
+
Existing utilities remain available. Implementations stay in `src/ezytools/core.py`.
|
|
120
|
+
|
|
121
|
+
```python
|
|
122
|
+
import ezytools as e
|
|
123
|
+
|
|
124
|
+
members = e.voice_members(bot, server_id, channel_id)
|
|
125
|
+
count = e.voice_member_count(bot, server_id, channel_id)
|
|
126
|
+
current = e.member_voice_channel(bot, server_id, user_id) # ID or None
|
|
127
|
+
present = e.is_in_voice(bot, server_id, user_id)
|
|
128
|
+
snapshot = e.voice_channels(bot, server_id)
|
|
129
|
+
|
|
130
|
+
# Authorise the command user first (e.g. command_guard / require_roles).
|
|
131
|
+
e.move_member(bot, server_id, user_id, destination_channel_id)
|
|
132
|
+
e.disconnect_member(bot, server_id, user_id)
|
|
133
|
+
e.move_members(bot, server_id, [user_id, other_id], destination_channel_id)
|
|
134
|
+
e.disconnect_members(bot, server_id, [user_id, other_id])
|
|
135
|
+
|
|
136
|
+
# A ticket alone does not connect audio; do not log its secret fields.
|
|
137
|
+
ticket = e.join_voice(bot, server_id, channel_id)
|
|
138
|
+
e.leave_voice(bot, server_id)
|
|
139
|
+
|
|
140
|
+
# Inside an async function, with SDK audio dependencies installed:
|
|
141
|
+
call = await e.connect_voice(bot, server_id, channel_id)
|
|
142
|
+
try:
|
|
143
|
+
pass # Use the SDK call.source to supply audio frames.
|
|
144
|
+
finally:
|
|
145
|
+
await call.leave()
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
Moving requires a member already connected to voice; helpers cannot force
|
|
149
|
+
someone to join a call. Server permissions and SDK errors still apply.
|
|
150
|
+
Bulk actions validate all IDs first and deduplicate them; execution stops at
|
|
151
|
+
the first failure, leaving earlier successful actions applied. Respect platform
|
|
152
|
+
rate limits; there are no automatic retries or background moderation actions.
|
|
153
|
+
Voice snapshots can change between lookup and action. Audio connections require
|
|
154
|
+
the Yapper SDK's optional `livekit` and `cryptography` dependencies.
|
|
155
|
+
|
|
156
|
+
<a id="workflows"></a>
|
|
10
157
|
|
|
11
158
|
## Faster workflows inside your handlers
|
|
12
159
|
|
|
@@ -66,6 +213,8 @@ or expression evaluation; supplied mentions and Markdown stay active.
|
|
|
66
213
|
`msg.argv`. For strict quote validation with usage feedback, use
|
|
67
214
|
`command_arguments(msg, ...)` instead.
|
|
68
215
|
|
|
216
|
+
<a id="bot-building"></a>
|
|
217
|
+
|
|
69
218
|
## Yapper bot-building helpers
|
|
70
219
|
|
|
71
220
|
These helpers use the synchronous Yapper SDK's command, event, member, role,
|
|
@@ -140,6 +289,8 @@ Help reads the command list when invoked, so later commands appear automatically
|
|
|
140
289
|
`hidden=["internal"]` hides names from help only; guards enforce access.
|
|
141
290
|
See [the runnable example](examples/yapper_bot.py) for environment-based setup.
|
|
142
291
|
|
|
292
|
+
<a id="developer-utilities"></a>
|
|
293
|
+
|
|
143
294
|
## Developer utilities
|
|
144
295
|
|
|
145
296
|
Install the package from this checkout (Python 3.10+):
|
|
@@ -274,6 +425,8 @@ your-project/
|
|
|
274
425
|
import ezytools
|
|
275
426
|
```
|
|
276
427
|
|
|
428
|
+
<a id="moderation-utilities"></a>
|
|
429
|
+
|
|
277
430
|
## 🛡️ Moderation Utilities
|
|
278
431
|
|
|
279
432
|
Ezytools currently provides these moderation helpers:
|
|
@@ -444,43 +597,3 @@ More utilities can be added as the library develops.
|
|
|
444
597
|
|
|
445
598
|
|
|
446
599
|
|
|
447
|
-
## Voice shortcuts — 0.3.0
|
|
448
|
-
|
|
449
|
-
Requires a Yapper SDK exposing `voice`, `move_member`, `disconnect_member`,
|
|
450
|
-
`join_voice`, `leave_voice`, and (for audio) `connect_voice`.
|
|
451
|
-
Existing utilities remain available. Implementations stay in `src/ezytools/core.py`.
|
|
452
|
-
|
|
453
|
-
```python
|
|
454
|
-
import ezytools as e
|
|
455
|
-
|
|
456
|
-
members = e.voice_members(bot, server_id, channel_id)
|
|
457
|
-
count = e.voice_member_count(bot, server_id, channel_id)
|
|
458
|
-
current = e.member_voice_channel(bot, server_id, user_id) # ID or None
|
|
459
|
-
present = e.is_in_voice(bot, server_id, user_id)
|
|
460
|
-
snapshot = e.voice_channels(bot, server_id)
|
|
461
|
-
|
|
462
|
-
# Authorise the command user first (e.g. command_guard / require_roles).
|
|
463
|
-
e.move_member(bot, server_id, user_id, destination_channel_id)
|
|
464
|
-
e.disconnect_member(bot, server_id, user_id)
|
|
465
|
-
e.move_members(bot, server_id, [user_id, other_id], destination_channel_id)
|
|
466
|
-
e.disconnect_members(bot, server_id, [user_id, other_id])
|
|
467
|
-
|
|
468
|
-
# A ticket alone does not connect audio; do not log its secret fields.
|
|
469
|
-
ticket = e.join_voice(bot, server_id, channel_id)
|
|
470
|
-
e.leave_voice(bot, server_id)
|
|
471
|
-
|
|
472
|
-
# Inside an async function, with SDK audio dependencies installed:
|
|
473
|
-
call = await e.connect_voice(bot, server_id, channel_id)
|
|
474
|
-
try:
|
|
475
|
-
pass # Use the SDK call.source to supply audio frames.
|
|
476
|
-
finally:
|
|
477
|
-
await call.leave()
|
|
478
|
-
```
|
|
479
|
-
|
|
480
|
-
Moving requires a member already connected to voice; helpers cannot force
|
|
481
|
-
someone to join a call. Server permissions and SDK errors still apply.
|
|
482
|
-
Bulk actions validate all IDs first and deduplicate them; execution stops at
|
|
483
|
-
the first failure, leaving earlier successful actions applied. Respect platform
|
|
484
|
-
rate limits; there are no automatic retries or background moderation actions.
|
|
485
|
-
Voice snapshots can change between lookup and action. Audio connections require
|
|
486
|
-
the Yapper SDK's optional `livekit` and `cryptography` dependencies.
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""Ezytools: reusable command building blocks for Yapper bots."""
|
|
2
|
+
from .core import *
|
|
3
|
+
from .core import __all__ as _core_all
|
|
4
|
+
from .features import *
|
|
5
|
+
from .features import __all__ as _features_all
|
|
6
|
+
__all__ = _core_all + _features_all
|
|
7
|
+
|
|
8
|
+
__version__ = '0.4.0'
|
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
"""Explicit, dependency-free building blocks for developer-owned commands."""
|
|
2
|
+
import copy
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from datetime import datetime, timezone
|
|
5
|
+
import json
|
|
6
|
+
import math
|
|
7
|
+
import re
|
|
8
|
+
import shlex
|
|
9
|
+
import sqlite3
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class ArgumentError(ValueError):
|
|
13
|
+
"""Invalid command input; safe to display to the command user."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True)
|
|
17
|
+
class Argument:
|
|
18
|
+
"""A positional argument. Optional arguments must follow required ones.
|
|
19
|
+
|
|
20
|
+
kind: str, int, float, bool, 'user', 'channel', or 'duration' (seconds).
|
|
21
|
+
rest consumes remaining tokens. Defaults are returned as supplied.
|
|
22
|
+
"""
|
|
23
|
+
name: str
|
|
24
|
+
kind: object = str
|
|
25
|
+
optional: bool = False
|
|
26
|
+
default: object = None
|
|
27
|
+
minimum: object = None
|
|
28
|
+
maximum: object = None
|
|
29
|
+
choices: object = None
|
|
30
|
+
rest: bool = False
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def parse_arguments(source, arguments):
|
|
34
|
+
"""Parse a string, token iterable, or SDK message into a named dictionary.
|
|
35
|
+
|
|
36
|
+
Raises ArgumentError without replying or invoking bot actions.
|
|
37
|
+
Duration accepts positive integer s/m/h/d units, defaulting to seconds.
|
|
38
|
+
IDs accept letters, digits, underscores and hyphens; no network lookup.
|
|
39
|
+
"""
|
|
40
|
+
specs = list(arguments)
|
|
41
|
+
optional = False
|
|
42
|
+
names = set()
|
|
43
|
+
for index, spec in enumerate(specs):
|
|
44
|
+
if not isinstance(spec, Argument) or not spec.name or spec.name in names:
|
|
45
|
+
raise ValueError('Arguments need unique nonempty names')
|
|
46
|
+
if spec.kind not in (str, int, float, bool, 'user', 'channel', 'duration'):
|
|
47
|
+
raise ValueError('Unsupported argument kind')
|
|
48
|
+
if optional and not spec.optional:
|
|
49
|
+
raise ValueError('Required arguments must precede optional arguments')
|
|
50
|
+
if spec.rest and (index != len(specs) - 1 or spec.kind is not str):
|
|
51
|
+
raise ValueError('Only the final string argument may consume remaining tokens')
|
|
52
|
+
optional = optional or spec.optional
|
|
53
|
+
names.add(spec.name)
|
|
54
|
+
if hasattr(source, 'args'):
|
|
55
|
+
source = source.args or ''
|
|
56
|
+
try:
|
|
57
|
+
tokens = shlex.split(source) if isinstance(source, str) else list(source)
|
|
58
|
+
except ValueError as exc:
|
|
59
|
+
raise ArgumentError(f'Invalid quoting: {exc}') from exc
|
|
60
|
+
result = {}
|
|
61
|
+
for spec in specs:
|
|
62
|
+
if not tokens:
|
|
63
|
+
if not spec.optional:
|
|
64
|
+
raise ArgumentError(f'{spec.name}: required argument is missing')
|
|
65
|
+
result[spec.name] = copy.deepcopy(spec.default)
|
|
66
|
+
continue
|
|
67
|
+
raw = ' '.join(tokens) if spec.rest else tokens[0]
|
|
68
|
+
tokens = [] if spec.rest else tokens[1:]
|
|
69
|
+
try:
|
|
70
|
+
if spec.kind in ('user', 'channel'):
|
|
71
|
+
pattern = r'<@!?([\w-]+)>|([\w-]+)' if spec.kind == 'user' else r'<#([\w-]+)>|([\w-]+)'
|
|
72
|
+
match = re.fullmatch(pattern, raw, flags=re.ASCII)
|
|
73
|
+
if not match:
|
|
74
|
+
raise ValueError('expected an ID or mention')
|
|
75
|
+
value = match.group(1) or match.group(2)
|
|
76
|
+
elif spec.kind == 'duration':
|
|
77
|
+
match = re.fullmatch(r'([0-9]+)([smhd]?)', raw.lower())
|
|
78
|
+
if not match or int(match.group(1)) <= 0:
|
|
79
|
+
raise ValueError('expected a positive duration such as 10m')
|
|
80
|
+
value = int(match.group(1)) * {'': 1, 's': 1, 'm': 60, 'h': 3600, 'd': 86400}[match.group(2)]
|
|
81
|
+
elif spec.kind is bool:
|
|
82
|
+
if raw.lower() not in ('true', 'false', 'yes', 'no', '1', '0'):
|
|
83
|
+
raise ValueError('expected true/false, yes/no, or 1/0')
|
|
84
|
+
value = raw.lower() in ('true', 'yes', '1')
|
|
85
|
+
else:
|
|
86
|
+
value = spec.kind(raw)
|
|
87
|
+
if isinstance(value, float) and not math.isfinite(value):
|
|
88
|
+
raise ValueError('expected a finite number')
|
|
89
|
+
if spec.minimum is not None and value < spec.minimum:
|
|
90
|
+
raise ValueError(f'must be at least {spec.minimum}')
|
|
91
|
+
if spec.maximum is not None and value > spec.maximum:
|
|
92
|
+
raise ValueError(f'must be at most {spec.maximum}')
|
|
93
|
+
if spec.choices is not None and value not in spec.choices:
|
|
94
|
+
raise ValueError(f'expected one of {list(spec.choices)}')
|
|
95
|
+
except (ValueError, TypeError) as exc:
|
|
96
|
+
raise ArgumentError(f'{spec.name}: {exc}') from exc
|
|
97
|
+
result[spec.name] = value
|
|
98
|
+
if tokens:
|
|
99
|
+
raise ArgumentError('Too many arguments')
|
|
100
|
+
return result
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _ids(values):
|
|
104
|
+
if isinstance(values, (str, bytes)):
|
|
105
|
+
raise ValueError('Pass a collection of IDs, not a string')
|
|
106
|
+
result = list(dict.fromkeys(str(value) for value in values))
|
|
107
|
+
if not result or any(not value.strip() for value in result):
|
|
108
|
+
raise ValueError('Provide at least one nonempty ID')
|
|
109
|
+
return result
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def missing_roles(bot, server_id, user_id, role_ids):
|
|
113
|
+
"""Return missing role IDs in requested order. SDK errors propagate."""
|
|
114
|
+
from .core import member_role_ids
|
|
115
|
+
required = _ids(role_ids)
|
|
116
|
+
actual = set(member_role_ids(bot.member(server_id, user_id)))
|
|
117
|
+
return [role for role in required if role not in actual]
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def has_all_roles(bot, server_id, user_id, role_ids):
|
|
121
|
+
return not missing_roles(bot, server_id, user_id, role_ids)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def has_any_role(bot, server_id, user_id, role_ids):
|
|
125
|
+
required = _ids(role_ids)
|
|
126
|
+
return len(missing_roles(bot, server_id, user_id, required)) < len(required)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def missing_permissions(permissions, required):
|
|
130
|
+
"""Check SDK-exposed names, supplied as a collection or bool mapping.
|
|
131
|
+
|
|
132
|
+
No guessed bit flags, role inference, administrator or owner bypass.
|
|
133
|
+
Pass the SDK's effective permissions for the relevant member/channel.
|
|
134
|
+
"""
|
|
135
|
+
required = _ids(required)
|
|
136
|
+
if isinstance(permissions, dict):
|
|
137
|
+
actual = {str(key) for key, value in permissions.items() if value is True}
|
|
138
|
+
else:
|
|
139
|
+
if isinstance(permissions, (str, bytes)) or permissions is None:
|
|
140
|
+
raise ValueError('Provide permission names or a boolean mapping')
|
|
141
|
+
actual = set(map(str, permissions))
|
|
142
|
+
return [name for name in required if name not in actual]
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def has_permissions(permissions, required):
|
|
146
|
+
return not missing_permissions(permissions, required)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
@dataclass(frozen=True)
|
|
150
|
+
class ErrorInfo:
|
|
151
|
+
category: str
|
|
152
|
+
original: Exception
|
|
153
|
+
status: object = None
|
|
154
|
+
retry_after: object = None
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def classify_error(error):
|
|
158
|
+
"""Preserve the error; categorize HTTP status or standard network errors.
|
|
159
|
+
|
|
160
|
+
Does not retry actions, log secrets, or send a reply.
|
|
161
|
+
"""
|
|
162
|
+
status = getattr(error, 'status', getattr(error, 'status_code', None))
|
|
163
|
+
category = {400: 'invalid_request', 401: 'unauthorized', 403: 'forbidden',
|
|
164
|
+
404: 'not_found', 409: 'conflict', 429: 'rate_limited'}.get(status)
|
|
165
|
+
if category is None:
|
|
166
|
+
category = ('server_error' if isinstance(status, int) and 500 <= status <= 599
|
|
167
|
+
else 'timeout' if isinstance(error, TimeoutError)
|
|
168
|
+
else 'network' if isinstance(error, ConnectionError) else 'unknown')
|
|
169
|
+
return ErrorInfo(category, error, status, getattr(error, 'retry_after', None))
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def check_interaction(interaction, owner_id, *, expires_at=None, now=None):
|
|
173
|
+
"""Return allowed/expired/not_owner without acknowledging. Times are Unix seconds."""
|
|
174
|
+
import time
|
|
175
|
+
if expires_at is not None and (time.time() if now is None else now) >= expires_at:
|
|
176
|
+
return 'expired'
|
|
177
|
+
return 'allowed' if str(interaction.user_id) == str(owner_id) else 'not_owner'
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def acknowledge_interaction(interaction, content=None):
|
|
181
|
+
"""Explicitly acknowledge via SDK ephemeral(content) or update(). Call once.
|
|
182
|
+
|
|
183
|
+
The caller owns acknowledgement state; SDK failures propagate.
|
|
184
|
+
"""
|
|
185
|
+
return interaction.update() if content is None else interaction.ephemeral(content)
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
class ServerStore:
|
|
189
|
+
"""SQLite settings and moderation history. Use a file for persistence.
|
|
190
|
+
|
|
191
|
+
Each instance belongs to its creating thread; use a context manager or close().
|
|
192
|
+
Settings updates are transactional. No bot actions are automatically recorded.
|
|
193
|
+
validators maps setting names to callables returning True for valid values.
|
|
194
|
+
"""
|
|
195
|
+
def __init__(self, path, *, defaults=None, validators=None):
|
|
196
|
+
self.defaults = copy.deepcopy(defaults or {})
|
|
197
|
+
self.validators = dict(validators or {})
|
|
198
|
+
self._validate(self.defaults)
|
|
199
|
+
self._db = sqlite3.connect(str(path))
|
|
200
|
+
self._db.row_factory = sqlite3.Row
|
|
201
|
+
self._db.executescript('''
|
|
202
|
+
CREATE TABLE IF NOT EXISTS ezy_settings (
|
|
203
|
+
server TEXT PRIMARY KEY, data TEXT NOT NULL);
|
|
204
|
+
CREATE TABLE IF NOT EXISTS ezy_cases (
|
|
205
|
+
server TEXT NOT NULL, case_id INTEGER NOT NULL,
|
|
206
|
+
action TEXT NOT NULL, moderator TEXT NOT NULL, target TEXT NOT NULL,
|
|
207
|
+
reason TEXT NOT NULL, timestamp TEXT NOT NULL,
|
|
208
|
+
PRIMARY KEY (server, case_id));
|
|
209
|
+
CREATE INDEX IF NOT EXISTS ezy_case_target ON ezy_cases(server, target);
|
|
210
|
+
''')
|
|
211
|
+
|
|
212
|
+
def _validate(self, values):
|
|
213
|
+
json.dumps(values, allow_nan=False)
|
|
214
|
+
for key, value in values.items():
|
|
215
|
+
if key in self.validators and self.validators[key](value) is not True:
|
|
216
|
+
raise ValueError(f'Invalid setting: {key}')
|
|
217
|
+
|
|
218
|
+
def settings(self, server_id):
|
|
219
|
+
row = self._db.execute('SELECT data FROM ezy_settings WHERE server=?', (str(server_id),)).fetchone()
|
|
220
|
+
return {**copy.deepcopy(self.defaults), **(json.loads(row[0]) if row else {})}
|
|
221
|
+
|
|
222
|
+
def update_settings(self, server_id, **changes):
|
|
223
|
+
self._validate(changes)
|
|
224
|
+
with self._db:
|
|
225
|
+
self._db.execute('BEGIN IMMEDIATE')
|
|
226
|
+
values = self.settings(server_id)
|
|
227
|
+
values.update(changes)
|
|
228
|
+
self._validate(values)
|
|
229
|
+
self._db.execute('INSERT OR REPLACE INTO ezy_settings VALUES (?,?)',
|
|
230
|
+
(str(server_id), json.dumps(values, allow_nan=False)))
|
|
231
|
+
return values
|
|
232
|
+
|
|
233
|
+
def reset_settings(self, server_id):
|
|
234
|
+
"""Remove server overrides and return independent defaults."""
|
|
235
|
+
with self._db:
|
|
236
|
+
self._db.execute('DELETE FROM ezy_settings WHERE server=?', (str(server_id),))
|
|
237
|
+
return self.settings(server_id)
|
|
238
|
+
|
|
239
|
+
def record_case(self, server_id, action, moderator, target, reason='No reason provided'):
|
|
240
|
+
"""Allocate a per-server case ID atomically; return the saved dictionary."""
|
|
241
|
+
if any(value is None or not str(value).strip() for value in (server_id, action, moderator, target)):
|
|
242
|
+
raise ValueError('Server, action, moderator and target are required')
|
|
243
|
+
with self._db:
|
|
244
|
+
self._db.execute('BEGIN IMMEDIATE')
|
|
245
|
+
case_id = self._db.execute('SELECT COALESCE(MAX(case_id),0)+1 FROM ezy_cases WHERE server=?',
|
|
246
|
+
(str(server_id),)).fetchone()[0]
|
|
247
|
+
self._db.execute('INSERT INTO ezy_cases VALUES (?,?,?,?,?,?,?)',
|
|
248
|
+
(str(server_id), case_id, str(action), str(moderator), str(target),
|
|
249
|
+
str(reason), datetime.now(timezone.utc).isoformat()))
|
|
250
|
+
return self.get_case(server_id, case_id)
|
|
251
|
+
|
|
252
|
+
def get_case(self, server_id, case_id):
|
|
253
|
+
row = self._db.execute('SELECT * FROM ezy_cases WHERE server=? AND case_id=?',
|
|
254
|
+
(str(server_id), case_id)).fetchone()
|
|
255
|
+
return dict(row) if row else None
|
|
256
|
+
|
|
257
|
+
def list_cases(self, server_id, *, target=None, action=None, limit=100, offset=0):
|
|
258
|
+
"""Newest first, with optional target/action filters and bounded pagination."""
|
|
259
|
+
if type(limit) is not int or not 1 <= limit <= 1000 or type(offset) is not int or offset < 0:
|
|
260
|
+
raise ValueError('limit must be 1..1000 and offset a nonnegative integer')
|
|
261
|
+
query, params = 'SELECT * FROM ezy_cases WHERE server=?', [str(server_id)]
|
|
262
|
+
for field, value in (('target', target), ('action', action)):
|
|
263
|
+
if value is not None:
|
|
264
|
+
query += f' AND {field}=?'
|
|
265
|
+
params.append(str(value))
|
|
266
|
+
return [dict(row) for row in self._db.execute(query + ' ORDER BY case_id DESC LIMIT ? OFFSET ?',
|
|
267
|
+
[*params, limit, offset])]
|
|
268
|
+
|
|
269
|
+
def close(self):
|
|
270
|
+
self._db.close()
|
|
271
|
+
|
|
272
|
+
def __enter__(self):
|
|
273
|
+
return self
|
|
274
|
+
|
|
275
|
+
def __exit__(self, *exc):
|
|
276
|
+
self.close()
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
__all__ = [name for name, value in list(globals().items())
|
|
280
|
+
if not name.startswith('_') and callable(value) and getattr(value, '__module__', None) == __name__]
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import tempfile
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
from types import SimpleNamespace
|
|
4
|
+
import unittest
|
|
5
|
+
from unittest.mock import Mock
|
|
6
|
+
|
|
7
|
+
import ezytools as e
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class FeaturesTests(unittest.TestCase):
|
|
11
|
+
def test_typed_arguments(self):
|
|
12
|
+
specs = [e.Argument('user', 'user'), e.Argument('time', 'duration', maximum=3600),
|
|
13
|
+
e.Argument('reason', optional=True, default='none', rest=True)]
|
|
14
|
+
self.assertEqual(e.parse_arguments('<@!abc> 10m two words', specs),
|
|
15
|
+
{'user': 'abc', 'time': 600, 'reason': 'two words'})
|
|
16
|
+
self.assertEqual(e.parse_arguments('abc 1s', specs)['reason'], 'none')
|
|
17
|
+
for text in ('<@&abc> 1m', 'abc 0s', 'abc 2h', 'abc', '"unfinished'):
|
|
18
|
+
with self.assertRaises(e.ArgumentError):
|
|
19
|
+
e.parse_arguments(text, specs)
|
|
20
|
+
self.assertEqual(e.parse_arguments('<#c> 4 yes', [e.Argument('c', 'channel'),
|
|
21
|
+
e.Argument('n', int, minimum=1, choices=[4]), e.Argument('b', bool)]),
|
|
22
|
+
{'c': 'c', 'n': 4, 'b': True})
|
|
23
|
+
for text in ('nan', 'inf', '-inf'):
|
|
24
|
+
with self.assertRaises(e.ArgumentError):
|
|
25
|
+
e.parse_arguments(text, [e.Argument('n', float)])
|
|
26
|
+
with self.assertRaises(e.ArgumentError):
|
|
27
|
+
e.parse_arguments('one extra', [e.Argument('one')])
|
|
28
|
+
with self.assertRaises(ValueError):
|
|
29
|
+
e.parse_arguments('', [e.Argument('x', optional=True), e.Argument('y')])
|
|
30
|
+
|
|
31
|
+
def test_roles_and_permissions(self):
|
|
32
|
+
bot = Mock()
|
|
33
|
+
bot.member.return_value = {'roles': [{'id': 'staff'}]}
|
|
34
|
+
self.assertTrue(e.has_any_role(bot, 's', 'u', ['staff', 'admin']))
|
|
35
|
+
self.assertFalse(e.has_all_roles(bot, 's', 'u', ['staff', 'admin']))
|
|
36
|
+
self.assertEqual(e.missing_roles(bot, 's', 'u', ['admin', 'admin']), ['admin'])
|
|
37
|
+
with self.assertRaises(ValueError):
|
|
38
|
+
e.has_all_roles(bot, 's', 'u', [])
|
|
39
|
+
self.assertEqual(e.missing_permissions({'kick': True, 'ban': False}, ['kick', 'ban']), ['ban'])
|
|
40
|
+
self.assertFalse(e.has_permissions({}, ['kick']))
|
|
41
|
+
self.assertTrue(e.has_permissions(['kick'], ['kick']))
|
|
42
|
+
bot.member.side_effect = RuntimeError('offline')
|
|
43
|
+
with self.assertRaises(RuntimeError):
|
|
44
|
+
e.has_any_role(bot, 's', 'u', ['staff'])
|
|
45
|
+
|
|
46
|
+
def test_persistence_validation_and_isolation(self):
|
|
47
|
+
with tempfile.TemporaryDirectory() as directory:
|
|
48
|
+
path = Path(directory) / 'bot.sqlite3'
|
|
49
|
+
with e.ServerStore(path, defaults={'prefix': '!'},
|
|
50
|
+
validators={'prefix': lambda v: isinstance(v, str) and bool(v)}) as store:
|
|
51
|
+
store.update_settings('s', prefix='?')
|
|
52
|
+
with self.assertRaises(ValueError):
|
|
53
|
+
store.update_settings('s', prefix='')
|
|
54
|
+
self.assertEqual(store.settings('s'), {'prefix': '?'})
|
|
55
|
+
self.assertEqual(store.settings('other'), {'prefix': '!'})
|
|
56
|
+
self.assertEqual(store.record_case('s', 'warn', 'mod', 'user')['case_id'], 1)
|
|
57
|
+
self.assertEqual(store.record_case('s', 'ban', 'mod', 'other')['case_id'], 2)
|
|
58
|
+
self.assertEqual(store.record_case('other', 'warn', 'mod', 'user')['case_id'], 1)
|
|
59
|
+
self.assertEqual(len(store.list_cases('s', target='user')), 1)
|
|
60
|
+
self.assertEqual(store.list_cases('s', action='ban')[0]['target'], 'other')
|
|
61
|
+
self.assertEqual(store.list_cases('s', limit=1, offset=1)[0]['case_id'], 1)
|
|
62
|
+
self.assertIsNone(store.get_case('missing', 1))
|
|
63
|
+
with e.ServerStore(path, defaults={'prefix': '!'}) as store:
|
|
64
|
+
self.assertEqual(store.settings('s')['prefix'], '?')
|
|
65
|
+
self.assertEqual(len(store.list_cases('s')), 2)
|
|
66
|
+
self.assertEqual(store.reset_settings('s'), {'prefix': '!'})
|
|
67
|
+
|
|
68
|
+
def test_errors_and_interactions(self):
|
|
69
|
+
error = RuntimeError('original')
|
|
70
|
+
error.status = 429
|
|
71
|
+
error.retry_after = 5
|
|
72
|
+
info = e.classify_error(error)
|
|
73
|
+
self.assertIs(info.original, error)
|
|
74
|
+
self.assertEqual((info.category, info.retry_after), ('rate_limited', 5))
|
|
75
|
+
self.assertEqual(e.classify_error(TimeoutError()).category, 'timeout')
|
|
76
|
+
interaction = SimpleNamespace(user_id='u', ephemeral=Mock(), update=Mock())
|
|
77
|
+
self.assertEqual(e.check_interaction(interaction, 'u', expires_at=10, now=9), 'allowed')
|
|
78
|
+
self.assertEqual(e.check_interaction(interaction, 'u', expires_at=10, now=10), 'expired')
|
|
79
|
+
self.assertEqual(e.check_interaction(interaction, 'other'), 'not_owner')
|
|
80
|
+
interaction.update.assert_not_called()
|
|
81
|
+
e.acknowledge_interaction(interaction)
|
|
82
|
+
interaction.update.assert_called_once_with()
|
|
83
|
+
e.acknowledge_interaction(interaction, 'Done')
|
|
84
|
+
interaction.ephemeral.assert_called_once_with('Done')
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
if __name__ == '__main__':
|
|
88
|
+
unittest.main()
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|