added possibility to translate messages with the google

This commit is contained in:
Konrad 2019-09-26 16:25:25 +02:00
parent 20e0025c26
commit 2f28bf2d05

View file

@ -13,6 +13,7 @@ from typing import Any
from urllib.error import HTTPError
import telepot
from googletrans import Translator
from telepot.aio import DelegatorBot
from telepot.aio.delegate import per_chat_id, create_open, pave_event_space
from telepot.aio.loop import MessageLoop
@ -41,6 +42,7 @@ info_str = "*Mensa-Bot der Hochschule Mittweida (beta)*\nDieser Bot versendet je
"[vecteezy.com](https://de.vecteezy.com)"
status = ""
essen = []
essen_eng = []
var = True
datum = None
@ -131,11 +133,16 @@ class HSMensaW(telepot.aio.helper.ChatHandler):
write_config()
async def send_essen(chat_id: int) -> None:
global datum, essen
nachricht = "Speiseplan am %s:\n" % datum.strftime("%A, den %d. %B %Y")
for i in essen:
nachricht += "- " + str(i).replace(".", ",") + "\n\n"
async def send_essen(chat_id: int, deutsch: bool = True) -> None:
global datum, essen, essen_eng
if deutsch:
nachricht = "Speiseplan am %s:\n" % datum.strftime("%A, den %d. %B %Y")
for i in essen:
nachricht += "- " + str(i).replace(".", ",") + "\n\n"
else:
nachricht = "Menu on %s:\n" % datum.strftime("%A, %d %B %Y")
for i in essen_eng:
nachricht += "- " + str(i) + "\n\n"
await send_message(bot_obj=bot, chat_id=chat_id, msg=nachricht, parse_mode="markdown")
@ -183,8 +190,9 @@ async def get_essen(only_today: bool) -> None:
:param only_today: only current day; no download if the mensa is closed
:return:
"""
global datum, essen, var # , ctx
global datum, essen, essen_eng, var # , ctx
essen = []
essen_eng = []
try:
# response = urllib.request.urlopen(url, context=ctx)
response = urllib.request.urlopen(url)
@ -221,15 +229,24 @@ async def get_essen(only_today: bool) -> None:
datum = date_dt
menus = et.findall("./menus/day[date='" + datum.isoformat() + "']/menu")
essen_transl = []
preise = []
for i in menus:
kategorie = i.findall("type")[0].text
essen_transl.append(kategorie)
name = i.findall("description")[0].text.rstrip("()1234567890, ")
essen_transl.append(name)
try:
preis = float(i.findall("./prices/price[label='Studenten']/value")[0].text.replace(",", "."))
except ValueError:
preis = -1
preise.append(preis)
essen.append(Essen(name, preis, kategorie))
translations = translator.translate(essen_transl)
for i in range(int(len(translations) / 2)):
essen_eng.append(Essen(translations[i * 2 + 1].text, preise[i], translations[i * 2].text))
def get_bot_id() -> int:
global botID
@ -304,6 +321,8 @@ signal.signal(signal.SIGINT, shutdown)
locale.setlocale(locale.LC_TIME, 'de_DE.UTF-8')
translator = Translator()
try:
with open(config_filename, 'r') as config_file:
config = json.load(config_file)