added possibility to change language

This commit is contained in:
Konrad 2019-09-27 18:43:56 +02:00
parent 19891b29a7
commit 86bcf2864f

View file

@ -9,6 +9,7 @@ import sys
import traceback import traceback
import urllib.request import urllib.request
import xml.etree.ElementTree as ET import xml.etree.ElementTree as ET
from enum import Enum
from typing import Any from typing import Any
from urllib.error import HTTPError from urllib.error import HTTPError
@ -17,7 +18,9 @@ from googletrans import Translator
from telepot.aio import DelegatorBot from telepot.aio import DelegatorBot
from telepot.aio.delegate import per_chat_id, create_open, pave_event_space from telepot.aio.delegate import per_chat_id, create_open, pave_event_space
from telepot.aio.loop import MessageLoop from telepot.aio.loop import MessageLoop
from telepot.delegate import include_callback_query_chat_id
from telepot.exception import BotWasBlockedError from telepot.exception import BotWasBlockedError
from telepot.namedtuple import InlineKeyboardMarkup, InlineKeyboardButton
class Essen: class Essen:
@ -33,6 +36,12 @@ class Essen:
return str("*%s*: `%s`" % (self.kategorie, self.name)) return str("*%s*: `%s`" % (self.kategorie, self.name))
class Language(Enum):
GERMAN = "de"
ENGLISH = "en"
GERMAN_ENGLISH = "de+en"
config_filename = "config.json" config_filename = "config.json"
info_str = "*Mensa-Bot der Hochschule Mittweida (beta)*\nDieser Bot versendet jeden Tag um 10 Uhr den aktuellen " \ info_str = "*Mensa-Bot der Hochschule Mittweida (beta)*\nDieser Bot versendet jeden Tag um 10 Uhr den aktuellen " \
"Mensa-Speiseplan. Er wird über /start für den aktuellen Chat oder die aktuelle Gruppe gestartet, /stop " \ "Mensa-Speiseplan. Er wird über /start für den aktuellen Chat oder die aktuelle Gruppe gestartet, /stop " \
@ -50,17 +59,23 @@ botID = -1
class HSMensaW(telepot.aio.helper.ChatHandler): class HSMensaW(telepot.aio.helper.ChatHandler):
@staticmethod keyboard = InlineKeyboardMarkup(inline_keyboard=[
async def on_chat_message(msg: dict) -> None: [InlineKeyboardButton(text="Deutsch", callback_data=Language.GERMAN.value)],
[InlineKeyboardButton(text="English", callback_data=Language.ENGLISH.value)],
[InlineKeyboardButton(text="Deutsch + English", callback_data=Language.GERMAN_ENGLISH.value)],
])
editors = dict()
async def on_chat_message(self, msg: dict) -> None:
global config, essen, status, var, logging_enabled global config, essen, status, var, logging_enabled
content_type, chat_type, chat_id = telepot.glance(msg) content_type, chat_type, chat_id = telepot.glance(msg)
if content_type == "text": if content_type == "text":
text = str(msg["text"]).lower() text = str(msg["text"]).lower()
if text.startswith("/start"): if text.startswith("/start"):
if chat_id not in ids: if chat_id not in ids:
ids.append(chat_id) ids[chat_id] = Language.GERMAN
config['ids'] = ids config['ids'] = ids
await send_message(bot_obj=bot, chat_id=chat_id, msg="Bot wurde aktiviert") await send_message(bot_obj=bot, chat_id=chat_id, msg="Bot wurde aktiviert")
@ -72,8 +87,7 @@ class HSMensaW(telepot.aio.helper.ChatHandler):
await send_message(bot_obj=bot, chat_id=chat_id, msg="Bot war bereits aktiviert") await send_message(bot_obj=bot, chat_id=chat_id, msg="Bot war bereits aktiviert")
elif text.startswith("/stop"): elif text.startswith("/stop"):
if chat_id in ids: if ids.pop(chat_id, None) is not None:
ids.remove(chat_id)
config['ids'] = ids config['ids'] = ids
await send_message(bot_obj=bot, chat_id=chat_id, msg="Bot wurde deaktiviert") await send_message(bot_obj=bot, chat_id=chat_id, msg="Bot wurde deaktiviert")
@ -103,6 +117,16 @@ class HSMensaW(telepot.aio.helper.ChatHandler):
elif text.startswith("/help"): elif text.startswith("/help"):
await send_message(bot_obj=bot, chat_id=chat_id, msg=info_str, parse_mode="markdown") await send_message(bot_obj=bot, chat_id=chat_id, msg=info_str, parse_mode="markdown")
elif text.startswith("/settings"):
old_editor = self.editors.pop(chat_id, None)
if old_editor is not None:
await old_editor.deleteMessage()
sent = await self.sender.sendMessage("Bitte Sprache(n) auswählen/Please select language(s)",
reply_markup=self.keyboard)
self.editors[chat_id] = telepot.aio.helper.Editor(bot, sent)
elif text.startswith("/status") and chat_id in config_ids: elif text.startswith("/status") and chat_id in config_ids:
await send_message(bot_obj=bot, chat_id=chat_id, msg=status, parse_mode="markdown") await send_message(bot_obj=bot, chat_id=chat_id, msg=status, parse_mode="markdown")
@ -127,23 +151,47 @@ class HSMensaW(telepot.aio.helper.ChatHandler):
elif content_type == "left_chat_member": elif content_type == "left_chat_member":
if msg["left_chat_participant"]["id"] == get_bot_id(): if msg["left_chat_participant"]["id"] == get_bot_id():
if chat_id in ids: if ids.pop(chat_id, None) is not None:
ids.remove(chat_id)
config['ids'] = ids config['ids'] = ids
write_config() write_config()
async def on_callback_query(self, msg):
global config, ids
query_id, from_id, query_data = telepot.glance(msg, flavor='callback_query')
async def send_essen(chat_id: int, deutsch: bool = True) -> None: editor = self.editors.pop(from_id, None)
if editor is not None:
await editor.editMessageReplyMarkup(reply_markup=None)
message = "Fehler beim Setzen der Sprache"
if query_data == Language.GERMAN.value:
message = "Sprache geändert nach _deutsch_."
elif query_data == Language.ENGLISH.value:
message = "Changed language to _english_."
elif query_data == Language.GERMAN_ENGLISH.value:
message = "Sprache geändert nach _deutsch + englisch_. Changed language to _german + english_."
if from_id in ids:
ids[from_id] = Language(query_data)
config['ids'] = ids
write_config()
await send_message(bot_obj=bot, chat_id=from_id, msg=message, parse_mode="markdown")
async def send_essen(chat_id: int, sprache: Language = Language.GERMAN) -> None:
global datum, essen, essen_eng global datum, essen, essen_eng
if deutsch: if sprache == Language.GERMAN or sprache == Language.GERMAN_ENGLISH:
nachricht = "Speiseplan am %s:\n" % datum.strftime("%A, den %d. %B %Y") nachricht = "Speiseplan am %s:\n" % datum.strftime("%A, den %d. %B %Y")
for i in essen: for i in essen:
nachricht += "- " + str(i).replace(".", ",") + "\n\n" nachricht += "- " + str(i).replace(".", ",") + "\n\n"
else: await send_message(bot_obj=bot, chat_id=chat_id, msg=nachricht, parse_mode="markdown")
if sprache == Language.ENGLISH or sprache == Language.GERMAN_ENGLISH:
nachricht = "Menu on %s:\n" % datum.strftime("%A, %d %B %Y") nachricht = "Menu on %s:\n" % datum.strftime("%A, %d %B %Y")
for i in essen_eng: for i in essen_eng:
nachricht += "- " + str(i) + "\n\n" nachricht += "- " + str(i) + "\n\n"
await send_message(bot_obj=bot, chat_id=chat_id, msg=nachricht, parse_mode="markdown") await send_message(bot_obj=bot, chat_id=chat_id, msg=nachricht, parse_mode="markdown")
async def send_status(text: str, ignore_flag: bool = False) -> None: async def send_status(text: str, ignore_flag: bool = False) -> None:
@ -170,8 +218,7 @@ async def send_message(bot_obj: DelegatorBot, chat_id: int, msg: str, parse_mode
disable_notification=disable_notification, reply_to_message_id=reply_to_message_id, disable_notification=disable_notification, reply_to_message_id=reply_to_message_id,
reply_markup=reply_markup) reply_markup=reply_markup)
except BotWasBlockedError: except BotWasBlockedError:
if chat_id in ids: if ids.pop(chat_id, None) is not None:
ids.remove(chat_id)
config['ids'] = ids config['ids'] = ids
await send_status("Bot wurde blockiert für Chat ID %i" % chat_id) await send_status("Bot wurde blockiert für Chat ID %i" % chat_id)
@ -302,7 +349,7 @@ async def essen_loop() -> None:
status = "Essen senden" status = "Essen senden"
if len(essen) > 0: if len(essen) > 0:
await send_status("Essen werden gesendet") await send_status("Essen werden gesendet")
for i in ids: for i in ids.keys():
await send_essen(i) await send_essen(i)
await send_status("Abgeschlossen, warte 30 Sekunden") await send_status("Abgeschlossen, warte 30 Sekunden")
status = "Warte 30 Sekunden" status = "Warte 30 Sekunden"
@ -340,7 +387,8 @@ config_ids = config.get("config_ids")
logging_enabled = config.get("logging_enabled") logging_enabled = config.get("logging_enabled")
bot = telepot.aio.DelegatorBot(telegram_bot_token, [ bot = telepot.aio.DelegatorBot(telegram_bot_token, [
pave_event_space()( include_callback_query_chat_id(
pave_event_space())(
per_chat_id(), create_open, HSMensaW, timeout=10 per_chat_id(), create_open, HSMensaW, timeout=10
), ),
]) ])