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.
 
 

313 lines
9.6 KiB

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
from telegram import ParseMode
from db import Db
import logging
import os
import random
import requests
import datetime
import cat
import pydog
DIETS = {
"veggy" : "fleischlos",
"fleisch" : "mit Fleisch",
"fisch" : "mit Fisch/ Meeresfrüchten"
}
WEEKDAYS = {
"montag" : 1,
"dienstag" : 2,
"mittwoch" : 3,
"donnerstag" : 4,
"freitag" : 5,
"samstag" : 6
}
MENSA_URL = {
"zentral": "zentralmensa",
"nord": "nordmensa",
"turm": "turmmensa",
"italia": "mensaitalia",
"fasthochschule": "bistrohawk"
}
MENSA_NAME = {
"zentral": "Zentralmensa",
"nord": "Nordmensa",
"turm": "Turmmensa",
"italia": "Mensa Italia",
"fasthochschule": "Bistro Fasthochschule"
}
HIDE_CATEGORIES_LIGHT = {
"CampusCurry",
"natürlich fit",
"Fitnesscenter",
"Salatbuffet",
"Studentenfutter",
"Süße Versuchung",
"Süße Spezial Tagesangebot",
"Vollwert & Co. Stärke",
"Vollwert & Co. Gemüse",
"Bio-Beilagen",
"Dessertbuffet",
"Last Minute ab 14:30 Uhr",
## Nordmensa:
"Salatbuffet/Pastapoint",
"Last Minute ab 13:30 Uhr",
## Turmmensa:
"Beilagen",
"Last Minute ab 14:00Uhr"
}
HIDE_CATEGORIES_FULL = {
"Last Minute ab 14:30 Uhr",
"Last Minute ab 13:30 Uhr",
"Last Minute ab 14:00Uhr"
}
MODES = {
"light" : HIDE_CATEGORIES_LIGHT,
"full" : HIDE_CATEGORIES_FULL
}
# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
with open("stoll.txt", "r") as tmp_file:
STOLL = tmp_file.readlines()
with open("manta.txt", "r") as tmp_file:
MANTA = tmp_file.readlines()
with open("goodlife.txt", "r") as tmp_file:
GOOD_LIFE = tmp_file.readlines()
# Define a few command handlers. These usually take the two arguments bot and
# update. Error handlers also receive the raised TelegramError object in error.
def start(bot, update):
"""Was ist das hier für eins Bot?"""
update.message.reply_text("""Hallo, ich bin ein Bot.
Ich liefere tolle Informationen über die Mensa. Die Infos kommen von
https://mensa.schneider-hosting.de
Mhmm, lecker. Guten Appetit!""")
def help(bot, update):
"""Send a message when the command /help is issued."""
update.message.reply_text("""Commands:
*Mensa*:
/mensa _mensa_ - prints filtered list of meals for _mensa_ (if no _mensa_ given, zentralmensa is used)
/mensa _mensa_ full - prints full list of meals for _mensa_ (if no _mensa_ given, zentralmensa is used)
*Fun*:
/cat - random cat (using thecatapi.com)
/dog - random dog (using dog.ceo/dog-api)
/magie - random Axel Stoll quote
/manta - random Opel Manta joke
/goodlife - random good life quote
/shrug - prints shrug
/kill - kills you
/revive - revives you
/sudo kill/revive - force kill/revive
/graveyard - shows the dead people
/help - this help text""", parse_mode=ParseMode.MARKDOWN)
def sendCat(bot, update):
"""CUTE"""
catfile = cat.getCat();
bot.send_photo(chat_id=update.message.chat_id, photo=open(catfile, 'rb'))
os.remove(catfile)
def sendDog(bot, update):
"""CUTE 2.0"""
dog = pydog.PyDog()
bot.send_photo(chat_id=update.message.chat_id, photo=dog.get_random_image())
def kill(bot, update, sudocall = False):
"""kill me pls"""
db = Db()
user = update.message.from_user.first_name
if db.is_dead(user, update.message.chat_id):
if sudocall:
update.message.reply_text("%s killed again" % user)
return
update.message.reply_text("%s is already dead" % user)
return
message = update.message.from_user.first_name + " died"
if sudocall:
message += " for real"
db.kill(user, update.message.chat_id)
update.message.reply_text(message)
def revive(bot, update, sudocall = False):
"""unkill me pls"""
db = Db()
user = update.message.from_user.first_name
if not db.is_dead(user, update.message.chat_id):
update.message.reply_text("Maybe %s should have a litte 'accident' before" % user)
return
if sudocall:
update.message.reply_text("%s is living again, for real" % user)
db.revive(user, update.message.chat_id)
return
update.message.reply_text("You fool! You cannot revive a dead person!")
SUDOCMDS = {
"kill" : kill,
"revive" : revive
}
def graveyard(bot, update):
"""List the dead"""
db = Db()
update.message.reply_text("Here are the dead people:\n%s" % db.get_dead_bodies(update.message.chat_id))
def sudo(bot, update, args):
"""for real"""
if not args :
update.message.reply_text("Unknown command")
return
for arg in args:
if arg in SUDOCMDS:
SUDOCMDS[arg](bot, update, True)
else:
update.message.reply_text("Unknown command")
def sendCatDog(bot, update):
"""Best of both worlds!"""
catdog = "https://upload.wikimedia.org/wikipedia/en/6/64/CatDog.jpeg"
bot.send_photo(chat_id=update.message.chat_id, photo=catdog)
def magie(bot, update):
"""MAGIEEEEEE"""
rand = random.SystemRandom()
update.message.reply_text(STOLL[rand.randrange(0, len(STOLL), 1)])
def manta(bot, update):
"""Boah ey, geile Karre!"""
rand = random.SystemRandom()
update.message.reply_text(MANTA[rand.randrange(0, len(MANTA), 1)])
def goodlife(bot, update):
"""GOOD LIFE MY A..."""
rand = random.SystemRandom()
update.message.reply_text(GOOD_LIFE[rand.randrange(0, len(GOOD_LIFE), 1)])
def shrug(bot, update):
"""SHRUG"""
update.message.reply_text("¯\_(ツ)_/¯")
def simon(bot, update):
"KAUF DIR N HUND"
update.message.reply_text("@Justus_vonRamme bitte kauf dir einen Hund oder eine Katze, du hast zu viel Zeit")
def mensa(bot, update, args):
which = "zentral"
filter_categories = MODES["light"]
diet = ""
today = datetime.datetime.now().date().weekday() + 1
if datetime.datetime.now().time() > datetime.time(hour=16):
# Es ist zu spät am Tag, zeig das essen für morgen an
today += 1
today = today % 7
for arg in args:
arg = arg.lower()
if arg in MENSA_NAME:
which = arg
elif arg in MODES:
filter_categories = MODES[arg]
elif arg in WEEKDAYS:
today = WEEKDAYS[arg]
elif arg in DIETS:
diet = DIETS[arg]
else:
update.message.reply_text("Falscher Aufruf! RTFM und versuchs nochmal.")
return
if today == 0:
update.message.reply_text("Sonntags hat die Mensa zu")
return
url = "https://mensa.schneider-hosting.de/static/%s.%d.json" % (MENSA_URL[which], today)
request = requests.get(url)
request.encoding = 'utf-8'
data = request.json()
message = "Das Essen für %s in der %s \n\n" % (data["date"], MENSA_NAME[which])
if len(data["meals"]) > 1:
for meal in data["meals"]:
if meal["category"] not in filter_categories and diet in meal["diet"]:
meal_line = "*%s*\n" % meal["category"]
meal_line += meal["title"].strip() + "\n"
# Discord only allows up to 2000 chars per message
if len(message) + len(meal_line) > 2000:
update.message.reply_text(message, parse_mode=ParseMode.MARKDOWN)
message = meal_line + "\n"
else:
message += meal_line + "\n"
update.message.reply_text(message, parse_mode=ParseMode.MARKDOWN)
else:
update.message.reply_text("Nix zu futtern heute :(")
def echo(bot, update):
"""Echo the user message."""
update.message.reply_text(update.message.text)
def error(bot, update, error):
"""Log Errors caused by Updates."""
logger.warning('Update "%s" caused error "%s"', update, error)
def main():
"""Start the bot."""
# Create the EventHandler and pass it your bot's token.
token = open("token").read()
updater = Updater(token.strip())
# Get the dispatcher to register handlers
dp = updater.dispatcher
# on different commands - answer in Telegram
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", help))
dp.add_handler(CommandHandler("magie", magie))
dp.add_handler(CommandHandler("manta", manta))
dp.add_handler(CommandHandler("goodlife", goodlife))
dp.add_handler(CommandHandler("mensa", mensa, pass_args=True))
dp.add_handler(CommandHandler("sudo", sudo, pass_args=True))
dp.add_handler(CommandHandler("cat", sendCat))
dp.add_handler(CommandHandler("dog", sendDog))
dp.add_handler(CommandHandler("catdog", sendCatDog))
dp.add_handler(CommandHandler("shrug", shrug))
dp.add_handler(CommandHandler("kill", kill))
dp.add_handler(CommandHandler("revive", revive))
dp.add_handler(CommandHandler("simon", simon))
dp.add_handler(CommandHandler("graveyard", graveyard))
# log all errors
dp.add_error_handler(error)
# Start the Bot
updater.start_polling()
# Run the bot until you press Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT. This should be used most of the time, since
# start_polling() is non-blocking and will stop the bot gracefully.
updater.idle()
if __name__ == '__main__':
main()