Replacer.py (view raw)
1from telegram import Update, InlineKeyboardMarkup, InlineKeyboardButton
2from telegram.constants import ParseMode
3from Config import INLINE_SEP, FEEDBACK_TIMEOUT
4import logging, re, json
5from asyncio import sleep
6logger = logging.getLogger(__name__)
7
8re_flags = re.I | re.M
9
10replacers = [
11 {
12 "regex": re.compile(r"(?:https?:\/\/)?(?:www\.)?youtu\.?be(?:\.com)?\/?.*(?:watch|embed)?(?:.*v=|v\/|\/)([\w\-_]+)\&?", re_flags),
13 "becomes": "https://y.outube.duckdns.org/{}",
14 },
15 {
16 "regex": re.compile(r"(?:https?:\/\/)?(?:www\.)?twitter\.com\/(?:#!\/)?(.*)\/status(?:es)?\/([^\/\?\s]+)", re_flags),
17 "becomes": "https://fxtwitter.com/{}/status/{}",
18 },
19]
20
21link_message = "Link di {}[\.]({})"
22
23def get_callback_data(feedback: bool) -> str:
24 payload = { "feedback": feedback }
25 return "feedback" + INLINE_SEP + json.dumps(payload)
26
27def get_message_markup() -> InlineKeyboardMarkup:
28 buttons = [
29 [
30 InlineKeyboardButton(text="✅", callback_data=get_callback_data(True)),
31 InlineKeyboardButton(text="❌", callback_data=get_callback_data(False)),
32 ]
33 ]
34 return InlineKeyboardMarkup(buttons)
35
36def format_template(template: str, regex_result) -> str:
37 result_type = type(regex_result)
38 if result_type is str:
39 return template.format(regex_result)
40 elif result_type is tuple or result_type is list:
41 return template.format(*regex_result)
42 elif result_type is dict:
43 return template.format(**regex_result)
44 else:
45 return ""
46
47def parse_text(message: str) -> list:
48 output = []
49 for site in replacers:
50 regex = site["regex"]
51 res = regex.findall(message)
52 for r in res:
53 link = format_template(site["becomes"], r)
54 output.append(link)
55 return output
56
57async def replace(update: Update, _) -> None:
58 try:
59 links = parse_text(update.message.text)
60 except TypeError:
61 links = parse_text(update.message.caption)
62
63 for link in links:
64 logger.info(link)
65 text = link_message.format(update.effective_user.mention_markdown_v2(), link)
66 message = await update.message.reply_text(text, parse_mode=ParseMode.MARKDOWN_V2)
67 await sleep(FEEDBACK_TIMEOUT)
68 await message.edit_reply_markup(reply_markup=get_message_markup())
69
70async def feedback(update: Update, _, data_json: str) -> None:
71 data = json.loads(data_json)
72
73 if data["feedback"]:
74 await update.callback_query.answer("Bene!")
75 await update.effective_message.edit_reply_markup()
76 return
77
78 await update.callback_query.answer("Ci ho provato...")
79 await update.effective_message.delete()
80 return