Advertisement
Guest User

Untitled

a guest
Apr 9th, 2019
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.60 KB | None | 0 0
  1. from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackQueryHandler
  2. from telegram import InlineKeyboardButton, InlineKeyboardMarkup, ReplyKeyboardRemove, ReplyKeyboardMarkup, KeyboardButton
  3. import requests, os, telegram, datetime
  4. import psycopg2 as sql
  5.  
  6. up = Updater("728506589:AAEwkNES9a9koAm8CKaOqUDorarnRJaeFY4")
  7. dp = up.dispatcher
  8. bd = sql.connect(host="ec2-54-247-118-238.eu-west-1.compute.amazonaws.com", dbname="d94l6q6a6g2mvm", user="jguojvyjehytsn", password="2fa3407deca1f2bc920fefc973912b3ed4388f727c6bd88039552d6032a458d9")
  9. cur= bd.cursor()
  10.  
  11. #___________________Commands Settings____________________________________________________#
  12. def start(bot, up):
  13. bot.sendMessage(chat_id=up.message.chat.id, text="Hello. Bot works👌\nUse `/help` to get to know with functions this bot can perform", parse_mode=telegram.ParseMode.MARKDOWN)
  14. bot.sendDocument(chat_id=up.message.chat_id, document='CAADAQAD4AEAAkWQ0AeCTzUa7LnRbQI')
  15. check_id(up.message.chat.id)
  16. def help(bot, up):
  17. bot.sendMessage(chat_id=up.message.chat.id, text="*Hey✌️ I am an assistant bot 🤖*\nI can help you to monitor your health, show the weather and later will be able to remind you to do smth.\n - Use `/med_panel` to put your parameters (weight, height and age) and then use 'My Health' button 🏥\n - Use `/weather` to get current weather in Tashkent☀️", parse_mode=telegram.ParseMode.MARKDOWN)
  18. def echo(bot, up):
  19. button_check(bot, up)
  20.  
  21. #___________________ID + BD Settings_____________________________________________________#
  22. def check_id(id): # Занесение ID в базу данных data
  23. cur.execute("SELECT id from data;")
  24. data_id = cur.fetchall()
  25. if (id,) not in data_id:
  26. cur.execute("INSERT into data (id) VALUES({0});".format(id))
  27. bd.commit()
  28. def db_add(number, param, id_db): # Занесение параметров пользователя в data
  29. cur.execute(f"UPDATE data SET {param} = {number} WHERE id = {id_db};")
  30. bd.commit()
  31.  
  32. #___________________Panel + Buttons Settings_____________________________________________#
  33. remove=telegram.ReplyKeyboardRemove()
  34. force=telegram.ForceReply()
  35. med_keyb=[["Weight","Height", "Age"],["My Health"],["EXIT"]] # Med Settings
  36. med_panel_set=telegram.ReplyKeyboardMarkup(med_keyb,resize_keyboard=True,one_time_keyboard=True)
  37.  
  38. def buttons():
  39. keys = [[InlineKeyboardButton('Tomorrow', callback_data='1'), InlineKeyboardButton('No, thanks!', callback_data='2')]]
  40. return InlineKeyboardMarkup(inline_keyboard=keys)
  41. def med_panel(bot, up):
  42. bot.sendMessage(up.message.chat.id,"Choose:",reply_markup=med_panel_set)
  43.  
  44. #___________________Functions Processing_________________________________________________#
  45. def body_surface_area(weight, height):
  46. body_surface_area_number = float(((weight*height)**(1/2))/60)
  47. return("{0:.10f}".format(body_surface_area_number))
  48.  
  49. def body_mass_index(weight, height):
  50. body_mass_index_number = float((weight*10000)/(height*height))
  51. return("{0:.10f}".format(body_mass_index_number))
  52.  
  53. def body_mass_index_spec(bmi):
  54. if bmi <= 16:
  55. return("Acute Underweight.")
  56. elif bmi > 16 and bmi <= 18.5:
  57. return("Underweight.")
  58. elif bmi > 18.5 and bmi <= 25:
  59. return("Standard.")
  60. elif bmi > 25 and bmi <= 30:
  61. return ("Overweight.")
  62. elif bmi > 30 and bmi <= 35:
  63. return("First Degree Obesity.")
  64. elif bmi > 35 and bmi <= 40:
  65. return("Second Degree Obesity.")
  66. elif bmi > 40:
  67. return("Third Degree Obesity.")
  68.  
  69. def get_health(id):
  70. cur.execute(f"SELECT * from data where id={id};")
  71. health_param = cur.fetchone()
  72. bsa=body_surface_area(float(health_param[3]), float(health_param[1])) #bsa=body_surface_area
  73. bmi=body_mass_index(float(health_param[3]), float(health_param[1])) #bmi=body_mass_index
  74. bmi_specification=body_mass_index_spec(float(bmi))
  75. message_text=f"*Your BSA = {bsa}\nYour BMI = {bmi} | {bmi_specification}*"
  76. return message_text
  77.  
  78. def get_weather(api):
  79. settings = {'q': 'Tashkent', 'units': 'metric', 'lang': 'en', 'APPID': api}
  80. r = requests.get('http://api.openweathermap.org/data/2.5/forecast', params=settings)
  81. return(r.json())
  82.  
  83. def try_except(function):
  84. def wrapper(*args):
  85. try:
  86. function(*args)
  87. except:
  88. args[0].sendMessage(chat_id=args[1].message.chat.id, text="Ooops, sorry, incorrect data. Try again! ┐('~`;)┌", reply_markup=remove)
  89. return wrapper
  90. #_________________________________________________________________________________________________#
  91. @try_except
  92. def button_check(bot, up): # Panel Processing
  93. if up.message.text=="EXIT":
  94. bot.sendMessage(up.message.chat.id,"Exit 😥",reply_markup=remove)
  95.  
  96. elif up.message.text=="Weight": # Weight Processing
  97. bot.sendMessage(chat_id=up.message.chat.id, text="Enter your weight (use point with floating point numbers):", reply_markup=force)
  98. elif up.message.text=="Height": # Height Processing
  99. bot.sendMessage(chat_id=up.message.chat.id, text="Enter your height in integers:", reply_markup=force)
  100. elif up.message.text=="Age": # Age Processing
  101. bot.sendMessage(chat_id=up.message.chat.id, text="Enter the number of years and months since your last birthday (use strictly this order with a space between them):", reply_markup=force)
  102.  
  103. elif up.message.text=="My Health":
  104. health_text=get_health(up.message.chat.id)
  105. bot.sendMessage(chat_id=up.message.chat.id, text=health_text, parse_mode=telegram.ParseMode.MARKDOWN)
  106. elif up.message.reply_to_message.text == "Enter the number of years and months since your last birthday (use strictly this order with a space between them):": # Answer Processing
  107. years_months=up.message.text.split() #splitting the answer into separated words
  108. db_add((int(years_months[0]))*12+int(years_months[1]), 'age', up.message.chat.id)
  109. bot.sendMessage(up.message.chat.id, "Your age is added. Check the table!👌", reply_markup = remove)
  110. elif up.message.reply_to_message.text == "Enter your weight (use point with floating point numbers):" and (float(up.message.text))>=0:
  111. db_add(float(up.message.text), 'weight', up.message.chat.id)
  112. bot.sendMessage(up.message.chat.id, "Your weight is added. Check the table!👌", reply_markup = remove)
  113. elif up.message.reply_to_message.text == "Enter your height in integers:" and (int(up.message.text))>0:
  114. db_add(int(up.message.text), 'height', up.message.chat.id)
  115. bot.sendMessage(up.message.chat.id, "Your height is added. Check the table!👌", reply_markup = remove)
  116.  
  117. else:
  118. bot.sendMessage(chat_id=up.message.chat.id, text="Ooops, sorry, incorrect data. Try again! ┐('~`;)┌", reply_markup=remove)
  119.  
  120. #_________________________________________________________________________________________________#
  121. @try_except
  122. def weather(bot, up): # Tashkent Weather
  123. data=get_weather('0f798fa08e77c5b4a2ad9d1bcbf5d700')
  124. bot.sendMessage(chat_id=up.message.chat_id, text=f"Current weather in Tashkent: {int(data['list'][0]['main']['temp_max'])}°C", reply_markup=buttons())
  125.  
  126. @try_except
  127. def get_callback_from_button(bot, up): # Buttons Processing
  128. if int(up.callback_query.data) == 1:
  129. up.callback_query.answer()
  130. data = get_weather('0f798fa08e77c5b4a2ad9d1bcbf5d700')
  131. bot.sendMessage(chat_id=up.callback_query.message.chat.id, text=f"Tomorrow's weather in Tashkent: {int(data['list'][1]['main']['temp_max'])}°C")
  132. elif int(up.callback_query.data) == 2:
  133. up.callback_query.answer()
  134. bot.sendMessage(chat_id=up.callback_query.message.chat.id, text="You're welcome 🤗")
  135.  
  136. #___________________Dispatcher settgings_________________________________________________#
  137. dp.add_handler(CommandHandler("start", start))
  138. dp.add_handler(CommandHandler("help", help))
  139. dp.add_handler(CommandHandler("med_panel", med_panel))
  140. dp.add_handler(CommandHandler("weather", weather))
  141. dp.add_handler(MessageHandler(Filters.text, echo))
  142. dp.add_handler(CallbackQueryHandler(get_callback_from_button))
  143.  
  144. #___________________webhook settings_____________________________________________________#
  145. PORT = int(os.environ.get('PORT', '5000'))
  146. TOKEN = "728506589:AAEwkNES9a9koAm8CKaOqUDorarnRJaeFY4"
  147. up.start_webhook(listen='0.0.0.0', port=PORT, url_path=TOKEN)
  148. up.bot.set_webhook("https://project-py-bot.herokuapp.com/728506589:AAEwkNES9a9koAm8CKaOqUDorarnRJaeFY4")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement