forked from MadeByThePinsHub/GitGram
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGitGram.py
535 lines (458 loc) · 22.9 KB
/
GitGram.py
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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
#!/usr/bin/env python3
from logging import basicConfig, getLogger, INFO
from flask import Flask, request, jsonify
from html import escape
from requests import get, post
from os import environ
import config
## For handling Ctrl+C
import signal
import sys
def signal_handler(signal, frame):
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
from telegram.ext import CommandHandler, Updater
server = Flask(__name__)
basicConfig(level=INFO)
log = getLogger()
ENV = bool(environ.get('ENV', False))
if ENV:
BOT_TOKEN = environ.get('BOT_TOKEN', None)
PROJECT_NAME = environ.get('PROJECT_NAME', None)
ip_addr = environ.get('APP_URL', None)
# You kanged our project without forking it, we'll get you DMCA'd.
GIT_REPO_URL = environ.get('GIT_REPO_URL', "https://github.com/GitGram/vanila")
GITGRAM_SUPPORT = environ.get('GITGRAM_SUPPORT', "https://t.me/GitGramChat")
else:
BOT_TOKEN = config.BOT_TOKEN
PROJECT_NAME = config.PROJECT_NAME
ip_addr = get('https://api.ipify.org').text
GIT_REPO_URL = config.GIT_REPO_URL
GITGRAM_SUPPORT = config.GITGRAM_SUPPORT
updater = Updater(token=BOT_TOKEN, workers=1)
dispatcher = updater.dispatcher
print("If you need more help, join @GitGramChat in Telegram for assistance.")
def start(_bot, update):
"""/start message for bot"""
message = update.effective_message
message.reply_text(
f"This is the Updates watcher for {PROJECT_NAME}. I am just notify users about what's happen on their Git repositories thru webhooks.\n\nYou need to [self-host](https://github.com/MadeByThePinsHub/GitGram#readme) or see /help to use this bot on your groups.",
parse_mode="markdown")
def help(_bot, update):
"""/help message for the bot"""
message = update.effective_message
message.reply_text(
f"*Available Commands*\n\n`/connect` - Setup how to connect this chat to receive Git activity notifications.\n`/support` - Get links to get support if you're stuck.\n`/source` - Get the Git repository URL.",
parse_mode="markdown"
)
def support(_bot, update):
"""Links to Support"""
message = update.effective_message
message.reply_text(
f"*Getting Support*\n\nTo get support in using the bot, join [the GitGram support]({GITGRAM_SUPPORT}).",
parse_mode="markdown"
)
def source(_bot, update):
"""Link to Source"""
message = update.effective_message
message.reply_text(
f"*Source*:\n\nThis instance: {GIT_REPO_URL}",
parse_mode="markdown"
)
start_handler = CommandHandler("start", start)
help_handler = CommandHandler("help", help)
supportCmd = CommandHandler("support", support)
sourcecode = CommandHandler("source", source)
dispatcher.add_handler(start_handler)
dispatcher.add_handler(help_handler)
dispatcher.add_handler(supportCmd)
dispatcher.add_handler(sourcecode)
updater.start_polling()
TG_BOT_API = f'https://api.telegram.org/bot{BOT_TOKEN}/'
checkbot = get(TG_BOT_API + "getMe").json()
if not checkbot['ok']:
log.error("[ERROR] Invalid Token!")
exit(1)
else:
username = checkbot['result']['username']
log.info(
f"[INFO] Logged in as @{username}, waiting for webhook requests...")
def post_tg(chat, message, parse_mode):
"""Send message to desired group"""
return post(
TG_BOT_API + "sendMessage",
params={
"chat_id": chat,
"text": message,
"parse_mode": parse_mode,
"disable_web_page_preview": True}).json()
def reply_tg(chat, message_id, message, parse_mode):
"""reply to message_id"""
return post(
TG_BOT_API + "sendMessage",
params={
"chat_id": chat,
"reply_to_message_id": message_id,
"text": message,
"parse_mode": parse_mode,
"disable_web_page_preview": True}).json()
@server.route("/", methods=['GET'])
# Just send 'Hello, world!' to tell that our server is up.
def helloWorld():
return 'Hello, world!'
# The usual one, only supports GitHub webhooks.
@server.route("/<groupid>", methods=['GET', 'POST'])
def git_api(groupid):
"""Requests to api.github.com"""
data = request.json
if not data:
return f"<b>Add this url:</b> {ip_addr}/{groupid} to webhooks of the project"
if data.get('hook'):
repo_url = data['repository']['html_url']
repo_name = data['repository']['name']
sender_url = data['sender']['html_url']
sender_name = data['sender']['login']
response = post_tg(
groupid,
f"🙌 Successfully set webhook for <a href='{repo_url}'>{repo_name}</a> by <a href='{sender_url}'>{sender_name}</a>!",
"html"
)
return response
if data.get('commits'):
commits_text = ""
rng = len(data['commits'])
if rng > 10:
rng = 10
for x in range(rng):
commit = data['commits'][x]
if len(escape(commit['message'])) > 300:
commit_msg = escape(commit['message']).split("\n")[0]
else:
commit_msg = escape(commit['message'])
commits_text += f"{commit_msg}\n<a href='{commit['url']}'>{commit['id'][:7]}</a> - {commit['author']['name']} {escape('<')}{commit['author']['email']}{escape('>')}\n\n"
if len(commits_text) > 1000:
text = f"""✨ <b>{escape(data['repository']['name'])}</b> - New {len(data['commits'])} commits ({escape(data['ref'].split('/')[-1])})
{commits_text}
"""
response = post_tg(groupid, text, "html")
commits_text = ""
if not commits_text:
return jsonify({"ok": True, "text": "Commits text is none"})
text = f"""✨ <b>{escape(data['repository']['name'])}</b> - New {len(data['commits'])} commits ({escape(data['ref'].split('/')[-1])})
{commits_text}
"""
if len(data['commits']) > 10:
text += f"\n\n<i>And {len(data['commits']) - 10} other commits</i>"
response = post_tg(groupid, text, "html")
return response
if data.get('issue'):
if data.get('comment'):
text = f"""💬 New comment: <b>{escape(data['repository']['name'])}</b>
{escape(data['comment']['body'])}
<a href='{data['comment']['html_url']}'>Issue #{data['issue']['number']}</a>
"""
response = post_tg(groupid, text, "html")
return response
text = f"""🚨 New {data['action']} issue for <b>{escape(data['repository']['name'])}</b>
<b>{escape(data['issue']['title'])}</b>
{escape(data['issue']['body'])}
<a href='{data['issue']['html_url']}'>issue #{data['issue']['number']}</a>
"""
response = post_tg(groupid, text, "html")
return response
if data.get('pull_request'):
if data.get('comment'):
text = f"""❗ There is a new pull request for <b>{escape(data['repository']['name'])}</b> ({data['pull_request']['state']})
{escape(data['comment']['body'])}
<a href='{data['comment']['html_url']}'>Pull request #{data['issue']['number']}</a>
"""
response = post_tg(groupid, text, "html")
return response
text = f"""❗ New {data['action']} pull request for <b>{escape(data['repository']['name'])}</b>
<b>{escape(data['pull_request']['title'])}</b> ({data['pull_request']['state']})
{escape(data['pull_request']['body'])}
<a href='{data['pull_request']['html_url']}'>Pull request #{data['pull_request']['number']}</a>
"""
response = post_tg(groupid, text, "html")
return response
if data.get('forkee'):
response = post_tg(
groupid,
f"🍴 <a href='{data['sender']['html_url']}'>{data['sender']['login']}</a> forked <a href='{data['repository']['html_url']}'>{data['repository']['name']}</a>!\nTotal forks now are {data['repository']['forks_count']}",
"html")
return response
if data.get('action'):
if data.get('action') == "published" and data.get('release'):
text = f"<a href='{data['sender']['html_url']}'>{data['sender']['login']}</a> {data['action']} <a href='{data['repository']['html_url']}'>{data['repository']['name']}</a>!"
text += f"\n\n<b>{data['release']['name']}</b> ({data['release']['tag_name']})\n{data['release']['body']}\n\n<a href='{data['release']['tarball_url']}'>Download tar</a> | <a href='{data['release']['zipball_url']}'>Download zip</a>"
response = post_tg(groupid, text, "html")
return response
if data.get('action') == "started":
text = f"🌟 <a href='{data['sender']['html_url']}'>{data['sender']['login']}</a> gave a star to <a href='{data['repository']['html_url']}'>{data['repository']['name']}</a>!\nTotal stars are now {data['repository']['stargazers_count']}"
response = post_tg(groupid, text, "html")
return response
if data.get('action') == "edited" and data.get('release'):
text = f"<a href='{data['sender']['html_url']}'>{data['sender']['login']}</a> {data['action']} <a href='{data['repository']['html_url']}'>{data['repository']['name']}</a>!"
text += f"\n\n<b>{data['release']['name']}</b> ({data['release']['tag_name']})\n{data['release']['body']}\n\n<a href='{data['release']['tarball_url']}'>Download tar</a> | <a href='{data['release']['zipball_url']}'>Download zip</a>"
response = post_tg(groupid, text, "html")
return response
if data.get('action') == "created":
return jsonify({"ok": True, "text": "Pass trigger for created"})
response = post_tg(
groupid,
f"<a href='{data['sender']['html_url']}'>{data['sender']['login']}</a> {data['action']} <a href='{data['repository']['html_url']}'>{data['repository']['name']}</a>!",
"html")
return response
if data.get('ref_type'):
response = post_tg(
groupid,
f"A new {data['ref_type']} on <a href='{data['repository']['html_url']}'>{data['repository']['name']}</a> was created by <a href='{data['sender']['html_url']}'>{data['sender']['login']}</a>!",
"html")
return response
if data.get('created'):
response = post_tg(groupid,
f"Branch {data['ref'].split('/')[-1]} <b>{data['ref'].split('/')[-2]}</b> on <a href='{data['repository']['html_url']}'>{data['repository']['name']}</a> was created by <a href='{data['sender']['html_url']}'>{data['sender']['login']}</a>!",
"html")
return response
if data.get('deleted'):
response = post_tg(groupid,
f"Branch {data['ref'].split('/')[-1]} <b>{data['ref'].split('/')[-2]}</b> on <a href='{data['repository']['html_url']}'>{data['repository']['name']}</a> was deleted by <a href='{data['sender']['html_url']}'>{data['sender']['login']}</a>!",
"html")
return response
if data.get('forced'):
response = post_tg(groupid,
f"Branch {data['ref'].split('/')[-1]} <b>{data['ref'].split('/')[-2]}</b>" +
" on <a href='{data['repository']['html_url']}'>{data['repository']['name']}</a> was" +
" forced by <a href='{data['sender']['html_url']}'>{data['sender']['login']}</a>!",
"html")
return response
if data.get('pages'):
text = f"<a href='{data['repository']['html_url']}'>{data['repository']['name']}</a> wiki pages were updated by <a href='{data['sender']['html_url']}'>{data['sender']['login']}</a>!\n\n"
for x in data['pages']:
summary = ""
if x['summary']:
summary = f"{x['summary']}\n"
text += f"📝 <b>{escape(x['title'])}</b> ({x['action']})\n{summary}<a href='{x['html_url']}'>{x['page_name']}</a> - {x['sha'][:7]}"
if len(data['pages']) >= 2:
text += "\n=====================\n"
response = post_tg(groupid, text, "html")
return response
if data.get('context'):
if data.get('state') == "pending":
emo = "⏳"
elif data.get('state') == "success":
emo = "✔️"
elif data.get('state') == "failure":
emo = "❌"
else:
emo = "🌀"
response = post_tg(
groupid,
f"{emo} <a href='{data['target_url']}'>{data['description']}</a>" +
" on <a href='{data['repository']['html_url']}'>{data['repository']['name']}</a>" +
" by <a href='{data['sender']['html_url']}'>{data['sender']['login']}</a>!" +
"\nLatest commit:\n<a href='{data['commit']['commit']['url']}'>{escape(data['commit']['commit']['message'])}</a>",
"html")
return response
url = deldog(data)
response = post_tg(
groupid,
"🚫 Webhook endpoint for this chat has received something that doesn't understood yet. " +
f"\n\nLink to logs for debugging: {url}",
"markdown")
return response
def deldog(data):
"""Pasing the stings to del.dog"""
BASE_URL = 'https://del.dog'
r = post(f'{BASE_URL}/documents', data=str(data).encode('utf-8'))
if r.status_code == 404:
r.raise_for_status()
res = r.json()
if r.status_code != 200:
r.raise_for_status()
key = res['key']
if res['isUrl']:
reply = f'DelDog URL: {BASE_URL}/{key}\nYou can view stats, etc. [here]({BASE_URL}/v/{key})'
else:
reply = f'{BASE_URL}/{key}'
return reply
# GitHub-specific webhooks stuff
@server.route("/gh/<chatid>", methods=['GET', 'POST'])
def github_webhooks(chatid):
"""Requests to api.github.com"""
data = request.json
if not data:
return f"<b>Add this url:</b> {ip_addr}/{chatid} to webhooks of the project"
if data.get('hook'):
repo_url = data['repository']['html_url']
repo_name = data['repository']['name']
sender_url = data['sender']['html_url']
sender_name = data['sender']['login']
response = post_tg(
groupid,
f"🙌 Successfully set webhook for <a href='{repo_url}'>{repo_name}</a> by <a href='{sender_url}'>{sender_name}</a>!",
"html"
)
return response
if data.get('commits'):
commits_text = ""
rng = len(data['commits'])
if rng > 10:
rng = 10
for x in range(rng):
commit = data['commits'][x]
if len(escape(commit['message'])) > 300:
commit_msg = escape(commit['message']).split("\n")[0]
else:
commit_msg = escape(commit['message'])
commits_text += f"{commit_msg}\n<a href='{commit['url']}'>{commit['id'][:7]}</a> - {commit['author']['name']} {escape('<')}{commit['author']['email']}{escape('>')}\n\n"
if len(commits_text) > 1000:
text = f"""✨ <b>{escape(data['repository']['name'])}</b> - New {len(data['commits'])} commits ({escape(data['ref'].split('/')[-1])})
{commits_text}
"""
response = post_tg(groupid, text, "html")
commits_text = ""
if not commits_text:
return jsonify({"ok": True, "text": "Commits text is none"})
text = f"""✨ <b>{escape(data['repository']['name'])}</b> - New {len(data['commits'])} commits ({escape(data['ref'].split('/')[-1])})
{commits_text}
"""
if len(data['commits']) > 10:
text += f"\n\n<i>And {len(data['commits']) - 10} other commits</i>"
response = post_tg(groupid, text, "html")
return response
if data.get('issue'):
if data.get('comment'):
text = f"""💬 New comment: <b>{escape(data['repository']['name'])}</b>
{escape(data['comment']['body'])}
<a href='{data['comment']['html_url']}'>Issue #{data['issue']['number']}</a>
"""
response = post_tg(groupid, text, "html")
return response
text = f"""🚨 New {data['action']} issue for <b>{escape(data['repository']['name'])}</b>
<b>{escape(data['issue']['title'])}</b>
{escape(data['issue']['body'])}
<a href='{data['issue']['html_url']}'>issue #{data['issue']['number']}</a>
"""
response = post_tg(groupid, text, "html")
return response
if data.get('pull_request'):
if data.get('comment'):
text = f"""❗ There is a new pull request for <b>{escape(data['repository']['name'])}</b> ({data['pull_request']['state']})
{escape(data['comment']['body'])}
<a href='{data['comment']['html_url']}'>Pull request #{data['issue']['number']}</a>
"""
response = post_tg(groupid, text, "html")
return response
text = f"""❗ New {data['action']} pull request for <b>{escape(data['repository']['name'])}</b>
<b>{escape(data['pull_request']['title'])}</b> ({data['pull_request']['state']})
{escape(data['pull_request']['body'])}
<a href='{data['pull_request']['html_url']}'>Pull request #{data['pull_request']['number']}</a>
"""
response = post_tg(groupid, text, "html")
return response
if data.get('forkee'):
response = post_tg(
groupid,
f"🍴 <a href='{data['sender']['html_url']}'>{data['sender']['login']}</a> forked <a href='{data['repository']['html_url']}'>{data['repository']['name']}</a>!\nTotal forks now are {data['repository']['forks_count']}",
"html")
return response
if data.get('action'):
if data.get('action') == "published" and data.get('release'):
text = f"<a href='{data['sender']['html_url']}'>{data['sender']['login']}</a> {data['action']} <a href='{data['repository']['html_url']}'>{data['repository']['name']}</a>!"
text += f"\n\n<b>{data['release']['name']}</b> ({data['release']['tag_name']})\n{data['release']['body']}\n\n<a href='{data['release']['tarball_url']}'>Download tar</a> | <a href='{data['release']['zipball_url']}'>Download zip</a>"
response = post_tg(groupid, text, "html")
return response
if data.get('action') == "started":
text = f"🌟 <a href='{data['sender']['html_url']}'>{data['sender']['login']}</a> gave a star to <a href='{data['repository']['html_url']}'>{data['repository']['name']}</a>!\nTotal stars are now {data['repository']['stargazers_count']}"
response = post_tg(groupid, text, "html")
return response
if data.get('action') == "edited" and data.get('release'):
text = f"<a href='{data['sender']['html_url']}'>{data['sender']['login']}</a> {data['action']} <a href='{data['repository']['html_url']}'>{data['repository']['name']}</a>!"
text += f"\n\n<b>{data['release']['name']}</b> ({data['release']['tag_name']})\n{data['release']['body']}\n\n<a href='{data['release']['tarball_url']}'>Download tar</a> | <a href='{data['release']['zipball_url']}'>Download zip</a>"
response = post_tg(groupid, text, "html")
return response
if data.get('action') == "created":
return jsonify({"ok": True, "text": "Pass trigger for created"})
response = post_tg(
groupid,
f"<a href='{data['sender']['html_url']}'>{data['sender']['login']}</a> {data['action']} <a href='{data['repository']['html_url']}'>{data['repository']['name']}</a>!",
"html")
return response
if data.get('ref_type'):
response = post_tg(
groupid,
f"A new {data['ref_type']} on <a href='{data['repository']['html_url']}'>{data['repository']['name']}</a> was created by <a href='{data['sender']['html_url']}'>{data['sender']['login']}</a>!",
"html")
return response
if data.get('created'):
response = post_tg(groupid,
f"Branch {data['ref'].split('/')[-1]} <b>{data['ref'].split('/')[-2]}</b> on <a href='{data['repository']['html_url']}'>{data['repository']['name']}</a> was created by <a href='{data['sender']['html_url']}'>{data['sender']['login']}</a>!",
"html")
return response
if data.get('deleted'):
response = post_tg(groupid,
f"Branch {data['ref'].split('/')[-1]} <b>{data['ref'].split('/')[-2]}</b> on <a href='{data['repository']['html_url']}'>{data['repository']['name']}</a> was deleted by <a href='{data['sender']['html_url']}'>{data['sender']['login']}</a>!",
"html")
return response
if data.get('forced'):
response = post_tg(groupid,
f"Branch {data['ref'].split('/')[-1]} <b>{data['ref'].split('/')[-2]}</b>" +
" on <a href='{data['repository']['html_url']}'>{data['repository']['name']}</a> was" +
" forced by <a href='{data['sender']['html_url']}'>{data['sender']['login']}</a>!",
"html")
return response
if data.get('pages'):
text = f"<a href='{data['repository']['html_url']}'>{data['repository']['name']}</a> wiki pages were updated by <a href='{data['sender']['html_url']}'>{data['sender']['login']}</a>!\n\n"
for x in data['pages']:
summary = ""
if x['summary']:
summary = f"{x['summary']}\n"
text += f"📝 <b>{escape(x['title'])}</b> ({x['action']})\n{summary}<a href='{x['html_url']}'>{x['page_name']}</a> - {x['sha'][:7]}"
if len(data['pages']) >= 2:
text += "\n=====================\n"
response = post_tg(groupid, text, "html")
return response
if data.get('context'):
if data.get('state') == "pending":
emo = "⏳"
elif data.get('state') == "success":
emo = "✔️"
elif data.get('state') == "failure":
emo = "❌"
else:
emo = "🌀"
response = post_tg(
groupid,
f"{emo} <a href='{data['target_url']}'>{data['description']}</a>" +
" on <a href='{data['repository']['html_url']}'>{data['repository']['name']}</a>" +
" by <a href='{data['sender']['html_url']}'>{data['sender']['login']}</a>!" +
"\nLatest commit:\n<a href='{data['commit']['commit']['url']}'>{escape(data['commit']['commit']['message'])}</a>",
"html")
return response
url = deldog(data)
response = post_tg(
groupid,
"🚫 Webhook endpoint for this chat has received something that doesn't understood yet. " +
f"\n\nLink to logs for debugging: {url}",
"markdown")
return response
def passUnknownJsonToDeldog(data):
"""Pasing the stings to del.dog"""
BASE_URL = 'https://del.dog'
r = post(f'{BASE_URL}/documents', data=str(data).encode('utf-8'))
if r.status_code == 404:
r.raise_for_status()
res = r.json()
if r.status_code != 200:
r.raise_for_status()
key = res['key']
if res['isUrl']:
reply = f'DelDog URL: {BASE_URL}/{key}\nYou can view stats, etc. [here]({BASE_URL}/v/{key})'
else:
reply = f'{BASE_URL}/{key}'
return reply
if __name__ == "__main__":
# We can't use port 80 due to the root access requirement.
port = int(environ.get("PORT", 8080))
server.run(host="0.0.0.0", port=port)