Artiom17

Covid19

Apr 11th, 2020
362
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 21.67 KB | None | 0 0
  1. import COVID19Py
  2. import telebot
  3. from telebot import types
  4. from flask import Flask, request
  5.  
  6. covid19 = COVID19Py.COVID19()
  7.  
  8. TOKEN = 'Your token'
  9.  
  10. bot = telebot.TeleBot(TOKEN, threaded=False)
  11.  
  12. secret = 'Your secret key'
  13. url = 'https://8e277600.ngrok.io/' + secret
  14.  
  15. bot.remove_webhook()
  16. bot.set_webhook(url=url)
  17.  
  18. app = Flask(__name__)
  19.  
  20. user_data = {}
  21.  
  22.  
  23. class User:
  24.     def __init__(self, age):
  25.         self.age = age
  26.         self.temperature = ''
  27.         self.cough = ''
  28.         self.check = ''
  29.  
  30.  
  31. @bot.message_handler(commands=["start"])
  32. def main(message):
  33.     markup = types.ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True)
  34.     but_test = types.KeyboardButton('Онлайн тест на коронавирус')
  35.     but_info = types.KeyboardButton('Онлайн иноформация о коронавирусе')
  36.     markup.add(but_test)
  37.     markup.add(but_info)
  38.     msg = bot.send_message(message.chat.id, message.from_user.first_name + " " + message.from_user.last_name +
  39.                            ", здесь вы сможете узнать статистику о заболевших коронавирусом! Для начала работы "
  40.                            "Телеграм Бота необходимо выбрать, что Вас интересует: ",
  41.                            reply_markup=markup)
  42.     bot.register_next_step_handler(msg, choose_info)
  43.  
  44.  
  45. @app.route('/' + secret, methods=['POST'])
  46. def webhook():
  47.     update = telebot.types.Update.de_json(request.stream.read().decode('utf-8'))
  48.     bot.process_new_updates([update])
  49.     return '!', 200
  50.  
  51.  
  52. @bot.message_handler(commands=["Main_Menu"])
  53. def inline(message):
  54.     key = types.ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True)
  55.     but_reg = types.KeyboardButton(text='Онлайн тест на коронавирус')
  56.     but_search = types.KeyboardButton(text='Онлайн иноформация о коронавирусе')
  57.     key.add(but_reg)
  58.     key.add(but_search)
  59.     msg = bot.send_message(message.chat.id, "Выберите, что Вас интересует?",
  60.                            reply_markup=key)
  61.     bot.register_next_step_handler(msg, choose_info)
  62.  
  63.  
  64. def choose_info(message):
  65.     markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=2)
  66.     but_main = types.KeyboardButton('/Main_Menu')
  67.     markup.add(but_main)
  68.  
  69.     if message.text == 'Онлайн тест на коронавирус':
  70.         key = types.ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True)
  71.         but_one = types.KeyboardButton('Мне меньше 18 лет')
  72.         but_two = types.KeyboardButton('18 - 30 лет')
  73.         but_three = types.KeyboardButton('30 - 50 лет')
  74.         but_four = types.KeyboardButton('50 - 65 лет')
  75.         but_five = types.KeyboardButton('Старше 65 лет')
  76.         key.add(but_one)
  77.         key.add(but_two, but_three)
  78.         key.add(but_four, but_five)
  79.         msg = bot.send_message(message.chat.id, "Сколько Вам лет?", reply_markup=key)
  80.         bot.register_next_step_handler(msg, test_age)
  81.  
  82.     elif message.text == 'Онлайн иноформация о коронавирусе':
  83.         key = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=2)
  84.         but_main_menu = types.KeyboardButton('Назад')
  85.         but_all_countries = types.KeyboardButton('Заболевших во всем мире')
  86.         but_uzb = types.KeyboardButton('Узбекистан')
  87.         but_kz = types.KeyboardButton('Казахстан')
  88.         but_rus = types.KeyboardButton('Россия')
  89.         but_ita = types.KeyboardButton('Италия')
  90.         but_spain = types.KeyboardButton('Испания')
  91.         but_usa = types.KeyboardButton('США')
  92.         key.add(but_uzb, but_kz)
  93.         key.add(but_rus, but_usa)
  94.         key.add(but_ita, but_spain)
  95.         key.add(but_all_countries)
  96.         key.add(but_main_menu)
  97.         msg = bot.send_message(message.chat.id, "Выберите страну для получения информации о количестве заболевших: ",
  98.                                reply_markup=key)
  99.         bot.register_next_step_handler(msg, covid_19_search)
  100.     else:
  101.         msg = bot.send_message(message.chat.id, "Возврат в главное меню: /Main_Menu")
  102.         bot.register_next_step_handler(msg, inline)
  103.  
  104.  
  105. def covid_19_search(message):
  106.  
  107.     if message.text == 'Узбекистан':
  108.         location_one = covid19.getLocationByCountryCode("UZ")
  109.         dic = location_one[0]
  110.         latest_one = dic.get('latest')
  111.         final_message = f"<u>Данные по стране</u>\n\nСтрана: {dic.get('country')} \nНаселение: {dic.get('country_population'):,}" \
  112.                         f"\nПоследнее обновление: {dic.get('last_updated')} \n<b>Заболевших: </b>" \
  113.                         f"{latest_one.get('confirmed'):,} \n<b>Сметрей: </b>{latest_one.get('deaths'):,}"
  114.         bot.send_message(message.chat.id, text=final_message, parse_mode='html')
  115.     elif message.text == 'Казахстан':
  116.         location_one = covid19.getLocationByCountryCode("KZ")
  117.         dic = location_one[0]
  118.         latest_one = dic.get('latest')
  119.         final_message = f"<u>Данные по стране</u>\n\nСтрана: {dic.get('country')} \nНаселение: {dic.get('country_population'):,}" \
  120.                         f"\nПоследнее обновление: {dic.get('last_updated')} \n<b>Заболевших: </b>" \
  121.                         f"{latest_one.get('confirmed'):,} \n<b>Сметрей: </b>{latest_one.get('deaths'):,}"
  122.         bot.send_message(message.chat.id, text=final_message, parse_mode='html')
  123.     elif message.text == 'Россия':
  124.         location_one = covid19.getLocationByCountryCode("RU")
  125.         dic = location_one[0]
  126.         latest_one = dic.get('latest')
  127.         final_message = f"<u>Данные по стране</u>\n\nСтрана: {dic.get('country')} \nНаселение: {dic.get('country_population'):,}" \
  128.                         f"\nПоследнее обновление: {dic.get('last_updated')} \n<b>Заболевших: </b>" \
  129.                         f"{latest_one.get('confirmed'):,} \n<b>Сметрей: </b>{latest_one.get('deaths'):,}"
  130.         bot.send_message(message.chat.id, text=final_message, parse_mode='html')
  131.     elif message.text == 'США':
  132.         location_one = covid19.getLocationByCountryCode("US")
  133.         dic = location_one[0]
  134.         latest_one = dic.get('latest')
  135.         final_message = f"<u>Данные по стране</u>\n\nСтрана: {dic.get('country')} \nНаселение: {dic.get('country_population'):,}" \
  136.                         f"\nПоследнее обновление: {dic.get('last_updated')} \n<b>Заболевших: </b>" \
  137.                         f"{latest_one.get('confirmed'):,} \n<b>Сметрей: </b>{latest_one.get('deaths'):,}"
  138.         bot.send_message(message.chat.id, text=final_message, parse_mode='html')
  139.     elif message.text == 'Италия':
  140.         location_one = covid19.getLocationByCountryCode("IT")
  141.         dic = location_one[0]
  142.         latest_one = dic.get('latest')
  143.         final_message = f"<u>Данные по стране</u>\n\nСтрана: {dic.get('country')} \nНаселение: {dic.get('country_population'):,}" \
  144.                         f"\nПоследнее обновление: {dic.get('last_updated')} \n<b>Заболевших: </b>" \
  145.                         f"{latest_one.get('confirmed'):,} \n<b>Сметрей: </b>{latest_one.get('deaths'):,}"
  146.         bot.send_message(message.chat.id, text=final_message, parse_mode='html')
  147.     elif message.text == 'Испания':
  148.         location_one = covid19.getLocationByCountryCode("ES")
  149.         dic = location_one[0]
  150.         latest_one = dic.get('latest')
  151.         final_message = f"<u>Данные по стране</u>\n\nСтрана: {dic.get('country')} \nНаселение: {dic.get('country_population'):,}" \
  152.                         f"\nПоследнее обновление: {dic.get('last_updated')} \n<b>Заболевших: </b>" \
  153.                         f"{latest_one.get('confirmed'):,} \n<b>Сметрей: </b>{latest_one.get('deaths'):,}"
  154.         bot.send_message(message.chat.id, text=final_message, parse_mode='html')
  155.     elif message.text == 'Заболевших во всем мире':
  156.         latest = covid19.getLatest()
  157.         dic = latest
  158.         final_message = f"<u>Данные по всему миру</u> \n\n<b>Заболевших: </b>"\
  159.                         f"{dic.get('confirmed'):,} \n<b>Сметрей: </b>{dic.get('deaths'):,}"
  160.         bot.send_message(message.chat.id, text=final_message, parse_mode='html')
  161.     else:
  162.         key = types.ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True)
  163.         but_main = types.KeyboardButton('Главное меню')
  164.         key.add(but_main)
  165.         msg = bot.send_message(message.chat.id, "Возврат в главное меню", reply_markup=key)
  166.         bot.register_next_step_handler(msg, inline)
  167.         return
  168.  
  169.     msg = bot.send_message(message.chat.id, "Выберите страну для получения информации о количестве заболевших: ")
  170.     bot.register_next_step_handler(msg, covid_19_search)
  171.     return
  172.  
  173.  
  174. def test_age(message):
  175.     try:
  176.         key = types.ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True)
  177.         but_one = types.KeyboardButton('36,6')
  178.         but_two = types.KeyboardButton('37')
  179.         but_three = types.KeyboardButton('37 - 38')
  180.         but_four = types.KeyboardButton('38 - 39')
  181.         but_five = types.KeyboardButton('39 - 40')
  182.         key.add(but_one, but_two)
  183.         key.add(but_three)
  184.         key.add(but_four)
  185.         key.add(but_five)
  186.  
  187.         user_id = message.from_user.id
  188.         user_data[user_id] = User(message.text)
  189.  
  190.         if message.text == 'Мне меньше 18 лет':
  191.             bot.send_message(message.chat.id, 'Отлично мой юный друг, продолжаем!')
  192.         elif message.text == '18 - 30 лет':
  193.             bot.send_message(message.chat.id, 'Отлично, продолжаем!')
  194.         elif message.text == '30 - 50 лет':
  195.             bot.send_message(message.chat.id, 'Отлично, Вы в самом рассвете сил, продолжаем!')
  196.         elif message.text == '50 - 65 лет':
  197.             bot.send_message(message.chat.id, 'Отлично, Вы хорошо держитесь, продолжаем!')
  198.         elif message.text == 'Старше 65 лет':
  199.             bot.send_message(message.chat.id, 'Отлично, Вы полны позитива, продолжаем!')
  200.         else:
  201.             key = types.ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True)
  202.             but_one = types.KeyboardButton('Мне меньше 18 лет')
  203.             but_two = types.KeyboardButton('18 - 30 лет')
  204.             but_three = types.KeyboardButton('30 - 50 лет')
  205.             but_four = types.KeyboardButton('50 - 65 лет')
  206.             but_five = types.KeyboardButton('Старше 65 лет')
  207.             key.add(but_one)
  208.             key.add(but_two, but_three)
  209.             key.add(but_four, but_five)
  210.             msg = bot.send_message(message.chat.id, 'Нажмите на кнопки, для выбора возраста!', reply_markup=key)
  211.             bot.register_next_step_handler(msg, test_age)
  212.             return
  213.  
  214.         msg = bot.send_message(message.chat.id, 'Какая у Вас температура? ', reply_markup=key)
  215.         bot.register_next_step_handler(msg, test_temperature)
  216.  
  217.     except Exception:
  218.         msg = bot.reply_to(message, 'Что-то пошло не так!')
  219.         bot.register_next_step_handler(msg, test_age)
  220.         return
  221.  
  222.  
  223. def test_temperature(message):
  224.     try:
  225.         user_id = message.from_user.id
  226.         user = user_data[user_id]
  227.         user.temperature = message.text.lower()
  228.  
  229.         key = types.ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True)
  230.         but_all = types.KeyboardButton('Есть все или несколько симптомов')
  231.         but_not_all = types.KeyboardButton('Нет симптомов')
  232.         key.add(but_all)
  233.         key.add(but_not_all)
  234.  
  235.         if message.text == '36,6':
  236.             bot.send_message(message.chat.id, 'Отлично, продолжаем!')
  237.         elif message.text == '37':
  238.             bot.send_message(message.chat.id, 'Могло бы быть и лучше!')
  239.         elif message.text == '37 - 38':
  240.             bot.send_message(message.chat.id, 'Что-то вы приболели!')
  241.         elif message.text == '38 - 39':
  242.             bot.send_message(message.chat.id, 'Как так!?')
  243.         elif message.text == '39 - 40':
  244.             bot.send_message(message.chat.id, 'Мм, это не хорошо!')
  245.         else:
  246.             key = types.ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True)
  247.             but_one = types.KeyboardButton('36,6')
  248.             but_two = types.KeyboardButton('37')
  249.             but_three = types.KeyboardButton('37 - 38')
  250.             but_four = types.KeyboardButton('38 - 39')
  251.             but_five = types.KeyboardButton('39 - 40')
  252.             key.add(but_one, but_two)
  253.             key.add(but_three)
  254.             key.add(but_four)
  255.             key.add(but_five)
  256.             msg = bot.send_message(message.chat.id, 'Нажмите на кнопки, для выбора температуры!', reply_markup=key)
  257.             bot.register_next_step_handler(msg, test_temperature)
  258.             return
  259.  
  260.         msg = bot.send_message(message.chat.id, 'Какие у Вас симптомы (головная боль, сухой кашель, насморк)?',
  261.                                reply_markup=key)
  262.         bot.register_next_step_handler(msg, test_cough)
  263.  
  264.     except Exception:
  265.         msg = bot.reply_to(message, 'Что-то пошло не так!')
  266.         bot.register_next_step_handler(msg, test_temperature)
  267.         return
  268.  
  269.  
  270. def test_cough(message):
  271.     try:
  272.         user_id = message.from_user.id
  273.         user = user_data[user_id]
  274.         user.cough = message.text
  275.  
  276.         question = 'Проверьте вашу информацию \n\nВозраст: ' + user.age + '\nТемпература: ' + user.temperature + \
  277.                    '\nСимптомы: ' + user.cough
  278.         markup = types.ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True)
  279.         but_yes = types.KeyboardButton(text='подтверждаю')
  280.         but_no = types.KeyboardButton(text='есть ошибка')
  281.         markup.add(but_yes, but_no)
  282.  
  283.         if message.text == 'Есть все или несколько симптомов':
  284.             bot.send_message(message.chat.id, 'Возможно, это просто простуда!')
  285.         elif message.text == 'Нет симптомов':
  286.             bot.send_message(message.chat.id, 'Отлично!')
  287.         else:
  288.             key = types.ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True)
  289.             but_all = types.KeyboardButton('Есть все или несколько симптомов')
  290.             but_not_all = types.KeyboardButton('Нет симптомов')
  291.             key.add(but_all)
  292.             key.add(but_not_all)
  293.             msg = bot.send_message(message.chat.id, 'Нажмите на кнопки, для выбора варианта!')
  294.             bot.register_next_step_handler(msg, test_cough)
  295.             return
  296.  
  297.         msg = bot.send_message(message.chat.id, text=question,
  298.                                reply_markup=markup)
  299.         bot.register_next_step_handler(msg, test_check)
  300.  
  301.     except Exception:
  302.         msg = bot.reply_to(message, 'Что-то пошло не так!')
  303.         bot.register_next_step_handler(msg, test_cough)
  304.         return
  305.  
  306.  
  307. def test_check(message):
  308.     try:
  309.         user_id = message.from_user.id
  310.         user = user_data[user_id]
  311.         user.check = message.text
  312.  
  313.         if message.text == 'подтверждаю':
  314.             if user.age == 'Старше 65 лет':
  315.                 if user.temperature == '37 - 38' or user.temperature == '38 - 39' or user.temperature == '39 - 40':
  316.                     if user.cough == 'Есть все или несколько симптомов':
  317.                         msg = bot.send_message(message.chat.id,
  318.                                                'Возможно это коронавирус, стоит срочно обратиться к врачу!!! '
  319.                                                'Вы в зоне риска! В любом случае это опасный вирус, '
  320.                                                'берегите себя и своих близких!')
  321.                         bot.register_next_step_handler(msg, inline)
  322.  
  323.                     else:
  324.                         msg = bot.send_message(message.chat.id, 'Если температура не спадает уже несколько дней, то '
  325.                                                                 'возможно это коронавирус, так как иногда болезнь может '
  326.                                                                 'протекать без явных симптомов, стоит обратиться '
  327.                                                                 'к врачу!!! Вы в зоне риска!'
  328.                                                                 'В любом случае это опасный вирус, берегите себя и своих '
  329.                                                                 'близких!')
  330.                         bot.register_next_step_handler(msg, inline)
  331.                 else:
  332.                     msg = bot.send_message(message.chat.id,
  333.                                            'Вы здоровы и полны сил! Берегите себя и своих близких!')
  334.                     bot.register_next_step_handler(msg, inline)
  335.             elif user.age == 'Мне меньше 18 лет' or user.age == '18 - 30 лет' or user.age == '30 - 50 лет' or \
  336.                     user.age == '50 - 65 лет':
  337.                 if user.temperature == '37 - 38' or user.temperature == '38 - 39' or user.temperature == '39 - 40':
  338.                     if user.cough == 'Есть все или несколько симптомов':
  339.                         msg = bot.send_message(message.chat.id,
  340.                                                'Возможно это коронавирус, стоит обратиться '
  341.                                                'к врачу!!! Если у Вас нет хранических заболеваний, то '
  342.                                                'Вы не в зоне риска, но стоит провериться!'
  343.                                                'В любом случае это опасный вирус, берегите себя и своих '
  344.                                                'близких!')
  345.                         bot.register_next_step_handler(msg, inline)
  346.                     else:
  347.                         msg = bot.send_message(message.chat.id, 'Если температура не спадает уже несколько дней, то '
  348.                                                                 'возможно это коронавирус, так как иногда болезнь может '
  349.                                                                 'протекать без явных симптомов, стоит обратиться '
  350.                                                                 'к врачу!!! Если у Вас нет хранических '
  351.                                                                 'заболеваний, то '
  352.                                                                 'Вы не в зоне риска, но стоит провериться! '
  353.                                                                 'В любом случае это опасный вирус, берегите себя и своих '
  354.                                                                 'близких!')
  355.                         bot.register_next_step_handler(msg, inline)
  356.                 else:
  357.                     msg = bot.send_message(message.chat.id, 'Вы здоровы и полны сил! Берегите себя и своих близких!')
  358.                     bot.register_next_step_handler(msg, inline)
  359.         elif message.text == 'есть ошибка':
  360.             markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=2)
  361.             but_mm = types.KeyboardButton('Главное меню')
  362.             markup.add(but_mm)
  363.             msg = bot.send_message(message.chat.id, 'Возврат в главное меню', reply_markup=markup)
  364.             bot.register_next_step_handler(msg, inline)
  365.             return
  366.         else:
  367.             bot.reply_to(message, 'Что-то пошло не так!')
  368.  
  369.  
  370.         markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=2)
  371.         but_mm = types.KeyboardButton('/Main_Menu')
  372.         markup.add(but_mm)
  373.  
  374.         bot.send_message(message.chat.id, '/Main_Menu',
  375.                          reply_markup=markup)
  376.  
  377.     except Exception:
  378.         msg = bot.reply_to(message, 'Что-то пошло не так!')
  379.         bot.register_next_step_handler(msg, choose_info)
  380.         return
  381.  
  382.  
  383. if __name__ == '__main__':
  384.     app.run()
Advertisement
Add Comment
Please, Sign In to add comment