SaveText.Ru

Без имени
  1. #!/usr/bin/env python
  2. import telebot
  3. import re
  4.  
  5. bot = telebot.TeleBot('Тут токен')
  6.  
  7.  
  8. def calculate(text):
  9.     context = {}
  10.     line = "result = " + text
  11.     try:
  12.         exec(line, context)
  13.     except SyntaxError as e:
  14.         return "Syntax error"
  15.     except:
  16.         return "Unknown error"
  17.     return context["result"]
  18.  
  19.  
  20. @bot.message_handler(content_types=["text"])
  21. def get_text_messages(message):
  22.     print message.text
  23.     if message.text.lower() == "hello" or message.text.lower() == "hi":
  24.         bot.send_message(message.from_user.id, "Hello, my friend!")
  25.     elif message.text == "/help":
  26.         bot.send_message(message.from_user.id, "Write something easy to calculate (1+1, 2+3*4)")
  27.     elif re.match(r'^[0-9+-*/()s]+$', message.text):
  28.         answer = calculate(message.text)
  29.         bot.send_message(message.from_user.id, answer)
  30.     else:
  31.         bot.send_message(message.from_user.id, "What?! Try /help.")
  32.  
  33. if __name__ == "__main__":
  34.     bot.polling(none_stop=True, interval=0)

Share with your friends:

Print