hungernetbot 1.0.dev1__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.
- hungernetbot/__init__.py +15 -0
- hungernetbot/__main__.py +4 -0
- hungernetbot/bot.py +126 -0
- hungernetbot/commands/__init__.py +11 -0
- hungernetbot/commands/general.py +42 -0
- hungernetbot/commands/github.py +117 -0
- hungernetbot/commands/posts.py +76 -0
- hungernetbot/commands/server.py +231 -0
- hungernetbot/config.py +81 -0
- hungernetbot/database.py +164 -0
- hungernetbot/embeds.py +31 -0
- hungernetbot/emojis.py +160 -0
- hungernetbot/github/__init__.py +3 -0
- hungernetbot/github/dispatcher.py +83 -0
- hungernetbot/github/events.py +246 -0
- hungernetbot/github/repo.py +16 -0
- hungernetbot/github/security.py +12 -0
- hungernetbot/github/server.py +59 -0
- hungernetbot/posts.py +253 -0
- hungernetbot/runner.py +15 -0
- hungernetbot/webhooks.py +126 -0
- hungernetbot-1.0.dev1.dist-info/METADATA +127 -0
- hungernetbot-1.0.dev1.dist-info/RECORD +27 -0
- hungernetbot-1.0.dev1.dist-info/WHEEL +5 -0
- hungernetbot-1.0.dev1.dist-info/entry_points.txt +2 -0
- hungernetbot-1.0.dev1.dist-info/licenses/LICENSE +674 -0
- hungernetbot-1.0.dev1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
from datetime import datetime, timezone
|
|
2
|
+
|
|
3
|
+
import discord
|
|
4
|
+
from mapres import res
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def build_event_embed(event, payload, owner_id):
|
|
8
|
+
entry = EVENT_BUILDERS.get(event)
|
|
9
|
+
if entry is None:
|
|
10
|
+
return None, None
|
|
11
|
+
category, builder = entry
|
|
12
|
+
embed, notify_owner = builder(payload)
|
|
13
|
+
if embed is None:
|
|
14
|
+
return category, None
|
|
15
|
+
if notify_owner:
|
|
16
|
+
description = embed.description or ''
|
|
17
|
+
embed.description = f'{description}\n\n<@{owner_id}>' if description else f'<@{owner_id}>'
|
|
18
|
+
return category, embed
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _build_issue(payload):
|
|
22
|
+
action = payload.get('action')
|
|
23
|
+
if action not in {'opened', 'closed', 'reopened'}:
|
|
24
|
+
return None, False
|
|
25
|
+
issue = payload.get('issue') or {}
|
|
26
|
+
number = issue.get('number', '?')
|
|
27
|
+
title = issue.get('title') or '(no title)'
|
|
28
|
+
if action == 'opened':
|
|
29
|
+
label, color = res(':issue: Issue opened'), 0x2DA44E
|
|
30
|
+
elif action == 'reopened':
|
|
31
|
+
label, color = res(':issue: Issue reopened'), 0x2DA44E
|
|
32
|
+
elif issue.get('state_reason') == 'completed':
|
|
33
|
+
label, color = res(':success: Issue completed'), 0x8250DF
|
|
34
|
+
else:
|
|
35
|
+
label, color = res(':failure: Issue closed'), 0x6E7781
|
|
36
|
+
body = issue.get('body') if action == 'opened' else None
|
|
37
|
+
embed = _base_embed(payload, f'{label} · #{number} {title}', issue.get('html_url'), color, body)
|
|
38
|
+
_add_labels(embed, issue.get('labels'))
|
|
39
|
+
return embed, False
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _build_pull_request(payload):
|
|
43
|
+
action = payload.get('action')
|
|
44
|
+
supported = {'opened', 'closed', 'reopened', 'ready_for_review', 'review_requested'}
|
|
45
|
+
if action not in supported:
|
|
46
|
+
return None, False
|
|
47
|
+
pull = payload.get('pull_request') or {}
|
|
48
|
+
number = pull.get('number', '?')
|
|
49
|
+
title = pull.get('title') or '(no title)'
|
|
50
|
+
merged = bool(pull.get('merged'))
|
|
51
|
+
draft = bool(pull.get('draft'))
|
|
52
|
+
if action == 'opened':
|
|
53
|
+
label = res(':pull_request: Draft pull request opened') if draft else res(':pull_request: Pull request opened')
|
|
54
|
+
color = 0x6E7781 if draft else 0x2DA44E
|
|
55
|
+
elif action == 'reopened':
|
|
56
|
+
label, color = res(':pull_request: Pull request reopened'), 0x2DA44E
|
|
57
|
+
elif action == 'ready_for_review':
|
|
58
|
+
label, color = res(':success: Pull request ready for review'), 0x2DA44E
|
|
59
|
+
elif action == 'review_requested':
|
|
60
|
+
reviewer = (payload.get('requested_reviewer') or {}).get('login')
|
|
61
|
+
review_label = res(':review: Review requested')
|
|
62
|
+
label = f'{review_label}: {reviewer}' if reviewer else review_label
|
|
63
|
+
color = 0x0969DA
|
|
64
|
+
elif merged:
|
|
65
|
+
label, color = res(':success: Pull request merged'), 0x8250DF
|
|
66
|
+
else:
|
|
67
|
+
label, color = res(':failure: Pull request closed'), 0xCF222E
|
|
68
|
+
|
|
69
|
+
body = pull.get('body') if action == 'opened' else None
|
|
70
|
+
embed = _base_embed(payload, f'{label} · #{number} {title}', pull.get('html_url'), color, body)
|
|
71
|
+
head = (pull.get('head') or {}).get('ref')
|
|
72
|
+
base = (pull.get('base') or {}).get('ref')
|
|
73
|
+
if head and base:
|
|
74
|
+
embed.add_field(name='Branches', value=f'`{head}` → `{base}`', inline=True)
|
|
75
|
+
changed = pull.get('changed_files')
|
|
76
|
+
if changed is not None:
|
|
77
|
+
additions = pull.get('additions') or 0
|
|
78
|
+
deletions = pull.get('deletions') or 0
|
|
79
|
+
embed.add_field(
|
|
80
|
+
name='Changes',
|
|
81
|
+
value=f'{changed} files · +{additions} / -{deletions}',
|
|
82
|
+
inline=True,
|
|
83
|
+
)
|
|
84
|
+
_add_labels(embed, pull.get('labels'))
|
|
85
|
+
return embed, False
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _build_review(payload):
|
|
89
|
+
if payload.get('action') != 'submitted':
|
|
90
|
+
return None, False
|
|
91
|
+
review = payload.get('review') or {}
|
|
92
|
+
pull = payload.get('pull_request') or {}
|
|
93
|
+
state = (review.get('state') or '').lower()
|
|
94
|
+
if state == 'approved':
|
|
95
|
+
label, color = res(':success: Review approved'), 0x2DA44E
|
|
96
|
+
elif state == 'changes_requested':
|
|
97
|
+
label, color = res(':status_warning: Changes requested'), 0xBF8700
|
|
98
|
+
elif state == 'commented' and (review.get('body') or '').strip():
|
|
99
|
+
label, color = 'Review comment', 0x0969DA
|
|
100
|
+
else:
|
|
101
|
+
return None, False
|
|
102
|
+
title = pull.get('title') or '(no title)'
|
|
103
|
+
number = pull.get('number', '?')
|
|
104
|
+
url = review.get('html_url') or pull.get('html_url')
|
|
105
|
+
embed = _base_embed(payload, f'{label} on #{number} {title}', url, color, review.get('body'))
|
|
106
|
+
return embed, False
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _build_push(payload):
|
|
110
|
+
ref = payload.get('ref') or ''
|
|
111
|
+
if ref.startswith('refs/tags/'):
|
|
112
|
+
return None, False
|
|
113
|
+
branch = ref.rsplit('/', 1)[-1] if ref else '?'
|
|
114
|
+
if any(tag in branch.lower() for tag in ('-dev', '-alpha', '-beta')):
|
|
115
|
+
return None, False
|
|
116
|
+
commits = payload.get('commits') or []
|
|
117
|
+
created = bool(payload.get('created'))
|
|
118
|
+
deleted = bool(payload.get('deleted'))
|
|
119
|
+
forced = bool(payload.get('forced'))
|
|
120
|
+
if not commits and not (created or deleted):
|
|
121
|
+
return None, False
|
|
122
|
+
if deleted:
|
|
123
|
+
label, color = f'Branch `{branch}` deleted', 0xCF222E
|
|
124
|
+
elif created:
|
|
125
|
+
label, color = f'Branch `{branch}` created', 0x2DA44E
|
|
126
|
+
elif forced:
|
|
127
|
+
label, color = f'Force push to `{branch}`', 0xBF8700
|
|
128
|
+
else:
|
|
129
|
+
count = len(commits)
|
|
130
|
+
suffix = 's' if count != 1 else ''
|
|
131
|
+
label, color = f'{count} commit{suffix} pushed to `{branch}`', 0x0969DA
|
|
132
|
+
if deleted:
|
|
133
|
+
label = res(f':failure: {label}')
|
|
134
|
+
elif forced:
|
|
135
|
+
label = res(f':status_warning: {label}')
|
|
136
|
+
else:
|
|
137
|
+
label = res(f':push: {label}')
|
|
138
|
+
|
|
139
|
+
lines = []
|
|
140
|
+
for commit in commits[:10]:
|
|
141
|
+
sha = (commit.get('id') or '')[:7]
|
|
142
|
+
message = (commit.get('message') or '').splitlines()
|
|
143
|
+
message = message[0] if message else '(no message)'
|
|
144
|
+
url = commit.get('url')
|
|
145
|
+
lines.append(f'{_truncate(message, 90)} · [`{sha}`]({url})')
|
|
146
|
+
if len(commits) > 10:
|
|
147
|
+
lines.append(f'And {len(commits) - 10} more commit(s)')
|
|
148
|
+
embed = _base_embed(payload, label, payload.get('compare'), color, '\n'.join(lines) or None)
|
|
149
|
+
return embed, False
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _build_release(payload):
|
|
153
|
+
if payload.get('action') != 'published':
|
|
154
|
+
return None, False
|
|
155
|
+
release = payload.get('release') or {}
|
|
156
|
+
tag = release.get('tag_name') or '?'
|
|
157
|
+
if any(value in tag.lower() for value in ('-dev', '-alpha', '-beta')):
|
|
158
|
+
return None, False
|
|
159
|
+
repo_name = (payload.get('repository') or {}).get('name') or 'repository'
|
|
160
|
+
label = res(f':release: {repo_name} `{tag}` published')
|
|
161
|
+
return _base_embed(payload, label, release.get('html_url'), 0x8250DF, release.get('body')), False
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _build_workflow(payload):
|
|
165
|
+
if payload.get('action') != 'completed':
|
|
166
|
+
return None, False
|
|
167
|
+
workflow = payload.get('workflow_run') or {}
|
|
168
|
+
conclusion = (workflow.get('conclusion') or 'completed').lower()
|
|
169
|
+
name = workflow.get('name') or 'Workflow'
|
|
170
|
+
branch = workflow.get('head_branch') or '?'
|
|
171
|
+
if name == 'Versioned Release' and conclusion == 'success':
|
|
172
|
+
return None, False
|
|
173
|
+
icons = {
|
|
174
|
+
'success': (res(':success:'), 0x2DA44E),
|
|
175
|
+
'failure': (res(':failure:'), 0xCF222E),
|
|
176
|
+
'cancelled': (res(':status_warning:'), 0x6E7781),
|
|
177
|
+
'timed_out': (res(':status_warning:'), 0xCF222E),
|
|
178
|
+
'action_required': (res(':status_warning:'), 0xBF8700),
|
|
179
|
+
'neutral': (res(':workflow:'), 0x6E7781),
|
|
180
|
+
'skipped': (res(':workflow:'), 0x6E7781),
|
|
181
|
+
'stale': (res(':workflow:'), 0x6E7781),
|
|
182
|
+
}
|
|
183
|
+
icon, color = icons.get(conclusion, (res(':workflow:'), 0x6E7781))
|
|
184
|
+
embed = _base_embed(
|
|
185
|
+
payload,
|
|
186
|
+
f'{icon} {name} {conclusion} on `{branch}`',
|
|
187
|
+
workflow.get('html_url'),
|
|
188
|
+
color,
|
|
189
|
+
None,
|
|
190
|
+
)
|
|
191
|
+
head_commit = workflow.get('head_commit') or {}
|
|
192
|
+
message = (head_commit.get('message') or '').splitlines()
|
|
193
|
+
if message:
|
|
194
|
+
embed.add_field(name='Commit', value=_truncate(message[0], 1024), inline=False)
|
|
195
|
+
event_name = workflow.get('event')
|
|
196
|
+
if event_name:
|
|
197
|
+
embed.add_field(name='Trigger', value=f'`{event_name}`', inline=True)
|
|
198
|
+
return embed, conclusion != 'success'
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
EVENT_BUILDERS = {
|
|
202
|
+
'issues': ('issues', _build_issue),
|
|
203
|
+
'pull_request': ('pulls', _build_pull_request),
|
|
204
|
+
'pull_request_review': ('reviews', _build_review),
|
|
205
|
+
'push': ('pushes', _build_push),
|
|
206
|
+
'release': ('releases', _build_release),
|
|
207
|
+
'workflow_run': ('ci', _build_workflow),
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _base_embed(payload, title, url, color, description):
|
|
212
|
+
repo = payload.get('repository') or {}
|
|
213
|
+
sender = payload.get('sender') or payload.get('pusher') or {}
|
|
214
|
+
name = sender.get('login') or sender.get('name') or 'GitHub'
|
|
215
|
+
repo_name = repo.get('name') or 'repository'
|
|
216
|
+
embed = discord.Embed(
|
|
217
|
+
title=_truncate(title, 256),
|
|
218
|
+
url=url,
|
|
219
|
+
color=color,
|
|
220
|
+
timestamp=_parse_time(payload.get('updated_at') or payload.get('created_at')),
|
|
221
|
+
description=_truncate(description, 4000) if description else None,
|
|
222
|
+
)
|
|
223
|
+
embed.set_author(name=f'{name} · {repo_name}', url=sender.get('html_url'), icon_url=sender.get('avatar_url'))
|
|
224
|
+
embed.set_footer(text=repo.get('full_name') or repo_name)
|
|
225
|
+
return embed
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _add_labels(embed, labels):
|
|
229
|
+
names = [label.get('name') for label in labels or [] if label.get('name')]
|
|
230
|
+
if names:
|
|
231
|
+
embed.add_field(name='Labels', value=_truncate(', '.join(f'`{name}`' for name in names), 1024), inline=False)
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _parse_time(value):
|
|
235
|
+
if not value:
|
|
236
|
+
return datetime.now(timezone.utc)
|
|
237
|
+
try:
|
|
238
|
+
return datetime.fromisoformat(value.replace('Z', '+00:00'))
|
|
239
|
+
except (AttributeError, ValueError):
|
|
240
|
+
return datetime.now(timezone.utc)
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def _truncate(value, limit):
|
|
244
|
+
if len(value) <= limit:
|
|
245
|
+
return value
|
|
246
|
+
return value[:limit - 1] + '…'
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import re
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
_REPO_PATTERN = re.compile(r'^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})/[A-Za-z0-9._-]{1,100}$')
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def parse_repository(value):
|
|
8
|
+
value = value.strip()
|
|
9
|
+
if value.startswith(('https://', 'http://')):
|
|
10
|
+
value = value.split('github.com/', 1)[-1].rstrip('/')
|
|
11
|
+
if value.endswith('.git'):
|
|
12
|
+
value = value[:-4]
|
|
13
|
+
if not _REPO_PATTERN.fullmatch(value):
|
|
14
|
+
raise ValueError('Enter a repository as `owner/name` or a GitHub URL.')
|
|
15
|
+
owner, name = value.split('/', 1)
|
|
16
|
+
return owner.lower(), name.lower()
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import hashlib
|
|
2
|
+
import hmac
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
_PREFIX = 'sha256='
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def verify_signature(secret, payload, signature):
|
|
9
|
+
if not secret or not signature or not signature.startswith(_PREFIX):
|
|
10
|
+
return False
|
|
11
|
+
expected = hmac.new(secret.encode('utf-8'), payload, hashlib.sha256).hexdigest()
|
|
12
|
+
return hmac.compare_digest(signature[len(_PREFIX):], expected)
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import logging
|
|
3
|
+
|
|
4
|
+
from fastapi import FastAPI, Header, HTTPException, Request, status
|
|
5
|
+
from fastapi.responses import JSONResponse
|
|
6
|
+
|
|
7
|
+
from .security import verify_signature
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
logger = logging.getLogger(__name__)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def create_github_app(settings, dispatcher):
|
|
14
|
+
app = FastAPI(
|
|
15
|
+
title='HungerNet Bot GitHub Webhooks',
|
|
16
|
+
docs_url=None,
|
|
17
|
+
redoc_url=None,
|
|
18
|
+
openapi_url=None,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
@app.get('/', include_in_schema=False)
|
|
22
|
+
async def root():
|
|
23
|
+
return {'service': 'hungernetbot-github'}
|
|
24
|
+
|
|
25
|
+
@app.get('/health', include_in_schema=False)
|
|
26
|
+
async def health():
|
|
27
|
+
return {'status': 'ok'}
|
|
28
|
+
|
|
29
|
+
@app.post('/github/webhook')
|
|
30
|
+
async def github_webhook(
|
|
31
|
+
request: Request,
|
|
32
|
+
x_github_event: str = Header(default=None),
|
|
33
|
+
x_hub_signature_256: str = Header(default=None),
|
|
34
|
+
x_github_delivery: str = Header(default=None),
|
|
35
|
+
):
|
|
36
|
+
raw = await request.body()
|
|
37
|
+
if not verify_signature(settings.github_webhook_secret, raw, x_hub_signature_256):
|
|
38
|
+
logger.warning('Rejected GitHub delivery %s: signature check failed.', x_github_delivery)
|
|
39
|
+
raise HTTPException(status.HTTP_401_UNAUTHORIZED, 'Invalid webhook signature.')
|
|
40
|
+
if not x_github_event:
|
|
41
|
+
raise HTTPException(status.HTTP_400_BAD_REQUEST, 'Missing X-GitHub-Event header.')
|
|
42
|
+
|
|
43
|
+
try:
|
|
44
|
+
payload = json.loads(raw.decode('utf-8'))
|
|
45
|
+
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
|
|
46
|
+
raise HTTPException(status.HTTP_400_BAD_REQUEST, 'Webhook body must be valid JSON.') from exc
|
|
47
|
+
if not isinstance(payload, dict):
|
|
48
|
+
raise HTTPException(status.HTTP_400_BAD_REQUEST, 'Webhook body must be a JSON object.')
|
|
49
|
+
|
|
50
|
+
logger.info(
|
|
51
|
+
'Accepted GitHub event %s (%s) for %s.',
|
|
52
|
+
x_github_event,
|
|
53
|
+
x_github_delivery,
|
|
54
|
+
(payload.get('repository') or {}).get('full_name', 'unknown repository'),
|
|
55
|
+
)
|
|
56
|
+
delivered = await dispatcher.handle(x_github_event, payload)
|
|
57
|
+
return JSONResponse({'ok': True, 'delivered_to': delivered})
|
|
58
|
+
|
|
59
|
+
return app
|
hungernetbot/posts.py
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
from dataclasses import dataclass
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
|
|
4
|
+
import discord
|
|
5
|
+
import yaml
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
_ALLOWED_POST_KEYS = {
|
|
9
|
+
'content',
|
|
10
|
+
'embeds',
|
|
11
|
+
'poll',
|
|
12
|
+
'attachments',
|
|
13
|
+
'allowed_mentions',
|
|
14
|
+
'suppress_embeds',
|
|
15
|
+
'silent',
|
|
16
|
+
'tts',
|
|
17
|
+
'buttons',
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass
|
|
22
|
+
class PostDefinition:
|
|
23
|
+
content: str
|
|
24
|
+
embeds: list[discord.Embed]
|
|
25
|
+
poll: object
|
|
26
|
+
attachments: list
|
|
27
|
+
allowed_mentions: discord.AllowedMentions
|
|
28
|
+
suppress_embeds: bool
|
|
29
|
+
silent: bool
|
|
30
|
+
tts: bool
|
|
31
|
+
view: discord.ui.View
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def resolve_post(name, directory):
|
|
35
|
+
name = name.strip()
|
|
36
|
+
root = Path(directory).resolve()
|
|
37
|
+
supplied = Path(name)
|
|
38
|
+
|
|
39
|
+
if supplied.name != name or name in {'', '.', '..'}:
|
|
40
|
+
raise ValueError('Post names must be file names, not paths.')
|
|
41
|
+
|
|
42
|
+
if supplied.suffix.lower() in {'.md', '.yaml'}:
|
|
43
|
+
candidates = [root / supplied.name]
|
|
44
|
+
elif supplied.suffix:
|
|
45
|
+
raise ValueError('Posts must use the .md or .yaml extension.')
|
|
46
|
+
else:
|
|
47
|
+
candidates = [root / f'{name}.md', root / f'{name}.yaml']
|
|
48
|
+
|
|
49
|
+
existing = [path for path in candidates if path.is_file()]
|
|
50
|
+
if not existing:
|
|
51
|
+
raise FileNotFoundError(f'No post named {name!r} exists in {root}.')
|
|
52
|
+
if len(existing) > 1:
|
|
53
|
+
raise ValueError(f'Both {name}.md and {name}.yaml exist; specify an extension.')
|
|
54
|
+
|
|
55
|
+
path = existing[0].resolve()
|
|
56
|
+
if not path.is_relative_to(root):
|
|
57
|
+
raise ValueError('Post files must stay inside the configured posts directory.')
|
|
58
|
+
return path
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def load_post(name, directory):
|
|
62
|
+
path = resolve_post(name, directory)
|
|
63
|
+
if path.suffix.lower() == '.md':
|
|
64
|
+
return PostDefinition(
|
|
65
|
+
content=path.read_text(encoding='utf-8'),
|
|
66
|
+
embeds=[],
|
|
67
|
+
poll=None,
|
|
68
|
+
attachments=[],
|
|
69
|
+
allowed_mentions=discord.AllowedMentions.all(),
|
|
70
|
+
suppress_embeds=False,
|
|
71
|
+
silent=False,
|
|
72
|
+
tts=False,
|
|
73
|
+
view=None,
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
try:
|
|
77
|
+
definition = yaml.safe_load(path.read_text(encoding='utf-8'))
|
|
78
|
+
except yaml.YAMLError as exc:
|
|
79
|
+
raise ValueError(f'Invalid YAML in {path.name}: {exc}') from exc
|
|
80
|
+
|
|
81
|
+
if not isinstance(definition, dict):
|
|
82
|
+
raise ValueError('A YAML post must contain a mapping at its root.')
|
|
83
|
+
|
|
84
|
+
unknown = set(definition) - _ALLOWED_POST_KEYS
|
|
85
|
+
if unknown:
|
|
86
|
+
keys = ', '.join(sorted(unknown))
|
|
87
|
+
raise ValueError(f'Unsupported post definition key(s): {keys}')
|
|
88
|
+
|
|
89
|
+
content = definition.get('content', '')
|
|
90
|
+
if not isinstance(content, str):
|
|
91
|
+
raise ValueError('The post content must be a string.')
|
|
92
|
+
|
|
93
|
+
embed_values = definition.get('embeds', [])
|
|
94
|
+
if not isinstance(embed_values, list) or len(embed_values) > 10:
|
|
95
|
+
raise ValueError('A post may contain up to 10 embeds.')
|
|
96
|
+
embeds = [_build_embed(value) for value in embed_values]
|
|
97
|
+
poll = _build_poll(definition.get('poll'))
|
|
98
|
+
attachments = _build_attachments(definition.get('attachments', []), path.parent)
|
|
99
|
+
allowed_mentions = _build_allowed_mentions(definition.get('allowed_mentions'))
|
|
100
|
+
view = _build_view(definition.get('buttons', []))
|
|
101
|
+
|
|
102
|
+
return PostDefinition(
|
|
103
|
+
content=content,
|
|
104
|
+
embeds=embeds,
|
|
105
|
+
poll=poll,
|
|
106
|
+
attachments=attachments,
|
|
107
|
+
allowed_mentions=allowed_mentions,
|
|
108
|
+
suppress_embeds=_boolean(definition, 'suppress_embeds', False),
|
|
109
|
+
silent=_boolean(definition, 'silent', False),
|
|
110
|
+
tts=_boolean(definition, 'tts', False),
|
|
111
|
+
view=view,
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _build_embed(value):
|
|
116
|
+
if not isinstance(value, dict):
|
|
117
|
+
raise ValueError('Each embed must be a mapping.')
|
|
118
|
+
embed_data = dict(value)
|
|
119
|
+
color = embed_data.get('color')
|
|
120
|
+
if isinstance(color, str):
|
|
121
|
+
try:
|
|
122
|
+
embed_data['color'] = int(color.lstrip('#'), 16)
|
|
123
|
+
except ValueError as exc:
|
|
124
|
+
raise ValueError(f'Invalid embed color: {color!r}.') from exc
|
|
125
|
+
try:
|
|
126
|
+
return discord.Embed.from_dict(embed_data)
|
|
127
|
+
except (TypeError, ValueError) as exc:
|
|
128
|
+
raise ValueError(f'Invalid embed definition: {exc}') from exc
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _build_poll(value):
|
|
132
|
+
if value is None:
|
|
133
|
+
return None
|
|
134
|
+
if not isinstance(value, dict):
|
|
135
|
+
raise ValueError('A poll must be a mapping.')
|
|
136
|
+
|
|
137
|
+
question = value.get('question')
|
|
138
|
+
answers = value.get('answers')
|
|
139
|
+
duration = value.get('duration', 24)
|
|
140
|
+
multiple = value.get('multiple', False)
|
|
141
|
+
if not isinstance(question, str) or not question.strip():
|
|
142
|
+
raise ValueError('A poll requires a non-empty question.')
|
|
143
|
+
if not isinstance(answers, list) or not 2 <= len(answers) <= 10:
|
|
144
|
+
raise ValueError('A poll requires between 2 and 10 answers.')
|
|
145
|
+
if not isinstance(duration, int) or not 1 <= duration <= 32:
|
|
146
|
+
raise ValueError('Poll duration must be from 1 to 32 hours.')
|
|
147
|
+
if not isinstance(multiple, bool):
|
|
148
|
+
raise ValueError('Poll multiple must be true or false.')
|
|
149
|
+
|
|
150
|
+
poll = discord.Poll(question=question, duration=duration, multiple=multiple)
|
|
151
|
+
for answer in answers:
|
|
152
|
+
if isinstance(answer, str):
|
|
153
|
+
poll.add_answer(text=answer)
|
|
154
|
+
elif isinstance(answer, dict) and isinstance(answer.get('text'), str):
|
|
155
|
+
poll.add_answer(text=answer['text'], emoji=answer.get('emoji'))
|
|
156
|
+
else:
|
|
157
|
+
raise ValueError('Poll answers must be strings or mappings with a text field.')
|
|
158
|
+
return poll
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _build_attachments(values, directory):
|
|
162
|
+
if not isinstance(values, list):
|
|
163
|
+
raise ValueError('Attachments must be a list of relative file paths.')
|
|
164
|
+
if len(values) > 10:
|
|
165
|
+
raise ValueError('A post cannot contain more than 10 attachment files.')
|
|
166
|
+
|
|
167
|
+
files = []
|
|
168
|
+
root = Path(directory).resolve()
|
|
169
|
+
for value in values:
|
|
170
|
+
if not isinstance(value, str):
|
|
171
|
+
raise ValueError('Attachment paths must be strings.')
|
|
172
|
+
path = (root / value).resolve()
|
|
173
|
+
if not path.is_relative_to(root):
|
|
174
|
+
raise ValueError('Attachments must stay inside the configured posts directory.')
|
|
175
|
+
if not path.is_file():
|
|
176
|
+
raise ValueError(f'Attachment file does not exist: {value!r}.')
|
|
177
|
+
files.append(discord.File(path))
|
|
178
|
+
return files
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _build_allowed_mentions(value):
|
|
182
|
+
if value is None:
|
|
183
|
+
return discord.AllowedMentions.all()
|
|
184
|
+
if not isinstance(value, dict):
|
|
185
|
+
raise ValueError('allowed_mentions must be a mapping.')
|
|
186
|
+
|
|
187
|
+
valid_keys = {'everyone', 'users', 'roles', 'replied_user'}
|
|
188
|
+
unknown = set(value) - valid_keys
|
|
189
|
+
if unknown:
|
|
190
|
+
keys = ', '.join(sorted(unknown))
|
|
191
|
+
raise ValueError(f'Unsupported allowed_mentions key(s): {keys}')
|
|
192
|
+
|
|
193
|
+
everyone = value.get('everyone', True)
|
|
194
|
+
users = value.get('users', True)
|
|
195
|
+
roles = value.get('roles', True)
|
|
196
|
+
replied_user = value.get('replied_user', True)
|
|
197
|
+
if not isinstance(everyone, bool) or not isinstance(replied_user, bool):
|
|
198
|
+
raise ValueError('everyone and replied_user mention settings must be booleans.')
|
|
199
|
+
if isinstance(users, list):
|
|
200
|
+
users = [discord.Object(id=int(user_id)) for user_id in users]
|
|
201
|
+
if isinstance(roles, list):
|
|
202
|
+
roles = [discord.Object(id=int(role_id)) for role_id in roles]
|
|
203
|
+
if not isinstance(users, (bool, list)) or not isinstance(roles, (bool, list)):
|
|
204
|
+
raise ValueError('users and roles must be booleans or lists of Discord IDs.')
|
|
205
|
+
|
|
206
|
+
return discord.AllowedMentions(
|
|
207
|
+
everyone=everyone,
|
|
208
|
+
users=users,
|
|
209
|
+
roles=roles,
|
|
210
|
+
replied_user=replied_user,
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _build_view(buttons):
|
|
215
|
+
if not isinstance(buttons, list):
|
|
216
|
+
raise ValueError('Buttons must be a list.')
|
|
217
|
+
if not buttons:
|
|
218
|
+
return None
|
|
219
|
+
if len(buttons) > 25:
|
|
220
|
+
raise ValueError('A post cannot contain more than 25 buttons.')
|
|
221
|
+
|
|
222
|
+
view = discord.ui.View(timeout=None)
|
|
223
|
+
for button in buttons:
|
|
224
|
+
if not isinstance(button, dict):
|
|
225
|
+
raise ValueError('Each button must be a mapping.')
|
|
226
|
+
if set(button) - {'label', 'url', 'emoji', 'disabled'}:
|
|
227
|
+
raise ValueError('Only link buttons are supported in post files.')
|
|
228
|
+
label = button.get('label')
|
|
229
|
+
url = button.get('url')
|
|
230
|
+
if not isinstance(label, str) or not label.strip():
|
|
231
|
+
raise ValueError('Each link button requires a non-empty label.')
|
|
232
|
+
if not isinstance(url, str) or not url.startswith(('https://', 'http://')):
|
|
233
|
+
raise ValueError('Each link button requires an http or https URL.')
|
|
234
|
+
disabled = button.get('disabled', False)
|
|
235
|
+
if not isinstance(disabled, bool):
|
|
236
|
+
raise ValueError('Button disabled must be true or false.')
|
|
237
|
+
view.add_item(
|
|
238
|
+
discord.ui.Button(
|
|
239
|
+
label=label,
|
|
240
|
+
style=discord.ButtonStyle.link,
|
|
241
|
+
url=url,
|
|
242
|
+
emoji=button.get('emoji'),
|
|
243
|
+
disabled=disabled,
|
|
244
|
+
)
|
|
245
|
+
)
|
|
246
|
+
return view
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def _boolean(values, key, default):
|
|
250
|
+
value = values.get(key, default)
|
|
251
|
+
if not isinstance(value, bool):
|
|
252
|
+
raise ValueError(f'{key} must be true or false.')
|
|
253
|
+
return value
|
hungernetbot/runner.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
|
|
3
|
+
from .bot import HungerNetBot
|
|
4
|
+
from .config import Settings
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def main():
|
|
8
|
+
logging.basicConfig(
|
|
9
|
+
level=logging.INFO,
|
|
10
|
+
format='%(asctime)s | %(levelname)-8s | %(name)s | %(message)s',
|
|
11
|
+
datefmt='%Y-%m-%d %H:%M:%S',
|
|
12
|
+
)
|
|
13
|
+
settings = Settings.from_environment()
|
|
14
|
+
bot = HungerNetBot(settings)
|
|
15
|
+
bot.run(settings.discord_token, log_handler=None)
|