fulvia/modules/calc.py

62 lines
1.4 KiB
Python
Raw Normal View History

2018-03-16 03:13:43 -04:00
#!/usr/bin/env python3
"""
A basic calculator and python interpreter application.
"""
2020-01-31 09:47:46 -05:00
import multiprocessing
2018-03-16 03:13:43 -04:00
2020-01-31 09:47:46 -05:00
import numpy
import numexpr
2018-03-16 03:13:43 -04:00
import requests
from module import commands, example
BASE_TUMBOLIA_URI = 'https://tumbolia-two.appspot.com/'
@commands('calc', 'c')
2018-03-16 03:13:43 -04:00
@example('.c 5 + 3', '8')
def c(bot, trigger):
2020-01-31 09:47:46 -05:00
"""Evaluates a mathematical expression."""
2020-01-07 18:58:19 -05:00
if len(trigger.args) < 2:
2018-03-16 03:13:43 -04:00
return bot.reply("Nothing to calculate.")
2020-01-31 09:47:46 -05:00
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()
2020-01-31 10:08:11 -05:00
except Exception as e:
value = type(e).__name__ + ': ' + str(e)
2020-01-31 09:47:46 -05:00
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']))
2018-03-16 03:13:43 -04:00
@commands('py')
@example('.py len([1,2,3])', '3')
def py(bot, trigger):
"""Evaluate a Python expression."""
2020-01-07 18:58:19 -05:00
if len(trigger.args) < 2:
2018-05-25 15:21:18 -04:00
return bot.msg("Need an expression to evaluate")
2018-03-16 03:13:43 -04:00
2020-01-07 18:58:19 -05:00
query = trigger.args[1]
2018-03-16 03:13:43 -04:00
uri = BASE_TUMBOLIA_URI + 'py/'
res = requests.get(uri + query)
res.raise_for_status()
answer = res.text
2019-09-13 18:54:36 -04:00
answer = answer[:2000]
2018-03-16 03:13:43 -04:00
if answer:
2019-09-13 18:54:36 -04:00
bot.msg(answer, length=300)
2018-03-16 03:13:43 -04:00
else:
bot.reply('Sorry, no result.')