-
Notifications
You must be signed in to change notification settings - Fork 5
/
GitGram.py
351 lines (293 loc) · 13.8 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
#!/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
from utils import (
html_bold,
html_link,
html_normal,
)
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/MadeByThePinsHub/GitGram")
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
updater = Updater(token=BOT_TOKEN, workers=1)
dispatcher = updater.dispatcher
print("If you need more help, join @GitGramChat in Telegram.")
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://waa.ai/GitGram) 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](https://t.me/GitGramChat).",
parse_mode="markdown"
)
def source(_bot, update):
"""Link to Source"""
message = update.effective_message
message.reply_text(
f"*Source*:\n[GitGram Repo](https://waa.ai/GitGram).",
parse_mode="markdown"
)
def getSourceCodeLink(_bot, update):
"""Pulls link to the source code."""
message = update.effective_message
message.reply_text(
f"{GIT_REPO_URL}"
)
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"""
response = post(
TG_BOT_API + "sendMessage",
params={
"chat_id": chat,
"text": message,
"parse_mode": parse_mode,
"disable_web_page_preview": True}).json()
return response
def reply_tg(chat, message_id, message, parse_mode):
"""reply to message_id"""
response = 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()
return response
@server.route("/", methods=['GET'])
# Just send 'Hello, world!' to tell that our server is up.
def helloWorld():
return 'Hello, world!'
@server.route("/<groupid>", methods=['GET', 'POST'])
def git_api(groupid):
"""Requests to api.github.com"""
data: dict = 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
the_sender = data['sender']
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'])
email_part = ''
if commit['author']['email'] and commit['author']['email'].endswith("@kaizoku.cyou"):
email_part = f"<{commit['author']['email']}>"
commits_text += f"{commit_msg}\n<a href='{commit['url']}'>{commit['id'][:7]}</a> - {commit['author']['name']} {escape(email_part)}\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 on {html_bold(data['repository']['name'])} by {html_link(the_sender['login'], the_sender['html_url'])}:
{html_normal(data['comment']['body'])}
<a href='{data['comment']['html_url']}'>Issue #{data['issue']['number']}</a>
"""
response = post_tg(groupid, text, "html")
return response
if data['action'] == 'labeled':
# don't send labeled issue update to group, since it's spammy
return ''
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
if __name__ == "__main__":
# We can't use port 80 due to the root access requirement.
port = int(environ.get("PORT", 1600))
server.run(host="0.0.0.0", port=port)