1
0
Fork 0
This repository has been archived on 2024-06-28. You can view files and clone it, but cannot push or open issues or pull requests.
WienerLinienBot/bot.py

183 lines
6.2 KiB
Python
Raw Normal View History

2016-07-31 13:19:30 +02:00
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Simple Bot to reply to Telegram messages
# This program is dedicated to the public domain under the CC0 license.
"""
This Bot uses the Updater class to handle the bot.
First, a few handler functions are defined. Then, those functions are passed to
the Dispatcher and registered at their respective places.
Then, the bot is started and runs until we press Ctrl-C on the command line.
Usage:
Basic Echobot example, repeats messages.
Press Ctrl-C on the command line or send a signal to the process to stop the
bot.
"""
import logging
from pprint import pprint
import yaml
2016-08-01 09:27:15 +02:00
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, ConversationHandler, CallbackQueryHandler
2016-07-31 13:19:30 +02:00
from config import *
from wienerLinien import WienerLinien
2016-08-01 09:27:15 +02:00
from save import PersistentData
2016-07-31 13:19:30 +02:00
# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
wl = WienerLinien("stationen/cache/current.json")
2016-08-01 09:27:15 +02:00
save = PersistentData()
2016-07-31 13:19:30 +02:00
SELECT, TEST = range(2)
# 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):
2016-08-01 12:45:41 +02:00
bot.sendMessage(update.message.chat_id, text='Hallo, {name}!'.format(name=update.message.from_user.first_name))
save.user(update.message.chat_id, update.message.from_user.first_name, update.message.from_user.last_name)
2016-07-31 13:19:30 +02:00
def help_message(bot, update):
2016-08-01 09:27:15 +02:00
bot.sendMessage(update.message.chat_id, text='Hilfetext')
2016-07-31 13:19:30 +02:00
def echo(bot, update):
bot.sendMessage(update.message.chat_id, text=update.message.text)
def error(bot, update, error):
logger.warn('Update "%s" caused error "%s"' % (update, error))
def image(bot, update):
bot.sendMessage(update.message.chat_id, text="Bild")
2016-08-01 12:45:41 +02:00
def addstation(bot, update, args):
2016-07-31 13:48:50 +02:00
if not args:
bot.sendMessage(update.message.chat_id, text="Verwendung:\n/add [Stationenname]")
return ConversationHandler.END
2016-07-31 13:19:30 +02:00
userinput = " ".join(args)
print(userinput)
choice = wl.fuzzy_stationname(userinput)
2016-08-01 09:27:15 +02:00
save.save_choice(update.message.chat_id, choice)
2016-07-31 13:19:30 +02:00
pprint(choice)
2016-08-01 12:45:41 +02:00
if not choice:
2016-07-31 13:19:30 +02:00
bot.sendMessage(update.message.chat_id, text="Keine Station gefunden")
return ConversationHandler.END
2016-08-01 12:45:41 +02:00
elif len(choice) == 1:
save.add_station(update.message.chat_id, {"name": choice[0][0], "id": choice[0][2]})
bot.sendMessage(update.message.chat_id, text="Station '{station}' hinzugefügt".format(station=choice[0][0]))
else:
message = "Es wurden mehrere Stationen gefunden.\nBitte gib die Nummer der gewünschten Station an:\n"
keyboard = []
i = 1
for name, percentage, stationId in choice:
keyboard.append([InlineKeyboardButton(name, callback_data=str(i))])
i += 1
reply_markup = InlineKeyboardMarkup(keyboard)
bot.sendMessage(update.message.chat_id, text=message, reply_markup=reply_markup)
return SELECT
2016-07-31 13:19:30 +02:00
def select(bot, update):
2016-08-01 09:27:15 +02:00
query = update.callback_query
if query.data.isdigit():
selected_station = save.get_choice(query.message.chat_id)[int(query.data) - 1]
2016-07-31 13:19:30 +02:00
pprint(selected_station)
2016-08-01 09:27:15 +02:00
save.add_station(query.message.chat_id, {"name": selected_station[0], "id": selected_station[2]})
2016-08-01 12:45:41 +02:00
print(selected_station[0][0])
2016-08-01 09:27:15 +02:00
bot.editMessageText(text="Station '{station}' hinzugefügt".format(station=selected_station[0]),
chat_id=query.message.chat_id,
message_id=query.message.message_id)
2016-07-31 13:19:30 +02:00
return ConversationHandler.END
else:
bot.sendMessage(update.message.chat_id, text="Ungültige Eingabe")
return SELECT
def cancel(bot, update):
bot.sendMessage(update.message.chat_id, text="Aktion abgebrochen")
2016-08-01 09:27:15 +02:00
save.delete_choice(update.message.chat_id)
2016-07-31 13:19:30 +02:00
return ConversationHandler.END
def list_stations(bot, update):
2016-08-01 09:27:15 +02:00
stations = save.get_stations(update.message.chat_id)
if stations:
2016-07-31 13:48:50 +02:00
message = ""
2016-08-01 09:27:15 +02:00
for station in stations:
2016-08-01 12:45:41 +02:00
pprint(wl.getStationInfo(station["id"]))
2016-07-31 13:48:50 +02:00
message += station["name"] + "\n"
bot.sendMessage(update.message.chat_id, text=message)
else:
bot.sendMessage(update.message.chat_id,
text="Du hast noch keine Stationen hinzugefügt\n"
"mit /add kannst du eine neue Station hinzufügen")
2016-07-31 13:19:30 +02:00
def main():
# Create the EventHandler and pass it your bot's token.
updater = Updater(TOKEN)
# 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_message))
dp.add_handler(CommandHandler("list", list_stations))
2016-08-01 12:45:41 +02:00
dp.add_handler(CommandHandler('add', addstation, pass_args=True))
dp.add_handler(CallbackQueryHandler(select))
# conv_handler = ConversationHandler(
# entry_points=[],
#
# states={
# #
# # PHOTO: [MessageHandler([Filters.photo], photo),
# # CommandHandler('skip', skip_photo)],
# #
# # LOCATION: [MessageHandler([Filters.location], location),
# # CommandHandler('skip', skip_location)],
#
# SELECT: [MessageHandler([Filters.text], select)]
# },
#
# fallbacks=[CommandHandler('cancel', cancel)]
# )
# dp.add_handler(conv_handler)
2016-07-31 13:19:30 +02:00
# on noncommand i.e message - echo the message on Telegram
dp.add_handler(MessageHandler([Filters.text], echo))
dp.add_handler(MessageHandler([Filters.photo], image))
# log all errors
dp.add_error_handler(error)
# Start the Bot
updater.start_polling()
# Run the bot until the you presses 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()
print("------------------------------------------------------------------------") #
2016-08-01 09:27:15 +02:00
save.export()
2016-07-31 13:19:30 +02:00
if __name__ == '__main__':
main()