added lol_queue
authorGeorgios Atheridis <atheridis@tutamail.com>
Tue, 10 May 2022 04:39:23 +0000 (04:39 +0000)
committerGeorgios Atheridis <atheridis@tutamail.com>
Tue, 10 May 2022 04:39:23 +0000 (04:39 +0000)
20 files changed:
skgyorugo/analyze_auto_message.py
skgyorugo/commands/addaccount.py
skgyorugo/commands/available.py [new file with mode: 0644]
skgyorugo/commands/cleanqueue.py [new file with mode: 0644]
skgyorugo/commands/forceavailable.py [new file with mode: 0644]
skgyorugo/commands/forcejoin.py [new file with mode: 0644]
skgyorugo/commands/forceleave.py [new file with mode: 0644]
skgyorugo/commands/forceunavailable.py [new file with mode: 0644]
skgyorugo/commands/join.py [new file with mode: 0644]
skgyorugo/commands/leave.py [new file with mode: 0644]
skgyorugo/commands/opgg.py
skgyorugo/commands/queue.py [new file with mode: 0644]
skgyorugo/commands/queuesize.py [new file with mode: 0644]
skgyorugo/commands/unavailable.py [new file with mode: 0644]
skgyorugo/database_manager.py
skgyorugo/lol_api/spectator_v4.py
skgyorugo/main.py
skgyorugo/scripts/clean_queue.py [new file with mode: 0644]
skgyorugo/tools/smart_privmsg.py
skgyorugo/tools/smart_start_stream_time.py

index 3454adf644eb042a0932569fca419405b84608de..5caed271936ce31639fd8ddedc6f9db08a4d59d9 100644 (file)
@@ -15,7 +15,7 @@ logger.setLevel(logging.DEBUG)
 
 formatter = logging.Formatter("[%(levelname)s] %(asctime)s: %(name)s; %(message)s")
 
-file_handler = logging.FileHandler('/var/log/aptbot/logs.log')
+file_handler = logging.FileHandler("/var/log/aptbot/logs.log")
 file_handler.setFormatter(formatter)
 
 logger.handlers = []
@@ -26,13 +26,13 @@ logger.debug(f"analyze_auto_message PATH set to: {PATH}")
 
 
 def do_auto_message(bot: Bot, message: Message, auto_message_modules: dict):
-    conn = sqlite3.connect(os.path.join(PATH, "database.db"))
-    c = conn.cursor()
-
     start_stream_ts = tools.smart_start_stream_time.start_stream_timestamp()
     if not start_stream_ts:
         return
 
+    conn = sqlite3.connect(os.path.join(PATH, "database.db"))
+    c = conn.cursor()
+
     c.execute(
         """
         SELECT
@@ -71,7 +71,7 @@ def do_auto_message(bot: Bot, message: Message, auto_message_modules: dict):
                         WHERE
                             name = ?
                     """,
-                    (name, )
+                    (name,),
                 )
                 conn.commit()
                 continue
@@ -81,7 +81,7 @@ def do_auto_message(bot: Bot, message: Message, auto_message_modules: dict):
             (
                 int(time.time()),
                 name,
-            )
+            ),
         )
         conn.commit()
         break
index b6a921a0bc2ab53317b8c2629a89a4d11832357c..ffccbb1477430864a8d9fe4305301d8563fa1fbd 100644 (file)
@@ -10,7 +10,7 @@ logger.setLevel(logging.DEBUG)
 
 formatter = logging.Formatter("[%(levelname)s] %(asctime)s: %(name)s; %(message)s")
 
-file_handler = logging.FileHandler('/var/log/aptbot/logs.log')
+file_handler = logging.FileHandler("/var/log/aptbot/logs.log")
 file_handler.setFormatter(formatter)
 
 logger.handlers = []
@@ -18,7 +18,7 @@ logger.addHandler(file_handler)
 
 
 PERMISSION = 10
-PREFIX = '\\'
+PREFIX = "\\"
 DESCRIPTION = "Adds a LoL account to the database. Use: \\addaccount <summoner name> | <twitch name>"
 USER_COOLDOWN = 0
 GLOBAL_COOLDOWN = 0
@@ -28,18 +28,22 @@ PATH = os.path.join(PATH, "..")
 
 
 def main(bot: Bot, message: Message):
-    msg = ' '.join(message.value.split(' ')[1:])
-    summoner_name, twitch_name = msg.split('|')
+    msg = " ".join(message.value.split(" ")[1:])
+    summoner_name, twitch_name = msg.split("|")
     twitch_name = twitch_name.strip()
     summoner = lol_api.summoner_v4.get_summoner_from_name(summoner_name)
     twitch = ttv_api.users.get_users(user_logins=[twitch_name])
     if not summoner:
         logger.warning(f"Account {summoner_name} wasn't able to be added")
-        bot.send_privmsg(message.channel, f"Error, unable to add summoner: {summoner_name}")
+        bot.send_privmsg(
+            message.channel, f"Error, unable to add summoner: {summoner_name}"
+        )
         return
     if not twitch:
         logger.warning(f"Unable to use twitch account {twitch_name}")
-        bot.send_privmsg(message.channel, f"Error, unable to use twitch account: {twitch_name}")
+        bot.send_privmsg(
+            message.channel, f"Error, unable to use twitch account: {twitch_name}"
+        )
         return
     twitch_id = twitch[0].user_id
 
@@ -63,13 +67,18 @@ def main(bot: Bot, message: Message):
                 summoner.summoner_id,
                 summoner.account_id,
                 twitch_id,
-            )
+            ),
         )
     except sqlite3.IntegrityError:
-        logger.warning(f"Unable to add account with puuid: {summoner.puuid} and twitch id: {twitch_id}. Account probably already exists")
+        logger.warning(
+            f"Unable to add account with puuid: {summoner.puuid} and twitch id: {twitch_id}. Account probably already exists"
+        )
         bot.send_privmsg(message.channel, f"Account already exists.")
+        conn.close()
         return
     conn.commit()
-    logger.info(f"Successfully added account with puuid: {summoner.puuid} and twitch id: {twitch_id}")
+    logger.info(
+        f"Successfully added account with puuid: {summoner.puuid} and twitch id: {twitch_id}"
+    )
     bot.send_privmsg(message.channel, f"Successfully added account.")
     conn.close()
