Bot en telegram que parsea horóscopos del sitio de la Tía Yoli
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

bot.py 4.8KB

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from telegram.ext import *
  4. import telegram
  5. from telegram import InlineQueryResultArticle, InputTextMessageContent
  6. import feedparser
  7. import logging
  8. import time
  9. import locale
  10. locale.setlocale(locale.LC_ALL, 'es_ES.UTF-8')
  11. #From stackoverflow <3
  12. from HTMLParser import HTMLParser
  13. class MLStripper(HTMLParser):
  14. def __init__(self):
  15. self.reset()
  16. self.fed = []
  17. def handle_data(self, d):
  18. self.fed.append(d)
  19. def get_data(self):
  20. return ''.join(self.fed)
  21. def strip_tags(html):
  22. s = MLStripper()
  23. s.feed(html)
  24. return s.get_data()
  25. logging.basicConfig(level=logging.NOTSET,
  26. format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
  27. updater = Updater(token='229911324:AAEa_1xYrR5HhZ9Cqtr4VKsI-jr5NuB_ilI')
  28. dispatcher = updater.dispatcher
  29. #Bot data
  30. horoscopoData = {
  31. 'date':None,
  32. 'data':{},
  33. }
  34. def parseData(bot=None,update=None):
  35. if (horoscopoData['date']!= time.strftime("%d/%m/%Y")):
  36. if bot is not None and update is not None:
  37. text = u"Corazón, tengo que conectarme con los astros para resolver tu duda. Dame unos segundos..."
  38. bot.sendMessage(chat_id=update.message.chat_id, text=text)
  39. horoscopoData['date'] = time.strftime("%d/%m/%Y")
  40. d = feedparser.parse('http://www.horoscopo7.com/feed/')
  41. text = d.entries[0].content[0].value.replace(u"\xa0","").replace(u"Á","a").replace(u"Ó","o")
  42. text2 = strip_tags(text.encode("utf-8")).split("\n")
  43. i=0
  44. j = 0
  45. while i < len(text2)-4:
  46. sign = text2[i]
  47. signkey = sign.lower();
  48. print signkey +","
  49. horoscopoData['data'][signkey] = {}
  50. horoscopoData['data'][signkey]['sign'] = sign.replace("a",u"Á").replace("o",u"Ó").encode("utf-8")
  51. horoscopoData['data'][signkey]['order'] = j
  52. horoscopoData['data'][signkey]['birthday'] = text2[i+1]
  53. horoscopoData['data'][signkey]['prediction'] = text2[i+2]
  54. i+=4
  55. j+=1
  56. return horoscopoData['data']
  57. #Consigue de la lista info acerca de los signos consultados
  58. def getData(args):
  59. response = ""
  60. if args!=None:
  61. for arg in args:
  62. arg = arg.replace(u"Á","a").replace(u"Ó","o").replace(u"á","a").replace(u"ó","o")
  63. response += formatData(arg)
  64. if response == "":
  65. response += "Mi amor, necesitas preguntar por un signo para saber que le deparará el futuro. Escribe _/horoscopo <signo>_ y podré contestarte."
  66. else:
  67. response = "Ésta es mi predicción para el día de hoy, "+time.strftime("%A %d de %B de %Y")+"\n\n" + response
  68. return response
  69. def formatData(arg):
  70. response = ""
  71. arg = arg.lower()
  72. if arg in horoscopoData['data']:
  73. data = horoscopoData['data'][arg]
  74. response += "*"+data['sign']+"*\n"+\
  75. "_"+data['birthday']+"_\n"+\
  76. data['prediction']+"\n\n"
  77. return response
  78. def start(bot, update):
  79. text = u"Querido, las estrellas me dijeron que vendrías a visitarme. Pregunta por tu horóscopo o el de tus cercanos a través de este bot."
  80. bot.sendMessage(chat_id=update.message.chat_id, text=text)
  81. def horoscopo(bot,update,args = None):
  82. d = parseData(bot,update)
  83. response = ""
  84. response += getData(args)
  85. if response=="":
  86. response = u"Lo siento mi amor, reformula tu pregunta, los astros no me dijeron nada acerca de tu signo."
  87. bot.sendMessage(chat_id=update.message.chat_id, text=response, parse_mode=telegram.ParseMode.MARKDOWN)
  88. def inline_caps(bot, update):
  89. query = update.inline_query.query.lower().replace(u"Á","a").replace(u"Ó","o").replace(u"á","a").replace(u"ó","o").encode("utf-8")
  90. results = list()
  91. data = parseData()
  92. if query in data:
  93. result = data[query]
  94. sign = result['sign']
  95. prediction = formatData(query)
  96. print sign+" - "+prediction
  97. results.append(InlineQueryResultArticle(sign, sign, InputTextMessageContent(prediction,parse_mode=telegram.ParseMode.MARKDOWN)))
  98. elif query == "":
  99. for res in data:
  100. result = data[res]
  101. sign = result['sign']
  102. prediction = formatData(res)
  103. print sign+" - "+prediction
  104. results.append(InlineQueryResultArticle(sign, sign, InputTextMessageContent(prediction,parse_mode=telegram.ParseMode.MARKDOWN)))
  105. bot.answerInlineQuery(update.inline_query.id, results)
  106. start_handler = CommandHandler('start', start)
  107. start_handler = CommandHandler('horoscopo', horoscopo,pass_args=True)
  108. inline_caps_handler = InlineQueryHandler(inline_caps)
  109. dispatcher.addHandler(inline_caps_handler)
  110. dispatcher.addHandler(start_handler)
  111. updater.start_polling()