Telegram version of schneiderbot
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.

308 lines
9.3 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
  4. from telegram import ParseMode
  5. from db import Db
  6. import logging
  7. import os
  8. import random
  9. import requests
  10. import datetime
  11. import cat
  12. import pydog
  13. DIETS = {
  14. "veggy" : "fleischlos",
  15. "fleisch" : "mit Fleisch",
  16. "fisch" : "mit Fisch/ Meeresfrüchten"
  17. }
  18. WEEKDAYS = {
  19. "montag" : 1,
  20. "dienstag" : 2,
  21. "mittwoch" : 3,
  22. "donnerstag" : 4,
  23. "freitag" : 5,
  24. "samstag" : 6
  25. }
  26. MENSA_URL = {
  27. "zentral": "zentralmensa",
  28. "nord": "nordmensa",
  29. "turm": "turmmensa",
  30. "italia": "mensaitalia",
  31. "fasthochschule": "bistrohawk"
  32. }
  33. MENSA_NAME = {
  34. "zentral": "Zentralmensa",
  35. "nord": "Nordmensa",
  36. "turm": "Turmmensa",
  37. "italia": "Mensa Italia",
  38. "fasthochschule": "Bistro Fasthochschule"
  39. }
  40. HIDE_CATEGORIES_LIGHT = {
  41. "CampusCurry",
  42. "natürlich fit",
  43. "Fitnesscenter",
  44. "Salatbuffet",
  45. "Studentenfutter",
  46. "Süße Versuchung",
  47. "Süße Spezial Tagesangebot",
  48. "Vollwert & Co. Stärke",
  49. "Vollwert & Co. Gemüse",
  50. "Bio-Beilagen",
  51. "Dessertbuffet",
  52. "Last Minute ab 14:30 Uhr",
  53. ## Nordmensa:
  54. "Salatbuffet/Pastapoint",
  55. "Last Minute ab 13:30 Uhr",
  56. ## Turmmensa:
  57. "Beilagen",
  58. "Last Minute ab 14:00Uhr"
  59. }
  60. HIDE_CATEGORIES_FULL = {
  61. "Last Minute ab 14:30 Uhr",
  62. "Last Minute ab 13:30 Uhr",
  63. "Last Minute ab 14:00Uhr"
  64. }
  65. MODES = {
  66. "light" : HIDE_CATEGORIES_LIGHT,
  67. "full" : HIDE_CATEGORIES_FULL
  68. }
  69. # Enable logging
  70. logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
  71. level=logging.INFO)
  72. logger = logging.getLogger(__name__)
  73. with open("stoll.txt", "r") as tmp_file:
  74. STOLL = tmp_file.readlines()
  75. with open("manta.txt", "r") as tmp_file:
  76. MANTA = tmp_file.readlines()
  77. with open("goodlife.txt", "r") as tmp_file:
  78. GOOD_LIFE = tmp_file.readlines()
  79. # Define a few command handlers. These usually take the two arguments bot and
  80. # update. Error handlers also receive the raised TelegramError object in error.
  81. def start(bot, update):
  82. """Was ist das hier für eins Bot?"""
  83. update.message.reply_text("""Hallo, ich bin ein Bot.
  84. Ich liefere tolle Informationen über die Mensa. Die Infos kommen von
  85. https://mensa.schneider-hosting.de
  86. Mhmm, lecker. Guten Appetit!""")
  87. def help(bot, update):
  88. """Send a message when the command /help is issued."""
  89. update.message.reply_text("""Commands:
  90. *Mensa*:
  91. /mensa _mensa_ - prints filtered list of meals for _mensa_ (if no _mensa_ given, zentralmensa is used)
  92. /mensa _mensa_ full - prints full list of meals for _mensa_ (if no _mensa_ given, zentralmensa is used)
  93. *Fun*:
  94. /cat - random cat (using thecatapi.com)
  95. /dog - random dog (https://dog.ceo/dog-api)
  96. /magie - random Axel Stoll quote
  97. /manta - random Opel Manta joke
  98. /goodlife - random good life quote
  99. /help - this help text""", parse_mode=ParseMode.MARKDOWN)
  100. def sendCat(bot, update):
  101. """CUTE"""
  102. catfile = cat.getCat();
  103. bot.send_photo(chat_id=update.message.chat_id, photo=open(catfile, 'rb'))
  104. os.remove(catfile)
  105. def sendDog(bot, update):
  106. """CUTE 2.0"""
  107. dog = pydog.PyDog()
  108. bot.send_photo(chat_id=update.message.chat_id, photo=dog.get_random_image())
  109. def kill(bot, update, sudocall = False):
  110. """kill me pls"""
  111. db = Db()
  112. user = update.message.from_user.first_name
  113. if db.is_dead(user):
  114. if sudocall:
  115. update.message.reply_text("%s killed again" % user)
  116. return
  117. update.message.reply_text("%s is already dead" % user)
  118. return
  119. message = update.message.from_user.first_name + " died"
  120. if sudocall:
  121. message += " for real"
  122. db.kill(user)
  123. update.message.reply_text(message)
  124. def revive(bot, update, sudocall = False):
  125. """unkill me pls"""
  126. db = Db()
  127. user = update.message.from_user.first_name
  128. if not db.is_dead(user):
  129. update.message.reply_text("Maybe %s should have a litte 'accident' before" % user)
  130. return
  131. if sudocall:
  132. update.message.reply_text("%s is living again, for real" % user)
  133. db.revive(user)
  134. return
  135. update.message.reply_text("You fool! You cannot revive a dead person!")
  136. SUDOCMDS = {
  137. "kill" : kill,
  138. "revive" : revive
  139. }
  140. def graveyard(bot, update):
  141. """List the dead"""
  142. db = Db()
  143. update.message.reply_text("Here are the dead people:\n%s" % db.get_dead_bodies())
  144. def sudo(bot, update, args):
  145. """for real"""
  146. if not args :
  147. update.message.reply_text("Unknown command")
  148. return
  149. for arg in args:
  150. if arg in SUDOCMDS:
  151. SUDOCMDS[arg](bot, update, True)
  152. else:
  153. update.message.reply_text("Unknown command")
  154. def sendCatDog(bot, update):
  155. """Best of both worlds!"""
  156. catdog = "https://upload.wikimedia.org/wikipedia/en/6/64/CatDog.jpeg"
  157. bot.send_photo(chat_id=update.message.chat_id, photo=catdog)
  158. def magie(bot, update):
  159. """MAGIEEEEEE"""
  160. rand = random.SystemRandom()
  161. update.message.reply_text(STOLL[rand.randrange(0, len(STOLL), 1)])
  162. def manta(bot, update):
  163. """Boah ey, geile Karre!"""
  164. rand = random.SystemRandom()
  165. update.message.reply_text(MANTA[rand.randrange(0, len(MANTA), 1)])
  166. def goodlife(bot, update):
  167. """GOOD LIFE MY A..."""
  168. rand = random.SystemRandom()
  169. update.message.reply_text(GOOD_LIFE[rand.randrange(0, len(GOOD_LIFE), 1)])
  170. def shrug(bot, update):
  171. """SHRUG"""
  172. update.message.reply_text("¯\_(ツ)_/¯")
  173. def simon(bot, update):
  174. "KAUF DIR N HUND"
  175. update.message.reply_text("@Justus_vonRamme bitte kauf dir einen Hund oder eine Katze, du hast zu viel Zeit")
  176. def mensa(bot, update, args):
  177. which = "zentral"
  178. filter_categories = MODES["light"]
  179. diet = ""
  180. today = datetime.datetime.now().date().weekday() + 1
  181. if datetime.datetime.now().time() > datetime.time(hour=16):
  182. # Es ist zu spät am Tag, zeig das essen für morgen an
  183. today += 1
  184. today = today % 7
  185. for arg in args:
  186. if arg in MENSA_NAME:
  187. which = arg
  188. elif arg in MODES:
  189. filter_categories = MODES[arg]
  190. elif arg in WEEKDAYS:
  191. today = WEEKDAYS[arg]
  192. elif arg in DIETS:
  193. diet = DIETS[arg]
  194. else:
  195. update.message.reply_text("Falscher Aufruf! RTFM und versuchs nochmal.")
  196. return
  197. if today == 0:
  198. update.message.reply_text("Sonntags hat die Mensa zu")
  199. return
  200. url = "https://mensa.schneider-hosting.de/static/%s.%d.json" % (MENSA_URL[which], today)
  201. request = requests.get(url)
  202. request.encoding = 'utf-8'
  203. data = request.json()
  204. message = "Das Essen für %s in der %s \n\n" % (data["date"], MENSA_NAME[which])
  205. if len(data["meals"]) > 1:
  206. for meal in data["meals"]:
  207. if meal["category"] not in filter_categories and diet in meal["diet"]:
  208. meal_line = "*%s*\n" % meal["category"]
  209. meal_line += meal["title"].strip() + "\n"
  210. # Discord only allows up to 2000 chars per message
  211. if len(message) + len(meal_line) > 2000:
  212. update.message.reply_text(message, parse_mode=ParseMode.MARKDOWN)
  213. message = meal_line + "\n"
  214. else:
  215. message += meal_line + "\n"
  216. update.message.reply_text(message, parse_mode=ParseMode.MARKDOWN)
  217. else:
  218. update.message.reply_text("Nix zu futtern heute :(")
  219. def echo(bot, update):
  220. """Echo the user message."""
  221. update.message.reply_text(update.message.text)
  222. def error(bot, update, error):
  223. """Log Errors caused by Updates."""
  224. logger.warning('Update "%s" caused error "%s"', update, error)
  225. def main():
  226. """Start the bot."""
  227. # Create the EventHandler and pass it your bot's token.
  228. token = open("token").read()
  229. updater = Updater(token.strip())
  230. # Get the dispatcher to register handlers
  231. dp = updater.dispatcher
  232. # on different commands - answer in Telegram
  233. dp.add_handler(CommandHandler("start", start))
  234. dp.add_handler(CommandHandler("help", help))
  235. dp.add_handler(CommandHandler("magie", magie))
  236. dp.add_handler(CommandHandler("manta", manta))
  237. dp.add_handler(CommandHandler("goodlife", goodlife))
  238. dp.add_handler(CommandHandler("mensa", mensa, pass_args=True))
  239. dp.add_handler(CommandHandler("sudo", sudo, pass_args=True))
  240. dp.add_handler(CommandHandler("cat", sendCat))
  241. dp.add_handler(CommandHandler("dog", sendDog))
  242. dp.add_handler(CommandHandler("catdog", sendCatDog))
  243. dp.add_handler(CommandHandler("shrug", shrug))
  244. dp.add_handler(CommandHandler("kill", kill))
  245. dp.add_handler(CommandHandler("revive", revive))
  246. dp.add_handler(CommandHandler("simon", simon))
  247. dp.add_handler(CommandHandler("graveyard", graveyard))
  248. # log all errors
  249. dp.add_error_handler(error)
  250. # Start the Bot
  251. updater.start_polling()
  252. # Run the bot until you press Ctrl-C or the process receives SIGINT,
  253. # SIGTERM or SIGABRT. This should be used most of the time, since
  254. # start_polling() is non-blocking and will stop the bot gracefully.
  255. updater.idle()
  256. if __name__ == '__main__':
  257. main()