~sgeisenh/streambot

a31e87bcfd61cec6ddcda0538064c6b1e982505b — Samuel Eisenhandler 1 year, 5 months ago
It works
7 files changed, 365 insertions(+), 0 deletions(-)

A .dockerignore
A .gitignore
A Dockerfile
A LICENSE
A fly.toml
A requirements.txt
A streambot.py
A  => .dockerignore +4 -0
@@ 1,4 @@
fly.toml
venv
__pycache__
.env

A  => .gitignore +4 -0
@@ 1,4 @@
venv
zuliprc
__pycache__
.env

A  => Dockerfile +11 -0
@@ 1,11 @@
# syntax=docker/dockerfile:1

FROM python:3.9-slim-buster

WORKDIR /app

COPY requirements.txt requirements.txt
RUN pip3 install -r requirements.txt
COPY . .

CMD [ "python3", "-m", "zulip_botserver.server", "--config-file", "zuliprc", "--hostname", "0.0.0.0"]

A  => LICENSE +19 -0
@@ 1,19 @@
Copyright (c) 2023 Samuel Eisenhandler

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

A  => fly.toml +34 -0
@@ 1,34 @@
# fly.toml file generated for zulipstreambot on 2023-02-07T15:07:53-05:00

app = "zulipstreambot"
kill_signal = "SIGINT"
kill_timeout = 5
processes = []

[experimental]
  auto_rollback = true

[mounts]
  source="zulipstreambot_data"
  destination="/data"

[[services]]
  http_checks = []
  internal_port = 5002
  processes = ["app"]
  protocol = "tcp"
  script_checks = []
  [services.concurrency]
    hard_limit = 25
    soft_limit = 20
    type = "connections"

  [[services.ports]]
    handlers = ["http"]
    port = 80

  [[services.tcp_checks]]
    grace_period = "1s"
    interval = "15s"
    restart_limit = 0
    timeout = "2s"

A  => requirements.txt +23 -0
@@ 1,23 @@
beautifulsoup4==4.11.2
certifi==2022.12.7
charset-normalizer==3.0.1
click==8.1.3
distro==1.8.0
Flask==2.2.2
html2text==2020.1.16
idna==3.4
importlib-metadata==6.0.0
itsdangerous==2.1.2
Jinja2==3.1.2
lxml==4.9.2
MarkupSafe==2.1.2
matrix-client==0.4.0
requests==2.28.2
soupsieve==2.3.2.post1
typing_extensions==4.4.0
urllib3==1.26.14
Werkzeug==2.2.2
zipp==3.12.1
zulip==0.8.2
zulip-bots==0.8.2
zulip-botserver==0.8.2

A  => streambot.py +270 -0
@@ 1,270 @@
import logging
import os
import sqlite3
from datetime import datetime, timedelta
from typing import Dict, Final, List, Optional, Tuple

import requests

logger: logging.Logger = logging.getLogger("streambot")


# Environment variables.
CLIENT_ID: Final[str] = os.environ["CLIENT_ID"]
CLIENT_SECRET: Final[str] = os.environ["CLIENT_SECRET"]
DB_PATH: Final[str] = os.environ["DB_PATH"]
TWITCH_SECRET: Final[str] = os.environ["TWITCH_SECRET"]
CALLBACK_URL: Final[str] = os.environ["CALLBACK_URL"]


SUBSCRIPTION_URL: Final[str] = "https://api.twitch.tv/helix/eventsub/subscriptions"


OAUTH_URL: Final[str] = "https://id.twitch.tv/oauth2/token"
oauth_token: Optional[Tuple[str, datetime]] = None


def get_oauth_token() -> str:
    global oauth_token
    now = datetime.now()
    if oauth_token is None or now > oauth_token[1]:
        headers = {"Content-Type": "application/x-www-form-urlencoded"}
        data = {
            "grant_type": "client_credentials",
            "client_id": CLIENT_ID,
            "client_secret": CLIENT_SECRET,
        }
        response = requests.post(OAUTH_URL, data=data, headers=headers).json()
        oauth_token = response["access_token"], now + timedelta(
            seconds=response["expires_in"]
        )

    return oauth_token[0]


USERS_URL: Final[str] = "https://api.twitch.tv/helix/users"


def get_channel_id(channel_name) -> str:
    payload = {"login": channel_name}
    response = requests.get(USERS_URL, params=payload, headers=create_headers()).json()
    return response["data"][0]["id"]


class StreamBotHandler:
    def usage(self) -> str:
        return """
            This bot allows users to add streaming notifications for new twitch
            channels. Users should preface messages with the message
            @streambot

            This bot supports the following commands:
                - add <channel name>
                - remove <channel name>
                - list

            For example, to subscribe to the channel "sgeisenh", you would send
            the message:

            @streambot add sgeisenh
            """

    def handle_message(self, message, bot_handler) -> None:
        logger.info("received message: %s", message)

        def handle_error(error):
            bot_handler.send_reply(message, f"@streambot Error: {error}")

        content = message["content"]
        without_prefix = content.removeprefix("@streambot ")
        if content == without_prefix:
            handle_error("missing required prefix '@streambot '")
            return

        command = without_prefix.split()

        # TODO: update botserver to support python 3.10 and switch back to
        #       match.
        if len(command) == 2 and command[0] == "add":
            channel_name = command[1]
            channel_id = get_channel_id(channel_name)
            handle_add(message, channel_id, channel_name, bot_handler)
        elif len(command) == 2 and command[0] == "remove":
            channel_name = command[1]
            channel_id = get_channel_id(channel_name)
            handle_remove(message, channel_id, channel_name, bot_handler)
        elif len(command) == 1 and command[0] == "list":
            handle_list(message, bot_handler)
        else:
            handle_error(
                "the valid commands are 'add <channel name>', 'remove <channel name>', and 'list'"
            )