diff --git a/skgyorugo/commands/available.py b/skgyorugo/commands/available.py
new file mode 100644 (file)
index 0000000..bf96c50
--- /dev/null
@@ -0,0 +1,83 @@
+from aptbot.bot import Message, Commands, Bot
+import os
+import logging
+import ttv_api.users
+import sqlite3
+import time
+
+logger = logging.getLogger(__name__)
+logger.setLevel(logging.DEBUG)
+
+formatter = logging.Formatter("[%(levelname)s] %(asctime)s: %(name)s; %(message)s")
+
+file_handler = logging.FileHandler("/var/log/aptbot/logs.log")
+file_handler.setFormatter(formatter)
+
+logger.handlers = []
+logger.addHandler(file_handler)
+
+PERMISSION = 99
+PREFIX = "?"
+DESCRIPTION = r"Makes yourself available in the list."
+USER_COOLDOWN = 600
+GLOBAL_COOLDOWN = 0
+
+PATH = os.path.dirname(os.path.realpath(__file__))
+PATH = os.path.join(PATH, "..")
+
+
+def main(bot: Bot, message: Message):
+    twitch = ttv_api.users.get_users(user_logins=[message.nick])
+    if not twitch:
+        bot.send_privmsg(
+            message.channel,
+            "There was an issue fetching your twitch data. You weren't made unavailable.",
+            reply=message.tags["id"],
+        )
+        return
+    twitch_id = twitch[0].user_id
+    conn = sqlite3.connect(os.path.join(PATH, "lol_data.db"))
+    c = conn.cursor()
+
+    c.execute(
+        """
+        UPDATE
+            lol_queue
+        SET 
+            available = 1,
+            time_remaining = time_remaining - (? - last_available)
+        WHERE 
+            twitch_id = ?
+            AND available = 0;
+        """,
+        (
+            int(time.time()),
+            twitch_id,
+        ),
+    )
+    if c.rowcount < 1:
+        bot.send_privmsg(
+            message.channel,
+            "You aren't in the list or you were already available.",
+            reply=message.tags["id"],
+        )
+        conn.close()
+        return
+    conn.commit()
+    c.execute("DELETE FROM lol_queue WHERE time_remaining < 0;")
+    if c.rowcount > 0:
+        bot.send_privmsg(
+            message.channel,
+            "You were unavailable for too long, you have been removed from the list.",
+            reply=message.tags["id"],
+        )
+        conn.commit()
+        conn.close()
+        return
+    conn.commit()
+    bot.send_privmsg(
+        message.channel,
+        "Successfully made you available",
+        reply=message.tags["id"],
+    )
+    conn.close()
diff --git a/skgyorugo/commands/cleanqueue.py b/skgyorugo/commands/cleanqueue.py
new file mode 100644 (file)
index 0000000..9450b45
--- /dev/null
@@ -0,0 +1,66 @@
+from aptbot.bot import Message, Commands, Bot
+import os
+import logging
+import ttv_api.users
+import sqlite3
+import time
+
+logger = logging.getLogger(__name__)
+logger.setLevel(logging.DEBUG)
+
+formatter = logging.Formatter("[%(levelname)s] %(asctime)s: %(name)s; %(message)s")
+
+file_handler = logging.FileHandler("/var/log/aptbot/logs.log")
+file_handler.setFormatter(formatter)
+
+logger.handlers = []
+logger.addHandler(file_handler)
+
+PERMISSION = 10
+PREFIX = "\\"
+DESCRIPTION = r"Cleans the whole queue"
+USER_COOLDOWN = 0
+GLOBAL_COOLDOWN = 0
+
+PATH = os.path.dirname(os.path.realpath(__file__))
+PATH = os.path.join(PATH, "..")
+
+
+def main(bot: Bot, message: Message):
+    twitch = ttv_api.users.get_users(user_logins=[message.channel])
+    if not twitch:
+        bot.send_privmsg(
+            message.channel,
+            f"There was an issue fetching {message.channel} twitch data. The queue was not cleared.",
+            reply=message.tags["id"],
+        )
+        return
+    twitch_id = twitch[0].user_id
+
+    conn = sqlite3.connect(os.path.join(PATH, "lol_data.db"))
+    c = conn.cursor()
+
+    c.execute("DELETE FROM lol_queue")
+    conn.commit()
+
+    c.execute(
+        """
+        INSERT INTO lol_queue (
+            "twitch_id",
+            "position",
+            "available",
+            "last_available",
+            "time_remaining"
+        ) VALUES (?, ?, ?, ?, ?);
+        """,
+        (
+            twitch_id,
+            0,
+            1,
+            None,
+            9999999,
+        ),
+    )
+    conn.commit()
+
+    conn.close()
diff --git a/skgyorugo/commands/forceavailable.py b/skgyorugo/commands/forceavailable.py
new file mode 100644 (file)
index 0000000..210a167
--- /dev/null
@@ -0,0 +1,86 @@
+from aptbot.bot import Message, Commands, Bot
+import os
+import logging
+import ttv_api.users
+import sqlite3
+import time
+
+logger = logging.getLogger(__name__)
+logger.setLevel(logging.DEBUG)
+
+formatter = logging.Formatter("[%(levelname)s] %(asctime)s: %(name)s; %(message)s")
+
+file_handler = logging.FileHandler("/var/log/aptbot/logs.log")
+file_handler.setFormatter(formatter)
+
+logger.handlers = []
+logger.addHandler(file_handler)
+
+PERMISSION = 10
+PREFIX = "\\"
+DESCRIPTION = r"Force user to become available in the list."
+USER_COOLDOWN = 0
+GLOBAL_COOLDOWN = 0
+
+PATH = os.path.dirname(os.path.realpath(__file__))
+PATH = os.path.join(PATH, "..")
+
+
+def main(bot: Bot, message: Message):
+    twitch_name = message.tags.get("reply-parent-user-login", None)
+    if not twitch_name:
+        twitch_name = message.value.split(" ")[1]
+    twitch = ttv_api.users.get_users(user_logins=[twitch_name])
+    if not twitch:
+        bot.send_privmsg(
+            message.channel,
+            "There was an issue fetching their twitch data. They weren't made unavailable.",
+            reply=message.tags["id"],
+        )
+        return
+    twitch_id = twitch[0].user_id
+    conn = sqlite3.connect(os.path.join(PATH, "lol_data.db"))
+    c = conn.cursor()
+
+    c.execute(
+        """
+        UPDATE
+            lol_queue
+        SET 
+            available = 1,
+            time_remaining = time_remaining - (? - last_available)
+        WHERE 
+            twitch_id = ?
+            AND available = 0;
+        """,
+        (
+            int(time.time()),
+            twitch_id,
+        ),
+    )
+    if c.rowcount < 1:
+        bot.send_privmsg(
+            message.channel,
+            "They aren't in the list or they were already available.",
+            reply=message.tags["id"],
+        )
+        conn.close()
+        return
+    conn.commit()
+    c.execute("DELETE FROM lol_queue WHERE time_remaining < 0;")
+    if c.rowcount > 0:
+        bot.send_privmsg(
+            message.channel,
+            "They were unavailable for too long, they have been removed from the list.",
+            reply=message.tags["id"],
+        )
+        conn.commit()
+        conn.close()
+        return
+    conn.commit()
+    bot.send_privmsg(
+        message.channel,
+        "Successfully made them available",
+        reply=message.tags["id"],
+    )
+    conn.close()
diff --git a/skgyorugo/commands/forcejoin.py b/skgyorugo/commands/forcejoin.py
new file mode 100644 (file)
index 0000000..062b6fe
--- /dev/null
@@ -0,0 +1,90 @@
+from aptbot.bot import Message, Commands, Bot
+import os
+import logging
+import ttv_api.users
+import sqlite3
+
+logger = logging.getLogger(__name__)
+logger.setLevel(logging.DEBUG)
+
+formatter = logging.Formatter("[%(levelname)s] %(asctime)s: %(name)s; %(message)s")
+
+file_handler = logging.FileHandler("/var/log/aptbot/logs.log")
+file_handler.setFormatter(formatter)
+
+logger.handlers = []
+logger.addHandler(file_handler)
+
+PERMISSION = 10
+PREFIX = "\\"
+DESCRIPTION = r"Force user to join the queue to play the game with the streamer."
+USER_COOLDOWN = 0
+GLOBAL_COOLDOWN = 0
+
+PATH = os.path.dirname(os.path.realpath(__file__))
+PATH = os.path.join(PATH, "..")
+
+DEFAULT_TIME_REMAINING = 60 * 60
+
+
+def main(bot: Bot, message: Message):
+    twitch_name = message.tags.get("reply-parent-user-login", None)
+    if not twitch_name:
+        twitch_name = message.value.split(" ")[1]
+    twitch = ttv_api.users.get_users(user_logins=[twitch_name])
+    if not twitch:
+        bot.send_privmsg(
+            message.channel,
+            "There was an issue fetching the user's twitch data. They weren't added to the list Sadge",
+            reply=message.tags["id"],
+        )
+        return
+    twitch_id = twitch[0].user_id
+    conn = sqlite3.connect(os.path.join(PATH, "lol_data.db"))
+    c = conn.cursor()
+
+    c.execute(
+        """
+        SELECT position FROM lol_queue ORDER BY position DESC;
+        """
+    )
+
+    try:
+        last_position: int = c.fetchone()[0]
+    except TypeError:
+        last_position: int = -1
+
+    try:
+        c.execute(
+            """
+            INSERT INTO lol_queue (
+                "twitch_id",
+                "position",
+                "available",
+                "last_available",
+                "time_remaining"
+            ) VALUES (?, ?, ?, ?, ?);
+            """,
+            (
+                twitch_id,
+                last_position + 1,
+                1,
+                None,
+                DEFAULT_TIME_REMAINING,
+            ),
+        )
+    except sqlite3.IntegrityError:
+        bot.send_privmsg(
+            message.channel,
+            "They are already added into the list",
+            reply=message.tags["id"],
+        )
+        conn.close()
+        return
+    conn.commit()
+    bot.send_privmsg(
+        message.channel,
+        "Successfully added them into the list",
+        reply=message.tags["id"],
+    )
+    conn.close()
diff --git a/skgyorugo/commands/forceleave.py b/skgyorugo/commands/forceleave.py
new file mode 100644 (file)
index 0000000..2ea5fcb
--- /dev/null
@@ -0,0 +1,64 @@
+from aptbot.bot import Message, Commands, Bot
+import os
+import logging
+import ttv_api.users
+import sqlite3
+
+logger = logging.getLogger(__name__)
+logger.setLevel(logging.DEBUG)
+
+formatter = logging.Formatter("[%(levelname)s] %(asctime)s: %(name)s; %(message)s")
+
+file_handler = logging.FileHandler("/var/log/aptbot/logs.log")
+file_handler.setFormatter(formatter)
+
+logger.handlers = []
+logger.addHandler(file_handler)
+
+PERMISSION = 10
+PREFIX = "\\"
+DESCRIPTION = r"Force user to leave the queue which gives them the privalege to play with the streamer."
+USER_COOLDOWN = 0
+GLOBAL_COOLDOWN = 0
+
+PATH = os.path.dirname(os.path.realpath(__file__))
+PATH = os.path.join(PATH, "..")
+
+
+def main(bot: Bot, message: Message):
+    twitch_name = message.tags.get("reply-parent-user-login", None)
+    if not twitch_name:
+        twitch_name = message.value.split(" ")[1]
+    twitch = ttv_api.users.get_users(user_logins=[twitch_name])
+    if not twitch:
+        bot.send_privmsg(
+            message.channel,
+            "There was an issue fetching their twitch data. They weren't removed from the list Sadge",
+            reply=message.tags["id"],
+        )
+        return
+    twitch_id = twitch[0].user_id
+    conn = sqlite3.connect(os.path.join(PATH, "lol_data.db"))
+    c = conn.cursor()
+
+    c.execute(
+        """
+        DELETE FROM lol_queue WHERE twitch_id = ?;
+        """,
+        (twitch_id,),
+    )
+    if not c.rowcount:
+        bot.send_privmsg(
+            message.channel,
+            "They weren't in the list.",
+            reply=message.tags["id"],
+        )
+        conn.close()
+        return
+    conn.commit()
+    bot.send_privmsg(
+        message.channel,
+        "Successfully removed them from the list",
+        reply=message.tags["id"],
+    )
+    conn.close()
diff --git a/skgyorugo/commands/forceunavailable.py b/skgyorugo/commands/forceunavailable.py
new file mode 100644 (file)
index 0000000..4df29e0
--- /dev/null
@@ -0,0 +1,68 @@
+from aptbot.bot import Message, Commands, Bot
+import os
+import logging
+import ttv_api.users
+import sqlite3
+import time
+
+logger = logging.getLogger(__name__)
+logger.setLevel(logging.DEBUG)
+
+formatter = logging.Formatter("[%(levelname)s] %(asctime)s: %(name)s; %(message)s")
+
+file_handler = logging.FileHandler("/var/log/aptbot/logs.log")
+file_handler.setFormatter(formatter)
+
+logger.handlers = []
+logger.addHandler(file_handler)
+
+PERMISSION = 10
+PREFIX = "\\"
+DESCRIPTION = r"Makes yourself temporarily unavailable in the list."
+USER_COOLDOWN = 0
+GLOBAL_COOLDOWN = 0
+
+PATH = os.path.dirname(os.path.realpath(__file__))
+PATH = os.path.join(PATH, "..")
+
+
+def main(bot: Bot, message: Message):
+    twitch_name = message.tags.get("reply-parent-user-login", None)
+    if not twitch_name:
+        twitch_name = message.value.split(" ")[1]
+    twitch = ttv_api.users.get_users(user_logins=[twitch_name])
+    if not twitch:
+        bot.send_privmsg(
+            message.channel,
+            "There was an issue fetching their twitch data. They weren't made unavailable.",
+            reply=message.tags["id"],
+        )
+        return
+    twitch_id = twitch[0].user_id
+    conn = sqlite3.connect(os.path.join(PATH, "lol_data.db"))
+    c = conn.cursor()
+
+    c.execute(
+        """
+        UPDATE lol_queue SET available = 0, last_available = ? WHERE twitch_id = ?;
+        """,
+        (
+            int(time.time()),
+            twitch_id,
+        ),
+    )
+    if not c.rowcount:
+        bot.send_privmsg(
+            message.channel,
+            "They aren't in the list or they were already unavailable.",
+            reply=message.tags["id"],
+        )
+        conn.close()
+        return
+    conn.commit()
+    bot.send_privmsg(
+        message.channel,
+        "Successfully made them unavailable",
+        reply=message.tags["id"],
+    )
+    conn.close()
diff --git a/skgyorugo/commands/join.py b/skgyorugo/commands/join.py
new file mode 100644 (file)
index 0000000..badb0d7
--- /dev/null
@@ -0,0 +1,87 @@
+from aptbot.bot import Message, Commands, Bot
+import os
+import logging
+import ttv_api.users
+import sqlite3
+
+logger = logging.getLogger(__name__)
+logger.setLevel(logging.DEBUG)
+
+formatter = logging.Formatter("[%(levelname)s] %(asctime)s: %(name)s; %(message)s")
+
+file_handler = logging.FileHandler("/var/log/aptbot/logs.log")
+file_handler.setFormatter(formatter)
+
+logger.handlers = []
+logger.addHandler(file_handler)
+
+PERMISSION = 99
+PREFIX = "?"
+DESCRIPTION = r"Joins the queue to play the game with the streamer."
+USER_COOLDOWN = 60
+GLOBAL_COOLDOWN = 0
+
+PATH = os.path.dirname(os.path.realpath(__file__))
+PATH = os.path.join(PATH, "..")
+
+DEFAULT_TIME_REMAINING = 60 * 60
+
+
+def main(bot: Bot, message: Message):
+    twitch = ttv_api.users.get_users(user_logins=[message.nick])
+    if not twitch:
+        bot.send_privmsg(
+            message.channel,
+            "There was an issue fetching your twitch data. You weren't added to the list Sadge",
+            reply=message.tags["id"],
+        )
+        return
+    twitch_id = twitch[0].user_id
+    conn = sqlite3.connect(os.path.join(PATH, "lol_data.db"))
+    c = conn.cursor()
+
+    c.execute(
+        """
+        SELECT position FROM lol_queue ORDER BY position DESC;
+        """
+    )
+
+    try:
+        last_position: int = c.fetchone()[0]
+    except TypeError:
+        last_position: int = -1
+
+    try:
+        c.execute(
+            """
+            INSERT INTO lol_queue (
+                "twitch_id",
+                "position",
+                "available",
+                "last_available",
+                "time_remaining"
+            ) VALUES (?, ?, ?, ?, ?);
+            """,
+            (
+                twitch_id,
+                last_position + 1,
+                1,
+                None,
+                DEFAULT_TIME_REMAINING,
+            ),
+        )
+    except sqlite3.IntegrityError:
+        bot.send_privmsg(
+            message.channel,
+            "You are already added into the list",
+            reply=message.tags["id"],
+        )
+        conn.close()
+        return
+    conn.commit()
+    bot.send_privmsg(
+        message.channel,
+        "Successfully added you into the list",
+        reply=message.tags["id"],
+    )
+    conn.close()
diff --git a/skgyorugo/commands/leave.py b/skgyorugo/commands/leave.py
new file mode 100644 (file)
index 0000000..6de248c
--- /dev/null
@@ -0,0 +1,63 @@
+from aptbot.bot import Message, Commands, Bot
+import os
+import logging
+import ttv_api.users
+import sqlite3
+
+logger = logging.getLogger(__name__)
+logger.setLevel(logging.DEBUG)
+
+formatter = logging.Formatter("[%(levelname)s] %(asctime)s: %(name)s; %(message)s")
+
+file_handler = logging.FileHandler("/var/log/aptbot/logs.log")
+file_handler.setFormatter(formatter)
+
+logger.handlers = []
+logger.addHandler(file_handler)
+
+PERMISSION = 99
+PREFIX = "?"
+DESCRIPTION = (
+    r"Leaves the queue which gives you the privalege to play with the streamer."
+)
+USER_COOLDOWN = 60
+GLOBAL_COOLDOWN = 0
+
+PATH = os.path.dirname(os.path.realpath(__file__))
+PATH = os.path.join(PATH, "..")
+
+
+def main(bot: Bot, message: Message):
+    twitch = ttv_api.users.get_users(user_logins=[message.nick])
+    if not twitch:
+        bot.send_privmsg(
+            message.channel,
+            "There was an issue fetching your twitch data. You weren't removed from the list Sadge",
+            reply=message.tags["id"],
+        )
+        return
+    twitch_id = twitch[0].user_id
+    conn = sqlite3.connect(os.path.join(PATH, "lol_data.db"))
+    c = conn.cursor()
+
+    c.execute(
+        """
+        DELETE FROM lol_queue WHERE twitch_id = ?;
+        """,
+        (twitch_id,),
+    )
+    if not c.rowcount:
+        bot.send_privmsg(
+            message.channel,
+            "You weren't in the list.",
+            reply=message.tags["id"],
+        )
+        conn.close()
+        return
+    conn.commit()
+    bot.send_privmsg(
+        message.channel,
+        "Successfully removed you from the list",
+        reply=message.tags["id"],
+    )
+    conn.close()
index 1dd2cf17b7d514af94c7c32311796f894ed85997..d403e8e98e1bab6e973d01182bfc05ded760c7da 100644 (file)
@@ -12,7 +12,7 @@ logger.setLevel(logging.DEBUG)
 
 formatter = logging.Formatter("[%(levelname)s] %(asctime)s: %(name)s; %(message)s")
 
-file_handler = logging.FileHandler('/var/log/aptbot/logs.log')
+file_handler = logging.FileHandler("/var/log/aptbot/logs.log")
 file_handler.setFormatter(formatter)
 
 logger.handlers = []
@@ -20,7 +20,7 @@ logger.addHandler(file_handler)
 
 
 PERMISSION = 99
-PREFIX = '?'
+PREFIX = "?"
 DESCRIPTION = "Figures out which LoL Account {channel} is playing on"
 USER_COOLDOWN = 20
 GLOBAL_COOLDOWN = 15
@@ -29,21 +29,29 @@ GLOBAL_COOLDOWN = 15
 PATH = os.path.dirname(os.path.realpath(__file__))
 PATH = os.path.join(PATH, "..")
 
+
 def main(bot: Bot, message: Message):
     index_skip = 0
     if message.tags.get("reply-parent-user-id", None):
         index_skip += 1
     try:
-        twitch_user = message.value.split(' ')[1 + index_skip]
+        twitch_user = message.value.split(" ")[1 + index_skip]
     except IndexError:
         twitch_user = message.tags.get("reply-parent-display-name", message.channel)
-        twitch_id = message.tags.get("reply-parent-user-id", ttv_api.users.get_users(user_logins=[message.channel]))
+        twitch_id = message.tags.get(
+            "reply-parent-user-id",
+            ttv_api.users.get_users(user_logins=[message.channel]),
+        )
     else:
         twitch_id = ttv_api.users.get_users(user_logins=[twitch_user])
 
     if not twitch_id:
-        logger.warning(f"There was an issue getting twitch data for user {twitch_id}; message id was: {message.tags['id']}")
-        smart_privmsg.send(bot, message, "Couldn't retrieve data", reply=message.tags["id"])
+        logger.warning(
+            f"There was an issue getting twitch data for user {twitch_id}; message id was: {message.tags['id']}"
+        )
+        smart_privmsg.send(
+            bot, message, "Couldn't retrieve data", reply=message.tags["id"]
+        )
         return
 
     if not isinstance(twitch_id, str):
@@ -58,14 +66,20 @@ def main(bot: Bot, message: Message):
         """
         SELECT summoner_id, puuid FROM accounts WHERE twitch_id = ?;
         """,
-        (twitch_id,)
+        (twitch_id,),
     )
     fetched = c.fetchall()
 
     if not fetched:
-        smart_privmsg.send(bot, message, f"No summoners added for {twitch_user}", reply=message.tags["id"])
+        smart_privmsg.send(
+            bot,
+            message,
+            f"No summoners added for {twitch_user}",
+            reply=message.tags["id"],
+        )
+        conn.close()
         return
-    
+
     summoner_names = []
     for summoners in fetched:
         info = spectator_v4.get_spectator_info_from_summoner_id(summoners[0])
@@ -75,7 +89,19 @@ def main(bot: Bot, message: Message):
         if info:
             break
     else:
-        smart_privmsg.send(bot, message, f"{twitch_user} is currently not in game. These are all of their summoners: {summoner_names}", reply=message.tags["id"])
+        smart_privmsg.send(
+            bot,
+            message,
+            f"{twitch_user} is currently not in game. These are all of their summoners: {summoner_names}",
+            reply=message.tags["id"],
+        )
+        conn.close()
         return
 
-    smart_privmsg.send(bot, message, f"{twitch_user} is currently playing a game on: {summoner_names[-1]}", reply=message.tags["id"])
+    smart_privmsg.send(
+        bot,
+        message,
+        f"{twitch_user} is currently playing a game on: {summoner_names[-1]}",
+        reply=message.tags["id"],
+    )
+    conn.close()
diff --git a/skgyorugo/commands/queue.py b/skgyorugo/commands/queue.py
new file mode 100644 (file)
index 0000000..f0f87fb
--- /dev/null
@@ -0,0 +1,91 @@
+from aptbot.bot import Message, Commands, Bot
+import os
+import logging
+import ttv_api.users
+import sqlite3
+
+logger = logging.getLogger(__name__)
+logger.setLevel(logging.DEBUG)
+
+formatter = logging.Formatter("[%(levelname)s] %(asctime)s: %(name)s; %(message)s")
+
+file_handler = logging.FileHandler("/var/log/aptbot/logs.log")
+file_handler.setFormatter(formatter)
+
+logger.handlers = []
+logger.addHandler(file_handler)
+
+PERMISSION = 99
+PREFIX = "?"
+DESCRIPTION = r"Check who's currently in queue."
+USER_COOLDOWN = 30
+GLOBAL_COOLDOWN = 15
+
+PATH = os.path.dirname(os.path.realpath(__file__))
+PATH = os.path.join(PATH, "..")
+
+
+def main(bot: Bot, message: Message):
+    twitch = ttv_api.users.get_users(user_logins=[message.nick])
+    if not twitch:
+        bot.send_privmsg(
+            message.channel,
+            "There was an issue fetching your twitch data. You weren't made unavailable.",
+            reply=message.tags["id"],
+        )
+        return
+    twitch_id = twitch[0].user_id
+    conn = sqlite3.connect(os.path.join(PATH, "lol_data.db"))
+    c = conn.cursor()
+
+    c.execute(
+        """
+        SELECT twitch_id WHERE available = 1 ORDER BY position ASC;
+        """
+    )
+    fetched = c.fetchall()
+    queue = [x[0] for x in fetched]
+    twitch = ttv_api.users.get_users(user_ids=queue)
+    if not twitch:
+        bot.send_privmsg(
+            message.channel,
+            "There was an issue fetching twitch data. Sadge",
+            reply=message.tags["id"],
+        )
+        conn.close()
+        return
+    queue_names = []
+    for twitch_id in queue:
+        for twitch_user in twitch:
+            if int(twitch_user.user_id) == int(twitch_id):
+                queue_names.append(twitch_user.display_name)
+                break
+        else:
+            bot.send_privmsg(
+                message.channel,
+                f"There was an issue fetching data from the user with id {twitch_id}. They won't be in the list. This is a very weird problem to have occured. Sadge",
+                reply=message.tags["id"],
+            )
+    c.execute(
+        """
+        SELECT data FROM lol_queue_data WHERE name = 'queuesize';
+        """
+    )
+    fetched = c.fetchone()
+    try:
+        queue_size = fetched[0]
+    except TypeError:
+        bot.send_privmsg(
+            message.channel,
+            "There was an issue fetching the queue size, default set to 5",
+            reply=message.tags["id"],
+        )
+        queue_size = 5
+
+    bot.send_privmsg(
+        message.channel,
+        f"These people are to play with {message.channel}: {queue_names[1:queue_size]} | and these people are waiting: {queue_names[queue_size:]}",
+        reply=message.tags["id"],
+    )
+
+    conn.close()
diff --git a/skgyorugo/commands/queuesize.py b/skgyorugo/commands/queuesize.py
new file mode 100644 (file)
index 0000000..cca3cf1
--- /dev/null
@@ -0,0 +1,60 @@
+from aptbot.bot import Message, Commands, Bot
+import os
+import logging
+import sqlite3
+
+logger = logging.getLogger(__name__)
+logger.setLevel(logging.DEBUG)
+
+formatter = logging.Formatter("[%(levelname)s] %(asctime)s: %(name)s; %(message)s")
+
+file_handler = logging.FileHandler("/var/log/aptbot/logs.log")
+file_handler.setFormatter(formatter)
+
+logger.handlers = []
+logger.addHandler(file_handler)
+
+PERMISSION = 10
+PREFIX = "\\"
+DESCRIPTION = r"Change the queue size"
+USER_COOLDOWN = 0
+GLOBAL_COOLDOWN = 0
+
+PATH = os.path.dirname(os.path.realpath(__file__))
+PATH = os.path.join(PATH, "..")
+
+
+def main(bot: Bot, message: Message):
+    replied_message = message.tags.get("reply-parent-msg-body", None)
+    if replied_message:
+        queue_size = message.value.split(" ")[2]
+    else:
+        queue_size = message.value.split(" ")[1]
+    try:
+        queue_size = int(queue_size)
+    except ValueError:
+        bot.send_privmsg(
+            message.channel,
+            f"Please choose a number. {queue_size} is not a valid number.",
+            reply=message.tags["id"],
+        )
+        return
+
+    conn = sqlite3.connect(os.path.join(PATH, "lol_data.db"))
+    c = conn.cursor()
+
+    c.execute(
+        """
+        REPLACE INTO lol_queue_data (name, data) VALUES ('queuesize', ?)
+        """,
+        (queue_size,),
+    )
+    conn.commit()
+
+    bot.send_privmsg(
+        message.channel,
+        f"Successfully changed queue size to {queue_size}.",
+        reply=message.tags["id"],
+    )
+
+    conn.close()
diff --git a/skgyorugo/commands/unavailable.py b/skgyorugo/commands/unavailable.py
new file mode 100644 (file)
index 0000000..c95b59c
--- /dev/null
@@ -0,0 +1,65 @@
+from aptbot.bot import Message, Commands, Bot
+import os
+import logging
+import ttv_api.users
+import sqlite3
+import time
+
+logger = logging.getLogger(__name__)
+logger.setLevel(logging.DEBUG)
+
+formatter = logging.Formatter("[%(levelname)s] %(asctime)s: %(name)s; %(message)s")
+
+file_handler = logging.FileHandler("/var/log/aptbot/logs.log")
+file_handler.setFormatter(formatter)
+
+logger.handlers = []
+logger.addHandler(file_handler)
+
+PERMISSION = 99
+PREFIX = "?"
+DESCRIPTION = r"Makes yourself temporarily unavailable in the list."
+USER_COOLDOWN = 10
+GLOBAL_COOLDOWN = 0
+
+PATH = os.path.dirname(os.path.realpath(__file__))
+PATH = os.path.join(PATH, "..")
+
+
+def main(bot: Bot, message: Message):
+    twitch = ttv_api.users.get_users(user_logins=[message.nick])
+    if not twitch:
+        bot.send_privmsg(
+            message.channel,
+            "There was an issue fetching your twitch data. You weren't made unavailable.",
+            reply=message.tags["id"],
+        )
+        return
+    twitch_id = twitch[0].user_id
+    conn = sqlite3.connect(os.path.join(PATH, "lol_data.db"))
+    c = conn.cursor()
+
+    c.execute(
+        """
+        UPDATE lol_queue SET available = 0, last_available = ? WHERE twitch_id = ?;
+        """,
+        (
+            int(time.time()),
+            twitch_id,
+        ),
+    )
+    if not c.rowcount:
+        bot.send_privmsg(
+            message.channel,
+            "You aren't in the list or you were already unavailable.",
+            reply=message.tags["id"],
+        )
+        conn.close()
+        return
+    conn.commit()
+    bot.send_privmsg(
+        message.channel,
+        "Successfully made you unavailable",
+        reply=message.tags["id"],
+    )
+    conn.close()
index f4dd676ec895ff9bab177b517186993c63c9d5cb..bef000f7a5b4a904ce0016fb38a4343ecfdf0bc4 100644 (file)
@@ -90,6 +90,31 @@ def create_lol_database():
     )
     logger.info(f"created table accounts")
 
