ameliabot/core/owncast.py

130 lines
3.8 KiB
Python
Raw Normal View History

import importlib
import os
2022-04-19 13:27:39 +03:00
import random
import requests
from requests.structures import CaseInsensitiveDict
import sys
from core import __version__, config, aliases, commands
from core.logger import logging
2022-04-19 13:27:39 +03:00
from flask import request
# This is gross and needs to be replaced
plugin_path = "%s/../plugins" % os.path.dirname(os.path.realpath(__file__))
sys.path.append(plugin_path)
modules = os.listdir(plugin_path)
for module in modules:
if module.endswith(".py") and not module.startswith("__"):
globals()[module[:-3]] = importlib.import_module(module[:-3])
2022-04-19 13:27:39 +03:00
# prepare the header for the bot posts
headers = CaseInsensitiveDict()
headers["Content-Type"] = "application/json"
headers["Authorization"] = "Bearer {}".format(config["owncast"]["AccessToken"])
2022-04-19 13:27:39 +03:00
post_url = "%s/api/integrations/chat/send" % config["owncast"]["ServerURL"]
2022-04-19 14:06:44 +03:00
2022-04-19 13:27:39 +03:00
def parse_webhook():
hook_type = request.json["type"]
data = request.json["eventData"]
if "CHAT" in hook_type:
data = process_chat(data)
if data:
2022-04-19 13:59:19 +03:00
send_message(data)
2022-04-19 14:06:44 +03:00
2022-04-19 13:59:19 +03:00
def send_message(data):
data = '{"body": "%s"}' % data
resp = requests.post(
2022-04-19 14:06:44 +03:00
post_url,
2022-04-19 13:59:19 +03:00
headers=headers,
data=data.encode('utf-8'))
2022-04-19 13:27:39 +03:00
2022-04-19 13:59:19 +03:00
if resp.status_code == 200:
logging.debug("RESP: {}".format(resp.__dict__))
else:
logging.error("Status code {} returned".format(
str(resp.status_code)))
2022-04-19 13:27:39 +03:00
def get_command(text):
first_word = text.split()[0].lower()
if first_word in commands:
return commands[first_word]
elif first_word in aliases:
return commands[first_word]
def get_quote(num):
try:
num = int(num)
except TypeError:
pass
except ValueError:
pass
return quote.get(num) # NOQA should work even if linter complains
2022-04-24 03:23:50 +03:00
2022-04-19 13:27:39 +03:00
def process_placeholders(sender, param, text):
# Move this dictionary to a configuration file or something
# This is so bad, it runs everything every command :pikajoy:
logging.debug("Processing placeholders")
placeholders = {
"sender": sender,
"botowner": config["DEFAULT"]["BotOwner"],
"target": param,
"random": str(random.randrange(1, 100, 1)),
"commands": ", ".join(list(commands.keys())),
"aliases": ", ".join(list(aliases.keys())),
"bot_version": __version__,
"quote": get_quote(param),
"quote_parameters": "Not implemented yet",
}
for placeholder in placeholders:
findme = "{%s}" % placeholder
if findme in text:
logging.debug("Found {}".format(findme))
if placeholders[placeholder] == "":
logging.debug("Placeholder empty")
text = "%s required" % placeholder.upper()
try:
logging.debug(
"Replacing {} with {}".format(
findme, placeholders[placeholder]))
text = text.replace(
findme, placeholders[placeholder])
except TypeError:
text = "Target not specified."
return text
2022-04-19 13:27:39 +03:00
def process_chat(data):
sender = data["user"]["displayName"]
text = data["body"]
command_reply = get_command(text)
2022-04-19 13:59:19 +03:00
logging.info("<{}> {}".format(sender, text))
2022-04-19 13:27:39 +03:00
if command_reply:
logging.debug("Command found")
if command_reply.startswith("{plugins."):
plugin = command_reply[1:-1].split(".")
logging.debug("Attempting to run plugin: %s" % plugin[1])
reply = globals()[plugin[1]].run()
return reply
2022-04-19 13:27:39 +03:00
try:
first_parameter = text.split(" ")[1]
except IndexError:
first_parameter = None
command_reply = process_placeholders(
sender, first_parameter, command_reply)
logging.debug("Reply: {}".format(command_reply))
2022-04-19 13:27:39 +03:00
return command_reply