forked from jsmnbom/githubbotrevised
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsettings.py
More file actions
327 lines (246 loc) · 11.3 KB
/
settings.py
File metadata and controls
327 lines (246 loc) · 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
from itertools import zip_longest
from uuid import uuid4
from requests import HTTPError
from telegram import Chat, InlineQueryResultArticle, InputTextMessageContent, ParseMode
from telegram.ext import Dispatcher, InlineQueryHandler, CommandHandler
from bot.const import DEFAULT_TRUNCATION_LIMIT
from bot.github import github_api
from bot.menu import Button, Menu, BackButton, reply_menu, MenuHandler, ToggleButton, SetButton
from bot.repo import Repo
from bot.utils import encode_data_link, decode_first_data_entity
BACK = '⬅ Back'
class InlineQueries(object):
add_repo = 'Add repository:'
def grouper(iterable, n, fillvalue=None):
"""Collect data into fixed-length chunks or blocks"""
args = [iter(iterable)] * n
return zip_longest(*args, fillvalue=fillvalue)
def settings_text(update, context):
private = update.effective_chat.type == Chat.PRIVATE
text = f'⚙ Settings for {context.bot.name}\n\n'
if private:
access_token = context.user_data.get('access_token')
if access_token:
try:
github_user = github_api.get_user(access_token)
text += ('🔓 You are currently logged in as '
f'<a href="{github_user["html_url"]}">{github_user["login"]} ({github_user["name"]})</a>'
'.\n')
except HTTPError as exc:
if "Unauthorized for url" not in str(exc):
raise exc
context.user_data.pop('access_token', None)
text += f'🔒 You are currently not logged in.\n'
else:
text += f'🔒 You are currently not logged in.\n'
text += '\nNo repositories have been set up for this chat.\n'
return text
def settings_buttons(update, context):
private = update.effective_chat.type == Chat.PRIVATE
buttons = []
if private:
access_token = context.user_data.get('access_token')
if access_token:
buttons.append(SetButton('login', None, '🔒 Logout'))
else:
buttons.append(Button('🔑 Login', menu='login'))
else:
buttons.append(Button('👤 Go to User settings', url=f'https://telegram.me/{context.bot.username}?start=settings'))
buttons.append(Button('👥 Chat settings', menu='chat'))
buttons.append(Button('🗃️ Repositories', menu='repos'))
return [[button] for button in buttons]
def settings_set_data(_, context):
if context.key == 'login' and context.value is None:
del context.user_data['access_token']
settings_menu = Menu(
name='settings',
text=settings_text,
buttons=settings_buttons,
set_data=settings_set_data
)
def login_text(update, context):
access_token = context.user_data.get('access_token')
if access_token:
try:
github_user = github_api.get_user(access_token)
return ('Successfully logged in as '
f'<a href="{github_user["html_url"]}">{github_user["login"]} ({github_user["name"]})</a>'
'.\n')
except HTTPError as exc:
if "Unauthorized for url" not in str(exc):
raise exc
context.user_data.pop('access_token', None)
oauth_link = github_api.oauth_authorize_url(update.effective_user.id,
update.effective_message.message_id)
return f'Please click this link to login using GitHub: {oauth_link}'
else:
oauth_link = github_api.oauth_authorize_url(update.effective_user.id,
update.effective_message.message_id)
return f'Please click this link to login using GitHub: {oauth_link}'
login_menu = Menu(
name='login',
text=login_text,
buttons=lambda _, c: [[BackButton('OK' if c.user_data.get('access_token') else BACK)]]
)
def repos_buttons(update, context):
repos = context.chat_data.get('repos', {})
buttons = []
for row in grouper(repos.values(), 2):
buttons.append([Button(repo.name, menu=repo.id) for repo in row if repo is not None])
buttons.append([Button('Add repository', switch_inline_query_current_chat=InlineQueries.add_repo + ' ')])
buttons.append([BackButton(BACK)])
return buttons
repos_menu = Menu(
name='repos',
text='🗃️ Repositories\n\nRepositories installed in this chat are shown below. '
'Please choose a repository to configure, or press "New Repository" to add a new repository.',
buttons=repos_buttons
)
def repo_text(update, context):
try:
repo = context.chat_data['repos'][int(context.match.group(1))]
except KeyError:
return 'Repository removed successfully.'
return (f'🗃️ Notification settings for repository: {repo.name}\n\n'
f'Please select the notifications you would like to receive for this repository, '
f'or press the remove button to stop receiving notifications for it.')
def repo_buttons(update, context):
try:
repo: Repo = context.chat_data['repos'][int(context.match.group(1))]
except KeyError:
return [[BackButton('OK')]]
return [
[ToggleButton('issues', value=repo.issues, text='New issues')],
[ToggleButton('issue_comments', value=repo.issue_comments, text='Comments on issues')],
[ToggleButton('pulls', value=repo.pulls, text='New pull requests')],
[ToggleButton('pull_comments', value=repo.pull_comments, text='Comments on pull requests')],
[ToggleButton('pull_reviews', value=repo.pull_reviews, text='New pull request reviews')],
[ToggleButton('pull_review_comments', value=repo.pull_review_comments, text='Pull request review comments')],
[ToggleButton('commit_comments', value=repo.commit_comments, text='Comment on a commit/diff')],
[ToggleButton('wiki_pages', value=repo.wiki_pages, text='Wiki page updated')],
[ToggleButton('push', value=repo.push, text='Commits pushed to any branch')],
[ToggleButton('push_main', value=repo.push_main, text='Commits pushed to default branch')],
[SetButton('remove', None, '❌ Remove')],
[BackButton(BACK)]
]
def repo_set_data(update, context):
repo_id = int(context.match.group(1))
if context.key == 'remove':
del context.chat_data['repos'][repo_id]
else:
repo = context.chat_data['repos'][repo_id]
setattr(repo, context.key, context.value)
repo_menu = Menu(
name='repo',
pattern=('repos', r'(\d+)'),
text=repo_text,
buttons=repo_buttons,
set_data=repo_set_data
)
def chat_text(update, context):
if update.effective_chat.title:
chat = update.effective_chat.title
elif update.effective_chat.first_name:
chat = f'this chat with {update.effective_chat.first_name}'
else:
chat = 'this chat'
return f'⚙ Settings for {context.bot.name} for {chat}\n\n'
def chat_buttons(update, context):
truncation_limit = context.chat_data.get('truncation_limit', DEFAULT_TRUNCATION_LIMIT)
truncation_limits = [256, 512, 1024, 2048, 4096]
truncation_limit_states = [(limit, f'Max notification message length: {limit}') for limit in truncation_limits]
return [
[ToggleButton('truncation_limit', truncation_limit, states=truncation_limit_states)],
[BackButton(BACK)]
]
def chat_set_data(update, context):
context.chat_data[context.key] = context.value
chat_settings_menu = Menu(
name='chat',
text=chat_text,
buttons=chat_buttons,
set_data=chat_set_data
)
def settings_command(update, context):
if context.args:
context.menu_stack = context.args
reply_menu(update, context, settings_menu)
def inline_add_repo(update, context):
offset = update.inline_query.offset
installation_offset, repo_offset = -1, -1
if offset:
installation_offset, _, repo_offset = offset.partition('|')
installation_offset, repo_offset = int(installation_offset), int(repo_offset)
access_token = context.user_data.get('access_token')
results = []
if access_token:
filtered_repositories = []
search = context.match.group(1).strip()
installations = github_api.get_installations_for_user(access_token)
for installation_index, installation in enumerate(installations):
if installation_index <= installation_offset:
continue
repositories = github_api.get_repositories_for_installation(installation['id'],
access_token)
for repo_index, repo in enumerate(repositories):
if repo_index <= repo_offset:
continue
if repo['full_name'].startswith(search) or repo['name'].startswith(search):
filtered_repositories.append(repo)
if len(filtered_repositories) >= 50:
break
if len(filtered_repositories) >= 50:
break
results = []
for repo in filtered_repositories:
results.append(InlineQueryResultArticle(
id=repo['id'],
title=repo['full_name'],
description='Add this repository',
thumb_url=repo['owner']['avatar_url'],
input_message_content=InputTextMessageContent(
message_text=f'/add_repo {encode_data_link(repo["id"])}<a href="{repo["html_url"]}">{repo["full_name"]}</a>',
parse_mode=ParseMode.HTML
)
))
if not results and not offset:
results.append(InlineQueryResultArticle(
id=uuid4(),
title='No results.',
description='Tap me to learn how to add your repositories.',
input_message_content=InputTextMessageContent(
message_text=f'/help',
)
))
update.inline_query.answer(
results,
switch_pm_text=('Not seeing your repository? Tab here.'
if access_token else
'You are not logged in. Tap here to continue.'),
switch_pm_parameter='help',
cache_time=15,
is_personal=True,
next_offset=f'{installation_index-1}|{repo_index}' if results else ''
)
def add_repo_command(update, context):
repos = context.chat_data.setdefault('repos', {})
access_token = context.user_data['access_token']
repo_id = decode_first_data_entity(update.effective_message.entities)
if not repo_id:
update.effective_message.reply_text(
'Please use /settings to add repositories, instead of using the command directly.', disable_notification=True)
return
repository = github_api.get_repository(repo_id, access_token=access_token)
repos[repository['id']] = Repo(name=repository['full_name'], id=repository['id'])
context.menu_stack = ['settings']
reply_menu(update, context, repos_menu)
def add_handlers(dp: Dispatcher):
dp.add_handler(CommandHandler(('settings', 'options', 'config'), settings_command))
dp.add_handler(MenuHandler(settings_menu, [
repos_menu,
repo_menu,
login_menu,
chat_settings_menu
]))
dp.add_handler(InlineQueryHandler(inline_add_repo, pattern=InlineQueries.add_repo + r'(.*)'))
dp.add_handler(CommandHandler('add_repo', add_repo_command))