62 lines
1.4 KiB
Python
Executable File
62 lines
1.4 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""
|
|
A basic calculator and python interpreter application.
|
|
"""
|
|
import multiprocessing
|
|
|
|
import numpy
|
|
import numexpr
|
|
import requests
|
|
|
|
from module import commands, example
|
|
|
|
BASE_TUMBOLIA_URI = 'https://tumbolia-two.appspot.com/'
|
|
|
|
@commands('calc', 'c')
|
|
@example('.c 5 + 3', '8')
|
|
def c(bot, trigger):
|
|
"""Evaluates a mathematical expression."""
|
|
if len(trigger.args) < 2:
|
|
return bot.reply("Nothing to calculate.")
|
|
expr = ' '.join(trigger.args[1:])
|
|
|
|
def worker(expr, return_dict):
|
|
with numpy.errstate(all='ignore'):
|
|
try:
|
|
value = numexpr.evaluate(expr, local_dict={}, global_dict={})
|
|
value = value.item()
|
|
except Exception as e:
|
|
value = type(e).__name__ + ': ' + str(e)
|
|
return_dict['value'] = value
|
|
|
|
with multiprocessing.Manager() as manager:
|
|
d = manager.dict()
|
|
proc = multiprocessing.Process(target=worker, args=(expr, d))
|
|
proc.start()
|
|
proc.join(1)
|
|
if proc.is_alive():
|
|
proc.kill()
|
|
proc.join()
|
|
proc.close()
|
|
return bot.reply("Calculation timed out.")
|
|
bot.reply(str(d['value']))
|
|
|
|
|
|
@commands('py')
|
|
@example('.py len([1,2,3])', '3')
|
|
def py(bot, trigger):
|
|
"""Evaluate a Python expression."""
|
|
if len(trigger.args) < 2:
|
|
return bot.msg("Need an expression to evaluate")
|
|
|
|
query = trigger.args[1]
|
|
uri = BASE_TUMBOLIA_URI + 'py/'
|
|
res = requests.get(uri + query)
|
|
res.raise_for_status()
|
|
answer = res.text
|
|
answer = answer[:2000]
|
|
if answer:
|
|
bot.msg(answer, length=300)
|
|
else:
|
|
bot.reply('Sorry, no result.')
|