-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSympybot.py
executable file
·104 lines (93 loc) · 3.62 KB
/
Sympybot.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
#!/usr/bin/env python3
import sys
import telebot
import time
from LaTeX2IMG import LaTeX2IMG
from time import sleep
from threading import current_thread
from sympy import *
from telebot import logging
import os
TOKEN = os.environ['TelegramToken']
def listener(messages):
"""
When new messages arrive TeleBot will call this function.
"""
for m in messages:
chatid = m.chat.id
if m.content_type == 'text':
text = m.text
if text.startswith("/start "):
tb.reply_to(m,"¡Bienvenido a Sympybot!\n \
Tienes varios comandos disponibles:\n \
/numeric [expresion]\n \
/symbolic [expresion]\n \
/plot [expresion]\n \
/help o /ayuda\
")
break
elif text.startswith("/help") or text.startswith("/ayuda"):
tb.reply_to(m,"Aquí tienes los comandos disponibles:\n \
/numeric [expresion] -> evalúa la expresión\n \
/symbolic [expresion] -> igual que numeric pero sin evaluar a flotante\n \
/plot [expresion] -> devolverá una representación gráfica de una expresión\
")
break
elif text.startswith("/symbolic "):
text = text.split("/symbolic ")[-1]
command = "symbolic"
elif text.startswith("/numeric "):
text = text.split("/numeric ")[-1]
command = "numeric"
elif text.startswith("/plot "):
text = text.split("/plot ")[-1]
command = "plot"
else:
break
tb.send_chat_action(chatid,'upload_document')
filename = 'resultado' + current_thread().name
###########
# Calculus or plot
if command == "plot":
try:
functions = text.split(" ")
p = plot(*functions,show=False,title=text,ylabel="")
except SyntaxError:
tb.reply_to(m,"Sintaxis inválida")
except:
tb.reply_to(m,"Error desconocido " + str(sys.exc_info()))
else:
p.save(filename + '.png')
with open(filename + '.png','rb') as image:
tb.send_photo(chatid,image)
else:
try:
if command == "numeric":
output = latex(sympify(text).evalf())
else:
output = latex(sympify(text))
except ValueError:
tb.reply_to(m,"No has escrito bien la expresión")
except:
tb.reply_to(m,"Error desconocido " + str(sys.exc_info()))
else:
LaTeX2IMG.main(['LaTeX2IMG',output,filename,'webp'])
with open(filename + '.webp','rb') as result:
tb.send_sticker(chatid, result)
logger = telebot.logger
formatter = logging.Formatter('[%(asctime)s] %(thread)d {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s',
'%m-%d %H:%M:%S')
ch = logging.FileHandler("log.txt")
logger.addHandler(ch)
logger.setLevel(logging.INFO) # or use logging.INFO
ch.setFormatter(formatter)
# Init sympy session
x, y, z, t = symbols('x y z t')
k, m, n = symbols('k m n', integer=True)
f, g, h = symbols('f g h', cls=Function)
##########
tb = telebot.TeleBot(TOKEN)
tb.set_update_listener(listener) #register listener
tb.polling(True)
while True: # Don't let the main Thread end.
sleep(5)