Skip to content
Snippets Groups Projects
Commit cda966c9 authored by Philip Maas's avatar Philip Maas
Browse files

refactor main_file and document addsong

parent 9662b8c6
No related branches found
No related tags found
1 merge request!7refactor main_file and document addsong
...@@ -113,6 +113,8 @@ You can use:\ ...@@ -113,6 +113,8 @@ You can use:\
`.deepl <LC>, <String>` - Translate a word, sentence or even small texts with the DeepL translator. `<LC>` is a language code.\ `.deepl <LC>, <String>` - Translate a word, sentence or even small texts with the DeepL translator. `<LC>` is a language code.\
The bot will try to guess the language of `<String>`. Example: `.deepl ES, Where is the library?` Powered by [DeepL](https://www.deepl.com) The bot will try to guess the language of `<String>`. Example: `.deepl ES, Where is the library?` Powered by [DeepL](https://www.deepl.com)
`.addSong <Message>` - Just add .addSong tou your normal Spotify Song Message. The bot will do the rest.
## Crawlers ## Crawlers
`.genderneutral <German String>` or `.gn <German String>` - Looks if a string (can be more than one sentence) is genderneutral and displays alternatives for genderspecific words. Powered by [geschicktgendern](https://www.geschicktgendern.de) `.genderneutral <German String>` or `.gn <German String>` - Looks if a string (can be more than one sentence) is genderneutral and displays alternatives for genderspecific words. Powered by [geschicktgendern](https://www.geschicktgendern.de)
......
...@@ -10,21 +10,15 @@ ...@@ -10,21 +10,15 @@
"name_2": "link" "name_2": "link"
} }
}, },
"FUN_DICT": {
"ping": "pong",
"marco": "Polo",
"foo": "bar",
"hello": "world!",
"answer": "42",
"echo": "echo",
"beep": "boop"
},
"GROUPS": [ "GROUPS": [
{ {
"group_1": "Groupname: doesn't nedd to match the real groupname", "group_1": "Groupname: doesn't nedd to match the real groupname",
"ID": ["replace this string with the group_id_array"], "ID": [
"COMMANDS": ["echo", "help", "credits", "remusfeinste", "trueamerican", "links", "yesno", "yn", "dadjoke", "genderneutral", "gn", "freegames", "savequote", "addquote", "createquote" "replace this string with the group_id_array"
, "randomquote", "saveevent", "addevent", "createevent", "nextevent", "allevents", "savebirthday", "addbirthday", "createbirthday", "nextbirthday", "allbirthdays", "tex", "sips", "schlücke", "challenge", "roll", "request", "deepl"] , ],
"COMMANDS": ["echo", "help", "credits", "remusfeinste", "trueamerican", "links", "yesno", "yn", "dadjoke", "genderneutral", "gn", "freegames", "savequote",
"addquote", "createquote", "randomquote", "saveevent", "addevent", "createevent", "nextevent", "allevents", "savebirthday",
"addbirthday", "createbirthday", "nextbirthday", "allbirthdays", "tex", "sips", "schlücke", "challenge", "roll", "request", "deepl"],
"LINKS": { "LINKS": {
"category_1": { "category_1": {
"name": "link", "name": "link",
...@@ -38,7 +32,6 @@ ...@@ -38,7 +32,6 @@
"QUOTESDIR": "/path/to/group_1.csv", "QUOTESDIR": "/path/to/group_1.csv",
"BIRTHDAYDIR": "/path/to/group_1.csv", "BIRTHDAYDIR": "/path/to/group_1.csv",
"EVENTDIR": "/path/to/group_1.csv" "EVENTDIR": "/path/to/group_1.csv"
} }
], ],
"Admins": { "Admins": {
...@@ -58,5 +51,10 @@ ...@@ -58,5 +51,10 @@
"group_name": "replace this string with the group_id_array", "group_name": "replace this string with the group_id_array",
"person_name": "phone_number" "person_name": "phone_number"
}, },
"Spotify": {
"spotify_client_id": "replace this string with the spotify_client_id",
"client_secret": "replace this string with the client_secret",
"redirect_uri": "replace this string with the redirect_uri"
},
"DEEPLAPI": "API-Key" "DEEPLAPI": "API-Key"
} }
\ No newline at end of file
...@@ -6,7 +6,6 @@ import json ...@@ -6,7 +6,6 @@ import json
import logging import logging
import random import random
import time import time
import calendar
from datetime import date, datetime, timedelta from datetime import date, datetime, timedelta
from threading import Thread from threading import Thread
...@@ -60,67 +59,15 @@ commands = None ...@@ -60,67 +59,15 @@ commands = None
event_reminder = None event_reminder = None
translator = None translator = None
today = None today = None
CONFIG = {}
FUN_DICT = {}
MQTT_USER = ""
MQTT_PWD = ""
MQTT_IP = ""
MQTT_PORT = None
MQTT_TIMEOUT = None
FREE_GAMES_SUBSCRIBER = {}
GROUPS = {}
def load_config(filename): def load_config(filename):
global CONFIG global CONFIG
global FUN_DICT
global MQTT_USER
global MQTT_PWD
global MQTT_IP
global MQTT_PORT
global MQTT_TIMEOUT
global FREE_GAMES_SUBSCRIBER
global GROUPS
global translator
global spotify_client_id
global spotify_client_secret
global spotify_redirect_uri
try: try:
CONFIG = json.load(open(filename, "r")) CONFIG = {}
if "FUN_DICT" in CONFIG: with open(filename, 'r') as file:
FUN_DICT = CONFIG["FUN_DICT"] CONFIG = json.load(file)
if "MQTT" in CONFIG:
if "mqtt.local" in CONFIG["MQTT"]:
if "MQTT_USER" in CONFIG["MQTT"]["mqtt.local"]:
MQTT_USER = CONFIG["MQTT"]["mqtt.local"]["MQTT_USER"]
if "MQTT_PWD" in CONFIG["MQTT"]["mqtt.local"]:
MQTT_PWD = CONFIG["MQTT"]["mqtt.local"]["MQTT_PWD"]
if "MQTT_IP" in CONFIG["MQTT"]["mqtt.local"]:
MQTT_IP = CONFIG["MQTT"]["mqtt.local"]["MQTT_IP"]
if "MQTT_PORT" in CONFIG["MQTT"]["mqtt.local"]:
MQTT_PORT = CONFIG["MQTT"]["mqtt.local"]["MQTT_PORT"]
if "MQTT_TIMEOUT" in CONFIG["MQTT"]["mqtt.local"]:
MQTT_TIMEOUT = CONFIG["MQTT"]["mqtt.local"]["MQTT_TIMEOUT"]
if "FREE_GAMES_SUBSCRIBER" in CONFIG:
FREE_GAMES_SUBSCRIBER = CONFIG["FREE_GAMES_SUBSCRIBER"]
if "GROUPS" in CONFIG:
GROUPS = CONFIG["GROUPS"]
if "DEEPLAPI" in CONFIG:
if CONFIG["DEEPLAPI"] != "API-Key":
translator = deepl.Translator(CONFIG["DEEPLAPI"])
if "Spotify" in CONFIG:
if "client_id" in CONFIG["Spotify"]:
spotify_client_id = CONFIG["Spotify"]["client_id"]
if "client_secret" in CONFIG["Spotify"]:
spotify_client_secret = CONFIG["Spotify"]["client_secret"]
if "redirect_uri" in CONFIG["Spotify"]:
spotify_redirect_uri = CONFIG["Spotify"]["redirect_uri"]
except FileNotFoundError: except FileNotFoundError:
log.error(f"File:'{filename}' not accessible. Running in reduced mode.") log.error(f"File:'{filename}' not accessible. Running in reduced mode.")
...@@ -189,12 +136,9 @@ def send(message, receiver): ...@@ -189,12 +136,9 @@ def send(message, receiver):
if "f43e6540-0274-481e-838d-feefbb0686df" in err_message: if "f43e6540-0274-481e-838d-feefbb0686df" in err_message:
return return
request_group = None testung = next((group for group in GROUPS if group["NAME"] == "Testung"), None)
for group in GROUPS: if testung is not None:
if group["NAME"] == "Testung": send(err_message, testung["ID"])
request_group = group
break
send(err_message, request_group["ID"])
def send_a(message, receiver, attachment): def send_a(message, receiver, attachment):
...@@ -210,12 +154,9 @@ def send_a(message, receiver, attachment): ...@@ -210,12 +154,9 @@ def send_a(message, receiver, attachment):
log.error(err_message) log.error(err_message)
if "f43e6540-0274-481e-838d-feefbb0686df" in err_message: if "f43e6540-0274-481e-838d-feefbb0686df" in err_message:
return return
request_group = None testung = next((group for group in GROUPS if group["NAME"] == "Testung"), None)
for group in GROUPS: if testung is not None:
if group["NAME"] == "Testung": send(err_message, testung["ID"])
request_group = group
break
send(err_message, request_group["ID"])
def echo(msgDict): def echo(msgDict):
...@@ -384,19 +325,19 @@ def roll(msgDict): ...@@ -384,19 +325,19 @@ def roll(msgDict):
def request(msgDict): def request(msgDict):
answer = "" answer = ""
request_group = None request_group = next((group for group in GROUPS if group["NAME"] == "Requests"), None)
for group in GROUPS:
if group["NAME"] == "Requests":
request_group = group
break
if not msgDict["content"]: if not msgDict["content"]:
answer = "Was soll denn hinzugefügt werden?" answer = "Was soll denn hinzugefügt werden?"
else: else:
answer = "Besten Dank! Die Anfrage wurde weitergeleitet." answer = "Besten Dank! Die Anfrage wurde weitergeleitet."
if request_group is not None:
send(answer, msgDict["receiver"]) send(answer, msgDict["receiver"])
send(msgDict["content"], request_group["ID"]) send(msgDict["content"], request_group["ID"])
else:
send('Der Befehl Requests funktioniert gerade nicht :(', msgDict["receiver"])
def get_random_challenge(msgDict): def get_random_challenge(msgDict):
...@@ -485,11 +426,12 @@ def get_deepl_translation(msgDict): ...@@ -485,11 +426,12 @@ def get_deepl_translation(msgDict):
def add_song_to_playlist(msgDict): def add_song_to_playlist(msgDict):
spotify_config = CONFIG.get("Spotify", {})
if ( if (
ModuleSpotify is None ModuleSpotify is None
or spotify_client_id is None or spotify_config.get('spotify_client_id', None) is None
or spotify_client_secret is None or spotify_config.get('spotify_client_secret', None) is None
or spotify_redirect_uri is None or spotify_config.get('redirect_uri', None) is None
): # TODO bereits in der INit berücksichtigen, wenn die Secrets nicht am start sind ): # TODO bereits in der INit berücksichtigen, wenn die Secrets nicht am start sind
send("There is no Spotify!", msgDict["receiver"]) send("There is no Spotify!", msgDict["receiver"])
return return
...@@ -520,19 +462,21 @@ def on_mqtt_message(client, userdata, msg): ...@@ -520,19 +462,21 @@ def on_mqtt_message(client, userdata, msg):
def mqtt_client(): def mqtt_client():
mqtt_local = CONFIG.get("MQTT", {}).get("mqtt.local", {})
client2 = mqtt.Client() client2 = mqtt.Client()
client2.on_message = on_mqtt_message client2.on_message = on_mqtt_message
client2.username_pw_set(MQTT_USER, MQTT_PWD) client2.username_pw_set(mqtt_local.get("MQTT_USER", ""), mqtt_local.get("MQTT_PWD", ''))
client2.connect(MQTT_IP, MQTT_PORT, MQTT_TIMEOUT) client2.connect(mqtt_local.get("MQTT_IP", ''), mqtt_local.get("MQTT_PORT", None), mqtt_local.get("MQTT_TIMEOUT", None))
# TODO Topics und receiver in config auslagern, um dynamischer zu subscriben # TODO Topics und receiver in config auslagern, um dynamischer zu subscriben
client2.subscribe("Sensoren/Arbeitszimmer/temperature") client2.subscribe("Sensoren/Arbeitszimmer/temperature")
client2.loop_forever() client2.loop_forever()
def send_heartbeat(): def send_heartbeat():
for group in GROUPS: testung = next((group for group in GROUPS if group["NAME"] == "Testung"), None)
if group["NAME"] == "Testung": if testung is not None:
send("Still alive - there will be 🎂", group["ID"]) send("Still alive - there will be 🎂", testung["ID"])
def init_schedule_jobs(): def init_schedule_jobs():
...@@ -553,20 +497,16 @@ def init_schedule_jobs(): ...@@ -553,20 +497,16 @@ def init_schedule_jobs():
def remind_pflanzen(): def remind_pflanzen():
for group in GROUPS: tierwg = next((group for group in GROUPS if group["NAME"] == "TierWG"), None)
if group["NAME"] == "TierWG": if tierwg is not None:
send(f"Bitte gebt den armen Pflanzen etwas Lebenselixier!", group["ID"]) send(f"Bitte gebt den armen Pflanzen etwas Lebenselixier!", tierwg["ID"])
break
def gg_remind_schichten(): def gg_remind_schichten():
for group in GROUPS: gg_group = next((group for group in GROUPS if group["NAME"] == "GGOffiziell"), None)
if group["NAME"] == "GGOffiziell": if gg_group is not None:
send( send(f'Bitte tragt euch in die Planung ein:\n {gg_group["LINKS"]["Planung"]}', gg_group["ID"])
f'Bitte tragt euch in die Planung ein:\n {group["LINKS"]["Planung"]}',
group["ID"],
)
break
def gg_remind_stundenzettel(): def gg_remind_stundenzettel():
...@@ -594,13 +534,9 @@ def gg_remind_stundenzettel(): ...@@ -594,13 +534,9 @@ def gg_remind_stundenzettel():
last_day -= datetime.timedelta(days=5) last_day -= datetime.timedelta(days=5)
gg_group = None gg_group = next((group for group in GROUPS if group["NAME"] == "GGOffiziell"), None)
for group in GROUPS:
if group["NAME"] == "GGOffiziell":
gg_group = group
break
if last_day == date.today().day: if last_day == date.today().day and gg_group is not None:
send( send(
"""Bitte schickt eure ausgefüllten Stundenzettel! """Bitte schickt eure ausgefüllten Stundenzettel!
• ihr müsst eure Abrechnungen jeden Monat sowohl an Sarah, als auch an Ben senden. • ihr müsst eure Abrechnungen jeden Monat sowohl an Sarah, als auch an Ben senden.
...@@ -627,16 +563,20 @@ def run_threaded(job_func): ...@@ -627,16 +563,20 @@ def run_threaded(job_func):
if __name__ == "__main__": if __name__ == "__main__":
load_config("/home/pi/signalbot/config.json") load_config("/home/pi/signalbot/config.json")
# global GROUPS
GROUPS = CONFIG.get("GROUPS", {})
spotify_config = CONFIG.get("Spotify", {})
gn = ModuleGenderneutral("gn.json", log) gn = ModuleGenderneutral("gn.json", log)
quotes = ModuleQuotes(GROUPS, log) quotes = ModuleQuotes(GROUPS, log)
games = ModuleFreeGames(FREE_GAMES_SUBSCRIBER, send_a, log) games = ModuleFreeGames(CONFIG.get("FREE_GAMES_SUBSCRIBER", {}), send_a, log)
challenges = ModuleChallenge("/home/pi/signalbot/challenge.json", log) challenges = ModuleChallenge("/home/pi/signalbot/challenge.json", log)
birthday_reminder = ModuleBirthdayReminder(GROUPS, send, log) birthday_reminder = ModuleBirthdayReminder(GROUPS, send, log)
tex = ModuleTex(log) tex = ModuleTex(log)
commands = ModuleCommands("/home/pi/signalbot/commands.json", FUN_DICT, log) commands = ModuleCommands("/home/pi/signalbot/commands.json", CONFIG.get("FUN_DICT", {}), log)
event_reminder = ModuleEventReminder(GROUPS, send, log) event_reminder = ModuleEventReminder(GROUPS, send, log)
spotify = ModuleSpotify( spotify = ModuleSpotify(
send, spotify_client_id, spotify_client_secret, spotify_redirect_uri, log send, spotify_config.get('spotify_client_id', ''), spotify_config.get('spotify_client_secret', ''), spotify_config.get('redirect_uri', ''), log
) )
today = ModuleToday(log) today = ModuleToday(log)
loop = GLib.MainLoop() loop = GLib.MainLoop()
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment