early progress: untested so far

This commit is contained in:
Lili (Tlapka) 2022-06-08 14:22:58 +02:00
parent 1d3bce203c
commit de9294c754
5 changed files with 125 additions and 13 deletions

12
.gitignore vendored Normal file
View File

@ -0,0 +1,12 @@
*.pyc
__pycache__/
instance/
.pytest_cache/
.coverage
htmlcov/
dist/
build/
*.egg-info/

45
main.py
View File

@ -1,27 +1,46 @@
from flask import Flask,request,json
from flask import Flask,request,json,g
from tlapbot.db import get_db
import requests
app = Flask(__name__)
@app.route('/')
def hello():
return 'Webhooks with Python'
@app.route('/githubIssue',methods=['POST'])
def githubIssue():
data = request.json
print(f'Issue {data["issue"]["title"]} {data["action"]} \n')
print(f'{data["issue"]["body"]} \n')
print(f'{data["issue"]["url"]} \n')
return data
@app.route('/owncastWebhook',methods=['POST'])
def owncastWebhook():
data = request.json
db = get_db()
if data["type"] == "CHAT":
print("New chat message:")
print(f'from {data["eventData"]["user"]["displayName"]}:')
print(f'{data["eventData"]["body"]}')
elif data["type"] == "USER_JOINED":
user_id = data["eventData"]["user"]["id"]
try:
cursor = db.execute(
"SELECT username FROM points WHERE id = ?",
(user_id)
)
if cursor.fetchone() == None:
username = data["eventData"]["user"]["displayName"]
cursor.execute(
"INSERT INTO points(id, username, points) VALUES(?, ?, 0)",
(user_id, username)
)
db.commit()
elif data["type"] == "NAME_CHANGED":
user_id = data["eventData"]["user"]["id"]
new_username = data["eventData"]["user"]["newName"]
try:
db.execute(
"UPDATE points SET username = ? WHERE id = ?",
(new_username, user_id),
)
db.commit()
except db.IntegrityError:
print("Integrity Error.")
print(f"User ID {user_id} probably does not exist.")
return data
if __name__ == '__main__':

33
tlapbot/__init__.py Normal file
View File

@ -0,0 +1,33 @@
import os
from flask import Flask
def create_app(test_config=None):
# create and configure the app
app = Flask(__name__, instance_relative_config=True)
app.config.from_mapping(
SECRET_KEY='dev',
DATABASE=os.path.join(app.instance_path, 'tlapbot.sqlite'),
)
if test_config is None:
# load the instance config, if it exists, when not testing
app.config.from_pyfile('config.py', silent=True)
else:
# load the test config if passed in
app.config.from_mapping(test_config)
# ensure the instance folder exists
try:
os.makedirs(app.instance_path)
except OSError:
pass
from . import db
db.init_app(app)
return app
if __name__ == '__main__':
create_app()

41
tlapbot/db.py Normal file
View File

@ -0,0 +1,41 @@
import sqlite3
import click
from flask import current_app, g
from flask.cli import with_appcontext
def get_db():
if 'db' not in g:
g.db = sqlite3.connect(
current_app.config['DATABASE'],
detect_types=sqlite3.PARSE_DECLTYPES
)
g.db.row_factory = sqlite3.Row
return g.db
def close_db(e=None):
db = g.pop('db', None)
if db is not None:
db.close()
def init_db():
db = get_db()
with current_app.open_resource('schema.sql') as f:
db.executescript(f.read().decode('utf8'))
@click.command('init-db')
@with_appcontext
def init_db_command():
"""Clear the existing data and create new tables."""
init_db()
click.echo('Initialized the database.')
def init_app(app):
app.teardown_appcontext(close_db)
app.cli.add_command(init_db_command)

7
tlapbot/schema.sql Normal file
View File

@ -0,0 +1,7 @@
DROP TABLE IF EXISTS points;
CREATE TABLE points (
id TEXT PRIMARY KEY,
username TEXT NOT NULL,
points INTEGER
);