-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
333 lines (287 loc) · 8.12 KB
/
main.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
import os
import sys
import sqlite3
import logging
import asyncio
from enum import Enum
from pathlib import Path
from urllib.parse import urlparse
from aiogram import Bot, Dispatcher, html, types
from aiogram.client.default import DefaultBotProperties
from aiogram.enums import ParseMode
from aiogram.filters import CommandStart, Command
from aiogram.types import Message
from aiogram.fsm.context import FSMContext
from aiogram.fsm.state import State, StatesGroup
from github import Github, Auth
from github.GithubException import UnknownObjectException
from dotenv import load_dotenv
class Form(StatesGroup):
project_id = State()
admin_message_id = State()
bot_message_id = State()
project_gh_url = State()
class SupportedCodeHubs(Enum):
github = 'github.com'
dp = Dispatcher()
@dp.message(Form.project_gh_url)
async def handle_github_url(
message: Message, state: FSMContext
) -> None:
if not message.from_user.is_bot:
return
state_data = await state.get_data()
if message.reply_to_message.message_id != state_data.get("bot_message_id"):
return
url = message.text.strip()
parsed_url = urlparse(url)
if parsed_url.netloc != SupportedCodeHubs.github.value:
fail_msg = await message.reply(
f"[?] Not supported: {parsed_url.netloc or url}"
)
await asyncio.sleep(1.5)
await fail_msg.delete()
await message.delete()
return
project_id = state_data.get("project_id")
gh_repository_full_name = "/".join(
tuple(filter(bool, parsed_url.path.split("/", maxsplit=3)))[:2]
)
try:
repository = github.get_repo(gh_repository_full_name)
except UnknownObjectException:
fail_msg = await message.reply(
f"[?] Repository ({gh_repository_full_name}) is not found "
"or you have no access!"
)
await asyncio.sleep(2.5)
await fail_msg.delete()
await message.delete()
return
curr.execute(
"""
UPDATE
projects
SET
gh_repository_url = ?,
gh_repository_full_name = ?
WHERE
id = ?
""",
(
repository.html_url,
gh_repository_full_name,
project_id,
)
)
conn.commit()
last_msg = await message.reply(f"[!] Created a Project(id={project_id})")
await asyncio.sleep(1.5)
await last_msg.delete()
await message.delete()
await bot.delete_message(message.chat.id, state_data["bot_message_id"])
await bot.delete_message(message.chat.id, state_data["admin_message_id"])
await state.clear()
@dp.message(CommandStart())
async def command_start_handler(message: Message, state: FSMContext) -> None:
if not message.from_user.is_bot:
return
await state.set_state(Form.project_gh_url)
curr.execute(
"""
SELECT id FROM projects WHERE tg_channel_id = ?
""",
(
message.reply_to_message.sender_chat.id,
)
)
project = curr.fetchone()
if project:
await message.reply(
f"[!] Project(id={project[0]}) already has been created!"
)
await state.clear()
return
curr.execute(
"""
INSERT INTO
projects (
tg_channel_id,
tg_channel_title,
tg_channel_post_url,
tg_channel_post_date
)
VALUES (
?, ?, ?, ?
)
""",
(
message.reply_to_message.sender_chat.id,
message.reply_to_message.sender_chat.title,
message.reply_to_message.get_url(force_private=True),
message.reply_to_message.date.strftime(MESSAGE_DT_FORMAT),
)
)
conn.commit()
await state.update_data(project_id=curr.lastrowid)
await state.update_data(admin_message_id=message.message_id)
message = await message.reply("Reply GitHub/Project URL")
await state.update_data(bot_message_id=message.message_id)
@dp.message(Command("report"))
async def report_handler(message: Message) -> None:
# XXX: FEAT:
# - set the MAX issue "REAL" (not report) for the `tg_channel_post_url`
if not message.reply_to_message.sender_chat:
await message.reply("Comment to the channel post to `/report`")
return
curr.execute(
"""
SELECT
id, tg_channel_title, gh_repository_full_name
FROM
projects
WHERE
tg_channel_id = ?
""",
(
message.reply_to_message.sender_chat.id,
)
)
project = curr.fetchone()
# NOTE: checking any project is registered for the `channel`
if project is None:
await message.reply(
"[?] Project is not registered for the chat: "
f"{html.bold(message.reply_to_message.sender_chat.title)}\n"
"[!] Bot/Admin only /start"
)
return
project_id, tg_channel_title, gh_repository_full_name = project
tg_user_id = message.from_user.id
tg_user_is_bot = message.from_user.is_bot
tg_message_url = message.get_url(force_private=True)
tg_message_date = message.date.strftime(MESSAGE_DT_FORMAT)
tg_channel_post_url = message.reply_to_message.get_url(force_private=True)
curr.execute(
"""
SELECT
gh_issue_html_url
FROM
project_issues
WHERE
project_id = ?
AND
tg_channel_post_url = ?
""",
(
# XXX: `tg_channel_post_url` is unique, no need to filter by `project_id`
project_id,
tg_channel_post_url,
)
)
project_issue = curr.fetchone()
# NOTE: checking if any issue is registered for the `channel_post`
if project_issue:
await message.reply(
f"[!] GitHub Issue already has been created at: {project_issue[0]}",
)
return
try:
repository = github.get_repo(gh_repository_full_name)
except UnknownObjectException:
await message.reply(
f"[?] Repository ({gh_repository_full_name}) is not found "
"or you have no access!"
)
return
# ChannelTitle / ChannelPostTitle / message_id
issue = repository.create_issue(
title=f"{tg_channel_title} / {message.chat.title} / {message.message_id}",
body=\
f"[{tg_message_date}] - [{tg_user_is_bot}] - [{tg_user_id}]\n"
"---\n"
f"[ChannelPostURL]({tg_channel_post_url}) - [ChannelPostCommentURL]({tg_message_url})"
)
curr.execute(
"""
INSERT INTO
project_issues (
project_id,
tg_user_id,
tg_user_is_bot,
tg_message_url,
tg_message_date,
tg_channel_post_url,
gh_issue_id,
gh_issue_html_url,
gh_issue_created_at
)
VALUES
(?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
project_id,
tg_user_id,
tg_user_is_bot,
tg_message_url,
tg_message_date,
tg_channel_post_url,
issue.id,
issue.html_url,
issue.created_at.strftime(MESSAGE_DT_FORMAT),
)
)
conn.commit()
await message.reply(f"[!] GitHub Issue created at: {issue.html_url}")
if __name__ == "__main__":
MESSAGE_DT_FORMAT = "%Y-%m-%d %H:%M:%S"
STATIC_DIR = Path("./static")
STATIC_DIR.mkdir(exist_ok=True)
DB_FILE = STATIC_DIR / "db.sqlite3"
if not os.environ.get("TG__TOKEN"):
load_dotenv("deploy/secrets/.env-local")
github = Github(
auth=Auth.Token(os.environ.get("GH__TOKEN"))
)
conn = sqlite3.connect(DB_FILE)
curr = conn.cursor()
curr.execute(
"""
CREATE TABLE IF NOT EXISTS projects (
id INTEGER PRIMARY KEY AUTOINCREMENT,
tg_channel_id BIGINT,
tg_channel_title TEXT,
-- I may not need this here
-- Project is registered for the `channel_id`
-- I'll keep in case project will be registered to `channel_post_url`
tg_channel_post_url TEXT,
tg_channel_post_date TEXT,
gh_repository_url TEXT,
gh_repository_full_name TEXT
)
"""
)
curr.execute(
"""
CREATE TABLE IF NOT EXISTS project_issues (
id INTEGER PRIMARY KEY AUTOINCREMENT,
project_id INTEGER,
tg_user_id BIGINT,
tg_user_is_bot BOOLEAN,
tg_message_url TEXT,
tg_message_date TEXT,
-- issue per post, use to filter
tg_channel_post_url TEXT,
gh_issue_id INT,
gh_issue_html_url TEXT,
gh_issue_created_at TEXT
)
"""
)
conn.commit()
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
bot = Bot(
token=os.getenv("TG__TOKEN"),
default=DefaultBotProperties(parse_mode=ParseMode.HTML)
)
asyncio.run(dp.start_polling(bot))