Skip to content

Instantly share code, notes, and snippets.

@x0x8x
Created April 25, 2020 11:32
Show Gist options
  • Save x0x8x/ddc4154b200eda808b74692da4b138ba to your computer and use it in GitHub Desktop.
Save x0x8x/ddc4154b200eda808b74692da4b138ba to your computer and use it in GitHub Desktop.
Infinitive STDOUT using textwrap under meval
import logging, traceback, sys, html, textwrap, asyncio
from io import StringIO
from telethon.events import NewMessage, MessageEdited
from telethon.errors.rpcerrorlist import MessageTooLongError
@client.on(events.NewMessage(outgoing=True, pattern=r"(\,x\s).+"))
@client.on(events.MessageEdited(outgoing=True, pattern=r"(\,x\s).+"))
async def eval(event):
client = event.client
cmd = event.pattern_match.group(1)
code: str = event.raw_text
code = code.replace(cmd, "", 1)
caption = "<b>Evaluated expression:</b>\n<code>{}</code>\n\n<b>Result:</b>\n".format(
code
)
preserve_stdout = sys.stdout
sys.stdout = StringIO()
try:
res = str(await meval(code, locals()))
except Exception:
caption = "<b>Evaluation failed:</b>\n<code>{}</code>\n\n<b>Result:</b>\n".format(
code
)
etype, value, tb = sys.exc_info()
res = "".join(traceback.format_exception(etype, value, None, 0))
sys.stdout = preserve_stdout
try:
val = sys.stdout.getvalue()
except AttributeError:
val = None
sys.stdout = preserve_stdout
try:
await event.edit(
caption + f"<code>{html.escape(res)}</code>", parse_mode="html"
)
except MessageTooLongError:
res = textwrap.wrap(res, 4096 - len(caption))
await event.reply(caption + f"<code>{res[0]}</code>", parse_mode="html")
for part in res[1::]:
await asyncio.sleep(2)
await event.reply(f"<code>{part}</code>", parse_mode="html")
else:
await event.reply(caption, parse_mode="html")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment