Commit 644bde69 authored by Alisson Lauffer's avatar Alisson Lauffer

[sed.py] Better sed and error handling

parent 2f3b6b86
......@@ -20,13 +20,14 @@
import ctypes
import html
import re
from utils import timeout
from multiprocessing import Process, Manager
from config import bot
def replace(res, pattern, replace_with, text, count, rflags):
res.value = re.sub(pattern, replace_with, text, count=count, flags=rflags)
def replace(pattern, replace_with, text, count, rflags):
return re.sub(pattern, replace_with, text, count=count, flags=rflags)
async def sed(msg):
......@@ -56,19 +57,17 @@ async def sed(msg):
else:
return
manager = Manager()
res = manager.Value(ctypes.c_char_p, None)
p = Process(target=replace, args=(res, pattern, replace_with, text, count, rflags))
p.start()
p.join(0.2)
p.terminate()
if res.value is None:
await bot.sendMessage(msg['chat']['id'], 'Ocorreu um erro com o seu padrão regex.',
try:
with timeout(seconds=1):
res = replace(pattern, replace_with, text, count, rflags)
except TimeoutError:
await bot.sendMessage(msg['chat']['id'], 'Ops, o seu regex executou por muito tempo.',
reply_to_message_id=msg['message_id'])
except re.error as e:
await bot.sendMessage(msg['chat']['id'], "Erro: " + str(e),
reply_to_message_id=msg['message_id'])
else:
await bot.sendMessage(msg['chat']['id'], f'<pre>{html.escape(res.value)}</pre>', 'html',
await bot.sendMessage(msg['chat']['id'], f'<pre>{html.escape(res)}</pre>', 'html',
reply_to_message_id=msg['reply_to_message']['message_id'])
return True
......@@ -19,12 +19,25 @@
import os
import html
import signal
import aiohttp
import time
import zipfile
from aiohttp.client_exceptions import ContentTypeError
class timeout:
def __init__(self, seconds=1):
self.seconds = seconds
def handle_timeout(self, signum, frame):
raise TimeoutError()
def __enter__(self):
signal.signal(signal.SIGALRM, self.handle_timeout)
signal.alarm(self.seconds)
def __exit__(self, type, value, traceback):
signal.alarm(0)
async def send_to_amano(text):
if not isinstance(text, bytes):
text = text.encode()
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment