Skip to content
Snippets Groups Projects
Commit a63b3bac authored by dnns01's avatar dnns01
Browse files

Migrate Pipimeter to use the database to be configurable from the webinterface in future

parent 14dae17f
No related branches found
No related tags found
No related merge requests found
import sqlite3
def get_value(key):
conn = sqlite3.connect("db.sqlite3")
c = conn.cursor()
c.execute('SELECT value from haugebot_web_setting where key = ?', (key,))
value = c.fetchone()[0]
conn.close()
return value
def get_int(key):
return int(get_value(key))
def get_float(key):
return float(get_value(key))
def get_bool(key):
return get_value(key) == "1"
import asyncio
import logging
import os
import sqlite3
from abc import ABC
from dotenv import load_dotenv
from giveaway_cog import GiveawayCog
# from giveaway_cog import GiveawayGog
from info_cog import InfoCog
from pipi_cog import PipiCog
from twitchio.dataclasses import Context, Message, Channel
from twitchio.ext import commands
from vote_cog import VoteCog
# from pipi_cog import PipiCog
# from vote_cog import VoteCog
# logging.basicConfig(level=logging.INFO, filename='hausgeist.log')
logging.basicConfig(level=logging.INFO, filename='hausgeist.log')
load_dotenv()
IRC_TOKEN = os.getenv("IRC_TOKEN")
......
......@@ -2,6 +2,7 @@ import asyncio
import random
import sqlite3
import config
from twitchio.ext import commands
......@@ -12,13 +13,13 @@ class InfoCog:
async def info_loop(self):
while True:
sleep_duration = int(self.bot.get_setting("WusstestDuSchonLoop"))
sleep_duration = config.get_int("WusstestDuSchonLoop")
await asyncio.sleep(sleep_duration * 60)
if await self.bot.stream():
channel = self.bot.channel()
color = self.bot.get_setting("WusstestDuSchonColor")
prefix = self.bot.get_setting("WusstestDuSchonPrefix")
color = config.get_value("WusstestDuSchonColor")
prefix = config.get_value("WusstestDuSchonPrefix")
message = self.get_random_message(prefix)
await self.bot.send_me(channel, message, color)
......
import asyncio
import logging
import os
import sqlite3
from datetime import datetime
import config
from twitchio.dataclasses import Message
from twitchio.ext import commands
......@@ -11,20 +12,10 @@ from twitchio.ext import commands
class PipiCog:
def __init__(self, bot):
self.bot = bot
self.DELAY = int(os.getenv("PIPI_DELAY"))
self.THRESHOLD_1 = int(os.getenv("PIPI_THRESHOLD_1"))
self.THRESHOLD_2 = int(os.getenv("PIPI_THRESHOLD_2"))
self.PIPIMETER_LOOP = int(os.getenv("PIPIMETER_LOOP"))
self.RESET_THRESHOLD = int(os.getenv("PIPI_RESET_THRESHOLD"))
self.COLOR_0 = os.getenv("PIPI_COLOR_0")
self.COLOR_1 = os.getenv("PIPI_COLOR_1")
self.COLOR_2 = os.getenv("PIPI_COLOR_2")
self.COLOR_3 = os.getenv("PIPI_COLOR_3")
self.pipi_task = None
self.pipi_votes = {}
async def notify_pipi(self, ctx, use_timer=True, message=None):
""" Write a message in chat, if there hasn't been a notification since DELAY seconds. """
""" Write a message in chat, if there hasn't been a notification since <PipiDelay> seconds. """
if use_timer and self.pipi_task and not self.pipi_task.done():
return
......@@ -33,37 +24,36 @@ class PipiCog:
self.pipi_task.cancel()
self.pipi_task = asyncio.create_task(self.pipi_block_notification())
vote_ctr = 0
chatters = await self.bot.chatters()
if message is not None:
await self.bot.send_me(ctx, message, self.COLOR_0)
await self.bot.send_me(ctx, message, config.get_value("PipiColor0"))
else:
for vote in self.pipi_votes.values():
if vote == 1:
vote_ctr += 1
vote_ctr = self.get_pipimeter()
percentage = self.bot.get_percentage(vote_ctr, chatters.count)
if vote_ctr == 0:
await self.bot.send_me(ctx,
f'Kein Druck (mehr) auf der Blase. Es kann fröhlich weiter gestreamt werden!',
self.COLOR_0)
config.get_value("PipiColor0"))
elif vote_ctr == 1:
await self.bot.send_me(ctx, f'{vote_ctr} ({percentage}%) Mensch müsste mal', self.COLOR_1)
elif percentage < self.THRESHOLD_1:
await self.bot.send_me(ctx, f'{vote_ctr} ({percentage}%) Menschen müssten mal', self.COLOR_1)
elif percentage < self.THRESHOLD_2:
await self.bot.send_me(ctx, f'{vote_ctr} ({percentage}%) Mensch müsste mal',
config.get_value("PipiColor1"))
elif percentage < config.get_int("PipiThreshold1"):
await self.bot.send_me(ctx, f'{vote_ctr} ({percentage}%) Menschen müssten mal',
config.get_value("PipiColor1"))
elif percentage < config.get_int("PipiThreshold2"):
await self.bot.send_me(ctx, f'{vote_ctr} ({percentage}%) Menschen müssten mal haugeAgree',
self.COLOR_2)
config.get_value("PipiColor2"))
else:
await self.bot.send_me(ctx, f'{vote_ctr} ({percentage}%) Menschen müssten mal haugeAgree haugeAgree',
self.COLOR_3)
config.get_value("PipiColor3"))
async def pipi_block_notification(self):
""" Just do nothing but sleep for DELAY seconds """
""" Just do nothing but sleep for <PipiDelay> seconds """
await asyncio.sleep(self.DELAY)
await asyncio.sleep(config.get_int("PipiDelay"))
async def pipimeter_loop(self):
""" Send !pipimeter into the chat every x Minutes. Also check, whether the stream was offline for x Minutes.
......@@ -75,24 +65,25 @@ class PipiCog:
await asyncio.sleep(60)
while True:
pipimeter_loop = config.get_int("PipimeterLoop")
logging.log(logging.INFO,
f"Inside Pipi loop. Sleep for {self.PIPIMETER_LOOP} minutes. {datetime.now()} {self}")
await asyncio.sleep(self.PIPIMETER_LOOP * 60)
f"Inside Pipi loop. Sleep for {pipimeter_loop} minutes. {datetime.now()} {self}")
await asyncio.sleep(pipimeter_loop * 60)
logging.log(logging.INFO, f"Inside Pipi loop finished sleeping now. {datetime.now()} {self}")
if await self.bot.stream():
logging.log(logging.INFO,
f"Inside Pipi loop. Stream is online, so check for threshold!!! {datetime.now()} {self}")
if offline_since >= self.RESET_THRESHOLD:
self.pipi_votes = {}
if offline_since >= config.get_int("PipimeterResetThreshold"):
self.truncate_pipimeter()
offline_since = 0
if len(self.pipi_votes) > 0:
if self.get_pipimeter() > 0:
channel = self.bot.channel()
message = Message(channel=channel)
await self.notify_pipi(message, use_timer=False)
else:
offline_since += self.PIPIMETER_LOOP
offline_since += pipimeter_loop
logging.log(logging.INFO,
f"Inside Pipi loop. Ooooookay, Loop ended, let's continue with the next round!!! {datetime.now()} {self}")
......@@ -101,15 +92,15 @@ class PipiCog:
async def cmd_pipi(self, ctx):
""" User mentioned there is a need to go to toilet. """
self.pipi_votes[ctx.author.name] = 1
self.add_pipimeter(ctx.author.name)
await self.notify_pipi(ctx)
@commands.command(name="warpipi", aliases=["Warpipi", "zuspät", "Zuspät"])
async def cmd_warpipi(self, ctx):
""" User already went to toilet. """
if ctx.author.name in self.pipi_votes:
del self.pipi_votes[ctx.author.name]
if ctx.author.name:
self.remove_pipimeter(ctx.author.name)
await self.notify_pipi(ctx)
@commands.command(name="pause", aliases=["Pause"])
......@@ -117,18 +108,52 @@ class PipiCog:
""" We will do a break now! """
if ctx.author.is_mod:
self.pipi_votes = {}
self.truncate_pipimeter()
await self.bot.send_me(ctx, "Jetzt geht noch mal jeder aufs Klo, und dann streamen wir weiter!",
self.COLOR_0)
config.get_value("PipiColor0"))
@commands.command(name="reset", aliases=["Reset"])
async def cmd_reset(self, ctx):
""" Reset pipi votes """
if ctx.author.is_mod:
self.pipi_votes = {}
self.truncate_pipimeter()
@commands.command(name="pipimeter", aliases=["Pipimeter"])
async def cmd_pipimeter(self, ctx):
if ctx.author.is_mod:
await self.notify_pipi(ctx, use_timer=False)
def get_pipimeter(self):
conn = sqlite3.connect("db.sqlite3")
c = conn.cursor()
c.execute('SELECT count(user) from haugebot_web_pipimeter')
pipimeter = c.fetchone()[0]
conn.close()
return int(pipimeter)
def truncate_pipimeter(self):
conn = sqlite3.connect("db.sqlite3")
c = conn.cursor()
c.execute('DELETE from haugebot_web_pipimeter')
conn.commit()
conn.close()
def add_pipimeter(self, user):
conn = sqlite3.connect("db.sqlite3")
c = conn.cursor()
c.execute('INSERT OR REPLACE INTO haugebot_web_pipimeter(user) values (?)', (user,))
conn.commit()
conn.close()
def remove_pipimeter(self, user):
conn = sqlite3.connect("db.sqlite3")
c = conn.cursor()
c.execute('DELETE from haugebot_web_pipimeter where user = ?', (user,))
conn.commit()
conn.close()
# Generated by Django 3.1.5 on 2021-01-13 22:06
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('haugebot_web', '0002_twitchuser_admin'),
]
operations = [
migrations.CreateModel(
name='Pipimeter',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('user', models.CharField(max_length=25, unique=True)),
],
),
migrations.RunSQL("INSERT INTO haugebot_web_setting(key, value) VALUES ('PipiDelay', '15')"),
migrations.RunSQL("INSERT INTO haugebot_web_setting(key, value) VALUES ('PipiThreshold1', '1')"),
migrations.RunSQL("INSERT INTO haugebot_web_setting(key, value) VALUES ('PipiThreshold2', '3')"),
migrations.RunSQL("INSERT INTO haugebot_web_setting(key, value) VALUES ('PipimeterLoop', '10')"),
migrations.RunSQL("INSERT INTO haugebot_web_setting(key, value) VALUES ('PipimeterResetThreshold', '30')"),
migrations.RunSQL("INSERT INTO haugebot_web_setting(key, value) VALUES ('PipiColor0', 'YellowGreen')"),
migrations.RunSQL("INSERT INTO haugebot_web_setting(key, value) VALUES ('PipiColor1', 'Green')"),
migrations.RunSQL("INSERT INTO haugebot_web_setting(key, value) VALUES ('PipiColor2', 'GoldenRod')"),
migrations.RunSQL("INSERT INTO haugebot_web_setting(key, value) VALUES ('PipiColor3', 'Red')"),
]
......@@ -24,6 +24,10 @@ class WusstestDuSchon(models.Model):
active = models.BooleanField(default=True, verbose_name="Aktiv")
class Pipimeter(models.Model):
user = models.CharField(max_length=25, unique=True)
class TwitchUser(models.Model):
objects = TwitchUserManager()
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment