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 = []
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
WHERE
name = ?
""",
- (name, )
+ (name,),
)
conn.commit()
continue
(
int(time.time()),
name,
- )
+ ),
)
conn.commit()
break
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 = []
PERMISSION = 10
-PREFIX = '\\'
+PREFIX = "\\"
DESCRIPTION = "Adds a LoL account to the database. Use: \\addaccount <summoner name> | <twitch name>"
USER_COOLDOWN = 0
GLOBAL_COOLDOWN = 0
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
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()
--- /dev/null
+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()
--- /dev/null
+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()
--- /dev/null
+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()
--- /dev/null
+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()
--- /dev/null
+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()
--- /dev/null
+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()
--- /dev/null
+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()
--- /dev/null
+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()
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 = []
PERMISSION = 99
-PREFIX = '?'
+PREFIX = "?"
DESCRIPTION = "Figures out which LoL Account {channel} is playing on"
USER_COOLDOWN = 20
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):
"""
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])
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()
--- /dev/null
+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()
--- /dev/null
+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()
--- /dev/null
+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()
)
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()
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 = []
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
spell1_id: int
spell2_id: int
+
@dataclass
class GameInfo:
game_id: int
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
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"))
perks = Perks(
[perk_id for perk_id in participant["perks"]["perkIds"]],
participant["perks"]["perkStyle"],
- participant["perks"]["perkSubStyle"]
+ participant["perks"]["perkSubStyle"],
)
participants.append(
CurrentGameParticipant(
data["platformId"],
data["gameMode"],
banned_champions,
- data["gameQueueConfigId"],
+ data.get("gameQueueConfigId", None),
data["observers"]["encryptionKey"],
participants,
)
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
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)
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 = []
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:
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:
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)
--- /dev/null
+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()
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
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)
import ttv_api.channel
import sqlite3
import logging
+from scripts import clean_queue
from typing import Optional
logger = logging.getLogger(__name__)
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 = []
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()
last_checked = ?
AND ended = 0
""",
- (
- max_last_checked[0],
- )
+ (max_last_checked[0],),
)
fetched = c.fetchone()
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
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:
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
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