def handle_add(message, channel_id, channel_name, bot_handler):
    data = {
        "type": "stream.online",
        "version": "1",
        "condition": {
            "broadcaster_user_id": channel_id,
        },
        "transport": {
            "method": "webhook",
            "callback": CALLBACK_URL,
            "secret": TWITCH_SECRET,
        },
    }

    try:
        response = requests.post(
            SUBSCRIPTION_URL,
            json=data,
            headers={**create_headers(), "Content-Type": "application/json"},
        )
        response_json = response.json()
        if response.status_code // 100 != 2:
            logger.warning("twitch subscription error: %s", repr(response_json))
            bot_handler.send_reply(
                message,
                f"error subscribing to '{channel_name}': {response_json['message']}",
            )
            return

        subscription_id = response_json["data"][0]["id"]
        insert_channel(channel_id, channel_name, subscription_id)
    except Exception as e:
        logger.warning("error subscribing to channel: %s", repr(e))
        bot_handler.send_reply(
            message,
            f"unable to subscribe to stream online notifications for '{channel_name}'",
        )
        return

    bot_handler.send_reply(
        message, f"subscribed to stream online notifications for '{channel_name}'"
    )


def handle_remove(message, channel_id, channel_name, bot_handler):
    subscription_id = get_subscription_id(channel_id)
    if subscription_id is None:
        delete_channel(channel_id)
        bot_handler.send_reply(
            message, f"could not find subscription to channel '{channel_name}'"
        )
        return

    payload = {"id": subscription_id}
    try:
        requests.delete(url=SUBSCRIPTION_URL, headers=create_headers(), params=payload)
    except Exception as e:
        logger.warning("request to delete subscription to channel failed: %s", repr(e))
        bot_handler.send_reply(
            message, f"error issuing unsubscribe request for channel '{channel_name}'"
        )
        return

    delete_channel(channel_id)
    bot_handler.send_reply(message, f"no longer subscribed to '{channel_name}'")


def handle_list(message, bot_handler):
    channel_list = "\n".join(f"- {channel}" for channel in list_channels())
    bot_handler.send_reply(
        message, f"List of current channel subscriptions:\n{channel_list}"
    )


con: Optional[sqlite3.Connection] = None
SCHEMA = """
CREATE TABLE IF NOT EXISTS channels (
        channel_id TEXT PRIMARY KEY,
        channel_name TEXT NOT NULL,
        subscription_id TEXT NOT NULL
) WITHOUT ROWID;
"""


def get_db() -> sqlite3.Connection:
    global con
    if con is None:
        con = sqlite3.connect(DB_PATH)
        con.execute("PRAGMA journal_mode='WAL';")
        con.execute("PRAGMA synchronous='NORMAL';")
        con.execute(SCHEMA)
        con.commit()
    return con


INSERT_CHANNEL: Final[
    str
] = """
INSERT INTO channels VALUES(:channel_id, :channel_name, :subscription_id)
ON CONFLICT(channel_id) DO UPDATE SET
    channel_name = :channel_name,
    subscription_id = :subscription_id;
"""


def insert_channel(channel_id: str, channel_name: str, subscription_id: str):
    con = get_db()
    con.execute(
        INSERT_CHANNEL,
        {
            "channel_id": channel_id,
            "channel_name": channel_name,
            "subscription_id": subscription_id,
        },
    )
    con.commit()


LIST_CHANNELS: Final[
    str
] = """
SELECT channel_name FROM channels;
"""


def list_channels() -> List[str]:
    con = get_db()
    res = con.execute(LIST_CHANNELS)
    return [row[0] for row in res.fetchall()]


GET_SUBSCRIPTION_ID: Final[
    str
] = """
SELECT subscription_id FROM channels WHERE channel_id = :channel_id;
"""


def get_subscription_id(channel_id: str) -> Optional[str]:
    con = get_db()
    res = con.execute(GET_SUBSCRIPTION_ID, {"channel_id": channel_id})
    result = res.fetchone()
    return None if result is None else result[0]


DELETE_CHANNEL: Final[
    str
] = """
DELETE FROM channels WHERE channel_id = :channel_id;
"""


def delete_channel(channel_id: str) -> bool:
    con = get_db()
    try:
        con.execute(DELETE_CHANNEL, {"channel_id": channel_id})
        con.commit()
    except sqlite3.IntegrityError:
        return False
    return True


def create_headers() -> Dict[str, str]:
    return {"Client-Id": CLIENT_ID, "Authorization": f"Bearer {get_oauth_token()}"}


handler_class = StreamBotHandler