forked from simonsmh/telegram-bili-feed-helper
/
main.py
374 lines (343 loc) · 11.9 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
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
import asyncio
import json
import logging
import os
import re
import sys
from functools import lru_cache
from io import BytesIO
from uuid import uuid4
import aiohttp
from PIL import Image
from telegram import (
InlineKeyboardButton,
InlineKeyboardMarkup,
InlineQueryResultArticle,
InlineQueryResultAudio,
InlineQueryResultGif,
InlineQueryResultPhoto,
InlineQueryResultVideo,
InputMediaPhoto,
InputTextMessageContent,
ParseMode,
)
from telegram.error import BadRequest, TimedOut
from telegram.ext import (
CommandHandler,
Filters,
InlineQueryHandler,
MessageHandler,
Updater,
)
from telegram.ext.dispatcher import run_async
from telegram.ext.filters import Filters
from telegram.utils.helpers import escape_markdown
from feedparser import feedparser, headers
logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(message)s", level=logging.INFO
)
logger = logging.getLogger("Telegram_Bili_Feed_Helper")
regex = r"(?i)\w*\.?(?:bilibili\.com|(?:b23|acg)\.tv)\S+"
sourcecodemarkup = InlineKeyboardMarkup(
[
[
InlineKeyboardButton(
text="源代码", url="https://github.com/simonsmh/telegram-bili-feed-helper",
)
]
]
)
def origin_link(content):
return InlineKeyboardMarkup([[InlineKeyboardButton(text="原链接", url=content)]])
@lru_cache(maxsize=16)
def captions(f):
def parser_helper(content):
charegex = r"\W"
content = re.sub(
r"\\#([^#]+)\\#?",
lambda x: f"\\#{re.sub(charegex, '', x.group(1))} ",
content,
)
return content
captions = f"{f.user_markdown}:\n"
if f.content_markdown:
captions += f.content_markdown
if f.comment_markdown:
captions += f"\n\\-\\-\\-\\-\\-\\-\n{f.comment_markdown}"
return parser_helper(captions)
async def get_media(f, url, size=1280, compression=True):
def compress(inpil):
pil = Image.open(inpil)
pil.thumbnail((size, size), Image.LANCZOS)
pil.save(outpil := BytesIO(), "PNG", optimize=True)
return outpil
async with aiohttp.ClientSession(headers=headers) as session:
async with session.get(url, headers={"Referer": f.url}) as resp:
media = BytesIO(await resp.read())
mediatype = resp.headers["Content-Type"]
if compression:
if mediatype in ["image/jpeg", "image/png"]:
logger.info(f"压缩: {url} {mediatype}")
media = compress(media)
media.seek(0)
return media
@run_async
def parse(update, context):
message = update.effective_message
data = message.text
urls = re.findall(regex, data)
logger.info(f"Parse: {urls}")
async def callback(f, caption):
if f.mediathumb:
mediathumb = await get_media(f, f.mediathumb, size=320)
if f.mediaraws:
tasks = [get_media(f, img) for img in f.mediaurls]
media = await asyncio.gather(*tasks)
logger.info(f"上传中: {f.url}")
else:
if f.mediatype == "image":
media = [i if ".gif" in i else i + "@1280w.jpg" for i in f.mediaurls]
else:
media = f.mediaurls
if f.mediatype == "video":
message.reply_video(
media[0],
caption=captions(f),
parse_mode=ParseMode.MARKDOWN_V2,
quote=False,
reply_markup=origin_link(f.url),
supports_streaming=True,
thumb=mediathumb,
timeout=120,
)
elif f.mediatype == "audio":
message.reply_audio(
media[0],
caption=captions(f),
duration=f.mediaduration,
parse_mode=ParseMode.MARKDOWN_V2,
performer=f.user,
quote=False,
reply_markup=origin_link(f.url),
thumb=mediathumb,
timeout=120,
title=f.mediatitle,
)
elif len(f.mediaurls) == 1:
if ".gif" in f.mediaurls[0]:
message.reply_animation(
media[0],
caption=captions(f),
parse_mode=ParseMode.MARKDOWN_V2,
quote=False,
reply_markup=origin_link(f.url),
timeout=60,
)
else:
message.reply_photo(
media[0],
caption=captions(f),
parse_mode=ParseMode.MARKDOWN_V2,
quote=False,
reply_markup=origin_link(f.url),
timeout=60,
)
else:
media = [
InputMediaPhoto(
img, caption=captions(f), parse_mode=ParseMode.MARKDOWN_V2
)
for img in media
]
message.reply_media_group(media, quote=False, timeout=120)
message.reply_text(
captions(f),
disable_web_page_preview=True,
parse_mode=ParseMode.MARKDOWN_V2,
quote=False,
reply_markup=origin_link(f.url),
)
async def parse_queue(url):
f = await feedparser(url, video=False)
if not f:
logger.warning("解析错误!")
return
reply_markup = InlineKeyboardMarkup(
[[InlineKeyboardButton(text="原链接", url=f.url)]]
)
if f.mediaurls:
try:
await callback(f, captions(f))
except (TimedOut, BadRequest) as err:
logger.exception(err)
logger.info(f"{err} -> 下载中: {f.url}")
f.mediaraws = True
await callback(f, captions(f))
else:
message.reply_text(
captions(f),
disable_web_page_preview=True,
parse_mode=ParseMode.MARKDOWN_V2,
quote=False,
reply_markup=reply_markup,
)
loop = asyncio.new_event_loop()
tasks = [parse_queue(url) for url in urls]
loop.run_until_complete(asyncio.gather(*tasks, loop=loop))
loop.close()
@run_async
def fetch(update, context):
message = update.effective_message
data = message.text
urls = re.findall(regex, data)
logger.info(f"Fetch: {urls}")
async def fetch_queue(url):
f = await feedparser(url)
if not f:
logger.warning("解析错误!")
return
if f.mediaurls:
tasks = [get_media(f, img, compression=False) for img in f.mediaurls]
medias = await asyncio.gather(*tasks)
logger.info(f"上传中: {f.url}")
for media, mediafilename in zip(medias, f.mediafilename):
message.reply_document(
media,
filename=mediafilename,
quote=False,
reply_markup=origin_link(f.url),
timeout=120,
)
loop = asyncio.new_event_loop()
tasks = [fetch_queue(url) for url in urls]
loop.run_until_complete(asyncio.gather(*tasks, loop=loop))
loop.close()
@run_async
def inlineparse(update, context):
inline_query = update.inline_query
query = inline_query.query
helpmsg = [
InlineQueryResultArticle(
id=uuid4(),
title="帮助",
description="将 Bot 添加到群组可以自动匹配消息, Inline 模式只可发单张图。",
reply_markup=sourcecodemarkup,
input_message_content=InputTextMessageContent(
"欢迎使用 @bilifeedbot 的 Inline 模式来转发动态,您也可以将 Bot 添加到群组自动匹配消息。"
),
)
]
if not query:
inline_query.answer(helpmsg)
return
try:
url = re.search(regex, query).group(0)
except AttributeError:
inline_query.answer(helpmsg)
return
logger.info(f"Inline: {url}")
f = asyncio.run(feedparser(url))
if not f:
logger.warning("解析错误!")
return
if not f.mediaurls:
results = [
InlineQueryResultArticle(
id=uuid4(),
title=f.user,
description=f.content,
reply_markup=origin_link(f.url),
input_message_content=InputTextMessageContent(
captions(f),
parse_mode=ParseMode.MARKDOWN_V2,
disable_web_page_preview=True,
),
)
]
else:
if f.mediatype == "video":
results = [
InlineQueryResultVideo(
id=uuid4(),
caption=captions(f),
title=f.user,
description=f.content,
mime_type="video/mp4",
parse_mode=ParseMode.MARKDOWN_V2,
reply_markup=origin_link(f.url),
thumb_url=f.mediathumb,
video_url=f.mediaurls[0],
)
]
if f.mediatype == "audio":
results = [
InlineQueryResultAudio(
id=uuid4(),
caption=captions(f),
title=f.mediatitle,
description=f.content,
audio_duration=f.mediaduration,
audio_url=f.mediaurls[0],
parse_mode=ParseMode.MARKDOWN_V2,
performer=f.user,
reply_markup=origin_link(f.url),
thumb_url=f.mediathumb,
)
]
else:
results = [
InlineQueryResultGif(
id=uuid4(),
caption=captions(f),
title=f"{f.user}: {f.content}",
gif_url=img,
parse_mode=ParseMode.MARKDOWN_V2,
reply_markup=origin_link(f.url),
thumb_url=img,
)
if ".gif" in img
else InlineQueryResultPhoto(
id=uuid4(),
caption=captions(f),
title=f.user,
description=f.content,
parse_mode=ParseMode.MARKDOWN_V2,
photo_url=img + "@1280w.jpg",
reply_markup=origin_link(f.url),
thumb_url=img + "@512w_512h.jpg",
)
for img in f.mediaurls
]
if len(results) == 1:
results.extend(helpmsg)
inline_query.answer(results)
@run_async
def error(update, context):
logger.warning(f"Update {context} caused error {error}")
@run_async
def start(update, context):
update.effective_message.reply_text(
"欢迎使用 @bilifeedbot 的 Inline 模式来转发动态,您也可以将 Bot 添加到群组自动匹配消息。",
reply_markup=sourcecodemarkup,
)
if __name__ == "__main__":
if os.environ.get("TOKEN"):
TOKEN = os.environ.get("TOKEN")
elif len(sys.argv) >= 2:
TOKEN = sys.argv[1]
else:
logger.exception(f"Need TOKEN.")
sys.exit(1)
updater = Updater(TOKEN, use_context=True)
updater.dispatcher.add_handler(
CommandHandler("start", start, filters=Filters.private)
)
updater.dispatcher.add_handler(CommandHandler("file", fetch))
updater.dispatcher.add_handler(CommandHandler("parse", parse))
updater.dispatcher.add_handler(MessageHandler(Filters.regex(regex), parse))
updater.dispatcher.add_handler(InlineQueryHandler(inlineparse))
updater.dispatcher.add_error_handler(error)
updater.start_polling()
logger.info(f"Bot @{updater.bot.get_me().username} started.")
updater.bot.set_my_commands([["file", "获取匹配内容原始文件"], ["parse", "获取匹配内容"]])
updater.idle()