From 193c90336f713d3fdaece1621c54df2ed95ad9c5 Mon Sep 17 00:00:00 2001 From: EyeZiS Date: Tue, 10 Apr 2018 21:18:10 +0200 Subject: [PATCH] port re from walrinator --- stdplugins/re.py | 85 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 stdplugins/re.py diff --git a/stdplugins/re.py b/stdplugins/re.py new file mode 100644 index 0000000..0b22ad2 --- /dev/null +++ b/stdplugins/re.py @@ -0,0 +1,85 @@ +from collections import defaultdict, deque +import re + +import regex +from telethon import events, utils + +# Heavily based on +# https://github.com/SijmenSchoon/regexbot/blob/master/regexbot.py + +last_msgs = defaultdict(lambda: deque(maxlen=10)) + + +def doit(chat_id, match, original): + fr = match.group(1) + to = match.group(2) + to = to.replace('\\/', '/') + try: + fl = match.group(3) + if fl is None: + fl = '' + fl = fl[1:] + except IndexError: + fl = '' + + # Build Python regex flags + count = 1 + flags = 0 + for f in fl: + if f == 'i': + flags |= regex.IGNORECASE + elif f == 'g': + count = 0 + else: + return None, f"Unknown flag: {f}" + + def actually_doit(original): + try: + s, i = regex.subn(fr, to, original.message, + count=count, flags=flags) + if i > 0: + return original, s + except Exception as e: + return None, f"u dun goofed m8: {str(e)}" + return None, None + + if original is not None: + return actually_doit(original) + # Try matching the last few messages + for original in reversed(last_msgs[chat_id]): + m, s = actually_doit(original) + if s is not None: + return m, s + return None, None + + +async def group_has_regex(group): + return any(getattr(x, 'username', None) == 'regexbot' + async for x in borg.get_participants(group, search='@regexbot')) + + +@borg.on(events.NewMessage) +async def on_message(event): + chat_id = utils.get_peer_id(await event.input_chat) + last_msgs[chat_id].append(event.message) + + +@borg.on(events.NewMessage( + pattern=re.compile(r"^s/((?:\\/|[^/])+)/((?:\\/|[^/])*)(/.*)?"))) +async def on_regex(event): + if event.forward: + return + if not event.is_private and await group_has_regex(await event.input_chat): + return + + chat_id = utils.get_peer_id(await event.input_chat) + + m, s = doit(chat_id, event.pattern_match, await event.reply_message) + + if m is not None: + out = await borg.send_message(await event.input_chat, s, reply_to=m.id) + last_msgs[chat_id].append(out) + elif s is not None: + await event.reply(s) + + raise events.StopPropagation