+    c.execute(
+        """
+        CREATE TABLE IF NOT EXISTS lol_queue (
+            twitch_id INTEGER NOT NULL,
+            position INTEGER NOT NULL UNIQUE,
+            available INTEGER NOT NULL,
+            last_available INTEGER,
+            time_remaining INTEGER NOT NULL,
+            PRIMARY KEY (twitch_id)
+        );
+        """
+    )
+    logger.info(f"created table lol_queue")
+
+    c.execute(
+        """
+        CREATE TABLE IF NOT EXISTS lol_queue_data (
+            name TEXT NOT NULL,
+            data INTEGER NOT NULL,
+            PRIMARY KEY (name)
+        );
+        """
+    )
+    logger.info(f"created table lol_queue_data")
+
     conn.commit()
     conn.close()
 
index 3724297b812dcf297e30dd00cf2111aeef3c981d..3c2a69226dc4c29d7fcb61582771cda8ce73f3f3 100644 (file)
@@ -1,11 +1,12 @@
 from lol_api import *
+from typing import Optional
 
 logger = logging.getLogger(__name__)
 logger.setLevel(logging.DEBUG)
 
 formatter = logging.Formatter("[%(levelname)s] %(asctime)s: %(name)s; %(message)s")
 
-file_handler = logging.FileHandler('/var/log/aptbot/logs.log')
+file_handler = logging.FileHandler("/var/log/aptbot/logs.log")
 file_handler.setFormatter(formatter)
 
 logger.handlers = []
@@ -18,12 +19,14 @@ class BannedChampion:
     champion_id: int
     team_id: int
 
+
 @dataclass
 class Perks:
     perk_ids: list[int]
     perk_style: int
     perk_sub_style: int
 
+
 @dataclass
 class CurrentGameParticipant:
     champion_id: int
@@ -36,6 +39,7 @@ class CurrentGameParticipant:
     spell1_id: int
     spell2_id: int
 
+
 @dataclass
 class GameInfo:
     game_id: int
@@ -46,10 +50,11 @@ class GameInfo:
     platform_id: str
     game_mode: str
     banned_champions: list[BannedChampion]
-    game_queue_config_id: int
+    game_queue_config_id: Optional[int]
     observers: str
     participants: list[CurrentGameParticipant]
 
+
 def get_spectator_info_from_summoner_id(summoner_id: str) -> Optional[GameInfo]:
     endpoint = f"/lol/spectator/v4/active-games/by-summoner/{summoner_id}"
     url = BASE_URL + endpoint
@@ -60,10 +65,14 @@ def get_spectator_info_from_summoner_id(summoner_id: str) -> Optional[GameInfo]:
         headers=HEADER,
     )
     if r.status == 404:
-        logger.info(f"Summoner with summoner id: {summoner_id} wasn't found in game. Status code {r.status}")
+        logger.info(
+            f"Summoner with summoner id: {summoner_id} wasn't found in game. Status code {r.status}"
+        )
         return None
     if r.status != 200:
-        logger.warning(f"Couldn't retrieve summoner with summoner id: {summoner_id}. Status code {r.status}")
+        logger.warning(
+            f"Couldn't retrieve summoner with summoner id: {summoner_id}. Status code {r.status}"
+        )
         return None
     data = json.loads(r.data.decode("utf-8"))
 
