all repos — gif-escarbot @ 2ff3f843b8dc2f033f84613e7da3630e2e43a627

Earthbound Café's custom delivery bot with other cool utilities built-in.

Replacer.py (view raw)

 1from telegram import Update
 2import logging, re
 3logger = logging.getLogger(__name__)
 4
 5re_flags = re.I | re.M
 6
 7replacers = [
 8    {
 9        "regex": re.compile(r"(?:https?:\/\/)?(?:www\.)?youtu\.?be(?:\.com)?\/?.*(?:watch|embed)?(?:.*v=|v\/|\/)([\w\-_]+)\&?", re_flags),
10        "becomes": "https://y.outube.duckdns.org/{}"
11    },
12    {
13        "regex": re.compile(r"(?:https?:\/\/)?(?:www\.)?twitter\.com\/(?:#!\/)?(.*)\/status(?:es)?\/([^\/\?\s]+)", re_flags),
14        "becomes": "https://fxtwitter.com/{}/status/{}"
15    },
16]
17
18link_message = "[.]({})"
19
20def format_template(template: str, regex_result) -> str:
21    result_type = type(regex_result)
22    if result_type is str:
23        return template.format(regex_result)
24    elif result_type is tuple or result_type is list:
25        return template.format(*regex_result)
26    elif result_type is dict:
27        return template.format(**regex_result)
28    else:
29        return ""
30
31def parse_text(message: str) -> list:
32    output = []
33    for site in replacers:
34        regex = site["regex"]
35        res = regex.findall(message)
36        for r in res:
37            link = format_template(site["becomes"], r)
38            output.append(link)
39    logger.info(output)
40    return output
41
42async def replace(update: Update, _) -> None:
43    try:
44        links = parse_text(update.message.text)
45    except TypeError:
46        links = parse_text(update.message.caption)
47
48    for link in links:
49        message = link_message.format(link)
50        await update.message.reply_text(message, parse_mode="markdown")