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