@@ -82,7 +91,7 @@ def get_spectator_info_from_summoner_id(summoner_id: str) -> Optional[GameInfo]:
         perks = Perks(
             [perk_id for perk_id in participant["perks"]["perkIds"]],
             participant["perks"]["perkStyle"],
-            participant["perks"]["perkSubStyle"]
+            participant["perks"]["perkSubStyle"],
         )
         participants.append(
             CurrentGameParticipant(
@@ -107,7 +116,7 @@ def get_spectator_info_from_summoner_id(summoner_id: str) -> Optional[GameInfo]:
         data["platformId"],
         data["gameMode"],
         banned_champions,
-        data["gameQueueConfigId"],
+        data.get("gameQueueConfigId", None),
         data["observers"]["encryptionKey"],
         participants,
     )
index 525f8df73d44a17e14ab4e4ad5969a50a5889cb1..16942ed7c9f9ffae54f47f02b2e92d342cf005f9 100644 (file)
@@ -6,6 +6,7 @@ import traceback
 import tools.raid
 import tools.smart_privmsg
 import tools.permissions
+import tools.smart_start_stream_time
 import analyze_command
 import scripts.unit_converter
 import scripts.alwase
@@ -19,6 +20,7 @@ from importlib import reload
 reload(tools.raid)
 reload(tools.smart_privmsg)
 reload(tools.permissions)
+reload(tools.smart_start_stream_time)
 reload(analyze_command)
 reload(scripts.unit_converter)
 reload(scripts.alwase)
@@ -31,7 +33,7 @@ logger.setLevel(logging.DEBUG)
 
 formatter = logging.Formatter("[%(levelname)s] %(asctime)s: %(name)s; %(message)s")
 
-file_handler = logging.FileHandler('/var/log/aptbot/logs.log')
+file_handler = logging.FileHandler("/var/log/aptbot/logs.log")
 file_handler.setFormatter(formatter)
 
 logger.handlers = []
@@ -51,41 +53,37 @@ auto_message_specs = {}
 auto_message_modules = {}
 
 commands = [
-    c for c in os.listdir(COMMANDS_PATH) if os.path.isfile(os.path.join(COMMANDS_PATH, c))
+    c
+    for c in os.listdir(COMMANDS_PATH)
+    if os.path.isfile(os.path.join(COMMANDS_PATH, c))
 ]
-commands = filter(lambda x: not x.startswith('.'), commands)
+commands = filter(lambda x: not x.startswith("."), commands)
 commands = filter(lambda x: os.path.splitext(x)[1] == ".py", commands)
 commands = list(commands)
 for command in commands:
-    commands_specs[command.split('.')[0]] = (
-        importlib.util.spec_from_file_location(
-            f"{command.split('.')[0]}",
-            os.path.join(COMMANDS_PATH, command)
-        )
+    commands_specs[command.split(".")[0]] = importlib.util.spec_from_file_location(
+        f"{command.split('.')[0]}", os.path.join(COMMANDS_PATH, command)
     )
 logger.info(f"List of commands: {commands}")
 
 auto_messages = [
-    c for c in os.listdir(AUTO_MESSAGES_PATH) if os.path.isfile(os.path.join(AUTO_MESSAGES_PATH, c))
+    c
+    for c in os.listdir(AUTO_MESSAGES_PATH)
+    if os.path.isfile(os.path.join(AUTO_MESSAGES_PATH, c))
 ]
-auto_messages = filter(lambda x: not x.startswith('.'), auto_messages)
-auto_messages = filter(
-    lambda x: os.path.splitext(x)[1] == ".py",
-    auto_messages
-)
+auto_messages = filter(lambda x: not x.startswith("."), auto_messages)
+auto_messages = filter(lambda x: os.path.splitext(x)[1] == ".py", auto_messages)
 auto_messages = list(auto_messages)
 for auto_message in auto_messages:
-    auto_message_specs[auto_message.split('.')[0]] = (
-        importlib.util.spec_from_file_location(
-            f"{auto_message.split('.')[0]}",
-            os.path.join(AUTO_MESSAGES_PATH, auto_message)
-        )
+    auto_message_specs[
+        auto_message.split(".")[0]
+    ] = importlib.util.spec_from_file_location(
+        f"{auto_message.split('.')[0]}", os.path.join(AUTO_MESSAGES_PATH, auto_message)
     )
 logger.info(f"List of auto_messages: {auto_messages}")
 
 for spec in commands_specs:
-    commands_modules[spec] = importlib.util.module_from_spec(
-        commands_specs[spec])
+    commands_modules[spec] = importlib.util.module_from_spec(commands_specs[spec])
     if not commands_specs[spec]:
         continue
     try:
@@ -96,7 +94,8 @@ for spec in commands_specs:
 
 for spec in auto_message_specs:
     auto_message_modules[spec] = importlib.util.module_from_spec(
-        auto_message_specs[spec])
+        auto_message_specs[spec]
+    )
     if not auto_message_specs[spec]:
         continue
     try:
@@ -111,12 +110,12 @@ database_manager.create_lol_database()
 database_manager.create_variables_db()
 database_manager.create_chat_history_database()
 database_manager.update_commands_in_database(commands_modules, commands)
-database_manager.update_auto_messages_in_database(
-    auto_message_modules, auto_messages)
+database_manager.update_auto_messages_in_database(auto_message_modules, auto_messages)
 
 
 def start(bot: Bot, message: Message):
     while True:
+        tools.smart_start_stream_time.update_start_stream_timestamp()
         analyze_auto_message.do_auto_message(bot, message, auto_message_modules)
         time.sleep(30)
 
diff --git a/skgyorugo/scripts/clean_queue.py b/skgyorugo/scripts/clean_queue.py
new file mode 100644 (file)
index 0000000..9bf9d43
--- /dev/null
@@ -0,0 +1,70 @@
+import sqlite3
+import os
+import ttv_api.users
+import time
+import logging
+
+PATH = os.path.dirname(os.path.realpath(__file__))
+PATH = os.path.join(PATH, "..")
+
+STREAMER_PATH = os.path.abspath(os.path.join(__file__, "../.."))
+streamer_login = os.path.split(STREAMER_PATH)[1]
+
+logger = logging.getLogger(__name__)
+logger.setLevel(logging.DEBUG)
+
+formatter = logging.Formatter("[%(levelname)s] %(asctime)s: %(name)s; %(message)s")
+
+file_handler = logging.FileHandler("/var/log/aptbot/logs.log")
+file_handler.setFormatter(formatter)
+
+logger.handlers = []
+logger.addHandler(file_handler)
+
+
+def clean_queue():
+    tries = 0
+    while True:
+        tries += 1
+        twitch = ttv_api.users.get_users(user_logins=[streamer_login])
+        if twitch:
+            try:
+                twitch_id = twitch[0].user_id
+            except IndexError:
+                logger.critical(
+                    f"UNABLE TO CLEAN LOL QUEUE; GOT INDEX ERROR twitch = {twitch}"
+                )
+                continue
+            break
+        elif tries > 60:
+            return
+        logger.critical(f"UNABLE TO CLEAN LOL QUEUE; twitch = {twitch}")
+        time.sleep(3)
+
+    conn = sqlite3.connect(os.path.join(PATH, "lol_data.db"))
+    c = conn.cursor()
+
+    c.execute("DELETE FROM lol_queue")
+    conn.commit()
+
+    c.execute(
+        """
+        INSERT INTO lol_queue (
+            "twitch_id",
+            "position",
+            "available",
+            "last_available",
+            "time_remaining"
+        ) VALUES (?, ?, ?, ?, ?);
+        """,
+        (
+            twitch_id,
+            0,
+            1,
+            None,
+            9999999,
+        ),
+    )
+    conn.commit()
+
+    conn.close()
index c70791bcb1aa695452b0a48601ae952e55a7aa5f..13c477de16e9a580e8a5680d6c0485c4f07da83c 100644 (file)
@@ -6,13 +6,13 @@ MAX_LENGTH = 480
 
 def _split_message(message: str) -> list[str]:
     split_count = len(message) // MAX_LENGTH + 1
-    words = message.split(' ')
-    word_list = [''] * split_count
+    words = message.split(" ")
+    word_list = [""] * split_count
     index = 0
     for word in words:
         if len(word_list[index]) >= MAX_LENGTH:
             index += 1
-        word_list[index] += word + ' '
+        word_list[index] += word + " "
 
     return word_list
 
@@ -20,20 +20,43 @@ def _split_message(message: str) -> list[str]:
 def send_safe(bot: Bot, channel: str, messages: Union[str, list], reply=None):
     if isinstance(messages, list):
         for i in range(len(messages)):
-            if messages[i].startswith('/') or messages[i].startswith('!') or messages[i].startswith('\\') or messages[i].startswith('?'):
-                messages[i] = messages[i][1:]
+            while True:
+                if (
+                    messages[i].startswith("/")
+                    or messages[i].startswith("!")
+                    or messages[i].startswith("\\")
+                    or messages[i].startswith("?")
+                ):
+                    messages[i] = messages[i][1:]
+                else:
+                    break
     else:
-        if messages.startswith('/') or messages.startswith('!') or messages.startswith('\\') or messages.startswith('?'):
-            messages = messages[1:]
+        while True:
+            if (
+                messages.startswith("/")
+                or messages.startswith("!")
+                or messages.startswith("\\")
+                or messages.startswith("?")
+            ):
+                messages = messages[1:]
+            else:
+                break
     bot.send_privmsg(channel, messages, reply)
 
 
-def send(bot: Bot, message_data: Message, message: str, to_remove: int = 1, safe_send: bool = True, reply=None):
+def send(
+    bot: Bot,
+    message_data: Message,
+    message: str,
+    to_remove: int = 1,
+    safe_send: bool = True,
+    reply=None,
+):
     # for msg in _split_message(' '.join(message_data.value.split(' ')[1:])):
     #     message = message.replace("{message}", msg)
     #     message = message.replace("{nick}", message_data.nick)
     #     message = message.replace("{channel}", message_data.channel)
-    msg = ' '.join(message_data.value.split(' ')[to_remove:])
+    msg = " ".join(message_data.value.split(" ")[to_remove:])
     message = message.replace("{message}", msg)
     message = message.replace("{nick}", message_data.nick)
     message = message.replace("{channel}", message_data.channel)
index 389acfdda4ad0838fedb9d2727c90b7cb2b3c47b..82585258a44e0fca33bf93e5fc098863ff5a404b 100644 (file)
@@ -5,6 +5,7 @@ import ttv_api.stream
 import ttv_api.channel
 import sqlite3
 import logging
+from scripts import clean_queue
 from typing import Optional
 
 logger = logging.getLogger(__name__)
@@ -12,7 +13,7 @@ logger.setLevel(logging.DEBUG)
 
 formatter = logging.Formatter("[%(levelname)s] %(asctime)s: %(name)s; %(message)s")
 
-file_handler = logging.FileHandler('/var/log/aptbot/logs.log')
+file_handler = logging.FileHandler("/var/log/aptbot/logs.log")
 file_handler.setFormatter(formatter)
 
 logger.handlers = []
@@ -25,15 +26,47 @@ logger.debug(f"TOOLS_PATH set to: {TOOLS_PATH}")
 PATH = os.path.join(TOOLS_PATH, "..")
 logger.debug(f"PATH set to: {PATH}")
 
+streamer_login = os.path.split(STREAMER_PATH)[1]
+logger.debug(f"streamer_login set to: {streamer_login}")
+
 
 CHECK_STREAMTIME_CD = 5 * 60
 MAX_OFF_STREAM_MARGIN = 60 * 60
 
 
+def end_stream():
+    clean_queue.clean_queue()
+
+
+def start_stream():
+    clean_queue.clean_queue()
+
+
 def start_stream_timestamp() -> Optional[int]:
-    streamer_login = os.path.split(STREAMER_PATH)[1]
-    logger.debug(f"streamer_login set to: {streamer_login}")
+    conn = sqlite3.connect(os.path.join(PATH, "database.db"))
+    c = conn.cursor()
+
+    c.execute(
+        """
+        SELECT
+            start_stream_ts
+        FROM
+            stream_info
+        WHERE
+            ended = 0;
+        """
+    )
 
+    fetched = c.fetchone()
+    conn.close()
+
+    try:
+        return fetched[0]
+    except TypeError:
+        return None
+
+
+def update_start_stream_timestamp() -> Optional[int]:
     conn = sqlite3.connect(os.path.join(PATH, "database.db"))
     c = conn.cursor()
 
@@ -51,9 +84,7 @@ def start_stream_timestamp() -> Optional[int]:
                 last_checked = ?
                 AND ended = 0
             """,
-            (
-                max_last_checked[0],
-            )
+            (max_last_checked[0],),
         )
 
     fetched = c.fetchone()
@@ -79,7 +110,9 @@ def start_stream_timestamp() -> Optional[int]:
         logger.debug(f"start_stream_ts set to: {start_stream_ts}")
         logger.debug(f"last_checked set to: {last_checked}")
         if time.time() < last_checked + MAX_OFF_STREAM_MARGIN:
-            logger.info(f"streamer {streamer_login} is currently not streaming, stream not considered ended yet")
+            logger.info(
+                f"streamer {streamer_login} is currently not streaming, stream not considered ended yet"
+            )
             conn.close()
             return
 
@@ -89,11 +122,13 @@ def start_stream_timestamp() -> Optional[int]:
                 start_stream_ts,
                 last_checked,
                 1,
-            )
+            ),
         )
         conn.commit()
         logger.info(f"streamer {streamer_login} has ended stream")
         conn.close()
+        # TODO add hook, streamer ended stream
+        end_stream()
         return
 
     if not fetched:
@@ -105,12 +140,16 @@ def start_stream_timestamp() -> Optional[int]:
                 start_stream_ts,
                 current_time,
                 0,
-            )
+            ),
         )
         conn.commit()
-        logger.info(f"inserted database with start stream {start_stream_ts}, last updated {current_time}")
+        logger.info(
+            f"inserted database with start stream {start_stream_ts}, last updated {current_time}"
+        )
         conn.close()
         logger.info(f"returned api start stream time: {start_stream_ts}")
+        # TODO add hook, streamer started streaming
+        start_stream()
         return start_stream_ts
 
     start_stream_ts, last_checked = fetched
@@ -121,10 +160,12 @@ def start_stream_timestamp() -> Optional[int]:
             start_stream_ts,
             current_time,
             0,
-        )
+        ),
     )
     conn.commit()
-    logger.info(f"updated database with cached start stream {start_stream_ts}, last updated {current_time}")
+    logger.info(
+        f"updated database with cached start stream {start_stream_ts}, last updated {current_time}"
+    )
     conn.close()
     logger.info(f"returned cached start stream time: {start_stream_ts}")
     return start_stream_ts