forked from vijfhoek/regexbot
/
regexbot.py
115 lines (91 loc) · 2.68 KB
/
regexbot.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
from aiotg import Bot, Chat
import asyncio
import json
import os
import regex as re
from collections import defaultdict
from pprint import pprint
bot = Bot(api_token=os.environ['API_KEY'])
last_msgs = defaultdict(list)
def find_original(message):
if 'text' in message:
return message['text']
elif 'caption' in message:
return message['caption']
return None
async def doit(chat, match):
fr = match.group(1)
to = match.group(2)
to = to.replace('\\/', '/')
try:
fl = match.group(3)
if fl == None:
fl = ''
fl = fl[1:]
except IndexError:
fl = ''
# Build Python regex flags
count = 1
flags = 0
for f in fl:
if f == 'i':
flags |= re.IGNORECASE
elif f == 'g':
count = 0
else:
await chat.reply('unknown flag: {}'.format(f))
return
# Handle replies
if 'reply_to_message' in chat.message:
# Try to find the original message text
message = chat.message['reply_to_message']
original = find_original(message)
if not original:
return
# Substitute the text
try:
s, i = re.subn(fr, to, original)
if i > 0:
return (await Chat.from_message(bot, message).reply(s))['result']
except Exception as e:
await chat.reply('u dun goofed m8: ' + str(e))
return
# Try matching the last few messages
global last_msgs
if chat.id not in last_msgs:
return
for msg in reversed(last_msgs[chat.id]):
try:
original = find_original(msg)
if not original:
continue
s, i = re.subn(fr, to, original, count=count, flags=flags)
if i > 0:
return (await Chat.from_message(bot, msg).reply(s))['result']
except Exception as e:
await chat.reply('u dun goofed m8: ' + str(e))
return
@bot.command(r'^s/((?:\\/|[^/])+)/((?:\\/|[^/])*)(/.*)?')
async def test(chat, match):
global last_msgs
msg = await doit(chat, match)
if msg:
last_msgs[chat.id].append(msg)
pprint(last_msgs[chat.id])
@bot.command(r'(.*)')
@bot.handle('photo')
async def msg(chat, match):
global last_msgs
if chat.id not in last_msgs:
last_msgs[chat.id] = []
last_msgs[chat.id].append(chat.message)
if len(last_msgs[chat.id]) > 10:
last_msgs[chat.id] = last_msgs[chat.id][-10:]
async def main():
await bot.loop()
if __name__ == '__main__':
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(main())
except KeyboardInterrupt:
bot.stop()