ameliabot/ameliabot/owncast.py

104 lines
2.9 KiB
Python

import random
import requests
from requests.structures import CaseInsensitiveDict
from ameliabot import __version__, config, aliases, commands
from ameliabot.logger import logging
from flask import request
# Make quote system and dependencies optional
if config["quotes"]["Enabled"]:
from ameliabot.quote import Quote
quote = Quote()
# prepare the header for the bot posts
headers = CaseInsensitiveDict()
headers["Content-Type"] = "application/json"
headers["Authorization"] = "Bearer {}".format(config["owncast"]["AccessToken"])
post_url = "%s/api/integrations/chat/send" % config["owncast"]["ServerURL"]
def parse_webhook():
hook_type = request.json["type"]
data = request.json["eventData"]
if "CHAT" in hook_type:
data = process_chat(data)
if data:
send_message(data)
def send_message(data):
data = '{"body": "%s"}' % data
resp = requests.post(
post_url,
headers=headers,
data=data.encode('utf-8'))
if resp.status_code == 200:
logging.debug("RESP: {}".format(resp.__dict__))
else:
logging.error("Status code {} returned".format(
str(resp.status_code)))
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)
def process_chat(data):
sender = data["user"]["displayName"]
text = data["body"]
command_reply = get_command(text)
logging.info("<{}> {}".format(sender, text))
if command_reply:
try:
first_parameter = text.split(" ")[1]
except IndexError:
first_parameter = None
# Move this dictionary to a configuration file or something
# This is so bad, it runs everything every command :pikajoy:
placeholders = {
"sender": sender,
"streamer": config["DEFAULT"]["BotOwner"],
"target": first_parameter,
"random": str(random.randrange(1, 100, 1)),
"commands": ", ".join(list(commands.keys())),
"aliases": ", ".join(list(aliases.keys())),
"bot_version": __version__,
"quote": get_quote(first_parameter),
"quote_parameters": "Not implemented yet",
}
for placeholder in placeholders:
findme = "{%s}" % placeholder
if findme in command_reply:
if placeholders[placeholder] == "":
command_reply = "%s required" % placeholder.upper()
try:
command_reply = command_reply.replace(
findme, placeholders[placeholder])
except TypeError:
command_reply = "Target not specified."
return command_reply