--- /dev/null
+### TODO
+
+- [x] youtube api
+- [x] raid / host shoutout
+- [x] latege (command and auto), could look through auto schedule
+- [ ] basic math polish notation
+- [x] translator
+- [x] (?t a replied message / database in memory of messages)
+- [ ] followage command
+- [ ] commands in groups
+- [ ] quote adder / remover / getter
+- [ ] reminder (timer)
+- [x] inch to cm
+- [ ] license --- opensource --- info
+- [ ] streamer time
+- [ ] list maker (who's up for flex)
+- [ ] variable counter with cross-command functionality
+- [ ] random variable getter from db {random.quote}
+- [ ] specific word in message {message.0}, {message.1}, etc.
+- [ ] replied variable {reply.nick} {reply.message} {reply.message.0}
+- [ ] sub sellout bot
+- [ ] schedule
+- [ ] which LoL account are you playing on? (maybe add rank)
+
+## Basic Commands
+- [x] int
+- [x] bald
+- [ ] milk pasta
+- [x] make spam always output max length
+- [x] tea
+- [x] coffee
+- [ ] smelly
+- [x] coin
+- [ ] permissions
+- [x] jam
+- [x] screamlads
+- [x] supporters
--- /dev/null
+from aptbot.bot import Bot, Message, Commands
+import os
+import sqlite3
+import time
+import tools.smart_privmsg
+import tools.smart_start_stream_time
+import logging
+from importlib import reload
+
+reload(tools.smart_privmsg)
+reload(tools.smart_start_stream_time)
+
+logger = logging.getLogger(__name__)
+
+PATH = os.path.dirname(os.path.realpath(__file__))
+logger.debug(f"analyze_auto_message PATH set to: {PATH}")
+
+
+def do_auto_message(bot: Bot, message: Message, auto_message_modules: dict):
+ 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
+ name,
+ cooldown,
+ end_time,
+ last_used,
+ value
+ FROM
+ auto_messages
+ LEFT JOIN auto_message_values USING (name)
+ ORDER BY
+ last_used ASC
+ """
+ )
+ while True:
+ fetched = c.fetchone()
+ if not fetched:
+ break
+
+ name, cooldown, end_time, last_used, value = fetched
+ if time.time() < last_used + cooldown:
+ continue
+ if time.time() > start_stream_ts + end_time and end_time != 0:
+ continue
+ if value:
+ tools.smart_privmsg.send(bot, message, value)
+ else:
+ try:
+ auto_message_modules[name].main(bot, message)
+ except KeyError:
+ c.execute(
+ """
+ DELETE FROM
+ auto_messages
+ WHERE
+ name = ?
+ """,
+ (name,),
+ )
+ conn.commit()
+ continue
+
+ c.execute(
+ "UPDATE auto_messages SET last_used = ? WHERE name = ?",
+ (
+ int(time.time()),
+ name,
+ ),
+ )
+ conn.commit()
+ break
+ conn.close()
--- /dev/null
+import os
+import random
+import sqlite3
+import tools.permissions
+import tools.smart_privmsg
+import logging
+from aptbot.bot import Bot, Message, Commands
+
+logger = logging.getLogger(__name__)
+
+PATH = os.path.dirname(os.path.realpath(__file__))
+logger.debug(f"PATH set to: {PATH}")
+
+
+def do_command(bot: Bot, message: Message, command_modules: dict):
+ db_name_database = "database.db"
+ conn = sqlite3.connect(os.path.join(PATH, db_name_database))
+ c = conn.cursor()
+ logger.info(f"connected to database {db_name_database}")
+
+ try:
+ replied_message = message.tags["reply-parent-msg-body"]
+ except KeyError:
+ replied_message = None
+
+ if replied_message:
+ command = message.value.split(" ")[1]
+ else:
+ command = message.value.split(" ")[0]
+ prefix = command[0]
+ command = command[1:]
+ user_id = message.tags["user-id"]
+ message_timestamp = int(message.tags["tmi-sent-ts"]) // 1000
+ user_perm = tools.permissions.get_permission_from_id(user_id)
+
+ c.execute(
+ """
+ SELECT
+ commands.command,
+ value,
+ commands.user_cooldown,
+ commands.global_cooldown,
+ CASE
+ WHEN ? <= 10 THEN
+ 0
+ WHEN cooldowns.user_cooldown >= (commands.last_used + commands.global_cooldown) THEN
+ cooldowns.user_cooldown
+ ELSE
+ (commands.last_used + commands.global_cooldown)
+ END AS avail_time
+
+ FROM
+ commands
+ LEFT JOIN command_values USING (command)
+ LEFT JOIN cooldowns ON
+ (
+ cooldowns.command = commands.command
+ AND cooldowns.user_id = ?
+ )
+ WHERE
+ commands.command = ?
+ AND prefix = ?
+ AND permission >= ?
+ """,
+ (
+ user_perm,
+ user_id,
+ command,
+ prefix,
+ user_perm,
+ ),
+ )
+ fetched = c.fetchall()
+ if not fetched:
+ conn.close()
+ return
+
+ (
+ _,
+ value,
+ command_user_cooldown,
+ command_global_cooldown,
+ avail_time,
+ ) = random.choice(fetched)
+
+ if message_timestamp < avail_time:
+ bot.send_privmsg(
+ message.channel,
+ f"The command '{prefix}{command}' is on cooldown. \
+ Please wait {int(avail_time - message_timestamp) + 1} seconds.",
+ )
+ conn.close()
+ return
+
+ c.execute(
+ "REPLACE INTO cooldowns VALUES (?, ?, ?)",
+ (
+ user_id,
+ command,
+ command_user_cooldown + message_timestamp,
+ ),
+ )
+ c.execute(
+ "UPDATE commands SET last_used = ? WHERE command = ?",
+ (
+ message_timestamp,
+ command,
+ ),
+ )
+ conn.commit()
+ conn.close()
+ if value is None:
+ command_modules[command].main(bot, message)
+ else:
+ tools.smart_privmsg.send(bot, message, value)
--- /dev/null
+from aptbot.bot import Message, Commands, Bot
+import tools.smart_privmsg
+import urllib3
+import json
+
+COOLDOWN = 30 * 60
+END_TIME = 0
+
+header = {
+ "Accept": "application/json",
+ "User-Agent": "For my twitch bot [MurphyAI] on https://twitch.tv/ihaspeks",
+}
+
+
+def main(bot: Bot, message: Message):
+ http = urllib3.PoolManager()
+ r = http.request("GET", "https://icanhazdadjoke.com", headers=header)
+ if r.status != 200:
+ tools.smart_privmsg.send(bot, message, f"Couldn't get a joke Sadge")
+ return
+
+ data = json.loads(r.data.decode("utf-8"))
+ joke = data["joke"].replace("\r\n", " ")
+ tools.smart_privmsg.send(
+ bot, message, f"{joke} ||| Get more jokes by typing ?joke"
+ )
--- /dev/null
+from aptbot.bot import Message, Commands, Bot
+
+COOLDOWN = 120 * 60
+END_TIME = 0
+
+
+def main(bot: Bot, message: Message):
+ msg = "I collect data and occasionally post interesting statistics on peks' discord. "
+ msg += "The type of data you should expect to see is 'Chat frequency', 'Most used emotes', "
+ msg += "'Most active time and day', 'Reply graphs', etc. "
+ bot.send_privmsg(message.channel, msg)
+
+ msg = "If you are okay with these stats being publicly available with your name, "
+ msg += "please type ?accept_share to let me know. "
+ bot.send_privmsg(message.channel, msg)
--- /dev/null
+from aptbot.bot import Message, Commands, Bot
+
+COOLDOWN = 9 * 60
+END_TIME = 0.5 * 60 * 60
+
+
+def main(bot: Bot, message: Message):
+ msg = "peepoWave"
+ bot.send_privmsg(message.channel, msg)
--- /dev/null
+from aptbot.bot import Message, Commands, Bot
+
+COOLDOWN = 20 * 60
+END_TIME = 0
+
+
+def main(bot: Bot, message: Message):
+ msg = "Wanna ask 9ball a question and get an answer? use: ?9ball <question>"
+ bot.send_privmsg(message.channel, msg)
--- /dev/null
+from aptbot.bot import Message, Commands, Bot
+
+COOLDOWN = 30 * 60
+END_TIME = 1 * 60 * 60
+
+
+def main(bot: Bot, message: Message):
+ msg = "I'm a cute lil' wolf UwU and you're all cute lil' chatters OwO"
+ bot.send_privmsg(message.channel, msg)
--- /dev/null
+from aptbot.bot import Message, Commands, Bot
+import datetime as dt
+from datetime import datetime
+import tools.smart_start_stream_time
+
+COOLDOWN = 180
+END_TIME = COOLDOWN * 5
+
+STREAM_SCHEDULE = dt.time(18, 30)
+
+
+def main(bot: Bot, message: Message):
+ start_stream_ts = tools.smart_start_stream_time.start_stream_timestamp()
+ if not start_stream_ts:
+ return
+ start_stream_dt = datetime.utcfromtimestamp(start_stream_ts)
+ stream_schedule_dt = datetime.combine(datetime.now(), STREAM_SCHEDULE)
+ latege_amount = (start_stream_dt - stream_schedule_dt).total_seconds()
+ if latege_amount > 45 * 60:
+ msg = f"{message.channel} is so Latege he might as well have not \
+ streamed today. At least he's early for tomorrow COPIUM . \
+ {message.channel} is Latege by {latege_amount} seconds Madge"
+ elif latege_amount > 0:
+ msg = f"{message.channel} is Latege by {latege_amount} seconds again Madge"
+ elif latege_amount == 0:
+ msg = f"Amazing!!! {message.channel} is EXACTLY on time today POGGERS"
+ else:
+ msg = f"UNBELIEVABLE!!!!! {message.channel} is EARLY by {-latege_amount} seconds!!!!\
+ Something very wrong is going on in this world monkaW"
+ bot.send_privmsg(message.channel, "/announce " + msg)
--- /dev/null
+from aptbot.bot import Message, Commands, Bot
+
+COOLDOWN = 48 * 60
+END_TIME = 2.5 * 60 * 60
+
+
+def main(bot: Bot, message: Message):
+ msg = "IF YOU WANT TO PLAY WITH PEKS TYPE: ?join ------------------------------------------------------------------------------- You can find more info here: https://i.imgur.com/mv89SMr.png"
+ bot.send_privmsg(message.channel, msg)
--- /dev/null
+import os
+import sqlite3
+import time
+from aptbot.bot import Message, Commands, Bot
+
+COOLDOWN = 60
+END_TIME = 0
+
+PATH = os.path.dirname(os.path.realpath(__file__))
+PATH = os.path.join(PATH, "..")
+
+
+def main(bot: Bot, message: Message):
+ conn = sqlite3.connect(os.path.join(PATH, "lol_data.db"))
+ c = conn.cursor()
+
+ tables = ["lol_queue", "ow"]
+
+ for table in tables:
+ c.execute(
+ f"""
+ UPDATE
+ {table}
+ SET
+ last_available = ?,
+ time_remaining = time_remaining - (? - last_available)
+ WHERE
+ available = 0;
+ """,
+ (
+ int(time.time()),
+ int(time.time()),
+ ),
+ )
+ c.execute(f"DELETE FROM {table} WHERE time_remaining < 0;")
+ if c.rowcount:
+ bot.send_privmsg(message.channel, f"/announce {c.rowcount} user{'s were' if c.rowcount > 1 else ' was'} just removed from {table if table != 'lol_queue' else 'lol'} queue.")
+
+ conn.commit()
+
+ conn.close()
--- /dev/null
+from aptbot.bot import Message, Commands, Bot
+import yt_api.videos
+
+COOLDOWN = 42 * 60
+END_TIME = 0
+
+CHANNEL_ID = "UCQ7C3NUKY6TSkURdUdVoYFw"
+
+
+def main(bot: Bot, message: Message):
+ video = yt_api.videos.get_newest_video(CHANNEL_ID)
+ if video:
+ video_link = f"https://www.youtube.com/watch?v={video.video_id}"
+ msg = f'Watch Peks\' latest video "{video.video_name}" here: {video_link}'
+ else:
+ msg = f"Check out my youtube channel here -> https://www.youtube.com/channel/{CHANNEL_ID}"
+ bot.send_privmsg(message.channel, msg)
--- /dev/null
+from aptbot.bot import Message, Commands, Bot
+import tools.smart_start_stream_time
+
+PERMISSION = 99
+PREFIX = "?"
+DESCRIPTION = ""
+USER_COOLDOWN = 5
+GLOBAL_COOLDOWN = 2
+
+
+def main(bot: Bot, message: Message):
+ start_stream_ts = tools.smart_start_stream_time.start_stream_timestamp()
+ if not start_stream_ts:
+ msg = r"The Sponsor is World of Warships, which is a historical strategy online combat PC game. It looks very 5Head but i will conquer elmoFire so imma be testing it out. If u want to join in with us, try it urself, or if you just want to help me out Gladge u can sign up with my link: https://strms.net/warships_ihaspeks you get a fair few bonuses for using mah link too ihaspeBased and after u have won your first game and bought ur first ship ill get a notification on stream peksJAM"
+ else:
+ msg = r"Peks is live so he can awnser that KEKW but here is the link just in case BASED https://strms.net/warships_ihaspeks"
+ tools.smart_privmsg.send_safe(bot, message.channel, msg)
+
--- /dev/null
+from aptbot.bot import Message, Commands, Bot
+import os
+import tools.smart_privmsg
+import openai
+from openai.error import RateLimitError
+
+PERMISSION = 99
+PREFIX = "?"
+DESCRIPTION = ""
+USER_COOLDOWN = 40
+GLOBAL_COOLDOWN = 20
+
+openai.api_key = os.getenv("OPENAI_API")
+
+def main(bot: Bot, message: Message):
+ replied_message = message.tags.get("reply-parent-msg-body", None)
+ if replied_message:
+ msg = replied_message
+ replied_msg_id = message.tags["reply-parent-msg-id"]
+ else:
+ msg = " ".join(message.value.split(" ")[1:])
+ replied_msg_id = message.tags['id']
+
+
+ try:
+ response = openai.Completion.create(
+ # model="davinci:ft-personal:9ball-2022-12-05-08-37-36",
+ model="davinci:ft-personal-2022-12-06-10-03-18",
+ prompt=f"9ball is an 8ball. 9ball answers your questions reluctantly with sarcastic and unhelpful responses.\n{message.nick}: {msg}\n\n###\n\n",
+ temperature=1,
+ max_tokens=60,
+ top_p=0.3,
+ frequency_penalty=0.5,
+ presence_penalty=0.0,
+ stop=[" END"],
+ )
+ except RateLimitError:
+ tools.smart_privmsg.send_safe(bot, message.channel, "UwU Sowwy. The sevwews awe ovewloaded :( Twy again in a few minutes OwO", reply=replied_msg_id)
+
+ print(response)
+ if response:
+ msg = response["choices"][0]["text"]
+ # msg = msg[:msg.find("#")]
+ else:
+ msg = "Sadge nothing was returned"
+
+ tools.smart_privmsg.send_safe(bot, message.channel, msg, reply=replied_msg_id)
+ # bot.send_privmsg(message.channel, msg, reply=replied_msg_id)
--- /dev/null
+from aptbot.bot import Message, Commands, Bot
+import os
+import logging
+import ttv_api.users
+import sqlite3
+import tools.smart_privmsg
+import random
+import shlex
+
+logger = logging.getLogger(__name__)
+
+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 check_queue(bot: Bot, message: Message, table: str):
+ if random.random() < 0.02:
+ q = [
+ "https://imgur.com/d5qGioI",
+ "https://imgur.com/oaMmxXI",
+ "https://imgur.com/4btWipx",
+ "https://imgur.com/VvvD8d8",
+ "https://imgur.com/v7oflTv",
+ "https://imgur.com/MSnBNDz",
+ "https://imgur.com/x2pPkvw",
+ "https://imgur.com/xZgFcYG",
+ ]
+ msg = (
+ "You wanted to see the queue, but instead you got visited by the Q. monkaW "
+ )
+ msg += random.choice(q)
+ tools.smart_privmsg.send(
+ bot,
+ message,
+ msg,
+ reply=message.tags["id"],
+ )
+ return
+ conn = sqlite3.connect(os.path.join(PATH, "lol_data.db"))
+ c = conn.cursor()
+
+ c.execute(
+ f"""
+ SELECT twitch_id, priority_queue FROM {table} 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_users = []
+ for twitch_id in queue:
+ for twitch_user in twitch:
+ if int(twitch_user.user_id) == int(twitch_id):
+ queue_users.append(twitch_user)
+ 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(
+ f"""
+ SELECT data FROM {table}_data WHERE name = 'queuesize';
+ """
+ )
+ try:
+ queue_size = c.fetchone()[0]
+ except TypeError:
+ queue_size = 5
+ bot.send_privmsg(
+ message.channel,
+ f"There was an issue fetching the queue size, default set to {queue_size}",
+ reply=message.tags["id"],
+ )
+
+ c.execute(
+ f"""
+ SELECT twitch_id FROM {table} WHERE available = 0 ORDER BY position ASC;
+ """
+ )
+ fetched_unavailable = c.fetchall()
+ unavailable = [x[0] for x in fetched_unavailable]
+ twitch_unavailable = ttv_api.users.get_users(user_ids=unavailable)
+
+ unavailable_users = []
+ for twitch_id in unavailable:
+ for twitch_user in twitch_unavailable:
+ if int(twitch_user.user_id) == int(twitch_id):
+ unavailable_users.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"],
+ )
+
+ play_list = [user.display_name for user in queue_users[0:queue_size]]
+ prio_queue = []
+ wait_list = []
+ for user in queue_users[queue_size:]:
+ for fetch in fetched:
+ if int(user.user_id) == fetch[0] and fetch[1] == 1:
+ prio_queue.append(user.display_name)
+ elif int(user.user_id) == fetch[0]:
+ wait_list.append(user.display_name)
+
+ if prio_queue:
+ msg = f"These people are playing with {play_list[0]}: {play_list[1:]} | These people are in Priority Queue: {prio_queue} | These people are in the Wait List: {wait_list}."
+ else:
+ msg = f"These people are playing with {play_list[0]}: {play_list[1:]} | These people are in the Wait List: {wait_list}."
+
+ if unavailable_users:
+ msg += f" | These people are also not here: {unavailable_users}."
+
+ tools.smart_privmsg.send(
+ bot,
+ message,
+ msg,
+ reply=message.tags["id"],
+ )
+
+ conn.close()
+
+
+def parse(query):
+ query = query.split()
+ try:
+ if query[0].lower() in {"ow", "overwatch", "ow2", "overwatch2"}:
+ return {"--game": "ow"}
+ except:
+ pass
+ return {"--game": "lol_queue"}
+ d = dict()
+ for i in shlex.split(query):
+ try:
+ d[i.split('=')[0]] = i.split('=')[1]
+ except:
+ pass
+ return d
+
+
+def scrub(table_name):
+ return ''.join(chr for chr in table_name if chr.isalnum() or chr == '_')
+
+
+def main(bot: Bot, message: Message):
+ args = " ".join(message.value.split(" ")[1:])
+ args = parse(args)
+ check_queue(bot, message, scrub(args.get("--game", "lol_queue")))
--- /dev/null
+from aptbot.bot import Message, Commands, Bot
+import tools.smart_privmsg
+import os
+
+PERMISSION = 99
+PREFIX = "?"
+DESCRIPTION = ""
+USER_COOLDOWN = 30
+GLOBAL_COOLDOWN = 15
+
+
+COMMANDS_PATH = os.path.dirname(os.path.realpath(__file__))
+PATH = os.path.join(COMMANDS_PATH, "..")
+DATA_PATH = os.path.join(PATH, "data")
+
+
+def main(bot: Bot, message: Message):
+ accepted_path = os.path.join(DATA_PATH, "permission")
+ with open(accepted_path, "r") as f:
+ accepted = [user_id.rstrip() for user_id in f]
+ if message.tags["user-id"] in accepted:
+ tools.smart_privmsg.send(bot, message, "You have already given permission")
+ return
+
+ with open(accepted_path, "a") as f:
+ f.write(f"{message.tags['user-id']}\n")
+ tools.smart_privmsg.send(bot, message, "Thank you for giving permission")
+
--- /dev/null
+from aptbot.bot import Message, Commands, Bot
+import sqlite3
+import os
+import logging
+import lol_api.summoner_v4
+import ttv_api.users
+
+logger = logging.getLogger(__name__)
+
+
+PERMISSION = 10
+PREFIX = "\\"
+DESCRIPTION = "Adds a LoL account to the database. Use: \\addaccount <summoner name> | <twitch name>"
+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):
+ 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}"
+ )
+ 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}"
+ )
+ return
+ twitch_id = twitch[0].user_id
+
+ conn = sqlite3.connect(os.path.join(PATH, "lol_data.db"))
+ c = conn.cursor()
+
+ try:
+ c.execute(
+ """
+ INSERT INTO accounts (
+ "puuid",
+ "summoner_id",
+ "account_id",
+ "twitch_id"
+ ) VALUES (
+ ?, ?, ?, ?
+ );
+ """,
+ (
+ summoner.puuid,
+ 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"
+ )
+ 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}"
+ )
+ bot.send_privmsg(message.channel, f"Successfully added account.")
+ conn.close()
--- /dev/null
+from aptbot.bot import Message, Commands, Bot
+import sqlite3
+import os
+
+PERMISSION = 10
+PREFIX = "\\"
+DESCRIPTION = ""
+USER_COOLDOWN = 0
+GLOBAL_COOLDOWN = 0
+
+PATH = os.path.dirname(os.path.realpath(__file__))
+PATH = os.path.join(PATH, "..")
+
+DEFAULT_PERMISSION = 99
+DEFAULT_DESCRIPTION = ""
+DEFAULT_USER_COOLDOWN = 5
+DEFAULT_GLOBAL_COOLDOWN = 0
+DEFAULT_LAST_USED = 0
+
+
+def main(bot: Bot, message: Message):
+ msg = " ".join(message.value.split(" ")[1:])
+ command = msg.split(" ")[0]
+ command_prefix = command[0]
+ command_name = command[1:]
+ command_value = msg = " ".join(msg.split(" ")[1:])
+ if command_prefix != "?":
+ bot.send_privmsg(
+ message.channel,
+ f"{message.nick} you cannot use {command_prefix} as a prefix",
+ )
+ return
+
+ conn = sqlite3.connect(os.path.join(PATH, "database.db"))
+ c = conn.cursor()
+ c.execute(
+ "SELECT value FROM commands LEFT JOIN command_values USING(command) WHERE command = ? AND prefix = ?",
+ (
+ command_name,
+ command_prefix,
+ ),
+ )
+ try:
+ if not c.fetchone()[0]:
+ bot.send_privmsg(
+ message.channel,
+ f"The command {command_prefix}{command_name} already exists",
+ )
+ return
+ except TypeError:
+ pass
+ try:
+ c.execute(
+ "INSERT INTO commands VALUES (?, ?, ?, ?, ?, ?, ?)",
+ (
+ command_name,
+ command_prefix,
+ DEFAULT_PERMISSION,
+ DEFAULT_DESCRIPTION,
+ DEFAULT_USER_COOLDOWN,
+ DEFAULT_GLOBAL_COOLDOWN,
+ DEFAULT_LAST_USED,
+ ),
+ )
+ except sqlite3.IntegrityError:
+ pass
+ except Exception as e:
+ bot.send_privmsg(message.channel, f"There was an error adding the command: {e}")
+ conn.close()
+ return
+ c.execute(
+ "INSERT INTO command_values VALUES (?, ?)",
+ (
+ command_name,
+ command_value,
+ ),
+ )
+ bot.send_privmsg(message.channel, f"Successfully added {command_name}.")
+ conn.commit()
+ conn.close()
--- /dev/null
+from aptbot.bot import Message, Commands, Bot
+import os
+import logging
+import ttv_api.users
+import sqlite3
+import tools.smart_privmsg
+import random
+import shlex
+
+logger = logging.getLogger(__name__)
+
+PERMISSION = 99
+PREFIX = "?"
+DESCRIPTION = r"Sekiro death counter"
+USER_COOLDOWN = 10
+GLOBAL_COOLDOWN = 5
+
+PATH = os.path.dirname(os.path.realpath(__file__))
+PATH = os.path.join(PATH, "..")
+
+def check_queue(bot: Bot, message: Message, table: str):
+ conn = sqlite3.connect(os.path.join(PATH, "database.db"))
+ c = conn.cursor()
+
+ c.execute(
+ f"""
+ SELECT id, val FROM varvalues WHERE id = 'cannon';
+ """
+ )
+ _, val = c.fetchone()
+
+ if table == "show":
+ msg = f"Peks is at cannon {val % 1000} of prestige {val // 1000}"
+
+ tools.smart_privmsg.send(
+ bot,
+ message,
+ msg,
+ reply=message.tags["id"],
+ )
+
+ conn.close()
+ return
+ if table == "remove":
+ val = val - 1
+ c.execute(
+ f"""
+ UPDATE varvalues SET val = ? WHERE id = 'cannon';
+ """,
+ (val,)
+ )
+
+ msg = f"Peks is at cannon {val % 1000} of prestige {val // 1000}"
+
+ tools.smart_privmsg.send(
+ bot,
+ message,
+ msg,
+ reply=message.tags["id"],
+ )
+ conn.commit()
+ conn.close()
+ return
+ if table == "add":
+ val = val + 1
+ c.execute(
+ f"""
+ UPDATE varvalues SET val = ? WHERE id = 'cannon';
+ """,
+ (val,)
+ )
+
+ msg = f"Peks is at cannon {val % 1000} of prestige {val // 1000}"
+
+ tools.smart_privmsg.send(
+ bot,
+ message,
+ msg,
+ reply=message.tags["id"],
+ )
+ conn.commit()
+ conn.close()
+ return
+
+
+def parse(query):
+ query = query.split()
+ try:
+ if query[0].lower() == "add":
+ return {"--do": "add"}
+ if query[0].lower() == "remove":
+ return {"--do": "remove"}
+ except:
+ pass
+ return {"--game": "show"}
+ d = dict()
+ for i in shlex.split(query):
+ try:
+ d[i.split('=')[0]] = i.split('=')[1]
+ except:
+ pass
+ return d
+
+
+def scrub(table_name):
+ return ''.join(chr for chr in table_name if chr.isalnum() or chr == '_')
+
+
+def main(bot: Bot, message: Message):
+ args = " ".join(message.value.split(" ")[1:])
+ args = parse(args)
+ check_queue(bot, message, scrub(args.get("--do", "show")))
--- /dev/null
+from aptbot.bot import Message, Commands, Bot
+import os
+import logging
+import ttv_api.users
+import sqlite3
+import time
+import shlex
+
+logger = logging.getLogger(__name__)
+
+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 clean_queue(bot: Bot, message: Message, table: str):
+ 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(f"DELETE FROM {table}")
+ conn.commit()
+
+ c.execute(
+ f"""
+ INSERT INTO {table} (
+ "twitch_id",
+ "position",
+ "available",
+ "last_available",
+ "time_remaining"
+ ) VALUES (?, ?, ?, ?, ?);
+ """,
+ (
+ twitch_id,
+ 0,
+ 1,
+ None,
+ 9999999,
+ ),
+ )
+ conn.commit()
+
+ bot.send_privmsg(
+ message.channel,
+ f"Successfully cleaned the queue.",
+ reply=message.tags["id"],
+ )
+
+ conn.close()
+
+
+def parse(query):
+ query = query.split()
+ try:
+ if query[0].lower() in {"ow", "overwatch", "ow2", "overwatch2"}:
+ return {"--game": "ow"}
+ except:
+ pass
+ return {"--game": "lol_queue"}
+ d = dict()
+ for i in shlex.split(query):
+ try:
+ d[i.split('=')[0]] = i.split('=')[1]
+ except:
+ pass
+ return d
+
+
+def scrub(table_name):
+ return ''.join(chr for chr in table_name if chr.isalnum() or chr == '_')
+
+
+def main(bot: Bot, message: Message):
+ args = " ".join(message.value.split(" ")[1:])
+ args = parse(args)
+ clean_queue(bot, message, scrub(args.get("--game", "lol_queue")))
--- /dev/null
+from aptbot.bot import Message, Commands, Bot
+import tools.smart_privmsg
+import random
+
+PERMISSION = 99
+PREFIX = "?"
+DESCRIPTION = (
+ r"Tosses a coin, there's a 50% chance it's heads and a 50% chance it's tails"
+)
+USER_COOLDOWN = 10
+GLOBAL_COOLDOWN = 5
+
+
+def main(bot: Bot, message: Message):
+ r = random.random()
+ if r < 0.02:
+ tools.smart_privmsg.send(
+ bot,
+ message,
+ f"the coin landed on it's side, try again.",
+ reply=message.tags["id"],
+ )
+ elif r < 0.51:
+ tools.smart_privmsg.send(bot, message, f"heads", reply=message.tags["id"])
+ else:
+ tools.smart_privmsg.send(bot, message, f"tails", reply=message.tags["id"])
--- /dev/null
+from aptbot.bot import Message, Commands, Bot
+import tools.permissions
+import tools.smart_privmsg
+import sqlite3
+import os
+
+PERMISSION = 99
+PREFIX = "?"
+DESCRIPTION = ""
+USER_COOLDOWN = 30
+GLOBAL_COOLDOWN = 15
+
+
+COMMANDS_PATH = os.path.dirname(os.path.realpath(__file__))
+PATH = os.path.join(COMMANDS_PATH, "..")
+
+
+def main(bot: Bot, message: Message):
+ conn = sqlite3.connect(os.path.join(PATH, "database.db"))
+ c = conn.cursor()
+
+ user_perm = tools.permissions.get_permission_from_id(message.tags["user-id"])
+
+ c.execute(
+ "SELECT prefix, command FROM commands WHERE permission >= ? ORDER BY permission ASC",
+ (user_perm,),
+ )
+
+ fetched_commands = c.fetchall()
+
+ conn.commit()
+ conn.close()
+
+ commands = []
+ for command in fetched_commands:
+ commands.append(f"{command[0]}{command[1]}")
+
+ commands = " ".join(commands)
+ tools.smart_privmsg.send(bot, message, commands)
--- /dev/null
+from aptbot.bot import Message, Commands, Bot
+import os
+import logging
+import ttv_api.users
+import sqlite3
+import tools.smart_privmsg
+import random
+import shlex
+
+logger = logging.getLogger(__name__)
+
+PERMISSION = 99
+PREFIX = "?"
+DESCRIPTION = r"Sekiro death counter"
+USER_COOLDOWN = 10
+GLOBAL_COOLDOWN = 5
+
+PATH = os.path.dirname(os.path.realpath(__file__))
+PATH = os.path.join(PATH, "..")
+
+def check_queue(bot: Bot, message: Message, table: str):
+ conn = sqlite3.connect(os.path.join(PATH, "database.db"))
+ c = conn.cursor()
+
+ c.execute(
+ f"""
+ SELECT id, val FROM varvalues WHERE id = 'deadge_sekiro';
+ """
+ )
+ _, val = c.fetchone()
+
+ if table == "show":
+ msg = f"Peks has currently died {val} times"
+
+ tools.smart_privmsg.send(
+ bot,
+ message,
+ msg,
+ reply=message.tags["id"],
+ )
+
+ conn.close()
+ return
+ if table == "remove":
+ val = val - 1
+ c.execute(
+ f"""
+ UPDATE varvalues SET val = ? WHERE id = 'deadge_sekiro';
+ """,
+ (val,)
+ )
+
+ msg = f"Peks has currently died {val} times"
+
+ tools.smart_privmsg.send(
+ bot,
+ message,
+ msg,
+ reply=message.tags["id"],
+ )
+ conn.commit()
+ conn.close()
+ return
+ if table == "add":
+ val = val + 1
+ c.execute(
+ f"""
+ UPDATE varvalues SET val = ? WHERE id = 'deadge_sekiro';
+ """,
+ (val,)
+ )
+
+ msg = f"Peks has currently died {val} times"
+
+ tools.smart_privmsg.send(
+ bot,
+ message,
+ msg,
+ reply=message.tags["id"],
+ )
+ conn.commit()
+ conn.close()
+ return
+
+
+def parse(query):
+ query = query.split()
+ try:
+ if query[0].lower() == "add":
+ return {"--do": "add"}
+ if query[0].lower() == "remove":
+ return {"--do": "remove"}
+ except:
+ pass
+ return {"--game": "show"}
+ d = dict()
+ for i in shlex.split(query):
+ try:
+ d[i.split('=')[0]] = i.split('=')[1]
+ except:
+ pass
+ return d
+
+
+def scrub(table_name):
+ return ''.join(chr for chr in table_name if chr.isalnum() or chr == '_')
+
+
+def main(bot: Bot, message: Message):
+ args = " ".join(message.value.split(" ")[1:])
+ args = parse(args)
+ check_queue(bot, message, scrub(args.get("--do", "show")))
--- /dev/null
+from aptbot.bot import Message, Commands, Bot
+
+PERMISSION = 10
+PREFIX = "\\"
+DESCRIPTION = "Reply to a message with \\delete to delete that message"
+USER_COOLDOWN = 0
+GLOBAL_COOLDOWN = 0
+
+
+def main(bot: Bot, message: Message):
+ try:
+ replied_msg_id = message.tags["reply-parent-msg-id"]
+ except KeyError:
+ return
+ delete = f"/delete {replied_msg_id}"
+ bot.send_privmsg(message.channel, delete)
--- /dev/null
+from aptbot.bot import Message, Commands, Bot
+import sqlite3
+import os
+
+PERMISSION = 10
+PREFIX = "\\"
+DESCRIPTION = ""
+USER_COOLDOWN = 0
+GLOBAL_COOLDOWN = 0
+
+
+COMMANDS_PATH = os.path.dirname(os.path.realpath(__file__))
+PATH = os.path.join(COMMANDS_PATH, "..")
+
+
+def main(bot: Bot, message: Message):
+ msg = " ".join(message.value.split(" ")[1:])
+ command = msg.split(" ")[0]
+ command_prefix = command[0]
+ command_name = command[1:]
+ command_value = msg = " ".join(msg.split(" ")[1:])
+ if command_prefix != "?":
+ bot.send_privmsg(
+ message.channel,
+ f"{message.nick} you cannot use {command_prefix} as a prefix",
+ )
+ return
+
+ conn = sqlite3.connect(os.path.join(PATH, "database.db"))
+ c = conn.cursor()
+ c.execute(
+ "SELECT value FROM commands LEFT JOIN command_values USING(command) WHERE command = ? AND prefix = ?",
+ (
+ command_name,
+ command_prefix,
+ ),
+ )
+ if not c.fetchone()[0]:
+ bot.send_privmsg(
+ message.channel,
+ f"The command {command_prefix}{command_name} cannot be edited",
+ )
+ return
+
+ try:
+ c.execute(
+ "UPDATE command_values SET value = ? WHERE command = ?",
+ (
+ command_value,
+ command_name,
+ ),
+ )
+ except sqlite3.IntegrityError:
+ bot.send_privmsg(message.channel, f"The command {command_name} doesn't exist.")
+ else:
+ bot.send_privmsg(message.channel, f"Successfully updated {command_name}.")
+ conn.commit()
+ conn.close()
--- /dev/null
+from aptbot.bot import Message, Commands, Bot
+import tools.smart_privmsg
+import urllib3
+
+PERMISSION = 9
+PREFIX = "\\"
+DESCRIPTION = ""
+USER_COOLDOWN = 900
+GLOBAL_COOLDOWN = 600
+
+
+def main(bot: Bot, message: Message):
+ http = urllib3.PoolManager()
+ r1 = http.request(
+ "GET",
+ f"https://twitch.center/customapi/bttvemotes?channel={message.channel}",
+ )
+ r2 = http.request(
+ "GET",
+ f"https://twitch.center/customapi/ffzemotes?channel={message.channel}",
+ )
+
+ if r1.status != 200 or r2.status != 200:
+ bot.send_privmsg(
+ message.channel,
+ "NotLikeThis oopsie woopsie, we've made a fucky wucky. We can't \
+ get the emotes at the moment. Hopefuwwy UwU wiww wait patientwy \
+ tiww we get thiws pwobwem sowted. OwO",
+ )
+ return
+ emotes = r1.data.decode("utf-8")
+ emotes += " " + r2.data.decode("utf-8")
+ tools.smart_privmsg.send(bot, message, emotes)
--- /dev/null
+from aptbot.bot import Message, Commands, Bot
+import os
+import shlex
+import logging
+import ttv_api.users
+import sqlite3
+import time
+
+logger = logging.getLogger(__name__)
+
+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 force_here(bot: Bot, message: Message, table: str):
+ 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(
+ f"""
+ UPDATE
+ {table}
+ SET
+ position = (
+ CASE
+ WHEN (
+ SELECT
+ position
+ FROM
+ {table}
+ WHERE
+ twitch_id = ?
+ ) < (
+ SELECT
+ max(position)
+ FROM (
+ SELECT
+ position
+ FROM
+ {table}
+ WHERE
+ available = 1
+ ORDER BY
+ position
+ LIMIT (
+ SELECT
+ data
+ FROM
+ {table}_data
+ WHERE
+ name = 'queuesize'
+ )
+ )
+ )
+ THEN position + 1
+ ELSE position
+ END
+ )
+ WHERE
+ position > (
+ SELECT
+ max(position)
+ FROM
+ {table}
+ WHERE
+ priority_queue = 1
+ OR position <= (
+ SELECT
+ max(position)
+ FROM (
+ SELECT
+ position
+ FROM
+ {table}
+ WHERE
+ available = 1
+ ORDER BY
+ position
+ LIMIT (
+ SELECT
+ data
+ FROM
+ {table}_data
+ WHERE
+ name = 'queuesize'
+ )
+ )
+
+ )
+ );
+ """,
+ (twitch_id,),
+ )
+
+ c.execute(
+ f"""
+ UPDATE
+ {table}
+ SET
+ available = 1,
+ priority_queue = (
+ CASE
+ WHEN (
+ SELECT
+ position
+ FROM
+ {table}
+ WHERE
+ twitch_id = ?
+ ) < (
+ SELECT
+ max(position)
+ FROM (
+ SELECT
+ position
+ FROM
+ {table}
+ WHERE
+ available = 1
+ ORDER BY
+ position
+ LIMIT (
+ SELECT
+ data
+ FROM
+ {table}_data
+ WHERE
+ name = 'queuesize'
+ )
+ )
+ )
+ THEN 1
+ ELSE null
+ END
+ ),
+ position = (
+ CASE
+ WHEN (
+ SELECT
+ position
+ FROM
+ {table}
+ WHERE
+ twitch_id = ?
+ ) < (
+ SELECT
+ max(position)
+ FROM (
+ SELECT
+ position
+ FROM
+ {table}
+ WHERE
+ available = 1
+ ORDER BY
+ position
+ LIMIT (
+ SELECT
+ data
+ FROM
+ {table}_data
+ WHERE
+ name = 'queuesize'
+ )
+ )
+ )
+ THEN 1 + (
+ SELECT
+ max(position)
+ FROM
+ {table}
+ WHERE
+ priority_queue = 1
+ OR position <= (
+ SELECT
+ max(position)
+ FROM (
+ SELECT
+ position
+ FROM
+ {table}
+ WHERE
+ available = 1
+ ORDER BY
+ position
+ LIMIT (
+ SELECT
+ data
+ FROM
+ {table}_data
+ WHERE
+ name = 'queuesize'
+ )
+ )
+ )
+ )
+ ELSE position
+ END
+ ),
+ time_remaining = time_remaining - (? - last_available)
+ WHERE
+ twitch_id = ?
+ AND available = 0;
+ """,
+ (
+ twitch_id,
+ twitch_id,
+ 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(f"DELETE FROM {table} 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()
+
+
+def parse(query):
+ query = query.split()
+ try:
+ if query[1].lower() in {"ow", "overwatch", "ow2", "overwatch2"}:
+ return {"--game": "ow"}
+ except:
+ pass
+ return {"--game": "lol_queue"}
+ d = dict()
+ for i in shlex.split(query):
+ try:
+ d[i.split('=')[0]] = i.split('=')[1]
+ except:
+ pass
+ return d
+
+
+def scrub(table_name):
+ return ''.join(chr for chr in table_name if chr.isalnum() or chr == '_')
+
+
+def main(bot: Bot, message: Message):
+ args = " ".join(message.value.split(" ")[1:])
+ args = parse(args)
+ force_here(bot, message, scrub(args.get("--game", "lol_queue")))
--- /dev/null
+from aptbot.bot import Message, Commands, Bot
+import shlex
+import os
+import logging
+import ttv_api.users
+import sqlite3
+
+logger = logging.getLogger(__name__)
+
+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 force_join(bot: Bot, message: Message, table: str):
+ 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(
+ f"""
+ SELECT position FROM {table} ORDER BY position DESC;
+ """
+ )
+
+ try:
+ last_position: int = c.fetchone()[0]
+ except TypeError:
+ last_position: int = -1
+
+ try:
+ c.execute(
+ f"""
+ INSERT INTO {table} (
+ "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()
+
+
+def parse(query):
+ query = query.split()
+ try:
+ if query[1].lower() in {"ow", "overwatch", "ow2", "overwatch2"}:
+ return {"--game": "ow"}
+ except:
+ pass
+ return {"--game": "lol_queue"}
+ d = dict()
+ for i in shlex.split(query):
+ try:
+ d[i.split('=')[0]] = i.split('=')[1]
+ except:
+ pass
+ return d
+
+
+def scrub(table_name):
+ return ''.join(chr for chr in table_name if chr.isalnum() or chr == '_')
+
+
+def main(bot: Bot, message: Message):
+ args = " ".join(message.value.split(" ")[1:])
+ args = parse(args)
+ force_join(bot, message, scrub(args.get("--game", "lol_queue")))
--- /dev/null
+from aptbot.bot import Message, Commands, Bot
+import os
+import logging
+import ttv_api.users
+import sqlite3
+import shlex
+
+logger = logging.getLogger(__name__)
+
+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 force_leave(bot: Bot, message: Message, table: str):
+ 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(
+ f"""
+ DELETE FROM {table} 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()
+
+
+def parse(query):
+ query = query.split()
+ try:
+ if query[1].lower() in {"ow", "overwatch", "ow2", "overwatch2"}:
+ return {"--game": "ow"}
+ except:
+ pass
+ return {"--game": "lol_queue"}
+ d = dict()
+ for i in shlex.split(query):
+ try:
+ d[i.split('=')[0]] = i.split('=')[1]
+ except:
+ pass
+ return d
+
+
+def scrub(table_name):
+ return ''.join(chr for chr in table_name if chr.isalnum() or chr == '_')
+
+
+def main(bot: Bot, message: Message):
+ args = " ".join(message.value.split(" ")[1:])
+ args = parse(args)
+ force_leave(bot, message, scrub(args.get("--game", "lol_queue")))
--- /dev/null
+from aptbot.bot import Message, Commands, Bot
+import os
+import logging
+import ttv_api.users
+import sqlite3
+import time
+import shlex
+
+logger = logging.getLogger(__name__)
+
+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 force_not_here(bot: Bot, message: Message, table: str):
+ 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(
+ f"""
+ UPDATE {table} SET available = 0, priority_queue = null, 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()
+
+
+def parse(query):
+ query = query.split()
+ try:
+ if query[1].lower() in {"ow", "overwatch", "ow2", "overwatch2"}:
+ return {"--game": "ow"}
+ except:
+ pass
+ return {"--game": "lol_queue"}
+ d = dict()
+ for i in shlex.split(query):
+ try:
+ d[i.split('=')[0]] = i.split('=')[1]
+ except:
+ pass
+ return d
+
+
+def scrub(table_name):
+ return ''.join(chr for chr in table_name if chr.isalnum() or chr == '_')
+
+
+def main(bot: Bot, message: Message):
+ args = " ".join(message.value.split(" ")[1:])
+ args = parse(args)
+ force_not_here(bot, message, scrub(args.get("--game", "lol_queue")))
--- /dev/null
+from aptbot.bot import Message, Commands, Bot
+import os
+import logging
+import ttv_api.users
+import sqlite3
+import time
+import shlex
+
+logger = logging.getLogger(__name__)
+
+PERMISSION = 99
+PREFIX = "?"
+DESCRIPTION = r"Makes yourself available in the list."
+USER_COOLDOWN = 10
+GLOBAL_COOLDOWN = 0
+
+PATH = os.path.dirname(os.path.realpath(__file__))
+PATH = os.path.join(PATH, "..")
+
+
+def here(bot: Bot, message: Message, table: str):
+ 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(
+ f"""
+ UPDATE
+ {table}
+ SET
+ position = (
+ CASE
+ WHEN (
+ SELECT
+ position
+ FROM
+ {table}
+ WHERE
+ twitch_id = ?
+ ) < (
+ SELECT
+ max(position)
+ FROM (
+ SELECT
+ position
+ FROM
+ {table}
+ WHERE
+ available = 1
+ ORDER BY
+ position
+ LIMIT (
+ SELECT
+ data
+ FROM
+ {table}_data
+ WHERE
+ name = 'queuesize'
+ )
+ )
+ )
+ THEN position + 1
+ ELSE position
+ END
+ )
+ WHERE
+ position > (
+ SELECT
+ max(position)
+ FROM
+ {table}
+ WHERE
+ priority_queue = 1
+ OR position <= (
+ SELECT
+ max(position)
+ FROM (
+ SELECT
+ position
+ FROM
+ {table}
+ WHERE
+ available = 1
+ ORDER BY
+ position
+ LIMIT (
+ SELECT
+ data
+ FROM
+ {table}_data
+ WHERE
+ name = 'queuesize'
+ )
+ )
+
+ )
+ );
+ """,
+ (twitch_id,),
+ )
+
+ c.execute(
+ f"""
+ UPDATE
+ {table}
+ SET
+ available = 1,
+ priority_queue = (
+ CASE
+ WHEN (
+ SELECT
+ position
+ FROM
+ {table}
+ WHERE
+ twitch_id = ?
+ ) < (
+ SELECT
+ max(position)
+ FROM (
+ SELECT
+ position
+ FROM
+ {table}
+ WHERE
+ available = 1
+ ORDER BY
+ position
+ LIMIT (
+ SELECT
+ data
+ FROM
+ {table}_data
+ WHERE
+ name = 'queuesize'
+ )
+ )
+ )
+ THEN 1
+ ELSE null
+ END
+ ),
+ position = (
+ CASE
+ WHEN (
+ SELECT
+ position
+ FROM
+ {table}
+ WHERE
+ twitch_id = ?
+ ) < (
+ SELECT
+ max(position)
+ FROM (
+ SELECT
+ position
+ FROM
+ {table}
+ WHERE
+ available = 1
+ ORDER BY
+ position
+ LIMIT (
+ SELECT
+ data
+ FROM
+ {table}_data
+ WHERE
+ name = 'queuesize'
+ )
+ )
+ )
+ THEN 1 + (
+ SELECT
+ max(position)
+ FROM
+ {table}
+ WHERE
+ priority_queue = 1
+ OR position <= (
+ SELECT
+ max(position)
+ FROM (
+ SELECT
+ position
+ FROM
+ {table}
+ WHERE
+ available = 1
+ ORDER BY
+ position
+ LIMIT (
+ SELECT
+ data
+ FROM
+ {table}_data
+ WHERE
+ name = 'queuesize'
+ )
+ )
+ )
+ )
+ ELSE position
+ END
+ ),
+ time_remaining = time_remaining - (? - last_available)
+ WHERE
+ twitch_id = ?
+ AND available = 0;
+ """,
+ (
+ twitch_id,
+ twitch_id,
+ 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(f"DELETE FROM {table} 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()
+
+
+def parse(query):
+ query = query.split()
+ try:
+ if query[1].lower() in {"ow", "overwatch", "ow2", "overwatch2"}:
+ return {"--game": "ow"}
+ except:
+ pass
+ return {"--game": "lol_queue"}
+ d = dict()
+ for i in shlex.split(query):
+ try:
+ d[i.split('=')[0]] = i.split('=')[1]
+ except:
+ pass
+ return d
+
+
+def scrub(table_name):
+ return ''.join(chr for chr in table_name if chr.isalnum() or chr == '_')
+
+
+def main(bot: Bot, message: Message):
+ args = " ".join(message.value.split(" ")[1:])
+ args = parse(args)
+ here(bot, message, scrub(args.get("--game", "lol_queue")))
--- /dev/null
+from aptbot.bot import Message, Commands, Bot
+import os
+import logging
+import ttv_api.users
+import sqlite3
+import shlex
+
+logger = logging.getLogger(__name__)
+
+PERMISSION = 99
+PREFIX = "?"
+DESCRIPTION = r"Joins the queue to play the game with the streamer."
+USER_COOLDOWN = 10
+GLOBAL_COOLDOWN = 0
+
+PATH = os.path.dirname(os.path.realpath(__file__))
+PATH = os.path.join(PATH, "..")
+
+DEFAULT_TIME_REMAINING = 60 * 60
+
+
+def join(bot: Bot, message: Message, table: str):
+ 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(
+ f"""
+ SELECT position FROM {table} ORDER BY position DESC;
+ """
+ )
+
+ try:
+ last_position: int = c.fetchone()[0]
+ except TypeError:
+ last_position: int = -1
+
+ try:
+ c.execute(
+ f"""
+ INSERT INTO {table} (
+ "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()
+
+
+def parse(query):
+ query = query.split()
+ try:
+ if query[0].lower() in {"ow", "overwatch", "ow2", "overwatch2"}:
+ return {"--game": "ow"}
+ except:
+ pass
+ return {"--game": "lol_queue"}
+ d = dict()
+ for i in shlex.split(query):
+ try:
+ d[i.split('=')[0]] = i.split('=')[1]
+ except:
+ pass
+ return d
+
+
+def scrub(table_name):
+ return ''.join(chr for chr in table_name if chr.isalnum() or chr == '_')
+
+
+def main(bot: Bot, message: Message):
+ args = " ".join(message.value.split(" ")[1:])
+ args = parse(args)
+ join(bot, message, scrub(args.get("--game", "lol_queue")))
--- /dev/null
+from aptbot.bot import Message, Commands, Bot
+import tools.smart_privmsg
+import urllib3
+import json
+
+PERMISSION = 99
+PREFIX = "?"
+DESCRIPTION = r""
+USER_COOLDOWN = 30
+GLOBAL_COOLDOWN = 30
+
+header = {
+ "Accept": "application/json",
+ "User-Agent": "For my twitch bot [MurphyAI] on https://twitch.tv/ihaspeks",
+}
+
+
+def main(bot: Bot, message: Message):
+ http = urllib3.PoolManager()
+ r = http.request("GET", "https://icanhazdadjoke.com", headers=header)
+ if r.status != 200:
+ tools.smart_privmsg.send(
+ bot, message, f"Couldn't get a joke Sadge", reply=message.tags["id"]
+ )
+ return
+
+ data = json.loads(r.data.decode("utf-8"))
+ tools.smart_privmsg.send(bot, message, f"{data['joke']}", reply=message.tags["id"])
--- /dev/null
+from aptbot.bot import Message, Commands, Bot
+import tools.smart_start_stream_time
+from datetime import datetime
+import datetime as dt
+
+PERMISSION = 99
+PREFIX = "?"
+DESCRIPTION = ""
+USER_COOLDOWN = 15
+GLOBAL_COOLDOWN = 5
+
+STREAM_SCHEDULE = dt.time(18, 30)
+
+
+def main(bot: Bot, message: Message):
+ start_stream_ts = tools.smart_start_stream_time.start_stream_timestamp()
+ if not start_stream_ts:
+ return
+ start_stream_dt = datetime.utcfromtimestamp(start_stream_ts)
+ stream_schedule_dt = datetime.combine(
+ datetime.utcfromtimestamp(start_stream_ts), STREAM_SCHEDULE
+ )
+ latege_amount = (start_stream_dt - stream_schedule_dt).total_seconds()
+ if latege_amount > 45 * 60:
+ msg = f"{message.channel} is so Latege he might as well have not \
+ streamed today. At least he's early for tomorrow COPIUM . \
+ {message.channel} is Latege by {latege_amount} seconds Madge"
+ elif latege_amount > 0:
+ msg = f"{message.channel} is Latege by {latege_amount} seconds again Madge"
+ elif latege_amount == 0:
+ msg = f"Amazing!!! {message.channel} is EXACTLY on time today POGGERS"
+ else:
+ msg = f"UNBELIEVABLE!!!!! {message.channel} is EARLY by {-latege_amount} seconds!!!!\
+ This has NEVER happened before POGGERS"
+ bot.send_privmsg(message.channel, msg)
--- /dev/null
+from aptbot.bot import Message, Commands, Bot
+import os
+import logging
+import ttv_api.users
+import sqlite3
+import shlex
+
+logger = logging.getLogger(__name__)
+
+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 leave(bot: Bot, message: Message, table: str):
+ 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(
+ f"""
+ DELETE FROM {table} 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()
+
+
+def parse(query):
+ query = query.split()
+ try:
+ if query[0].lower() in {"ow", "overwatch", "ow2", "overwatch2"}:
+ return {"--game": "ow"}
+ except:
+ pass
+ return {"--game": "lol_queue"}
+ d = dict()
+ for i in shlex.split(query):
+ try:
+ d[i.split('=')[0]] = i.split('=')[1]
+ except:
+ pass
+ return d
+
+
+def scrub(table_name):
+ return ''.join(chr for chr in table_name if chr.isalnum() or chr == '_')
+
+
+def main(bot: Bot, message: Message):
+ args = " ".join(message.value.split(" ")[1:])
+ args = parse(args)
+ leave(bot, message, scrub(args.get("--game", "lol_queue")))
--- /dev/null
+from aptbot.bot import Message, Commands, Bot
+import os
+import logging
+import ttv_api.users
+import sqlite3
+import shlex
+
+logger = logging.getLogger(__name__)
+
+PERMISSION = 10
+PREFIX = "\\"
+DESCRIPTION = r"Move the user down one row in the queue."
+USER_COOLDOWN = 0
+GLOBAL_COOLDOWN = 0
+
+PATH = os.path.dirname(os.path.realpath(__file__))
+PATH = os.path.join(PATH, "..")
+
+
+def move_down(bot: Bot, message: Message, table: str):
+ 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 moved down in 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()
+
+ try:
+ c.execute(
+ f"""
+ UPDATE
+ {table}
+ SET
+ position = (
+ SELECT
+ min(position)
+ FROM
+ {table}
+ WHERE
+ position > (
+ SELECT
+ position
+ FROM
+ {table}
+ WHERE
+ twitch_id = ?
+ )
+ ) + (
+ SELECT
+ position
+ FROM
+ {table}
+ WHERE
+ twitch_id = ?
+ ) - position
+ WHERE
+ position in (
+ (
+ SELECT
+ min(position)
+ FROM
+ {table}
+ WHERE
+ position > (
+ SELECT
+ position
+ FROM
+ {table}
+ WHERE
+ twitch_id = ?
+ )
+ ),
+ (
+ SELECT
+ position
+ FROM
+ {table}
+ WHERE
+ twitch_id = ?
+ )
+ );
+ """,
+ (twitch_id,) * 4,
+ )
+ except sqlite3.IntegrityError:
+ bot.send_privmsg(
+ message.channel, "Can't move user down further", reply=message.tags["id"]
+ )
+ conn.close()
+ return
+ conn.commit()
+ bot.send_privmsg(
+ message.channel, "Successfully moved them down.", reply=message.tags["id"]
+ )
+ conn.close()
+
+
+def parse(query):
+ query = query.split()
+ try:
+ if query[1].lower() in {"ow", "overwatch", "ow2", "overwatch2"}:
+ return {"--game": "ow"}
+ except:
+ pass
+ return {"--game": "lol_queue"}
+ d = dict()
+ for i in shlex.split(query):
+ try:
+ d[i.split('=')[0]] = i.split('=')[1]
+ except:
+ pass
+ return d
+
+
+def scrub(table_name):
+ return ''.join(chr for chr in table_name if chr.isalnum() or chr == '_')
+
+
+def main(bot: Bot, message: Message):
+ args = " ".join(message.value.split(" ")[1:])
+ args = parse(args)
+ move_down(bot, message, scrub(args.get("--game", "lol_queue")))
--- /dev/null
+from aptbot.bot import Message, Commands, Bot
+import os
+import logging
+import ttv_api.users
+import sqlite3
+import shlex
+
+logger = logging.getLogger(__name__)
+
+PERMISSION = 10
+PREFIX = "\\"
+DESCRIPTION = r"Move the user up one row in the queue."
+USER_COOLDOWN = 0
+GLOBAL_COOLDOWN = 0
+
+PATH = os.path.dirname(os.path.realpath(__file__))
+PATH = os.path.join(PATH, "..")
+
+
+def move_up(bot: Bot, message: Message, table: str):
+ 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 moved up in 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()
+
+ try:
+ c.execute(
+ f"""
+ UPDATE
+ {table}
+ SET
+ position = (
+ SELECT
+ max(position)
+ FROM
+ {table}
+ WHERE
+ position < (
+ SELECT
+ position
+ FROM
+ {table}
+ WHERE
+ twitch_id = ?
+ )
+ ) + (
+ SELECT
+ position
+ FROM
+ {table}
+ WHERE
+ twitch_id = ?
+ ) - position
+ WHERE
+ position in (
+ (
+ SELECT
+ max(position)
+ FROM
+ {table}
+ WHERE
+ position < (
+ SELECT
+ position
+ FROM
+ {table}
+ WHERE
+ twitch_id = ?
+ )
+ ),
+ (
+ SELECT
+ position
+ FROM
+ {table}
+ WHERE
+ twitch_id = ?
+ )
+ );
+ """,
+ (twitch_id,) * 4,
+ )
+ except sqlite3.IntegrityError:
+ bot.send_privmsg(
+ message.channel, "Can't move user up further", reply=message.tags["id"]
+ )
+ conn.close()
+ return
+ conn.commit()
+ bot.send_privmsg(
+ message.channel, "Successfully moved them up.", reply=message.tags["id"]
+ )
+ conn.close()
+
+
+def parse(query):
+ query = query.split()
+ try:
+ if query[1].lower() in {"ow", "overwatch", "ow2", "overwatch2"}:
+ return {"--game": "ow"}
+ except:
+ pass
+ return {"--game": "lol_queue"}
+ d = dict()
+ for i in shlex.split(query):
+ try:
+ d[i.split('=')[0]] = i.split('=')[1]
+ except:
+ pass
+ return d
+
+
+def scrub(table_name):
+ return ''.join(chr for chr in table_name if chr.isalnum() or chr == '_')
+
+
+def main(bot: Bot, message: Message):
+ args = " ".join(message.value.split(" ")[1:])
+ args = parse(args)
+ move_up(bot, message, scrub(args.get("--game", "lol_queue")))
--- /dev/null
+from aptbot.bot import Message, Commands, Bot
+import os
+import logging
+import ttv_api.users
+import sqlite3
+import random
+import shlex
+
+logger = logging.getLogger(__name__)
+
+PERMISSION = 10
+PREFIX = "\\"
+DESCRIPTION = r"Check who's currently in queue."
+USER_COOLDOWN = 0
+GLOBAL_COOLDOWN = 0
+
+PATH = os.path.dirname(os.path.realpath(__file__))
+PATH = os.path.join(PATH, "..")
+
+
+def new_teams(bot: Bot, message: Message, table: str):
+ conn = sqlite3.connect(os.path.join(PATH, "lol_data.db"))
+ c = conn.cursor()
+
+ c.execute(
+ f"""
+ SELECT twitch_id FROM {table} WHERE available = 1 ORDER BY position ASC;
+ """
+ )
+ fetched = c.fetchall()
+ queue: list[str] = [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_users: list[ttv_api.users.User] = []
+ for twitch_id in queue:
+ for twitch_user in twitch:
+ if int(twitch_user.user_id) == int(twitch_id):
+ queue_users.append(twitch_user)
+ 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(
+ f"""
+ SELECT data FROM {table}_data WHERE name = 'queuesize';
+ """
+ )
+ fetched = c.fetchone()
+ try:
+ queue_size = fetched[0]
+ except TypeError:
+ queue_size = 10
+ bot.send_privmsg(
+ message.channel,
+ f"There was an issue fetching the queue size, default set to {queue_size}",
+ reply=message.tags["id"],
+ )
+
+ if len(queue_users) < queue_size:
+ bot.send_privmsg(
+ message.channel,
+ f"There aren't enough people in the queue. Current team size is {queue_size} while there are only {len(queue_users)} in queue.",
+ reply=message.tags["id"],
+ )
+
+ queue_users: list[ttv_api.users.User] = queue_users[:queue_size]
+ random.shuffle(queue_users)
+ blue_team: list[ttv_api.users.User] = queue_users[: queue_size // 2]
+ red_team: list[ttv_api.users.User] = queue_users[queue_size // 2 :]
+
+ c.execute(f"UPDATE {table} SET team = NULL")
+ sql = f"UPDATE {table} SET team = 0 WHERE twitch_id IN ({(', ?' * (queue_size // 2))[2:]})"
+ c.execute(sql, tuple(user.user_id for user in blue_team))
+ sql = f"UPDATE {table} SET team = 1 WHERE twitch_id IN ({(', ?' * (queue_size - queue_size // 2))[2:]})"
+ c.execute(sql, tuple(user.user_id for user in red_team))
+ conn.commit()
+
+ blue_team_users: list[str] = [user.display_name for user in blue_team]
+ red_team_users: list[str] = [user.display_name for user in red_team]
+
+ bot.send_privmsg(
+ message.channel,
+ [f"Blue team is: {blue_team_users}", f"Red team is: {red_team_users}"],
+ reply=message.tags["id"],
+ )
+
+ conn.close()
+
+
+def parse(query):
+ query = query.split()
+ try:
+ if query[1].lower() in {"ow", "overwatch", "ow2", "overwatch2"}:
+ return {"--game": "ow"}
+ except:
+ pass
+ return {"--game": "lol_queue"}
+ d = dict()
+ for i in shlex.split(query):
+ try:
+ d[i.split('=')[0]] = i.split('=')[1]
+ except:
+ pass
+ return d
+
+
+def scrub(table_name):
+ return ''.join(chr for chr in table_name if chr.isalnum() or chr == '_')
+
+
+def main(bot: Bot, message: Message):
+ args = " ".join(message.value.split(" ")[1:])
+ args = parse(args)
+ new_teams(bot, message, scrub(args.get("--game", "lol_queue")))
--- /dev/null
+from aptbot.bot import Message, Commands, Bot
+import os
+import logging
+import ttv_api.users
+import sqlite3
+import time
+import shlex
+
+logger = logging.getLogger(__name__)
+
+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 not_here(bot: Bot, message: Message, table: str):
+ 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(
+ f"""
+ UPDATE {table} SET available = 0, priority_queue = null, 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()
+
+
+def parse(query):
+ query = query.split()
+ try:
+ if query[1].lower() in {"ow", "overwatch", "ow2", "overwatch2"}:
+ return {"--game": "ow"}
+ except:
+ pass
+ return {"--game": "lol_queue"}
+ d = dict()
+ for i in shlex.split(query):
+ try:
+ d[i.split('=')[0]] = i.split('=')[1]
+ except:
+ pass
+ return d
+
+
+def scrub(table_name):
+ return ''.join(chr for chr in table_name if chr.isalnum() or chr == '_')
+
+
+def main(bot: Bot, message: Message):
+ args = " ".join(message.value.split(" ")[1:])
+ args = parse(args)
+ not_here(bot, message, scrub(args.get("--game", "lol_queue")))
--- /dev/null
+from aptbot.bot import Message, Commands, Bot
+import sqlite3
+import os
+import logging
+from lol_api import spectator_v4
+from lol_api import summoner_v4
+import ttv_api.users
+from tools import smart_privmsg
+import json
+
+logger = logging.getLogger(__name__)
+
+
+PERMISSION = 99
+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 find_champion(champ_id: int) -> str:
+ with open(os.path.join(PATH, "data/champion.json"), "r") as f:
+ champion_data = json.load(f)
+ champ_id = str(champ_id)
+ champion_data = champion_data["data"]
+ for champion in champion_data:
+ if champion_data[champion]["key"] == champ_id:
+ return champion_data[champion]["name"]
+ return "404"
+
+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]
+ 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]),
+ )
+ 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"]
+ )
+ return
+
+ if not isinstance(twitch_id, str):
+ twitch_id = int(twitch_id[0].user_id)
+ else:
+ twitch_id = int(twitch_id)
+ db_name_database = "lol_data.db"
+ conn = sqlite3.connect(os.path.join(PATH, db_name_database))
+ c = conn.cursor()
+
+ c.execute(
+ """
+ SELECT summoner_id, puuid FROM accounts WHERE twitch_id = ?;
+ """,
+ (twitch_id,),
+ )
+ fetched = c.fetchall()
+ c.execute(
+ """
+ SELECT twitch_id, summoner_id FROM accounts;
+ """,
+ )
+ fetched_all = c.fetchall()
+
+ if not fetched:
+ 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])
+ summoner = summoner_v4.get_summoner_from_puuid(summoners[1])
+ if summoner:
+ summoner_names.append(summoner.name)
+ 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"],
+ )
+ conn.close()
+ return
+
+ play_with = []
+ for summoner in info.participants:
+ for f in fetched_all:
+ if summoner.summoner_id == f[1] and summoner.summoner_id != fetched[0][0]:
+ play_with.append(
+ {
+ "name": ttv_api.users.get_users(user_ids=[f[0]])[0].display_name,
+ "champion": find_champion(summoner.champion_id),
+ },
+ )
+ break
+ msg = f"{twitch_user} is currently playing a game on: {summoner_names[-1]}"
+ if play_with:
+ msg += " and is playing with"
+ for player in play_with:
+ msg += f" {player['name']} on {player['champion']} |"
+ msg = msg[:-1] + "."
+
+ smart_privmsg.send(
+ bot,
+ message,
+ msg,
+ 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 tools.smart_privmsg
+import random
+import shlex
+
+logger = logging.getLogger(__name__)
+
+PERMISSION = 99
+PREFIX = "?"
+DESCRIPTION = r"Sekiro death counter"
+USER_COOLDOWN = 10
+GLOBAL_COOLDOWN = 5
+
+PATH = os.path.dirname(os.path.realpath(__file__))
+PATH = os.path.join(PATH, "..")
+
+def check_queue(bot: Bot, message: Message, table: str):
+ conn = sqlite3.connect(os.path.join(PATH, "database.db"))
+ c = conn.cursor()
+
+ c.execute(
+ f"""
+ SELECT id, val FROM varvalues WHERE id = 'penta';
+ """
+ )
+ _, val = c.fetchone()
+
+ if table == "show":
+ msg = f"Peks has gotten {val} pentas!"
+
+ tools.smart_privmsg.send(
+ bot,
+ message,
+ msg,
+ reply=message.tags["id"],
+ )
+
+ conn.close()
+ return
+ if table == "remove":
+ val = val - 1
+ c.execute(
+ f"""
+ UPDATE varvalues SET val = ? WHERE id = 'cannon';
+ """,
+ (val,)
+ )
+
+ msg = f"Peks has gotten {val} pentas!"
+
+ tools.smart_privmsg.send(
+ bot,
+ message,
+ msg,
+ reply=message.tags["id"],
+ )
+ conn.commit()
+ conn.close()
+ return
+ if table == "add":
+ val = val + 1
+ c.execute(
+ f"""
+ UPDATE varvalues SET val = ? WHERE id = 'cannon';
+ """,
+ (val,)
+ )
+
+ msg = f"Peks has gotten {val} pentas!"
+
+ tools.smart_privmsg.send(
+ bot,
+ message,
+ msg,
+ reply=message.tags["id"],
+ )
+ conn.commit()
+ conn.close()
+ return
+
+
+def parse(query):
+ query = query.split()
+ try:
+ if query[0].lower() == "add":
+ return {"--do": "add"}
+ if query[0].lower() == "remove":
+ return {"--do": "remove"}
+ except:
+ pass
+ return {"--game": "show"}
+ d = dict()
+ for i in shlex.split(query):
+ try:
+ d[i.split('=')[0]] = i.split('=')[1]
+ except:
+ pass
+ return d
+
+
+def scrub(table_name):
+ return ''.join(chr for chr in table_name if chr.isalnum() or chr == '_')
+
+
+def main(bot: Bot, message: Message):
+ args = " ".join(message.value.split(" ")[1:])
+ args = parse(args)
+ check_queue(bot, message, scrub(args.get("--do", "show")))
--- /dev/null
+from aptbot.bot import Message, Commands, Bot
+import os
+import logging
+import ttv_api.users
+import sqlite3
+import tools.smart_privmsg
+import random
+import shlex
+
+logger = logging.getLogger(__name__)
+
+PERMISSION = 99
+PREFIX = "?"
+DESCRIPTION = r"Sekiro death counter"
+USER_COOLDOWN = 10
+GLOBAL_COOLDOWN = 5
+
+PATH = os.path.dirname(os.path.realpath(__file__))
+PATH = os.path.join(PATH, "..")
+
+def check_queue(bot: Bot, message: Message, table: str):
+ conn = sqlite3.connect(os.path.join(PATH, "database.db"))
+ c = conn.cursor()
+
+ c.execute(
+ f"""
+ SELECT id, val FROM varvalues WHERE id = 'quadra';
+ """
+ )
+ _, val = c.fetchone()
+
+ if table == "show":
+ msg = f"Peks has missed out on {val} pentas!"
+
+ tools.smart_privmsg.send(
+ bot,
+ message,
+ msg,
+ reply=message.tags["id"],
+ )
+
+ conn.close()
+ return
+ if table == "remove":
+ val = val - 1
+ c.execute(
+ f"""
+ UPDATE varvalues SET val = ? WHERE id = 'cannon';
+ """,
+ (val,)
+ )
+
+ msg = f"Peks has missed out on {val} pentas!"
+
+ tools.smart_privmsg.send(
+ bot,
+ message,
+ msg,
+ reply=message.tags["id"],
+ )
+ conn.commit()
+ conn.close()
+ return
+ if table == "add":
+ val = val + 1
+ c.execute(
+ f"""
+ UPDATE varvalues SET val = ? WHERE id = 'cannon';
+ """,
+ (val,)
+ )
+
+ msg = f"Peks has missed out on {val} pentas!"
+
+ tools.smart_privmsg.send(
+ bot,
+ message,
+ msg,
+ reply=message.tags["id"],
+ )
+ conn.commit()
+ conn.close()
+ return
+
+
+def parse(query):
+ query = query.split()
+ try:
+ if query[0].lower() == "add":
+ return {"--do": "add"}
+ if query[0].lower() == "remove":
+ return {"--do": "remove"}
+ except:
+ pass
+ return {"--game": "show"}
+ d = dict()
+ for i in shlex.split(query):
+ try:
+ d[i.split('=')[0]] = i.split('=')[1]
+ except:
+ pass
+ return d
+
+
+def scrub(table_name):
+ return ''.join(chr for chr in table_name if chr.isalnum() or chr == '_')
+
+
+def main(bot: Bot, message: Message):
+ args = " ".join(message.value.split(" ")[1:])
+ args = parse(args)
+ check_queue(bot, message, scrub(args.get("--do", "show")))
--- /dev/null
+from aptbot.bot import Message, Commands, Bot
+import sqlite3
+import os
+
+PERMISSION = 10
+PREFIX = "\\"
+DESCRIPTION = ""
+USER_COOLDOWN = 0
+GLOBAL_COOLDOWN = 0
+
+COMMANDS_PATH = os.path.dirname(os.path.realpath(__file__))
+PATH = os.path.join(COMMANDS_PATH, "..")
+
+
+def main(bot: Bot, message: Message):
+ msg = " ".join(message.value.split(" ")[1:])
+ command = msg.split(" ")[0]
+ command_prefix = command[0]
+ command_name = command[1:]
+
+ conn = sqlite3.connect(os.path.join(PATH, "database.db"))
+ c = conn.cursor()
+ c.execute("SELECT value FROM command_values WHERE command = ?", (command_name,))
+ command_path = os.path.join(COMMANDS_PATH, f"{command_name}.py")
+ hidden_command_path = os.path.join(COMMANDS_PATH, f".{command_name}.py")
+ try:
+ if not c.fetchone()[0]:
+ try:
+ os.rename(command_path, hidden_command_path)
+ except FileNotFoundError:
+ pass
+ except TypeError:
+ pass
+
+ try:
+ c.execute(
+ "DELETE FROM commands WHERE command = ? AND prefix = ?",
+ (
+ command_name,
+ command_prefix,
+ ),
+ )
+ except sqlite3.IntegrityError:
+ bot.send_privmsg(message.channel, f"The command {command_name} doesn't exist.")
+ else:
+ bot.send_privmsg(message.channel, f"Successfully removed {command_name}.")
+ conn.commit()
+ conn.close()
--- /dev/null
+from aptbot.bot import Message, Commands, Bot
+
+PERMISSION = 99
+PREFIX = "?"
+DESCRIPTION = ""
+USER_COOLDOWN = 10
+GLOBAL_COOLDOWN = 10
+
+
+def main(bot: Bot, message: Message):
+ msg = message.nick + " you have been scammed KEKW"
+ bot.send_privmsg(message.channel, msg)
--- /dev/null
+from aptbot.bot import Message, Commands, Bot
+import tools.smart_privmsg
+
+PERMISSION = 99
+PREFIX = "?"
+DESCRIPTION = ""
+USER_COOLDOWN = 30
+GLOBAL_COOLDOWN = 15
+
+MAX_LENGTH = 450
+
+
+def main(bot: Bot, message: Message):
+ try:
+ replied_message = message.tags["reply-parent-msg-body"]
+ except KeyError:
+ replied_message = None
+ if replied_message:
+ msg = replied_message
+ else:
+ msg = " ".join(message.value.split(" ")[1:])
+ new_msg = ""
+ while len(new_msg) + len(msg) < MAX_LENGTH:
+ new_msg += msg + " "
+ tools.smart_privmsg.send_safe(bot, message.channel, new_msg)
--- /dev/null
+from aptbot.bot import Message, Commands, Bot
+import tools.smart_privmsg
+import scripts.translator
+
+PERMISSION = 99
+PREFIX = "?"
+DESCRIPTION = "Translates a message from any language (supported by google translate) into English. How to use: ?t <insert text to translate>"
+USER_COOLDOWN = 15
+GLOBAL_COOLDOWN = 5
+
+
+def main(bot: Bot, message: Message):
+ replied_message = message.tags.get("reply-parent-msg-body", None)
+ if replied_message:
+ msg = replied_message
+ replied_msg_id = message.tags["reply-parent-msg-id"]
+ else:
+ msg = " ".join(message.value.split(" ")[1:])
+ replied_msg_id = None
+ trans = scripts.translator.translate(msg)
+ print(trans)
+ tools.smart_privmsg.send(bot, message, trans, reply=replied_msg_id)
--- /dev/null
+from aptbot.bot import Message, Commands, Bot
+import os
+import logging
+import ttv_api.users
+import sqlite3
+import tools.smart_privmsg
+import shlex
+
+logger = logging.getLogger(__name__)
+
+PERMISSION = 99
+PREFIX = "?"
+DESCRIPTION = r"Check current teams"
+USER_COOLDOWN = 30
+GLOBAL_COOLDOWN = 15
+
+PATH = os.path.dirname(os.path.realpath(__file__))
+PATH = os.path.join(PATH, "..")
+
+
+def teams(bot: Bot, message: Message, table: str):
+ conn = sqlite3.connect(os.path.join(PATH, "lol_data.db"))
+ c = conn.cursor()
+
+ c.execute(
+ f"""
+ SELECT twitch_id, team FROM {table} WHERE team in (0, 1);
+ """
+ )
+ fetched = c.fetchall()
+ blue_team = []
+ red_team = []
+ for user in fetched:
+ if user[1] == 0:
+ blue_team.append(user[0])
+ elif user[1] == 1:
+ red_team.append(user[0])
+ else:
+ bot.send_privmsg(
+ message.channel,
+ f"Something VERY WEIRD occured. The user with id: {user[0]} is on team {user[1]}, which is neither blue = 0 or red = 1.",
+ reply=message.tags["id"],
+ )
+
+ users = [x[0] for x in fetched]
+ if not users:
+ bot.send_privmsg(
+ message.channel,
+ "No teams have been set yet.",
+ reply=message.tags["id"],
+ )
+ conn.close()
+ return
+
+ twitch = ttv_api.users.get_users(user_ids=users)
+ if not twitch:
+ bot.send_privmsg(
+ message.channel,
+ "There was an issue fetching twitch data. Sadge",
+ reply=message.tags["id"],
+ )
+ conn.close()
+ return
+ blue_team_users = []
+ red_team_users = []
+ for twitch_user in twitch:
+ if int(twitch_user.user_id) in blue_team:
+ blue_team_users.append(twitch_user.display_name)
+ elif int(twitch_user.user_id) in red_team:
+ red_team_users.append(twitch_user.display_name)
+ else:
+ bot.send_privmsg(
+ message.channel,
+ f"Something VERY WEIRD occured. The user with id: {twitch_user.user_id} who has the name {twitch_user.display_name} is not on a team.",
+ reply=message.tags["id"],
+ )
+
+ bot.send_privmsg(
+ message.channel,
+ [f"Blue team is: {blue_team_users}", f"Red team is: {red_team_users}"],
+ reply=message.tags["id"],
+ )
+
+ conn.close()
+
+
+def parse(query):
+ query = query.split()
+ try:
+ if query[1].lower() in {"ow", "overwatch", "ow2", "overwatch2"}:
+ return {"--game": "ow"}
+ except:
+ pass
+ return {"--game": "lol_queue"}
+ d = dict()
+ for i in shlex.split(query):
+ try:
+ d[i.split('=')[0]] = i.split('=')[1]
+ except:
+ pass
+ return d
+
+
+def scrub(table_name):
+ return ''.join(chr for chr in table_name if chr.isalnum() or chr == '_')
+
+
+def main(bot: Bot, message: Message):
+ args = " ".join(message.value.split(" ")[1:])
+ args = parse(args)
+ teams(bot, message, scrub(args.get("--game", "lol_queue")))
--- /dev/null
+from aptbot.bot import Message, Commands, Bot
+import os
+import logging
+import sqlite3
+import shlex
+
+logger = logging.getLogger(__name__)
+
+PERMISSION = 10
+PREFIX = "\\"
+DESCRIPTION = r"Change the team size"
+USER_COOLDOWN = 0
+GLOBAL_COOLDOWN = 0
+
+PATH = os.path.dirname(os.path.realpath(__file__))
+PATH = os.path.join(PATH, "..")
+
+
+def team_size(bot: Bot, message: Message, table: str):
+ 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(
+ f"""
+ REPLACE INTO {table}_data (name, data) VALUES ('queuesize', ?)
+ """,
+ (queue_size,),
+ )
+ conn.commit()
+
+ bot.send_privmsg(
+ message.channel,
+ f"Successfully changed team size to {queue_size}.",
+ reply=message.tags["id"],
+ )
+
+ conn.close()
+
+
+def parse(query):
+ query = query.split()
+ try:
+ if query[0].lower() in {"ow", "overwatch", "ow2", "overwatch2"}:
+ return {"--game": "ow"}
+ except:
+ pass
+ return {"--game": "lol_queue"}
+ d = dict()
+ for i in shlex.split(query):
+ try:
+ d[i.split('=')[0]] = i.split('=')[1]
+ except:
+ pass
+ return d
+
+
+def scrub(table_name):
+ return ''.join(chr for chr in table_name if chr.isalnum() or chr == '_')
+
+
+def main(bot: Bot, message: Message):
+ args = " ".join(message.value.split(" ")[1:])
+ args = parse(args)
+ team_size(bot, message, scrub(args.get("--game", "lol_queue")))
--- /dev/null
+from aptbot.bot import Message, Commands, Bot
+import tools.smart_privmsg
+import os
+import random
+
+PERMISSION = 99
+PREFIX = "?"
+DESCRIPTION = ""
+USER_COOLDOWN = 30
+GLOBAL_COOLDOWN = 15
+
+
+COMMANDS_PATH = os.path.dirname(os.path.realpath(__file__))
+PATH = os.path.join(COMMANDS_PATH, "..")
+DATA_PATH = os.path.join(PATH, "data")
+
+
+def main(bot: Bot, message: Message):
+ accepted_path = os.path.join(DATA_PATH, "jokes")
+ with open(accepted_path, "r") as f:
+ jokes = [user_id.rstrip() for user_id in f]
+ joke = random.choice(jokes)
+
+ tools.smart_privmsg.send(bot, message, f"{joke}", reply=message.tags["id"])
--- /dev/null
+from aptbot.bot import Message, Commands, Bot
+import os
+import logging
+from tools import smart_privmsg
+
+logger = logging.getLogger(__name__)
+
+
+PERMISSION = 99
+PREFIX = "?"
+DESCRIPTION = ""
+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):
+ if message.tags.get("reply-parent-display-name", None):
+ smart_privmsg.send(
+ bot,
+ message,
+ f"{message.tags['reply-parent-display-name']}, {message.nick} is UwUing you. Will you UwU back? PauseChamp",
+ reply=message.tags["reply-parent-msg-id"],
+ )
+ return
+ try:
+ user = message.value.split(" ")[1]
+ except IndexError:
+ smart_privmsg.send(
+ bot, message, f"UwU to you too {message.nick}!", reply=message.tags["id"]
+ )
+ return
+ else:
+ smart_privmsg.send(
+ bot,
+ message,
+ f"{user}, {message.nick} is UwUing you. Will you UwU back? PauseChamp",
+ )
+ return
--- /dev/null
+from aptbot.bot import Message, Commands, Bot
+import yt_api.videos
+
+PERMISSION = 99
+PREFIX = "?"
+DESCRIPTION = "Get my newest video! Just type ?video"
+USER_COOLDOWN = 15
+GLOBAL_COOLDOWN = 15
+
+CHANNEL_ID = "UCQ7C3NUKY6TSkURdUdVoYFw"
+
+
+def main(bot: Bot, message: Message):
+ video = yt_api.videos.get_newest_video(CHANNEL_ID)
+ if video:
+ video_link = f"https://www.youtube.com/watch?v={video.video_id}"
+ msg = f'Watch Peks\' latest video "{video.video_name}" here: {video_link}'
+ else:
+ msg = f"Check out my youtube channel here -> https://www.youtube.com/channel/{CHANNEL_ID}"
+ bot.send_privmsg(message.channel, msg)
--- /dev/null
+from aptbot.bot import Message, Commands
+import sqlite3
+import os
+import ttv_api.users
+import logging
+
+logger = logging.getLogger(__name__)
+
+PATH = os.path.dirname(os.path.realpath(__file__))
+logger.debug(f"PATH set to: {PATH}")
+
+STREAMER_PATH = os.path.abspath(os.path.join(__file__, ".."))
+logger.debug(f"STREAMER_PATH set to: {STREAMER_PATH}")
+streamer_login = os.path.split(STREAMER_PATH)[1]
+logger.debug(f"streamer_login set to: {streamer_login}")
+
+
+def create_variables_db():
+ db_name_var = "variables.db"
+ conn = sqlite3.connect(os.path.join(PATH, db_name_var))
+ c = conn.cursor()
+ logger.info(f"connected to database {db_name_var}")
+
+ c.execute(
+ """
+ CREATE TABLE IF NOT EXISTS variables (
+ name TEXT NOT NULL,
+ type TEXT NOT NULL,
+ value TEXT NOT NULL,
+ PRIMARY KEY (name)
+ )
+ """
+ )
+ logger.info(f"created table variables")
+
+ c.execute(
+ """
+ CREATE TABLE IF NOT EXISTS methods (
+ name TEXT NOT NULL,
+ type TEXT NOT NULL,
+ input TEXT,
+ PRIMARY KEY (name, type)
+ )
+ """
+ )
+ logger.info(f"created table methods")
+
+ c.execute(
+ """
+ CREATE TABLE IF NOT EXISTS list_values (
+ id INTEGER NOT NULL,
+ name TEXT NOT NULL,
+ type TEXT NOT NULL,
+ value TEXT NOT NULL,
+ FOREIGN KEY(name) REFERENCES variables(name)
+ PRIMARY KEY (id, name)
+ )
+ """
+ )
+ logger.info(f"created table list_values")
+
+ conn.commit()
+ conn.close()
+
+
+def create_lol_database():
+ db_name_database = "lol_data.db"
+ conn = sqlite3.connect(os.path.join(PATH, db_name_database))
+ c = conn.cursor()
+ logger.info(f"connected to database {db_name_database}")
+
+ c.execute(
+ """
+ CREATE TABLE IF NOT EXISTS accounts (
+ puuid TEXT NOT NULL,
+ summoner_id TEXT NOT NULL,
+ account_id TEXT NOT NULL,
+ twitch_id INTEGER,
+ PRIMARY KEY (puuid)
+ )
+ """
+ )
+ logger.info(f"created table accounts")
+
+ c.execute(
+ """
+ CREATE TABLE IF NOT EXISTS lol_queue (
+ twitch_id INTEGER NOT NULL,
+ position INTEGER NOT NULL,
+ available INTEGER NOT NULL,
+ last_available INTEGER,
+ time_remaining INTEGER NOT NULL,
+ team INTEGER,
+ priority_queue INTEGER,
+ 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")
+
+ c.execute(
+ """
+ CREATE TABLE IF NOT EXISTS ow (
+ twitch_id INTEGER NOT NULL,
+ position INTEGER NOT NULL,
+ available INTEGER NOT NULL,
+ last_available INTEGER,
+ time_remaining INTEGER NOT NULL,
+ team INTEGER,
+ priority_queue INTEGER,
+ PRIMARY KEY (twitch_id)
+ );
+ """
+ )
+ logger.info(f"created table ow")
+
+ c.execute(
+ """
+ CREATE TABLE IF NOT EXISTS ow_data (
+ name TEXT NOT NULL,
+ data INTEGER NOT NULL,
+ PRIMARY KEY (name)
+ );
+ """
+ )
+ logger.info(f"created table ow_data")
+
+ conn.commit()
+ conn.close()
+
+
+def create_database():
+ db_name_database = "database.db"
+ conn = sqlite3.connect(os.path.join(PATH, db_name_database))
+ c = conn.cursor()
+ logger.info(f"connected to database {db_name_database}")
+
+ c.execute(
+ """
+ CREATE TABLE IF NOT EXISTS commands (
+ command TEXT NOT NULL,
+ prefix TEXT NOT NULL,
+ permission INTEGER NOT NULL,
+ description TEXT,
+ user_cooldown INTEGER NOT NULL,
+ global_cooldown INTEGER NOT NULL,
+ last_used INTEGER NOT NULL,
+ PRIMARY KEY (command)
+ )
+ """
+ )
+ logger.info(f"created table commands")
+
+ c.execute(
+ """
+ CREATE TABLE IF NOT EXISTS varvalues (
+ id TEXT NOT NULL,
+ val INTEGER NOT NULL,
+ PRIMARY KEY (id)
+ )
+ """
+ )
+ logger.info(f"created table varvalues")
+
+
+ c.execute(
+ """
+ CREATE TABLE IF NOT EXISTS clips (
+ url TEXT NOT NULL,
+ from_user INTEGER NOT NULL,
+ PRIMARY KEY (url)
+ )
+ """
+ )
+ logger.info(f"created table clips")
+
+ c.execute(
+ """
+ CREATE TABLE IF NOT EXISTS users (
+ user_id text NOT NULL,
+ permission INTEGER NOT NULL,
+ PRIMARY KEY (user_id)
+ )
+ """
+ )
+ logger.info(f"created table users")
+
+ admin_id = ttv_api.users.get_users(user_logins=["skgyorugo"])
+ aptbot_id = ttv_api.users.get_users(user_logins=["murphyai"])
+ broadcaster_id = ttv_api.users.get_users(user_logins=[streamer_login])
+ if admin_id:
+ c.execute("INSERT OR IGNORE INTO users VALUES (?, ?)", (admin_id[0].user_id, 0))
+ logger.info(f"inserted user {admin_id[0].user_id} with permission {0}")
+ if aptbot_id:
+ c.execute(
+ "INSERT OR IGNORE INTO users VALUES (?, ?)", (aptbot_id[0].user_id, 0)
+ )
+ logger.info(f"inserted user {aptbot_id[0].user_id} with permission {0}")
+ if broadcaster_id:
+ c.execute(
+ "INSERT OR IGNORE INTO users VALUES (?, ?)", (broadcaster_id[0].user_id, 1)
+ )
+ logger.info(f"inserted user {broadcaster_id[0].user_id} with permission {1}")
+
+ c.execute(
+ """
+ CREATE TABLE IF NOT EXISTS cooldowns (
+ user_id TEXT NOT NULL,
+ command TEXT NOT NULL,
+ user_cooldown INTEGER NOT NULL,
+ FOREIGN KEY(user_id) REFERENCES users(user_id)
+ FOREIGN KEY(command) REFERENCES commands(command)
+ PRIMARY KEY (user_id, command)
+ )
+ """
+ )
+ logger.info(f"created table cooldowns")
+
+ c.execute(
+ """
+ CREATE TABLE IF NOT EXISTS command_values (
+ command TEXT NOT NULL,
+ value TEXT NOT NULL,
+ FOREIGN KEY(command) REFERENCES commands(command)
+ )
+ """
+ )
+ logger.info(f"created table command_values")
+
+ c.execute(
+ """
+ CREATE TABLE IF NOT EXISTS auto_messages (
+ name TEXT NOT NULL,
+ cooldown INTEGER NOT NULL,
+ end_time INTEGER NOT NULL,
+ last_used INTEGER NOT NULL,
+ PRIMARY KEY (name)
+ )
+ """
+ )
+ logger.info(f"created table auto_messages")
+
+ c.execute(
+ """
+ CREATE TABLE IF NOT EXISTS auto_message_values (
+ name TEXT NOT NULL,
+ value TEXT NOT NULL,
+ FOREIGN KEY(name) REFERENCES auto_messages(name)
+ )
+ """
+ )
+ logger.info(f"created table auto_message_values")
+
+ c.execute(
+ """
+ CREATE TABLE IF NOT EXISTS stream_info (
+ start_stream_ts INTEGER NOT NULL,
+ last_checked INTEGER NOT NULL,
+ ended INTEGER NOT NULL,
+ PRIMARY KEY (start_stream_ts)
+ )
+ """
+ )
+ logger.info(f"created table stream_info")
+
+ conn.commit()
+ conn.close()
+
+
+def update_commands_in_database(modules, commands):
+ db_name_database = "database.db"
+ conn = sqlite3.connect(os.path.join(PATH, db_name_database))
+ c = conn.cursor()
+ logger.info(f"connected to database {db_name_database}")
+
+ for command in commands:
+ command_name = command.split(".")[0]
+ command_permission = modules[command_name].PERMISSION
+ command_prefix = modules[command_name].PREFIX
+ command_description = modules[command_name].DESCRIPTION
+ command_user_cooldown = modules[command_name].USER_COOLDOWN
+ command_global_cooldown = modules[command_name].GLOBAL_COOLDOWN
+ command_last_used = 0
+ c.execute(
+ "REPLACE INTO commands VALUES (?, ?, ?, ?, ?, ?, ?)",
+ (
+ command_name,
+ command_prefix,
+ command_permission,
+ command_description,
+ command_user_cooldown,
+ command_global_cooldown,
+ command_last_used,
+ ),
+ )
+ logger.info(f"updating commands command_name: {command_prefix}{command_name}")
+ conn.commit()
+ conn.close()
+
+
+def add_message_to_chat_history(message: Message):
+ if message.command != Commands.PRIVMSG:
+ return
+ conn = sqlite3.connect(os.path.join(PATH, "chat_history.db"))
+ c = conn.cursor()
+
+ try:
+ bits = message.tags["bits"]
+ except KeyError:
+ bits = None
+ try:
+ rp_display_name = message.tags["reply-parent-display-name"]
+ rp_msg_body = message.tags["reply-parent-msg-body"]
+ rp_msg_id = message.tags["reply-parent-msg-id"]
+ rp_user_id = int(message.tags["reply-parent-user-id"])
+ rp_user_login = message.tags["reply-parent-user-login"]
+ except KeyError:
+ rp_display_name = None
+ rp_msg_body = None
+ rp_msg_id = None
+ rp_user_id = None
+ rp_user_login = None
+
+ c.execute(
+ """
+ INSERT INTO chat (
+ "id",
+ "nick",
+ "channel",
+ "message",
+ "tmi-sent-ts",
+ "badge-info",
+ "badges",
+ "bits",
+ "color",
+ "display-name",
+ "first-msg",
+ "mod",
+ "room-id",
+ "user-id",
+ "user-type",
+ "turbo",
+ "subscriber",
+ "reply-parent-display-name",
+ "reply-parent-msg-body",
+ "reply-parent-msg-id",
+ "reply-parent-user-id",
+ "reply-parent-user-login"
+ ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);
+ """,
+ (
+ message.tags["id"],
+ message.nick,
+ message.channel,
+ message.value,
+ int(message.tags["tmi-sent-ts"]),
+ message.tags["badge-info"],
+ message.tags["badges"],
+ bits,
+ message.tags["color"],
+ message.tags["display-name"],
+ int(message.tags["first-msg"]),
+ int(message.tags["mod"]),
+ int(message.tags["room-id"]),
+ int(message.tags["user-id"]),
+ message.tags["user-type"],
+ int(message.tags["turbo"]),
+ int(message.tags["subscriber"]),
+ rp_display_name,
+ rp_msg_body,
+ rp_msg_id,
+ rp_user_id,
+ rp_user_login,
+ ),
+ )
+ conn.commit()
+ conn.close()
+
+
+def create_chat_history_database():
+ conn = sqlite3.connect(os.path.join(PATH, "chat_history.db"))
+ c = conn.cursor()
+
+ c.execute(
+ """
+ CREATE TABLE IF NOT EXISTS "chat" (
+ "id" TEXT NOT NULL,
+ "nick" TEXT NOT NULL,
+ "channel" TEXT NOT NULL,
+ "message" TEXT NOT NULL,
+ "tmi-sent-ts" INTEGER NOT NULL,
+ "badge-info" TEXT NOT NULL,
+ "badges" TEXT NOT NULL,
+ "bits" TEXT,
+ "color" TEXT NOT NULL,
+ "display-name" TEXT NOT NULL,
+ "first-msg" INTEGER NOT NULL,
+ "mod" INTEGER NOT NULL,
+ "room-id" INTEGER NOT NULL,
+ "user-id" INTEGER NOT NULL,
+ "user-type" TEXT NOT NULL,
+ "turbo" INTEGER NOT NULL,
+ "subscriber" INTEGER NOT NULL,
+ "reply-parent-display-name" TEXT,
+ "reply-parent-msg-body" TEXT,
+ "reply-parent-msg-id" TEXT,
+ "reply-parent-user-id" INTEGER,
+ "reply-parent-user-login" TEXT,
+ PRIMARY KEY("id")
+ );
+ """
+ )
+ conn.commit()
+ conn.close()
+
+
+def update_auto_messages_in_database(modules, auto_messages):
+ conn = sqlite3.connect(os.path.join(PATH, "database.db"))
+ c = conn.cursor()
+
+ for auto_message in auto_messages:
+ auto_message_name = auto_message.split(".")[0]
+ auto_message_cooldown = modules[auto_message_name].COOLDOWN
+ auto_message_end_time = modules[auto_message_name].END_TIME
+ auto_message_last_used = 0
+ try:
+ c.execute(
+ "INSERT INTO auto_messages (name, cooldown, end_time, last_used) VALUES (?, ?, ?, ?)",
+ (
+ auto_message_name,
+ auto_message_cooldown,
+ auto_message_end_time,
+ auto_message_last_used,
+ ),
+ )
+ except Exception as e:
+ c.execute(
+ """
+ UPDATE auto_messages
+ SET
+ cooldown = ?,
+ end_time = ?
+ WHERE
+ name = ?
+ """,
+ (
+ auto_message_cooldown,
+ auto_message_end_time,
+ auto_message_name,
+ ),
+ )
+ conn.commit()
+ conn.close()
--- /dev/null
+import urllib3
+from dataclasses import dataclass
+import os
+import json
+import logging
+from typing import Optional
+
+BASE_URL = "https://euw1.api.riotgames.com"
+
+KEY = os.getenv("LOL_STREAM_HELPER")
+
+HEADER = {"X-Riot-Token": KEY}
--- /dev/null
+from lol_api import *
+
+logger = logging.getLogger(__name__)
--- /dev/null
+from lol_api import *
+from typing import Optional
+
+logger = logging.getLogger(__name__)
+
+
+@dataclass
+class BannedChampion:
+ pick_turn: int
+ 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
+ perks: Perks
+ profile_icon_id: int
+ bot: bool
+ team_id: int
+ summoner_name: str
+ summoner_id: str
+ spell1_id: int
+ spell2_id: int
+
+
+@dataclass
+class GameInfo:
+ game_id: int
+ game_type: str
+ game_start_time: int
+ map_id: int
+ game_length: int
+ platform_id: str
+ game_mode: str
+ banned_champions: list[BannedChampion]
+ 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
+ http = urllib3.PoolManager()
+ r = http.request(
+ "GET",
+ url,
+ headers=HEADER,
+ )
+ if r.status == 404:
+ 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}"
+ )
+ return None
+ data = json.loads(r.data.decode("utf-8"))
+
+ banned_champions: list[BannedChampion] = []
+ for banned in data["bannedChampions"]:
+ banned_champions.append(
+ BannedChampion(
+ banned["pickTurn"],
+ banned["championId"],
+ banned["teamId"],
+ )
+ )
+
+ participants: list[CurrentGameParticipant] = []
+ for participant in data["participants"]:
+ perks = Perks(
+ [perk_id for perk_id in participant["perks"]["perkIds"]],
+ participant["perks"]["perkStyle"],
+ participant["perks"]["perkSubStyle"],
+ )
+ participants.append(
+ CurrentGameParticipant(
+ participant["championId"],
+ perks,
+ participant["profileIconId"],
+ participant["bot"],
+ participant["teamId"],
+ participant["summonerName"],
+ participant["summonerId"],
+ participant["spell1Id"],
+ participant["spell2Id"],
+ )
+ )
+
+ return GameInfo(
+ data["gameId"],
+ data["gameType"],
+ data["gameStartTime"],
+ data["mapId"],
+ data["gameLength"],
+ data["platformId"],
+ data["gameMode"],
+ banned_champions,
+ data.get("gameQueueConfigId", None),
+ data["observers"]["encryptionKey"],
+ participants,
+ )
--- /dev/null
+from lol_api import *
+
+logger = logging.getLogger(__name__)
+
+
+@dataclass
+class Summoner:
+ summoner_id: str
+ account_id: str
+ puuid: str
+ name: str
+ profile_icon_id: int
+ revision_date: int
+ summoner_level: int
+
+
+def get_summoner_from_puuid(puuid: str) -> Optional[Summoner]:
+ endpoint = f"/lol/summoner/v4/summoners/by-puuid/{puuid}"
+ url = BASE_URL + endpoint
+ logger.debug(f"url is: {url}")
+ http = urllib3.PoolManager()
+ r = http.request(
+ "GET",
+ url,
+ headers=HEADER,
+ )
+ if r.status != 200:
+ logger.warning(
+ f"Couldn't retrieve summoner with puuid: {puuid}. Status code {r.status}"
+ )
+ return None
+ data = json.loads(r.data.decode("utf-8"))
+ return Summoner(
+ data["id"],
+ data["accountId"],
+ data["puuid"],
+ data["name"],
+ data["profileIconId"],
+ data["revisionDate"],
+ data["summonerLevel"],
+ )
+
+
+def get_summoner_from_name(name: str) -> Optional[Summoner]:
+ endpoint = f"/lol/summoner/v4/summoners/by-name/{name}"
+ url = BASE_URL + endpoint
+ logger.debug(f"url is: {url}")
+ http = urllib3.PoolManager()
+ r = http.request(
+ "GET",
+ url,
+ headers=HEADER,
+ )
+ if r.status != 200:
+ logger.warning(f"Couldn't retrieve summoner: {name}. Status code {r.status}")
+ return None
+ data = json.loads(r.data.decode("utf-8"))
+ return Summoner(
+ data["id"],
+ data["accountId"],
+ data["puuid"],
+ data["name"],
+ data["profileIconId"],
+ data["revisionDate"],
+ data["summonerLevel"],
+ )
--- /dev/null
+from aptbot import Bot, Message, Commands
+import os
+import importlib
+import importlib.util
+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
+import scripts.chatting
+import scripts.chat
+import scripts.crylaugh
+import database_manager
+import analyze_auto_message
+import time
+import logging
+from threading import Event
+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)
+reload(scripts.chatting)
+reload(scripts.chat)
+reload(scripts.crylaugh)
+reload(database_manager)
+reload(analyze_auto_message)
+
+logger = logging.getLogger(__name__)
+
+PATH = os.path.dirname(os.path.realpath(__file__))
+logger.info(f"PATH set to: {PATH}")
+COMMANDS_PATH = os.path.join(PATH, "commands")
+logger.info(f"COMMANDS_PATH set to: {COMMANDS_PATH}")
+AUTO_MESSAGES_PATH = os.path.join(PATH, "auto_messages")
+logger.info(f"AUTO_MESSAGES_PATH set to: {AUTO_MESSAGES_PATH}")
+
+commands_specs = {}
+commands_modules = {}
+
+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))
+]
+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)
+ )
+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))
+]
+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)
+ )
+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])
+ if not commands_specs[spec]:
+ continue
+ try:
+ commands_specs[spec].loader.exec_module(commands_modules[spec])
+ except Exception as e:
+ logger.critical(traceback.format_exc())
+ logger.critical(f"Problem Loading Module: {e}")
+
+for spec in auto_message_specs:
+ auto_message_modules[spec] = importlib.util.module_from_spec(
+ auto_message_specs[spec]
+ )
+ if not auto_message_specs[spec]:
+ continue
+ try:
+ auto_message_specs[spec].loader.exec_module(auto_message_modules[spec])
+ except Exception as e:
+ logger.critical(traceback.format_exc())
+ logger.critical(f"Problem Loading Module: {e}")
+
+
+database_manager.create_database()
+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)
+
+
+def start(bot: Bot, message: Message, stop_event: Event):
+ i = 0
+ wait = 5
+ while not stop_event.is_set():
+ i += wait
+ started = tools.smart_start_stream_time.update_start_stream_timestamp()
+ if started == "START":
+ bot.send_privmsg(
+ message.channel, "/announce Stream has started, you can now use ?join"
+ )
+ elif started == "END":
+ bot.send_privmsg(message.channel, "Stream has ended")
+ if i >= 30:
+ analyze_auto_message.do_auto_message(bot, message, auto_message_modules)
+ i = 0
+ time.sleep(wait)
+
+
+def main(bot: Bot, message: Message):
+ if message.command == Commands.PRIVMSG:
+ database_manager.add_message_to_chat_history(message)
+ if message.value[0] in {"?", "\\"}:
+ analyze_command.do_command(bot, message, commands_modules)
+ scripts.unit_converter.send_metric(bot, message)
+ scripts.alwase.alwase(bot, message)
+ scripts.chatting.chatting(bot, message)
+ scripts.chatting.chatting_annoy(bot, message)
+ scripts.chat.chat(bot, message)
+ scripts.crylaugh.crylaugh(bot, message)
+
+ # if message.command == Commands.PART:
+ # if message.nick in {'jelemar', 'flauenn', 'ihaspeks', 'blobin_wobin', 'officiallysp'}:
+ # bot.send_privmsg(message.channel, f"/announce {message.nick} has left chat")
+ # if message.command == Commands.JOIN:
+ # if message.nick in {'jelemar', 'flauenn', 'ihaspeks', 'blobin_wobin', 'officiallysp'}:
+ # bot.send_privmsg(message.channel, f"/announce {message.nick} has joined chat")
+
+ tools.raid.raid(bot, message)
--- /dev/null
+beautifulsoup4==4.11.1
+black==22.3.0
+blis==0.7.7
+catalogue==2.0.7
+certifi==2022.5.18.1
+charset-normalizer==2.0.12
+click==8.1.3
+cymem==2.0.6
+deep-translator==1.8.3
+en-core-web-sm @ https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-3.3.0/en_core_web_sm-3.3.0-py3-none-any.whl
+flake8==4.0.1
+flake8-black==0.3.3
+idna==3.3
+Jinja2==3.1.2
+langcodes==3.3.0
+MarkupSafe==2.1.1
+mccabe==0.6.1
+murmurhash==1.0.7
+mypy-extensions==0.4.3
+numpy==1.22.4
+packaging==21.3
+pathspec==0.9.0
+pathy==0.6.1
+platformdirs==2.5.2
+preshed==3.0.6
+pycodestyle==2.8.0
+pydantic==1.8.2
+pyflakes==2.4.0
+pyparsing==3.0.9
+python-dotenv==0.20.0
+requests==2.27.1
+smart-open==5.2.1
+soupsieve==2.3.2.post1
+spacy==3.3.0
+spacy-legacy==3.0.9
+spacy-loggers==1.0.2
+srsly==2.4.3
+thinc==8.0.16
+tomli==2.0.1
+tqdm==4.64.0
+typer==0.4.1
+typing-extensions==4.2.0
+urllib3==1.26.9
+wasabi==0.9.1
+websocket-client==1.3.2
--- /dev/null
+from aptbot.bot import Bot, Message, Commands
+import tools.smart_privmsg
+import random
+
+
+def alwase(bot: Bot, message: Message):
+ if "always" not in message.value.lower():
+ return
+ try:
+ replied_msg_id = message.tags["id"]
+ except KeyError:
+ replied_msg_id = None
+ msgs = [
+ "It's ALWASE gigaMadge",
+ "Why don't you spell it ALWASE ? gigaMadge",
+ "Spell it ALWASE or peepoArriveBan",
+ ]
+ msg = random.choice(msgs)
+ tools.smart_privmsg.send(bot, message, msg, reply=replied_msg_id)
--- /dev/null
+from aptbot.bot import Message, Commands, Bot
+import tools.smart_privmsg
+import openai
+import os
+
+openai.api_key = os.getenv("OPENAI_API")
+
+def chat(bot: Bot, message: Message):
+ if not message.nick in {'skgyorugo', 'ihaspeks'}:
+ return
+ if not message.value.startswith("# "):
+ return
+
+ replied_message = message.tags.get("reply-parent-msg-body", None)
+ if replied_message:
+ msg = replied_message
+ replied_msg_id = message.tags["reply-parent-msg-id"]
+ else:
+ msg = " ".join(message.value.split(" ")[1:])
+ replied_msg_id = message.tags['id']
+
+ response = openai.Completion.create(
+ model="text-davinci-003",
+ prompt=msg,
+ temperature=1,
+ max_tokens=4000,
+ top_p=0.3,
+ frequency_penalty=0.5,
+ presence_penalty=0.5,
+ )
+
+ if response:
+ msg = response["choices"][0]["text"]
+ msg = msg.replace("\n", " ")
+ else:
+ msg = "Sadge nothing was returned"
+
+ tools.smart_privmsg.send(bot, message, msg, reply=replied_msg_id)
--- /dev/null
+from aptbot.bot import Bot, Message, Commands
+import tools.smart_privmsg
+import random
+
+
+def chatting(bot: Bot, message: Message):
+ if "Chatting" not in message.value:
+ return
+ if random.random() > 0.4:
+ return
+ msg = ""
+ if "reply-parent-msg-body" in message.tags:
+ if message.value.split(" ")[1] == "Chatting":
+ msg = " ".join(message.value.split(" ")[1:])
+ else:
+ if message.value.split(" ")[0] == "Chatting":
+ msg = message.value
+ if msg:
+ tools.smart_privmsg.send(bot, message, msg)
+
+
+def chatting_annoy(bot: Bot, message: Message):
+ nicks = {}
+ if message.nick.lower() not in nicks:
+ return
+ msg = "Chatting " + message.value
+ # msg = "Pepelaff " + message.value
+ tools.smart_privmsg.send(bot, message, msg)
--- /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__)
+
+
+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")
+ c.execute("DELETE FROM ow")
+ conn.commit()
+
+ c.execute(
+ """
+ INSERT INTO lol_queue (
+ "twitch_id",
+ "position",
+ "available",
+ "last_available",
+ "time_remaining"
+ ) VALUES (?, ?, ?, ?, ?);
+ """,
+ (
+ twitch_id,
+ 0,
+ 1,
+ None,
+ 9999999,
+ ),
+ )
+ c.execute(
+ """
+ INSERT INTO ow (
+ "twitch_id",
+ "position",
+ "available",
+ "last_available",
+ "time_remaining"
+ ) VALUES (?, ?, ?, ?, ?);
+ """,
+ (
+ twitch_id,
+ 0,
+ 1,
+ None,
+ 9999999,
+ ),
+ )
+ conn.commit()
+
+ conn.close()
--- /dev/null
+import os
+import random
+import sqlite3
+import logging
+from fastapi import FastAPI
+from fastapi.middleware.cors import CORSMiddleware
+
+app = FastAPI()
+
+origins = ["*"]
+
+app.add_middleware(
+ CORSMiddleware,
+ allow_origins=origins,
+ allow_credentials=True,
+ allow_methods=["*"],
+ allow_headers=["*"],
+)
+
+@app.get("/clip")
+async def root():
+ clips = [
+ "https://clips-media-assets2.twitch.tv/AT-cm%7CMGyhlrJbd3gtietAgP63LA.mp4",
+ "https://clips-media-assets2.twitch.tv/WATxq6O_aQBU1qrftJJ0fQ/AT-cm%7CWATxq6O_aQBU1qrftJJ0fQ.mp4",
+ ]
+ return random.choice(clips)
+
+# logger = logging.getLogger(__name__)
+
+# PATH = os.path.dirname(os.path.realpath(__file__))
+# logger.debug(f"PATH set to: {PATH}")
+
+
+# def do_command(bot: Bot, message: Message, command_modules: dict):
+# db_name_database = "database.db"
+# conn = sqlite3.connect(os.path.join(PATH, db_name_database))
+# c = conn.cursor()
+# logger.info(f"connected to database {db_name_database}")
--- /dev/null
+from aptbot.bot import Bot, Message, Commands
+import tools.smart_privmsg
+import random
+
+
+def crylaugh(bot: Bot, message: Message):
+ if random.random() > 0.05:
+ return
+ if "😂" not in message.value:
+ return
+ try:
+ replied_msg_id = message.tags["id"]
+ except KeyError:
+ replied_msg_id = None
+ msg = "Oh 😂 look 😂 at 😂 me 😂 I 😂 use 😂 this 😂 funny 😂 emoji 😂 hahahaha 😂😂😂😂😂 lit 💯 👌"
+ tools.smart_privmsg.send(bot, message, msg, reply=replied_msg_id)
--- /dev/null
+from deep_translator import GoogleTranslator
+
+
+def translate(text: str) -> str:
+ trans = GoogleTranslator(source="auto", target="en").translate(text)
+ return trans
--- /dev/null
+from aptbot.bot import Bot, Message, Commands
+import spacy
+import re
+import tools.smart_privmsg
+
+nlp = spacy.load("en_core_web_sm")
+
+
+def send_metric(bot: Bot, message: Message):
+ text = ""
+ ft_inch, cm = _tometric(message.value)
+ for i in range(len(cm)):
+ if cm[i] > 230:
+ text += f"{ft_inch[i][0]:.1f}ft. and {ft_inch[i][1]:.1f}in. is {cm[i] / 100:.2f}m. | "
+ elif cm[i] > 0:
+ text += f"{ft_inch[i][0]:.1f}ft. and {ft_inch[i][1]:.1f}in. is {cm[i]:.1f}cm. | "
+ if text:
+ try:
+ replied_msg_id = message.tags["id"]
+ except KeyError:
+ replied_msg_id = None
+ tools.smart_privmsg.send(bot, message, text, reply=replied_msg_id)
+
+
+def _tometric(text: str) -> tuple[list[tuple[int, int]], list[float]]:
+ ft_inch: list[tuple] = []
+ feet = 0
+ inches = 0
+ text = text.replace("-", " ")
+ text = re.sub(r"([0-9]+(\.[0-9]+)?)", r"\1 ", text)
+ text = re.sub(r"\s{2,}", r" ", text)
+ doc = nlp(text)
+ feet_was_last = False
+ next_should_be_double = False
+ found_single = False
+ for w in doc:
+ # print(w.text, w.pos_)
+ if w.pos_ in {"AUX", "VERB", "ADP"}:
+ if feet_was_last and not next_should_be_double:
+ ft_inch.append((feet, 0.0))
+ feet = 0
+ inches = 0
+ if w.like_num or w.pos_ == "NUM":
+ # index_of_previous_token = w.i - 1
+ # try:
+ # prev_token = doc[index_of_previous_token]
+ # print(prev_token.lemma_)
+ # if prev_token.lemma_ != "be":
+ # continue
+ # except:
+ # pass
+ # if "'" in w.text:
+ # feet_and_inches = w.text.split("'")
+ # try:
+ # feet = float(feet_and_inches[0])
+ # inches = float(feet_and_inches[1])
+ # except:
+ # pass
+ index_of_next_token = w.i + 1
+ try:
+ next_token = doc[index_of_next_token]
+ if next_token.lemma_ in {"ft", "foot", "'"}:
+ if next_token.lemma_ == "'" and not next_should_be_double:
+ next_should_be_double = True
+ elif next_token.lemma_ == "'":
+ feet = 0
+ inches = 0
+ continue
+ if feet_was_last:
+ ft_inch.append((feet, 0.0))
+ feet = float(w.text)
+ feet_was_last = True
+ elif next_token.lemma_ in {"inch", '"'}:
+ if next_token.lemma_ == '"' and next_should_be_double:
+ inches = float(w.text)
+ next_should_be_double = False
+ elif next_token.lemma_ == '"':
+ inches = 0
+ elif next_should_be_double:
+ feet = 0
+ inches = float(w.text)
+ else:
+ inches = float(w.text)
+ ft_inch.append((feet, inches))
+ feet = 0
+ inches = 0
+ feet_was_last = False
+ except:
+ pass
+ if feet_was_last and not next_should_be_double:
+ ft_inch.append((feet, 0.0))
+ cm: list[float] = []
+ for unit in ft_inch:
+ cm.append((unit[0] * 12 + unit[1]) * 2.54)
+ return (ft_inch, cm)
--- /dev/null
+import os
+import sqlite3
+
+TOOLS_PATH = os.path.dirname(os.path.realpath(__file__))
+PATH = os.path.join(TOOLS_PATH, "..")
+
+DEFAULT_PERMISSION = 99
+
+
+def get_permission_from_id(user_id: str) -> int:
+ conn = sqlite3.connect(os.path.join(PATH, "database.db"))
+ c = conn.cursor()
+ c.execute("SELECT permission FROM users WHERE user_id = ?", (user_id,))
+ fetched_user = c.fetchone()
+ if fetched_user:
+ return fetched_user[0]
+
+ return DEFAULT_PERMISSION
--- /dev/null
+import ttv_api.channel
+from aptbot.bot import Bot, Message, Commands
+
+
+def raid(bot: Bot, message: Message):
+ if message.command == Commands.USERNOTICE and message.tags["msg-id"] == "raid":
+ raider_name = message.tags["msg-param-displayName"]
+ raider_login = message.tags["msg-param-login"]
+ raider_id = message.tags["user-id"]
+ raider_channel_info = ttv_api.channel.get_channels(raider_id)
+ raider_game = ""
+ if raider_channel_info:
+ raider_game = raider_channel_info[0].game_name
+ viewers = message.tags["msg-param-viewerCount"]
+ viewers = f"{viewers} viewer" if viewers == "1" else f"{viewers} viewers"
+ msg_reply = f"POGGERS {raider_name} has raided {message.channel} \
+ with {viewers}!!! Why don't you check them out at: \
+ https://twitch.tv/{raider_login}"
+ if raider_game:
+ msg_reply += f" they were just playing {raider_game}!"
+ bot.send_privmsg(message.channel, msg_reply)
--- /dev/null
+from aptbot.bot import Bot, Message, Commands
+from typing import Union
+from .. import database_manager
+import time
+
+MAX_LENGTH = 480
+
+
+def _split_message(message: str) -> list[str]:
+ split_count = len(message) // MAX_LENGTH + 1
+ 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 + " "
+
+ 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)):
+ 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
+ messages[i] = messages[i].replace("always", "alwase")
+ messages[i] = messages[i].replace("Always", "Alwase")
+ messages[i] = messages[i].replace("ALWAYS", "ALWASE")
+ else:
+ while True:
+ if (
+ messages.startswith("/")
+ or messages.startswith("!")
+ or messages.startswith("\\")
+ or messages.startswith("?")
+ ):
+ messages = messages[1:]
+ else:
+ break
+ messages = messages.replace("always", "alwase")
+ messages = messages.replace("Always", "Alwase")
+ messages = messages.replace("ALWAYS", "ALWASE")
+ 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,
+):
+ # 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:])
+ message = message.replace("{message}", msg)
+ message = message.replace("{nick}", message_data.nick)
+ message = message.replace("{channel}", message_data.channel)
+
+ messages = _split_message(message)
+ for message in messages:
+ if reply:
+ tags = {"display-name": "MurphyAI", "tmi-sent-ts": int(time.time() * 1000), "user-id": "784114488", "room-id": "169701299", "reply-parent-msg-id": reply}
+ database_manager.add_message_tochat_history(
+ Message(
+ tags=tags,
+ nick="murphyai",
+ command=Commands.PRIVMSG,
+ message_data.channel,
+ value=message
+ )
+ )
+ if safe_send:
+ send_safe(bot, message_data.channel, messages, reply)
+ else:
+ bot.send_privmsg(message_data.channel, messages, reply)
--- /dev/null
+import time
+import os
+import ttv_api.users
+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__)
+
+STREAMER_PATH = os.path.abspath(os.path.join(__file__, "../.."))
+logger.debug(f"STREAMER_PATH set to: {STREAMER_PATH}")
+TOOLS_PATH = os.path.dirname(os.path.realpath(__file__))
+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():
+ logger.info(f"{STREAMER_LOGIN} has ended their stream")
+ clean_queue.clean_queue()
+
+
+def start_stream():
+ logger.info(f"{STREAMER_LOGIN} has started their stream")
+ clean_queue.clean_queue()
+
+
+def start_stream_timestamp() -> Optional[int]:
+ 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[str]:
+ conn = sqlite3.connect(os.path.join(PATH, "database.db"))
+ c = conn.cursor()
+
+ c.execute("SELECT MAX(last_checked) FROM stream_info")
+ max_last_checked = c.fetchone()
+ if max_last_checked:
+ c.execute(
+ """
+ SELECT
+ start_stream_ts,
+ last_checked
+ FROM
+ stream_info
+ WHERE
+ last_checked = ?
+ AND ended = 0
+ """,
+ (max_last_checked[0],),
+ )
+
+ fetched = c.fetchone()
+
+ if fetched:
+ start_stream_ts, last_checked = fetched
+ if time.time() < last_checked + CHECK_STREAMTIME_CD:
+ conn.close()
+ return
+
+ stream_info = ttv_api.stream.get_streams(user_logins=[STREAMER_LOGIN])
+ if not stream_info and not fetched:
+ conn.close()
+ return
+
+ if not stream_info:
+ start_stream_ts, last_checked = fetched
+ if time.time() < last_checked + MAX_OFF_STREAM_MARGIN:
+ conn.close()
+ return
+
+ c.execute(
+ "REPLACE INTO stream_info VALUES (?, ?, ?)",
+ (
+ start_stream_ts,
+ last_checked,
+ 1,
+ ),
+ )
+ conn.commit()
+ conn.close()
+ # TODO add hook, streamer ended stream
+ end_stream()
+ return "END"
+
+ if not fetched:
+ start_stream_ts = int(stream_info[0].started_at.timestamp())
+ current_time = int(time.time())
+ c.execute(
+ "REPLACE INTO stream_info VALUES (?, ?, ?)",
+ (
+ start_stream_ts,
+ current_time,
+ 0,
+ ),
+ )
+ conn.commit()
+ conn.close()
+ start_stream()
+ return "START"
+
+ start_stream_ts, last_checked = fetched
+ current_time = int(time.time())
+ c.execute(
+ "REPLACE INTO stream_info VALUES (?, ?, ?)",
+ (
+ start_stream_ts,
+ current_time,
+ 0,
+ ),
+ )
+ conn.commit()
+ conn.close()
+ return
--- /dev/null
+import os
+import re
+import sqlite3
+
+PATH = os.path.dirname(os.path.realpath(__file__))
+PATH = os.path.join(PATH, "..")
+
+
+class Expression:
+ def __init__(self, name: str, list_id: int, method: str, value: str):
+ self.name = name
+ self.list_id = list_id
+ self.method = method
+ self.value = value
+
+ def eval(self):
+ conn = sqlite3.connect(os.path.join(PATH, "variables.db"))
+ c = conn.cursor()
+
+ if self.list_id:
+ # TODO
+ c.execute(
+ """
+ SELECT
+ *
+ FROM
+ list_values
+ INNER JOIN methods USING(type)
+ WHERE
+ list_values.name = ?
+ AND list_values.id = ?
+ AND methods.name = ?
+ """,
+ (self.name, self.list_id, self.method),
+ )
+ conn.close()
+ pass
+
+ def __repr__(self) -> str:
+ print(type(self.list_id))
+ return f"Expression('{self.name}', '{self.list_id}', '{self.method}', '{self.value}')"
+
+
+def parse(text: str):
+ value = text
+ reg_parse = re.compile(r"\$(\w+)\[?(\d+)?\]?\.(\w+)\((.+)?\)")
+
+ expressions: list[Expression] = []
+ while True:
+
+ try:
+ name, list_id, method, value = reg_parse.findall(value)[0]
+ list_id = int(list_id)
+ except IndexError:
+ break
+ except ValueError:
+ list_id = None
+ expressions.append(Expression(name, list_id, method, value))
+ print(expressions)
+ if 2:
+ return None
+ return ""
+
+
+if __name__ == "__main__":
+ # parse(r"$fib[12].set($fib[11].add($fib[10].value()))")
+ # parse(r"$quotes[2].set(Hello, world)")
+ # parse(r"")
+ parse(r"wqe$quotes[].set($quotes[1].value(dw) + fw)")
--- /dev/null
+import urllib3
+from dataclasses import dataclass
+import os
+import json
+from typing import Optional
+
+URL = "https://www.googleapis.com/youtube/v3/search"
+
+API = os.getenv("YOUTUBE_API")
+CLIENT_ID = os.getenv("YOUTUBE_CLIENT_ID")
+CLIENT_SECRET = os.getenv("YOUTUBE_CLIENT_SECRET")
--- /dev/null
+from yt_api import *
+import html
+
+
+@dataclass
+class Video:
+ video_name: str
+ video_id: str
+
+
+def get_newest_video(channel_id: str) -> Optional[Video]:
+ get_video_snippets = "?part=snippet"
+ get_url = (
+ URL
+ + get_video_snippets
+ + f"&channelId={channel_id}&order=date&type=video"
+ + f"&key={API}"
+ )
+
+ http = urllib3.PoolManager()
+ r = http.request(
+ "GET",
+ get_url,
+ )
+ if r.status != 200:
+ return None
+ data = json.loads(r.data.decode("utf-8"))["items"][0]
+ video_id = data["id"]["videoId"]
+ video_title = html.unescape(data["snippet"]["title"])
+
+ return Video(video_title, video_id)
+++ /dev/null
-### TODO
-
-- [x] youtube api
-- [x] raid / host shoutout
-- [x] latege (command and auto), could look through auto schedule
-- [ ] basic math polish notation
-- [x] translator
-- [x] (?t a replied message / database in memory of messages)
-- [ ] followage command
-- [ ] commands in groups
-- [ ] quote adder / remover / getter
-- [ ] reminder (timer)
-- [x] inch to cm
-- [ ] license --- opensource --- info
-- [ ] streamer time
-- [ ] list maker (who's up for flex)
-- [ ] variable counter with cross-command functionality
-- [ ] random variable getter from db {random.quote}
-- [ ] specific word in message {message.0}, {message.1}, etc.
-- [ ] replied variable {reply.nick} {reply.message} {reply.message.0}
-- [ ] sub sellout bot
-- [ ] schedule
-- [ ] which LoL account are you playing on? (maybe add rank)
-
-## Basic Commands
-- [x] int
-- [x] bald
-- [ ] milk pasta
-- [x] make spam always output max length
-- [x] tea
-- [x] coffee
-- [ ] smelly
-- [x] coin
-- [ ] permissions
-- [x] jam
-- [x] screamlads
-- [x] supporters
+++ /dev/null
-from aptbot.bot import Bot, Message, Commands
-import os
-import sqlite3
-import time
-import tools.smart_privmsg
-import tools.smart_start_stream_time
-import logging
-from importlib import reload
-
-reload(tools.smart_privmsg)
-reload(tools.smart_start_stream_time)
-
-logger = logging.getLogger(__name__)
-
-PATH = os.path.dirname(os.path.realpath(__file__))
-logger.debug(f"analyze_auto_message PATH set to: {PATH}")
-
-
-def do_auto_message(bot: Bot, message: Message, auto_message_modules: dict):
- 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
- name,
- cooldown,
- end_time,
- last_used,
- value
- FROM
- auto_messages
- LEFT JOIN auto_message_values USING (name)
- ORDER BY
- last_used ASC
- """
- )
- while True:
- fetched = c.fetchone()
- if not fetched:
- break
-
- name, cooldown, end_time, last_used, value = fetched
- if time.time() < last_used + cooldown:
- continue
- if time.time() > start_stream_ts + end_time and end_time != 0:
- continue
- if value:
- tools.smart_privmsg.send(bot, message, value)
- else:
- try:
- auto_message_modules[name].main(bot, message)
- except KeyError:
- c.execute(
- """
- DELETE FROM
- auto_messages
- WHERE
- name = ?
- """,
- (name,),
- )
- conn.commit()
- continue
-
- c.execute(
- "UPDATE auto_messages SET last_used = ? WHERE name = ?",
- (
- int(time.time()),
- name,
- ),
- )
- conn.commit()
- break
- conn.close()
+++ /dev/null
-import os
-import random
-import sqlite3
-import tools.permissions
-import tools.smart_privmsg
-import logging
-from aptbot.bot import Bot, Message, Commands
-
-logger = logging.getLogger(__name__)
-
-PATH = os.path.dirname(os.path.realpath(__file__))
-logger.debug(f"PATH set to: {PATH}")
-
-
-def do_command(bot: Bot, message: Message, command_modules: dict):
- db_name_database = "database.db"
- conn = sqlite3.connect(os.path.join(PATH, db_name_database))
- c = conn.cursor()
- logger.info(f"connected to database {db_name_database}")
-
- try:
- replied_message = message.tags["reply-parent-msg-body"]
- except KeyError:
- replied_message = None
-
- if replied_message:
- command = message.value.split(" ")[1]
- else:
- command = message.value.split(" ")[0]
- prefix = command[0]
- command = command[1:]
- user_id = message.tags["user-id"]
- message_timestamp = int(message.tags["tmi-sent-ts"]) // 1000
- user_perm = tools.permissions.get_permission_from_id(user_id)
-
- c.execute(
- """
- SELECT
- commands.command,
- value,
- commands.user_cooldown,
- commands.global_cooldown,
- CASE
- WHEN ? <= 10 THEN
- 0
- WHEN cooldowns.user_cooldown >= (commands.last_used + commands.global_cooldown) THEN
- cooldowns.user_cooldown
- ELSE
- (commands.last_used + commands.global_cooldown)
- END AS avail_time
-
- FROM
- commands
- LEFT JOIN command_values USING (command)
- LEFT JOIN cooldowns ON
- (
- cooldowns.command = commands.command
- AND cooldowns.user_id = ?
- )
- WHERE
- commands.command = ?
- AND prefix = ?
- AND permission >= ?
- """,
- (
- user_perm,
- user_id,
- command,
- prefix,
- user_perm,
- ),
- )
- fetched = c.fetchall()
- if not fetched:
- conn.close()
- return
-
- (
- _,
- value,
- command_user_cooldown,
- command_global_cooldown,
- avail_time,
- ) = random.choice(fetched)
-
- if message_timestamp < avail_time:
- bot.send_privmsg(
- message.channel,
- f"The command '{prefix}{command}' is on cooldown. \
- Please wait {int(avail_time - message_timestamp) + 1} seconds.",
- )
- conn.close()
- return
-
- c.execute(
- "REPLACE INTO cooldowns VALUES (?, ?, ?)",
- (
- user_id,
- command,
- command_user_cooldown + message_timestamp,
- ),
- )
- c.execute(
- "UPDATE commands SET last_used = ? WHERE command = ?",
- (
- message_timestamp,
- command,
- ),
- )
- conn.commit()
- conn.close()
- if value is None:
- command_modules[command].main(bot, message)
- else:
- tools.smart_privmsg.send(bot, message, value)
+++ /dev/null
-from aptbot.bot import Message, Commands, Bot
-import tools.smart_privmsg
-import urllib3
-import json
-
-COOLDOWN = 30 * 60
-END_TIME = 0
-
-header = {
- "Accept": "application/json",
- "User-Agent": "For my twitch bot [MurphyAI] on https://twitch.tv/ihaspeks",
-}
-
-
-def main(bot: Bot, message: Message):
- http = urllib3.PoolManager()
- r = http.request("GET", "https://icanhazdadjoke.com", headers=header)
- if r.status != 200:
- tools.smart_privmsg.send(bot, message, f"Couldn't get a joke Sadge")
- return
-
- data = json.loads(r.data.decode("utf-8"))
- joke = data["joke"].replace("\r\n", " ")
- tools.smart_privmsg.send(
- bot, message, f"{joke} ||| Get more jokes by typing ?joke"
- )
+++ /dev/null
-from aptbot.bot import Message, Commands, Bot
-
-COOLDOWN = 120 * 60
-END_TIME = 0
-
-
-def main(bot: Bot, message: Message):
- msg = "I collect data and occasionally post interesting statistics on peks' discord. "
- msg += "The type of data you should expect to see is 'Chat frequency', 'Most used emotes', "
- msg += "'Most active time and day', 'Reply graphs', etc. "
- bot.send_privmsg(message.channel, msg)
-
- msg = "If you are okay with these stats being publicly available with your name, "
- msg += "please type ?accept_share to let me know. "
- bot.send_privmsg(message.channel, msg)
+++ /dev/null
-from aptbot.bot import Message, Commands, Bot
-
-COOLDOWN = 9 * 60
-END_TIME = 0.5 * 60 * 60
-
-
-def main(bot: Bot, message: Message):
- msg = "peepoWave"
- bot.send_privmsg(message.channel, msg)
+++ /dev/null
-from aptbot.bot import Message, Commands, Bot
-
-COOLDOWN = 20 * 60
-END_TIME = 0
-
-
-def main(bot: Bot, message: Message):
- msg = "Wanna ask 9ball a question and get an answer? use: ?9ball <question>"
- bot.send_privmsg(message.channel, msg)
+++ /dev/null
-from aptbot.bot import Message, Commands, Bot
-
-COOLDOWN = 30 * 60
-END_TIME = 1 * 60 * 60
-
-
-def main(bot: Bot, message: Message):
- msg = "I'm a cute lil' wolf UwU and you're all cute lil' chatters OwO"
- bot.send_privmsg(message.channel, msg)
+++ /dev/null
-from aptbot.bot import Message, Commands, Bot
-import datetime as dt
-from datetime import datetime
-import tools.smart_start_stream_time
-
-COOLDOWN = 180
-END_TIME = COOLDOWN * 5
-
-STREAM_SCHEDULE = dt.time(18, 30)
-
-
-def main(bot: Bot, message: Message):
- start_stream_ts = tools.smart_start_stream_time.start_stream_timestamp()
- if not start_stream_ts:
- return
- start_stream_dt = datetime.utcfromtimestamp(start_stream_ts)
- stream_schedule_dt = datetime.combine(datetime.now(), STREAM_SCHEDULE)
- latege_amount = (start_stream_dt - stream_schedule_dt).total_seconds()
- if latege_amount > 45 * 60:
- msg = f"{message.channel} is so Latege he might as well have not \
- streamed today. At least he's early for tomorrow COPIUM . \
- {message.channel} is Latege by {latege_amount} seconds Madge"
- elif latege_amount > 0:
- msg = f"{message.channel} is Latege by {latege_amount} seconds again Madge"
- elif latege_amount == 0:
- msg = f"Amazing!!! {message.channel} is EXACTLY on time today POGGERS"
- else:
- msg = f"UNBELIEVABLE!!!!! {message.channel} is EARLY by {-latege_amount} seconds!!!!\
- Something very wrong is going on in this world monkaW"
- bot.send_privmsg(message.channel, "/announce " + msg)
+++ /dev/null
-from aptbot.bot import Message, Commands, Bot
-
-COOLDOWN = 48 * 60
-END_TIME = 2.5 * 60 * 60
-
-
-def main(bot: Bot, message: Message):
- msg = "IF YOU WANT TO PLAY WITH PEKS TYPE: ?join ------------------------------------------------------------------------------- You can find more info here: https://i.imgur.com/mv89SMr.png"
- bot.send_privmsg(message.channel, msg)
+++ /dev/null
-import os
-import sqlite3
-import time
-from aptbot.bot import Message, Commands, Bot
-
-COOLDOWN = 60
-END_TIME = 0
-
-PATH = os.path.dirname(os.path.realpath(__file__))
-PATH = os.path.join(PATH, "..")
-
-
-def main(bot: Bot, message: Message):
- conn = sqlite3.connect(os.path.join(PATH, "lol_data.db"))
- c = conn.cursor()
-
- tables = ["lol_queue", "ow"]
-
- for table in tables:
- c.execute(
- f"""
- UPDATE
- {table}
- SET
- last_available = ?,
- time_remaining = time_remaining - (? - last_available)
- WHERE
- available = 0;
- """,
- (
- int(time.time()),
- int(time.time()),
- ),
- )
- c.execute(f"DELETE FROM {table} WHERE time_remaining < 0;")
- if c.rowcount:
- bot.send_privmsg(message.channel, f"/announce {c.rowcount} user{'s were' if c.rowcount > 1 else ' was'} just removed from {table if table != 'lol_queue' else 'lol'} queue.")
-
- conn.commit()
-
- conn.close()
+++ /dev/null
-from aptbot.bot import Message, Commands, Bot
-import yt_api.videos
-
-COOLDOWN = 42 * 60
-END_TIME = 0
-
-CHANNEL_ID = "UCQ7C3NUKY6TSkURdUdVoYFw"
-
-
-def main(bot: Bot, message: Message):
- video = yt_api.videos.get_newest_video(CHANNEL_ID)
- if video:
- video_link = f"https://www.youtube.com/watch?v={video.video_id}"
- msg = f'Watch Peks\' latest video "{video.video_name}" here: {video_link}'
- else:
- msg = f"Check out my youtube channel here -> https://www.youtube.com/channel/{CHANNEL_ID}"
- bot.send_privmsg(message.channel, msg)
+++ /dev/null
-from aptbot.bot import Message, Commands, Bot
-import tools.smart_start_stream_time
-
-PERMISSION = 99
-PREFIX = "?"
-DESCRIPTION = ""
-USER_COOLDOWN = 5
-GLOBAL_COOLDOWN = 2
-
-
-def main(bot: Bot, message: Message):
- start_stream_ts = tools.smart_start_stream_time.start_stream_timestamp()
- if not start_stream_ts:
- msg = r"The Sponsor is World of Warships, which is a historical strategy online combat PC game. It looks very 5Head but i will conquer elmoFire so imma be testing it out. If u want to join in with us, try it urself, or if you just want to help me out Gladge u can sign up with my link: https://strms.net/warships_ihaspeks you get a fair few bonuses for using mah link too ihaspeBased and after u have won your first game and bought ur first ship ill get a notification on stream peksJAM"
- else:
- msg = r"Peks is live so he can awnser that KEKW but here is the link just in case BASED https://strms.net/warships_ihaspeks"
- tools.smart_privmsg.send_safe(bot, message.channel, msg)
-
+++ /dev/null
-from aptbot.bot import Message, Commands, Bot
-import os
-import tools.smart_privmsg
-import openai
-from openai.error import RateLimitError
-
-PERMISSION = 99
-PREFIX = "?"
-DESCRIPTION = ""
-USER_COOLDOWN = 40
-GLOBAL_COOLDOWN = 20
-
-openai.api_key = os.getenv("OPENAI_API")
-
-def main(bot: Bot, message: Message):
- replied_message = message.tags.get("reply-parent-msg-body", None)
- if replied_message:
- msg = replied_message
- replied_msg_id = message.tags["reply-parent-msg-id"]
- else:
- msg = " ".join(message.value.split(" ")[1:])
- replied_msg_id = message.tags['id']
-
-
- try:
- response = openai.Completion.create(
- # model="davinci:ft-personal:9ball-2022-12-05-08-37-36",
- model="davinci:ft-personal-2022-12-06-10-03-18",
- prompt=f"9ball is an 8ball. 9ball answers your questions reluctantly with sarcastic and unhelpful responses.\n{message.nick}: {msg}\n\n###\n\n",
- temperature=1,
- max_tokens=60,
- top_p=0.3,
- frequency_penalty=0.5,
- presence_penalty=0.0,
- stop=[" END"],
- )
- except RateLimitError:
- tools.smart_privmsg.send_safe(bot, message.channel, "UwU Sowwy. The sevwews awe ovewloaded :( Twy again in a few minutes OwO", reply=replied_msg_id)
-
- print(response)
- if response:
- msg = response["choices"][0]["text"]
- # msg = msg[:msg.find("#")]
- else:
- msg = "Sadge nothing was returned"
-
- tools.smart_privmsg.send_safe(bot, message.channel, msg, reply=replied_msg_id)
- # bot.send_privmsg(message.channel, msg, reply=replied_msg_id)
+++ /dev/null
-from aptbot.bot import Message, Commands, Bot
-import os
-import logging
-import ttv_api.users
-import sqlite3
-import tools.smart_privmsg
-import random
-import shlex
-
-logger = logging.getLogger(__name__)
-
-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 check_queue(bot: Bot, message: Message, table: str):
- if random.random() < 0.02:
- q = [
- "https://imgur.com/d5qGioI",
- "https://imgur.com/oaMmxXI",
- "https://imgur.com/4btWipx",
- "https://imgur.com/VvvD8d8",
- "https://imgur.com/v7oflTv",
- "https://imgur.com/MSnBNDz",
- "https://imgur.com/x2pPkvw",
- "https://imgur.com/xZgFcYG",
- ]
- msg = (
- "You wanted to see the queue, but instead you got visited by the Q. monkaW "
- )
- msg += random.choice(q)
- tools.smart_privmsg.send(
- bot,
- message,
- msg,
- reply=message.tags["id"],
- )
- return
- conn = sqlite3.connect(os.path.join(PATH, "lol_data.db"))
- c = conn.cursor()
-
- c.execute(
- f"""
- SELECT twitch_id, priority_queue FROM {table} 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_users = []
- for twitch_id in queue:
- for twitch_user in twitch:
- if int(twitch_user.user_id) == int(twitch_id):
- queue_users.append(twitch_user)
- 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(
- f"""
- SELECT data FROM {table}_data WHERE name = 'queuesize';
- """
- )
- try:
- queue_size = c.fetchone()[0]
- except TypeError:
- queue_size = 5
- bot.send_privmsg(
- message.channel,
- f"There was an issue fetching the queue size, default set to {queue_size}",
- reply=message.tags["id"],
- )
-
- c.execute(
- f"""
- SELECT twitch_id FROM {table} WHERE available = 0 ORDER BY position ASC;
- """
- )
- fetched_unavailable = c.fetchall()
- unavailable = [x[0] for x in fetched_unavailable]
- twitch_unavailable = ttv_api.users.get_users(user_ids=unavailable)
-
- unavailable_users = []
- for twitch_id in unavailable:
- for twitch_user in twitch_unavailable:
- if int(twitch_user.user_id) == int(twitch_id):
- unavailable_users.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"],
- )
-
- play_list = [user.display_name for user in queue_users[0:queue_size]]
- prio_queue = []
- wait_list = []
- for user in queue_users[queue_size:]:
- for fetch in fetched:
- if int(user.user_id) == fetch[0] and fetch[1] == 1:
- prio_queue.append(user.display_name)
- elif int(user.user_id) == fetch[0]:
- wait_list.append(user.display_name)
-
- if prio_queue:
- msg = f"These people are playing with {play_list[0]}: {play_list[1:]} | These people are in Priority Queue: {prio_queue} | These people are in the Wait List: {wait_list}."
- else:
- msg = f"These people are playing with {play_list[0]}: {play_list[1:]} | These people are in the Wait List: {wait_list}."
-
- if unavailable_users:
- msg += f" | These people are also not here: {unavailable_users}."
-
- tools.smart_privmsg.send(
- bot,
- message,
- msg,
- reply=message.tags["id"],
- )
-
- conn.close()
-
-
-def parse(query):
- query = query.split()
- try:
- if query[0].lower() in {"ow", "overwatch", "ow2", "overwatch2"}:
- return {"--game": "ow"}
- except:
- pass
- return {"--game": "lol_queue"}
- d = dict()
- for i in shlex.split(query):
- try:
- d[i.split('=')[0]] = i.split('=')[1]
- except:
- pass
- return d
-
-
-def scrub(table_name):
- return ''.join(chr for chr in table_name if chr.isalnum() or chr == '_')
-
-
-def main(bot: Bot, message: Message):
- args = " ".join(message.value.split(" ")[1:])
- args = parse(args)
- check_queue(bot, message, scrub(args.get("--game", "lol_queue")))
+++ /dev/null
-from aptbot.bot import Message, Commands, Bot
-import tools.smart_privmsg
-import os
-
-PERMISSION = 99
-PREFIX = "?"
-DESCRIPTION = ""
-USER_COOLDOWN = 30
-GLOBAL_COOLDOWN = 15
-
-
-COMMANDS_PATH = os.path.dirname(os.path.realpath(__file__))
-PATH = os.path.join(COMMANDS_PATH, "..")
-DATA_PATH = os.path.join(PATH, "data")
-
-
-def main(bot: Bot, message: Message):
- accepted_path = os.path.join(DATA_PATH, "permission")
- with open(accepted_path, "r") as f:
- accepted = [user_id.rstrip() for user_id in f]
- if message.tags["user-id"] in accepted:
- tools.smart_privmsg.send(bot, message, "You have already given permission")
- return
-
- with open(accepted_path, "a") as f:
- f.write(f"{message.tags['user-id']}\n")
- tools.smart_privmsg.send(bot, message, "Thank you for giving permission")
-
+++ /dev/null
-from aptbot.bot import Message, Commands, Bot
-import sqlite3
-import os
-import logging
-import lol_api.summoner_v4
-import ttv_api.users
-
-logger = logging.getLogger(__name__)
-
-
-PERMISSION = 10
-PREFIX = "\\"
-DESCRIPTION = "Adds a LoL account to the database. Use: \\addaccount <summoner name> | <twitch name>"
-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):
- 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}"
- )
- 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}"
- )
- return
- twitch_id = twitch[0].user_id
-
- conn = sqlite3.connect(os.path.join(PATH, "lol_data.db"))
- c = conn.cursor()
-
- try:
- c.execute(
- """
- INSERT INTO accounts (
- "puuid",
- "summoner_id",
- "account_id",
- "twitch_id"
- ) VALUES (
- ?, ?, ?, ?
- );
- """,
- (
- summoner.puuid,
- 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"
- )
- 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}"
- )
- bot.send_privmsg(message.channel, f"Successfully added account.")
- conn.close()
+++ /dev/null
-from aptbot.bot import Message, Commands, Bot
-import sqlite3
-import os
-
-PERMISSION = 10
-PREFIX = "\\"
-DESCRIPTION = ""
-USER_COOLDOWN = 0
-GLOBAL_COOLDOWN = 0
-
-PATH = os.path.dirname(os.path.realpath(__file__))
-PATH = os.path.join(PATH, "..")
-
-DEFAULT_PERMISSION = 99
-DEFAULT_DESCRIPTION = ""
-DEFAULT_USER_COOLDOWN = 5
-DEFAULT_GLOBAL_COOLDOWN = 0
-DEFAULT_LAST_USED = 0
-
-
-def main(bot: Bot, message: Message):
- msg = " ".join(message.value.split(" ")[1:])
- command = msg.split(" ")[0]
- command_prefix = command[0]
- command_name = command[1:]
- command_value = msg = " ".join(msg.split(" ")[1:])
- if command_prefix != "?":
- bot.send_privmsg(
- message.channel,
- f"{message.nick} you cannot use {command_prefix} as a prefix",
- )
- return
-
- conn = sqlite3.connect(os.path.join(PATH, "database.db"))
- c = conn.cursor()
- c.execute(
- "SELECT value FROM commands LEFT JOIN command_values USING(command) WHERE command = ? AND prefix = ?",
- (
- command_name,
- command_prefix,
- ),
- )
- try:
- if not c.fetchone()[0]:
- bot.send_privmsg(
- message.channel,
- f"The command {command_prefix}{command_name} already exists",
- )
- return
- except TypeError:
- pass
- try:
- c.execute(
- "INSERT INTO commands VALUES (?, ?, ?, ?, ?, ?, ?)",
- (
- command_name,
- command_prefix,
- DEFAULT_PERMISSION,
- DEFAULT_DESCRIPTION,
- DEFAULT_USER_COOLDOWN,
- DEFAULT_GLOBAL_COOLDOWN,
- DEFAULT_LAST_USED,
- ),
- )
- except sqlite3.IntegrityError:
- pass
- except Exception as e:
- bot.send_privmsg(message.channel, f"There was an error adding the command: {e}")
- conn.close()
- return
- c.execute(
- "INSERT INTO command_values VALUES (?, ?)",
- (
- command_name,
- command_value,
- ),
- )
- bot.send_privmsg(message.channel, f"Successfully added {command_name}.")
- conn.commit()
- conn.close()
+++ /dev/null
-from aptbot.bot import Message, Commands, Bot
-import os
-import logging
-import ttv_api.users
-import sqlite3
-import tools.smart_privmsg
-import random
-import shlex
-
-logger = logging.getLogger(__name__)
-
-PERMISSION = 99
-PREFIX = "?"
-DESCRIPTION = r"Sekiro death counter"
-USER_COOLDOWN = 10
-GLOBAL_COOLDOWN = 5
-
-PATH = os.path.dirname(os.path.realpath(__file__))
-PATH = os.path.join(PATH, "..")
-
-def check_queue(bot: Bot, message: Message, table: str):
- conn = sqlite3.connect(os.path.join(PATH, "database.db"))
- c = conn.cursor()
-
- c.execute(
- f"""
- SELECT id, val FROM varvalues WHERE id = 'cannon';
- """
- )
- _, val = c.fetchone()
-
- if table == "show":
- msg = f"Peks is at cannon {val % 1000} of prestige {val // 1000}"
-
- tools.smart_privmsg.send(
- bot,
- message,
- msg,
- reply=message.tags["id"],
- )
-
- conn.close()
- return
- if table == "remove":
- val = val - 1
- c.execute(
- f"""
- UPDATE varvalues SET val = ? WHERE id = 'cannon';
- """,
- (val,)
- )
-
- msg = f"Peks is at cannon {val % 1000} of prestige {val // 1000}"
-
- tools.smart_privmsg.send(
- bot,
- message,
- msg,
- reply=message.tags["id"],
- )
- conn.commit()
- conn.close()
- return
- if table == "add":
- val = val + 1
- c.execute(
- f"""
- UPDATE varvalues SET val = ? WHERE id = 'cannon';
- """,
- (val,)
- )
-
- msg = f"Peks is at cannon {val % 1000} of prestige {val // 1000}"
-
- tools.smart_privmsg.send(
- bot,
- message,
- msg,
- reply=message.tags["id"],
- )
- conn.commit()
- conn.close()
- return
-
-
-def parse(query):
- query = query.split()
- try:
- if query[0].lower() == "add":
- return {"--do": "add"}
- if query[0].lower() == "remove":
- return {"--do": "remove"}
- except:
- pass
- return {"--game": "show"}
- d = dict()
- for i in shlex.split(query):
- try:
- d[i.split('=')[0]] = i.split('=')[1]
- except:
- pass
- return d
-
-
-def scrub(table_name):
- return ''.join(chr for chr in table_name if chr.isalnum() or chr == '_')
-
-
-def main(bot: Bot, message: Message):
- args = " ".join(message.value.split(" ")[1:])
- args = parse(args)
- check_queue(bot, message, scrub(args.get("--do", "show")))
+++ /dev/null
-from aptbot.bot import Message, Commands, Bot
-import os
-import logging
-import ttv_api.users
-import sqlite3
-import time
-import shlex
-
-logger = logging.getLogger(__name__)
-
-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 clean_queue(bot: Bot, message: Message, table: str):
- 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(f"DELETE FROM {table}")
- conn.commit()
-
- c.execute(
- f"""
- INSERT INTO {table} (
- "twitch_id",
- "position",
- "available",
- "last_available",
- "time_remaining"
- ) VALUES (?, ?, ?, ?, ?);
- """,
- (
- twitch_id,
- 0,
- 1,
- None,
- 9999999,
- ),
- )
- conn.commit()
-
- bot.send_privmsg(
- message.channel,
- f"Successfully cleaned the queue.",
- reply=message.tags["id"],
- )
-
- conn.close()
-
-
-def parse(query):
- query = query.split()
- try:
- if query[0].lower() in {"ow", "overwatch", "ow2", "overwatch2"}:
- return {"--game": "ow"}
- except:
- pass
- return {"--game": "lol_queue"}
- d = dict()
- for i in shlex.split(query):
- try:
- d[i.split('=')[0]] = i.split('=')[1]
- except:
- pass
- return d
-
-
-def scrub(table_name):
- return ''.join(chr for chr in table_name if chr.isalnum() or chr == '_')
-
-
-def main(bot: Bot, message: Message):
- args = " ".join(message.value.split(" ")[1:])
- args = parse(args)
- clean_queue(bot, message, scrub(args.get("--game", "lol_queue")))
+++ /dev/null
-from aptbot.bot import Message, Commands, Bot
-import tools.smart_privmsg
-import random
-
-PERMISSION = 99
-PREFIX = "?"
-DESCRIPTION = (
- r"Tosses a coin, there's a 50% chance it's heads and a 50% chance it's tails"
-)
-USER_COOLDOWN = 10
-GLOBAL_COOLDOWN = 5
-
-
-def main(bot: Bot, message: Message):
- r = random.random()
- if r < 0.02:
- tools.smart_privmsg.send(
- bot,
- message,
- f"the coin landed on it's side, try again.",
- reply=message.tags["id"],
- )
- elif r < 0.51:
- tools.smart_privmsg.send(bot, message, f"heads", reply=message.tags["id"])
- else:
- tools.smart_privmsg.send(bot, message, f"tails", reply=message.tags["id"])
+++ /dev/null
-from aptbot.bot import Message, Commands, Bot
-import tools.permissions
-import tools.smart_privmsg
-import sqlite3
-import os
-
-PERMISSION = 99
-PREFIX = "?"
-DESCRIPTION = ""
-USER_COOLDOWN = 30
-GLOBAL_COOLDOWN = 15
-
-
-COMMANDS_PATH = os.path.dirname(os.path.realpath(__file__))
-PATH = os.path.join(COMMANDS_PATH, "..")
-
-
-def main(bot: Bot, message: Message):
- conn = sqlite3.connect(os.path.join(PATH, "database.db"))
- c = conn.cursor()
-
- user_perm = tools.permissions.get_permission_from_id(message.tags["user-id"])
-
- c.execute(
- "SELECT prefix, command FROM commands WHERE permission >= ? ORDER BY permission ASC",
- (user_perm,),
- )
-
- fetched_commands = c.fetchall()
-
- conn.commit()
- conn.close()
-
- commands = []
- for command in fetched_commands:
- commands.append(f"{command[0]}{command[1]}")
-
- commands = " ".join(commands)
- tools.smart_privmsg.send(bot, message, commands)
+++ /dev/null
-from aptbot.bot import Message, Commands, Bot
-import os
-import logging
-import ttv_api.users
-import sqlite3
-import tools.smart_privmsg
-import random
-import shlex
-
-logger = logging.getLogger(__name__)
-
-PERMISSION = 99
-PREFIX = "?"
-DESCRIPTION = r"Sekiro death counter"
-USER_COOLDOWN = 10
-GLOBAL_COOLDOWN = 5
-
-PATH = os.path.dirname(os.path.realpath(__file__))
-PATH = os.path.join(PATH, "..")
-
-def check_queue(bot: Bot, message: Message, table: str):
- conn = sqlite3.connect(os.path.join(PATH, "database.db"))
- c = conn.cursor()
-
- c.execute(
- f"""
- SELECT id, val FROM varvalues WHERE id = 'deadge_sekiro';
- """
- )
- _, val = c.fetchone()
-
- if table == "show":
- msg = f"Peks has currently died {val} times"
-
- tools.smart_privmsg.send(
- bot,
- message,
- msg,
- reply=message.tags["id"],
- )
-
- conn.close()
- return
- if table == "remove":
- val = val - 1
- c.execute(
- f"""
- UPDATE varvalues SET val = ? WHERE id = 'deadge_sekiro';
- """,
- (val,)
- )
-
- msg = f"Peks has currently died {val} times"
-
- tools.smart_privmsg.send(
- bot,
- message,
- msg,
- reply=message.tags["id"],
- )
- conn.commit()
- conn.close()
- return
- if table == "add":
- val = val + 1
- c.execute(
- f"""
- UPDATE varvalues SET val = ? WHERE id = 'deadge_sekiro';
- """,
- (val,)
- )
-
- msg = f"Peks has currently died {val} times"
-
- tools.smart_privmsg.send(
- bot,
- message,
- msg,
- reply=message.tags["id"],
- )
- conn.commit()
- conn.close()
- return
-
-
-def parse(query):
- query = query.split()
- try:
- if query[0].lower() == "add":
- return {"--do": "add"}
- if query[0].lower() == "remove":
- return {"--do": "remove"}
- except:
- pass
- return {"--game": "show"}
- d = dict()
- for i in shlex.split(query):
- try:
- d[i.split('=')[0]] = i.split('=')[1]
- except:
- pass
- return d
-
-
-def scrub(table_name):
- return ''.join(chr for chr in table_name if chr.isalnum() or chr == '_')
-
-
-def main(bot: Bot, message: Message):
- args = " ".join(message.value.split(" ")[1:])
- args = parse(args)
- check_queue(bot, message, scrub(args.get("--do", "show")))
+++ /dev/null
-from aptbot.bot import Message, Commands, Bot
-
-PERMISSION = 10
-PREFIX = "\\"
-DESCRIPTION = "Reply to a message with \\delete to delete that message"
-USER_COOLDOWN = 0
-GLOBAL_COOLDOWN = 0
-
-
-def main(bot: Bot, message: Message):
- try:
- replied_msg_id = message.tags["reply-parent-msg-id"]
- except KeyError:
- return
- delete = f"/delete {replied_msg_id}"
- bot.send_privmsg(message.channel, delete)
+++ /dev/null
-from aptbot.bot import Message, Commands, Bot
-import sqlite3
-import os
-
-PERMISSION = 10
-PREFIX = "\\"
-DESCRIPTION = ""
-USER_COOLDOWN = 0
-GLOBAL_COOLDOWN = 0
-
-
-COMMANDS_PATH = os.path.dirname(os.path.realpath(__file__))
-PATH = os.path.join(COMMANDS_PATH, "..")
-
-
-def main(bot: Bot, message: Message):
- msg = " ".join(message.value.split(" ")[1:])
- command = msg.split(" ")[0]
- command_prefix = command[0]
- command_name = command[1:]
- command_value = msg = " ".join(msg.split(" ")[1:])
- if command_prefix != "?":
- bot.send_privmsg(
- message.channel,
- f"{message.nick} you cannot use {command_prefix} as a prefix",
- )
- return
-
- conn = sqlite3.connect(os.path.join(PATH, "database.db"))
- c = conn.cursor()
- c.execute(
- "SELECT value FROM commands LEFT JOIN command_values USING(command) WHERE command = ? AND prefix = ?",
- (
- command_name,
- command_prefix,
- ),
- )
- if not c.fetchone()[0]:
- bot.send_privmsg(
- message.channel,
- f"The command {command_prefix}{command_name} cannot be edited",
- )
- return
-
- try:
- c.execute(
- "UPDATE command_values SET value = ? WHERE command = ?",
- (
- command_value,
- command_name,
- ),
- )
- except sqlite3.IntegrityError:
- bot.send_privmsg(message.channel, f"The command {command_name} doesn't exist.")
- else:
- bot.send_privmsg(message.channel, f"Successfully updated {command_name}.")
- conn.commit()
- conn.close()
+++ /dev/null
-from aptbot.bot import Message, Commands, Bot
-import tools.smart_privmsg
-import urllib3
-
-PERMISSION = 9
-PREFIX = "\\"
-DESCRIPTION = ""
-USER_COOLDOWN = 900
-GLOBAL_COOLDOWN = 600
-
-
-def main(bot: Bot, message: Message):
- http = urllib3.PoolManager()
- r1 = http.request(
- "GET",
- f"https://twitch.center/customapi/bttvemotes?channel={message.channel}",
- )
- r2 = http.request(
- "GET",
- f"https://twitch.center/customapi/ffzemotes?channel={message.channel}",
- )
-
- if r1.status != 200 or r2.status != 200:
- bot.send_privmsg(
- message.channel,
- "NotLikeThis oopsie woopsie, we've made a fucky wucky. We can't \
- get the emotes at the moment. Hopefuwwy UwU wiww wait patientwy \
- tiww we get thiws pwobwem sowted. OwO",
- )
- return
- emotes = r1.data.decode("utf-8")
- emotes += " " + r2.data.decode("utf-8")
- tools.smart_privmsg.send(bot, message, emotes)
+++ /dev/null
-from aptbot.bot import Message, Commands, Bot
-import os
-import shlex
-import logging
-import ttv_api.users
-import sqlite3
-import time
-
-logger = logging.getLogger(__name__)
-
-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 force_here(bot: Bot, message: Message, table: str):
- 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(
- f"""
- UPDATE
- {table}
- SET
- position = (
- CASE
- WHEN (
- SELECT
- position
- FROM
- {table}
- WHERE
- twitch_id = ?
- ) < (
- SELECT
- max(position)
- FROM (
- SELECT
- position
- FROM
- {table}
- WHERE
- available = 1
- ORDER BY
- position
- LIMIT (
- SELECT
- data
- FROM
- {table}_data
- WHERE
- name = 'queuesize'
- )
- )
- )
- THEN position + 1
- ELSE position
- END
- )
- WHERE
- position > (
- SELECT
- max(position)
- FROM
- {table}
- WHERE
- priority_queue = 1
- OR position <= (
- SELECT
- max(position)
- FROM (
- SELECT
- position
- FROM
- {table}
- WHERE
- available = 1
- ORDER BY
- position
- LIMIT (
- SELECT
- data
- FROM
- {table}_data
- WHERE
- name = 'queuesize'
- )
- )
-
- )
- );
- """,
- (twitch_id,),
- )
-
- c.execute(
- f"""
- UPDATE
- {table}
- SET
- available = 1,
- priority_queue = (
- CASE
- WHEN (
- SELECT
- position
- FROM
- {table}
- WHERE
- twitch_id = ?
- ) < (
- SELECT
- max(position)
- FROM (
- SELECT
- position
- FROM
- {table}
- WHERE
- available = 1
- ORDER BY
- position
- LIMIT (
- SELECT
- data
- FROM
- {table}_data
- WHERE
- name = 'queuesize'
- )
- )
- )
- THEN 1
- ELSE null
- END
- ),
- position = (
- CASE
- WHEN (
- SELECT
- position
- FROM
- {table}
- WHERE
- twitch_id = ?
- ) < (
- SELECT
- max(position)
- FROM (
- SELECT
- position
- FROM
- {table}
- WHERE
- available = 1
- ORDER BY
- position
- LIMIT (
- SELECT
- data
- FROM
- {table}_data
- WHERE
- name = 'queuesize'
- )
- )
- )
- THEN 1 + (
- SELECT
- max(position)
- FROM
- {table}
- WHERE
- priority_queue = 1
- OR position <= (
- SELECT
- max(position)
- FROM (
- SELECT
- position
- FROM
- {table}
- WHERE
- available = 1
- ORDER BY
- position
- LIMIT (
- SELECT
- data
- FROM
- {table}_data
- WHERE
- name = 'queuesize'
- )
- )
- )
- )
- ELSE position
- END
- ),
- time_remaining = time_remaining - (? - last_available)
- WHERE
- twitch_id = ?
- AND available = 0;
- """,
- (
- twitch_id,
- twitch_id,
- 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(f"DELETE FROM {table} 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()
-
-
-def parse(query):
- query = query.split()
- try:
- if query[1].lower() in {"ow", "overwatch", "ow2", "overwatch2"}:
- return {"--game": "ow"}
- except:
- pass
- return {"--game": "lol_queue"}
- d = dict()
- for i in shlex.split(query):
- try:
- d[i.split('=')[0]] = i.split('=')[1]
- except:
- pass
- return d
-
-
-def scrub(table_name):
- return ''.join(chr for chr in table_name if chr.isalnum() or chr == '_')
-
-
-def main(bot: Bot, message: Message):
- args = " ".join(message.value.split(" ")[1:])
- args = parse(args)
- force_here(bot, message, scrub(args.get("--game", "lol_queue")))
+++ /dev/null
-from aptbot.bot import Message, Commands, Bot
-import shlex
-import os
-import logging
-import ttv_api.users
-import sqlite3
-
-logger = logging.getLogger(__name__)
-
-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 force_join(bot: Bot, message: Message, table: str):
- 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(
- f"""
- SELECT position FROM {table} ORDER BY position DESC;
- """
- )
-
- try:
- last_position: int = c.fetchone()[0]
- except TypeError:
- last_position: int = -1
-
- try:
- c.execute(
- f"""
- INSERT INTO {table} (
- "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()
-
-
-def parse(query):
- query = query.split()
- try:
- if query[1].lower() in {"ow", "overwatch", "ow2", "overwatch2"}:
- return {"--game": "ow"}
- except:
- pass
- return {"--game": "lol_queue"}
- d = dict()
- for i in shlex.split(query):
- try:
- d[i.split('=')[0]] = i.split('=')[1]
- except:
- pass
- return d
-
-
-def scrub(table_name):
- return ''.join(chr for chr in table_name if chr.isalnum() or chr == '_')
-
-
-def main(bot: Bot, message: Message):
- args = " ".join(message.value.split(" ")[1:])
- args = parse(args)
- force_join(bot, message, scrub(args.get("--game", "lol_queue")))
+++ /dev/null
-from aptbot.bot import Message, Commands, Bot
-import os
-import logging
-import ttv_api.users
-import sqlite3
-import shlex
-
-logger = logging.getLogger(__name__)
-
-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 force_leave(bot: Bot, message: Message, table: str):
- 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(
- f"""
- DELETE FROM {table} 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()
-
-
-def parse(query):
- query = query.split()
- try:
- if query[1].lower() in {"ow", "overwatch", "ow2", "overwatch2"}:
- return {"--game": "ow"}
- except:
- pass
- return {"--game": "lol_queue"}
- d = dict()
- for i in shlex.split(query):
- try:
- d[i.split('=')[0]] = i.split('=')[1]
- except:
- pass
- return d
-
-
-def scrub(table_name):
- return ''.join(chr for chr in table_name if chr.isalnum() or chr == '_')
-
-
-def main(bot: Bot, message: Message):
- args = " ".join(message.value.split(" ")[1:])
- args = parse(args)
- force_leave(bot, message, scrub(args.get("--game", "lol_queue")))
+++ /dev/null
-from aptbot.bot import Message, Commands, Bot
-import os
-import logging
-import ttv_api.users
-import sqlite3
-import time
-import shlex
-
-logger = logging.getLogger(__name__)
-
-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 force_not_here(bot: Bot, message: Message, table: str):
- 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(
- f"""
- UPDATE {table} SET available = 0, priority_queue = null, 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()
-
-
-def parse(query):
- query = query.split()
- try:
- if query[1].lower() in {"ow", "overwatch", "ow2", "overwatch2"}:
- return {"--game": "ow"}
- except:
- pass
- return {"--game": "lol_queue"}
- d = dict()
- for i in shlex.split(query):
- try:
- d[i.split('=')[0]] = i.split('=')[1]
- except:
- pass
- return d
-
-
-def scrub(table_name):
- return ''.join(chr for chr in table_name if chr.isalnum() or chr == '_')
-
-
-def main(bot: Bot, message: Message):
- args = " ".join(message.value.split(" ")[1:])
- args = parse(args)
- force_not_here(bot, message, scrub(args.get("--game", "lol_queue")))
+++ /dev/null
-from aptbot.bot import Message, Commands, Bot
-import os
-import logging
-import ttv_api.users
-import sqlite3
-import time
-import shlex
-
-logger = logging.getLogger(__name__)
-
-PERMISSION = 99
-PREFIX = "?"
-DESCRIPTION = r"Makes yourself available in the list."
-USER_COOLDOWN = 10
-GLOBAL_COOLDOWN = 0
-
-PATH = os.path.dirname(os.path.realpath(__file__))
-PATH = os.path.join(PATH, "..")
-
-
-def here(bot: Bot, message: Message, table: str):
- 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(
- f"""
- UPDATE
- {table}
- SET
- position = (
- CASE
- WHEN (
- SELECT
- position
- FROM
- {table}
- WHERE
- twitch_id = ?
- ) < (
- SELECT
- max(position)
- FROM (
- SELECT
- position
- FROM
- {table}
- WHERE
- available = 1
- ORDER BY
- position
- LIMIT (
- SELECT
- data
- FROM
- {table}_data
- WHERE
- name = 'queuesize'
- )
- )
- )
- THEN position + 1
- ELSE position
- END
- )
- WHERE
- position > (
- SELECT
- max(position)
- FROM
- {table}
- WHERE
- priority_queue = 1
- OR position <= (
- SELECT
- max(position)
- FROM (
- SELECT
- position
- FROM
- {table}
- WHERE
- available = 1
- ORDER BY
- position
- LIMIT (
- SELECT
- data
- FROM
- {table}_data
- WHERE
- name = 'queuesize'
- )
- )
-
- )
- );
- """,
- (twitch_id,),
- )
-
- c.execute(
- f"""
- UPDATE
- {table}
- SET
- available = 1,
- priority_queue = (
- CASE
- WHEN (
- SELECT
- position
- FROM
- {table}
- WHERE
- twitch_id = ?
- ) < (
- SELECT
- max(position)
- FROM (
- SELECT
- position
- FROM
- {table}
- WHERE
- available = 1
- ORDER BY
- position
- LIMIT (
- SELECT
- data
- FROM
- {table}_data
- WHERE
- name = 'queuesize'
- )
- )
- )
- THEN 1
- ELSE null
- END
- ),
- position = (
- CASE
- WHEN (
- SELECT
- position
- FROM
- {table}
- WHERE
- twitch_id = ?
- ) < (
- SELECT
- max(position)
- FROM (
- SELECT
- position
- FROM
- {table}
- WHERE
- available = 1
- ORDER BY
- position
- LIMIT (
- SELECT
- data
- FROM
- {table}_data
- WHERE
- name = 'queuesize'
- )
- )
- )
- THEN 1 + (
- SELECT
- max(position)
- FROM
- {table}
- WHERE
- priority_queue = 1
- OR position <= (
- SELECT
- max(position)
- FROM (
- SELECT
- position
- FROM
- {table}
- WHERE
- available = 1
- ORDER BY
- position
- LIMIT (
- SELECT
- data
- FROM
- {table}_data
- WHERE
- name = 'queuesize'
- )
- )
- )
- )
- ELSE position
- END
- ),
- time_remaining = time_remaining - (? - last_available)
- WHERE
- twitch_id = ?
- AND available = 0;
- """,
- (
- twitch_id,
- twitch_id,
- 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(f"DELETE FROM {table} 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()
-
-
-def parse(query):
- query = query.split()
- try:
- if query[1].lower() in {"ow", "overwatch", "ow2", "overwatch2"}:
- return {"--game": "ow"}
- except:
- pass
- return {"--game": "lol_queue"}
- d = dict()
- for i in shlex.split(query):
- try:
- d[i.split('=')[0]] = i.split('=')[1]
- except:
- pass
- return d
-
-
-def scrub(table_name):
- return ''.join(chr for chr in table_name if chr.isalnum() or chr == '_')
-
-
-def main(bot: Bot, message: Message):
- args = " ".join(message.value.split(" ")[1:])
- args = parse(args)
- here(bot, message, scrub(args.get("--game", "lol_queue")))
+++ /dev/null
-from aptbot.bot import Message, Commands, Bot
-import os
-import logging
-import ttv_api.users
-import sqlite3
-import shlex
-
-logger = logging.getLogger(__name__)
-
-PERMISSION = 99
-PREFIX = "?"
-DESCRIPTION = r"Joins the queue to play the game with the streamer."
-USER_COOLDOWN = 10
-GLOBAL_COOLDOWN = 0
-
-PATH = os.path.dirname(os.path.realpath(__file__))
-PATH = os.path.join(PATH, "..")
-
-DEFAULT_TIME_REMAINING = 60 * 60
-
-
-def join(bot: Bot, message: Message, table: str):
- 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(
- f"""
- SELECT position FROM {table} ORDER BY position DESC;
- """
- )
-
- try:
- last_position: int = c.fetchone()[0]
- except TypeError:
- last_position: int = -1
-
- try:
- c.execute(
- f"""
- INSERT INTO {table} (
- "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()
-
-
-def parse(query):
- query = query.split()
- try:
- if query[0].lower() in {"ow", "overwatch", "ow2", "overwatch2"}:
- return {"--game": "ow"}
- except:
- pass
- return {"--game": "lol_queue"}
- d = dict()
- for i in shlex.split(query):
- try:
- d[i.split('=')[0]] = i.split('=')[1]
- except:
- pass
- return d
-
-
-def scrub(table_name):
- return ''.join(chr for chr in table_name if chr.isalnum() or chr == '_')
-
-
-def main(bot: Bot, message: Message):
- args = " ".join(message.value.split(" ")[1:])
- args = parse(args)
- join(bot, message, scrub(args.get("--game", "lol_queue")))
+++ /dev/null
-from aptbot.bot import Message, Commands, Bot
-import tools.smart_privmsg
-import urllib3
-import json
-
-PERMISSION = 99
-PREFIX = "?"
-DESCRIPTION = r""
-USER_COOLDOWN = 30
-GLOBAL_COOLDOWN = 30
-
-header = {
- "Accept": "application/json",
- "User-Agent": "For my twitch bot [MurphyAI] on https://twitch.tv/ihaspeks",
-}
-
-
-def main(bot: Bot, message: Message):
- http = urllib3.PoolManager()
- r = http.request("GET", "https://icanhazdadjoke.com", headers=header)
- if r.status != 200:
- tools.smart_privmsg.send(
- bot, message, f"Couldn't get a joke Sadge", reply=message.tags["id"]
- )
- return
-
- data = json.loads(r.data.decode("utf-8"))
- tools.smart_privmsg.send(bot, message, f"{data['joke']}", reply=message.tags["id"])
+++ /dev/null
-from aptbot.bot import Message, Commands, Bot
-import tools.smart_start_stream_time
-from datetime import datetime
-import datetime as dt
-
-PERMISSION = 99
-PREFIX = "?"
-DESCRIPTION = ""
-USER_COOLDOWN = 15
-GLOBAL_COOLDOWN = 5
-
-STREAM_SCHEDULE = dt.time(18, 30)
-
-
-def main(bot: Bot, message: Message):
- start_stream_ts = tools.smart_start_stream_time.start_stream_timestamp()
- if not start_stream_ts:
- return
- start_stream_dt = datetime.utcfromtimestamp(start_stream_ts)
- stream_schedule_dt = datetime.combine(
- datetime.utcfromtimestamp(start_stream_ts), STREAM_SCHEDULE
- )
- latege_amount = (start_stream_dt - stream_schedule_dt).total_seconds()
- if latege_amount > 45 * 60:
- msg = f"{message.channel} is so Latege he might as well have not \
- streamed today. At least he's early for tomorrow COPIUM . \
- {message.channel} is Latege by {latege_amount} seconds Madge"
- elif latege_amount > 0:
- msg = f"{message.channel} is Latege by {latege_amount} seconds again Madge"
- elif latege_amount == 0:
- msg = f"Amazing!!! {message.channel} is EXACTLY on time today POGGERS"
- else:
- msg = f"UNBELIEVABLE!!!!! {message.channel} is EARLY by {-latege_amount} seconds!!!!\
- This has NEVER happened before POGGERS"
- bot.send_privmsg(message.channel, msg)
+++ /dev/null
-from aptbot.bot import Message, Commands, Bot
-import os
-import logging
-import ttv_api.users
-import sqlite3
-import shlex
-
-logger = logging.getLogger(__name__)
-
-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 leave(bot: Bot, message: Message, table: str):
- 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(
- f"""
- DELETE FROM {table} 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()
-
-
-def parse(query):
- query = query.split()
- try:
- if query[0].lower() in {"ow", "overwatch", "ow2", "overwatch2"}:
- return {"--game": "ow"}
- except:
- pass
- return {"--game": "lol_queue"}
- d = dict()
- for i in shlex.split(query):
- try:
- d[i.split('=')[0]] = i.split('=')[1]
- except:
- pass
- return d
-
-
-def scrub(table_name):
- return ''.join(chr for chr in table_name if chr.isalnum() or chr == '_')
-
-
-def main(bot: Bot, message: Message):
- args = " ".join(message.value.split(" ")[1:])
- args = parse(args)
- leave(bot, message, scrub(args.get("--game", "lol_queue")))
+++ /dev/null
-from aptbot.bot import Message, Commands, Bot
-import os
-import logging
-import ttv_api.users
-import sqlite3
-import shlex
-
-logger = logging.getLogger(__name__)
-
-PERMISSION = 10
-PREFIX = "\\"
-DESCRIPTION = r"Move the user down one row in the queue."
-USER_COOLDOWN = 0
-GLOBAL_COOLDOWN = 0
-
-PATH = os.path.dirname(os.path.realpath(__file__))
-PATH = os.path.join(PATH, "..")
-
-
-def move_down(bot: Bot, message: Message, table: str):
- 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 moved down in 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()
-
- try:
- c.execute(
- f"""
- UPDATE
- {table}
- SET
- position = (
- SELECT
- min(position)
- FROM
- {table}
- WHERE
- position > (
- SELECT
- position
- FROM
- {table}
- WHERE
- twitch_id = ?
- )
- ) + (
- SELECT
- position
- FROM
- {table}
- WHERE
- twitch_id = ?
- ) - position
- WHERE
- position in (
- (
- SELECT
- min(position)
- FROM
- {table}
- WHERE
- position > (
- SELECT
- position
- FROM
- {table}
- WHERE
- twitch_id = ?
- )
- ),
- (
- SELECT
- position
- FROM
- {table}
- WHERE
- twitch_id = ?
- )
- );
- """,
- (twitch_id,) * 4,
- )
- except sqlite3.IntegrityError:
- bot.send_privmsg(
- message.channel, "Can't move user down further", reply=message.tags["id"]
- )
- conn.close()
- return
- conn.commit()
- bot.send_privmsg(
- message.channel, "Successfully moved them down.", reply=message.tags["id"]
- )
- conn.close()
-
-
-def parse(query):
- query = query.split()
- try:
- if query[1].lower() in {"ow", "overwatch", "ow2", "overwatch2"}:
- return {"--game": "ow"}
- except:
- pass
- return {"--game": "lol_queue"}
- d = dict()
- for i in shlex.split(query):
- try:
- d[i.split('=')[0]] = i.split('=')[1]
- except:
- pass
- return d
-
-
-def scrub(table_name):
- return ''.join(chr for chr in table_name if chr.isalnum() or chr == '_')
-
-
-def main(bot: Bot, message: Message):
- args = " ".join(message.value.split(" ")[1:])
- args = parse(args)
- move_down(bot, message, scrub(args.get("--game", "lol_queue")))
+++ /dev/null
-from aptbot.bot import Message, Commands, Bot
-import os
-import logging
-import ttv_api.users
-import sqlite3
-import shlex
-
-logger = logging.getLogger(__name__)
-
-PERMISSION = 10
-PREFIX = "\\"
-DESCRIPTION = r"Move the user up one row in the queue."
-USER_COOLDOWN = 0
-GLOBAL_COOLDOWN = 0
-
-PATH = os.path.dirname(os.path.realpath(__file__))
-PATH = os.path.join(PATH, "..")
-
-
-def move_up(bot: Bot, message: Message, table: str):
- 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 moved up in 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()
-
- try:
- c.execute(
- f"""
- UPDATE
- {table}
- SET
- position = (
- SELECT
- max(position)
- FROM
- {table}
- WHERE
- position < (
- SELECT
- position
- FROM
- {table}
- WHERE
- twitch_id = ?
- )
- ) + (
- SELECT
- position
- FROM
- {table}
- WHERE
- twitch_id = ?
- ) - position
- WHERE
- position in (
- (
- SELECT
- max(position)
- FROM
- {table}
- WHERE
- position < (
- SELECT
- position
- FROM
- {table}
- WHERE
- twitch_id = ?
- )
- ),
- (
- SELECT
- position
- FROM
- {table}
- WHERE
- twitch_id = ?
- )
- );
- """,
- (twitch_id,) * 4,
- )
- except sqlite3.IntegrityError:
- bot.send_privmsg(
- message.channel, "Can't move user up further", reply=message.tags["id"]
- )
- conn.close()
- return
- conn.commit()
- bot.send_privmsg(
- message.channel, "Successfully moved them up.", reply=message.tags["id"]
- )
- conn.close()
-
-
-def parse(query):
- query = query.split()
- try:
- if query[1].lower() in {"ow", "overwatch", "ow2", "overwatch2"}:
- return {"--game": "ow"}
- except:
- pass
- return {"--game": "lol_queue"}
- d = dict()
- for i in shlex.split(query):
- try:
- d[i.split('=')[0]] = i.split('=')[1]
- except:
- pass
- return d
-
-
-def scrub(table_name):
- return ''.join(chr for chr in table_name if chr.isalnum() or chr == '_')
-
-
-def main(bot: Bot, message: Message):
- args = " ".join(message.value.split(" ")[1:])
- args = parse(args)
- move_up(bot, message, scrub(args.get("--game", "lol_queue")))
+++ /dev/null
-from aptbot.bot import Message, Commands, Bot
-import os
-import logging
-import ttv_api.users
-import sqlite3
-import random
-import shlex
-
-logger = logging.getLogger(__name__)
-
-PERMISSION = 10
-PREFIX = "\\"
-DESCRIPTION = r"Check who's currently in queue."
-USER_COOLDOWN = 0
-GLOBAL_COOLDOWN = 0
-
-PATH = os.path.dirname(os.path.realpath(__file__))
-PATH = os.path.join(PATH, "..")
-
-
-def new_teams(bot: Bot, message: Message, table: str):
- conn = sqlite3.connect(os.path.join(PATH, "lol_data.db"))
- c = conn.cursor()
-
- c.execute(
- f"""
- SELECT twitch_id FROM {table} WHERE available = 1 ORDER BY position ASC;
- """
- )
- fetched = c.fetchall()
- queue: list[str] = [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_users: list[ttv_api.users.User] = []
- for twitch_id in queue:
- for twitch_user in twitch:
- if int(twitch_user.user_id) == int(twitch_id):
- queue_users.append(twitch_user)
- 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(
- f"""
- SELECT data FROM {table}_data WHERE name = 'queuesize';
- """
- )
- fetched = c.fetchone()
- try:
- queue_size = fetched[0]
- except TypeError:
- queue_size = 10
- bot.send_privmsg(
- message.channel,
- f"There was an issue fetching the queue size, default set to {queue_size}",
- reply=message.tags["id"],
- )
-
- if len(queue_users) < queue_size:
- bot.send_privmsg(
- message.channel,
- f"There aren't enough people in the queue. Current team size is {queue_size} while there are only {len(queue_users)} in queue.",
- reply=message.tags["id"],
- )
-
- queue_users: list[ttv_api.users.User] = queue_users[:queue_size]
- random.shuffle(queue_users)
- blue_team: list[ttv_api.users.User] = queue_users[: queue_size // 2]
- red_team: list[ttv_api.users.User] = queue_users[queue_size // 2 :]
-
- c.execute(f"UPDATE {table} SET team = NULL")
- sql = f"UPDATE {table} SET team = 0 WHERE twitch_id IN ({(', ?' * (queue_size // 2))[2:]})"
- c.execute(sql, tuple(user.user_id for user in blue_team))
- sql = f"UPDATE {table} SET team = 1 WHERE twitch_id IN ({(', ?' * (queue_size - queue_size // 2))[2:]})"
- c.execute(sql, tuple(user.user_id for user in red_team))
- conn.commit()
-
- blue_team_users: list[str] = [user.display_name for user in blue_team]
- red_team_users: list[str] = [user.display_name for user in red_team]
-
- bot.send_privmsg(
- message.channel,
- [f"Blue team is: {blue_team_users}", f"Red team is: {red_team_users}"],
- reply=message.tags["id"],
- )
-
- conn.close()
-
-
-def parse(query):
- query = query.split()
- try:
- if query[1].lower() in {"ow", "overwatch", "ow2", "overwatch2"}:
- return {"--game": "ow"}
- except:
- pass
- return {"--game": "lol_queue"}
- d = dict()
- for i in shlex.split(query):
- try:
- d[i.split('=')[0]] = i.split('=')[1]
- except:
- pass
- return d
-
-
-def scrub(table_name):
- return ''.join(chr for chr in table_name if chr.isalnum() or chr == '_')
-
-
-def main(bot: Bot, message: Message):
- args = " ".join(message.value.split(" ")[1:])
- args = parse(args)
- new_teams(bot, message, scrub(args.get("--game", "lol_queue")))
+++ /dev/null
-from aptbot.bot import Message, Commands, Bot
-import os
-import logging
-import ttv_api.users
-import sqlite3
-import time
-import shlex
-
-logger = logging.getLogger(__name__)
-
-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 not_here(bot: Bot, message: Message, table: str):
- 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(
- f"""
- UPDATE {table} SET available = 0, priority_queue = null, 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()
-
-
-def parse(query):
- query = query.split()
- try:
- if query[1].lower() in {"ow", "overwatch", "ow2", "overwatch2"}:
- return {"--game": "ow"}
- except:
- pass
- return {"--game": "lol_queue"}
- d = dict()
- for i in shlex.split(query):
- try:
- d[i.split('=')[0]] = i.split('=')[1]
- except:
- pass
- return d
-
-
-def scrub(table_name):
- return ''.join(chr for chr in table_name if chr.isalnum() or chr == '_')
-
-
-def main(bot: Bot, message: Message):
- args = " ".join(message.value.split(" ")[1:])
- args = parse(args)
- not_here(bot, message, scrub(args.get("--game", "lol_queue")))
+++ /dev/null
-from aptbot.bot import Message, Commands, Bot
-import sqlite3
-import os
-import logging
-from lol_api import spectator_v4
-from lol_api import summoner_v4
-import ttv_api.users
-from tools import smart_privmsg
-import json
-
-logger = logging.getLogger(__name__)
-
-
-PERMISSION = 99
-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 find_champion(champ_id: int) -> str:
- with open(os.path.join(PATH, "data/champion.json"), "r") as f:
- champion_data = json.load(f)
- champ_id = str(champ_id)
- champion_data = champion_data["data"]
- for champion in champion_data:
- if champion_data[champion]["key"] == champ_id:
- return champion_data[champion]["name"]
- return "404"
-
-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]
- 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]),
- )
- 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"]
- )
- return
-
- if not isinstance(twitch_id, str):
- twitch_id = int(twitch_id[0].user_id)
- else:
- twitch_id = int(twitch_id)
- db_name_database = "lol_data.db"
- conn = sqlite3.connect(os.path.join(PATH, db_name_database))
- c = conn.cursor()
-
- c.execute(
- """
- SELECT summoner_id, puuid FROM accounts WHERE twitch_id = ?;
- """,
- (twitch_id,),
- )
- fetched = c.fetchall()
- c.execute(
- """
- SELECT twitch_id, summoner_id FROM accounts;
- """,
- )
- fetched_all = c.fetchall()
-
- if not fetched:
- 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])
- summoner = summoner_v4.get_summoner_from_puuid(summoners[1])
- if summoner:
- summoner_names.append(summoner.name)
- 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"],
- )
- conn.close()
- return
-
- play_with = []
- for summoner in info.participants:
- for f in fetched_all:
- if summoner.summoner_id == f[1] and summoner.summoner_id != fetched[0][0]:
- play_with.append(
- {
- "name": ttv_api.users.get_users(user_ids=[f[0]])[0].display_name,
- "champion": find_champion(summoner.champion_id),
- },
- )
- break
- msg = f"{twitch_user} is currently playing a game on: {summoner_names[-1]}"
- if play_with:
- msg += " and is playing with"
- for player in play_with:
- msg += f" {player['name']} on {player['champion']} |"
- msg = msg[:-1] + "."
-
- smart_privmsg.send(
- bot,
- message,
- msg,
- 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 tools.smart_privmsg
-import random
-import shlex
-
-logger = logging.getLogger(__name__)
-
-PERMISSION = 99
-PREFIX = "?"
-DESCRIPTION = r"Sekiro death counter"
-USER_COOLDOWN = 10
-GLOBAL_COOLDOWN = 5
-
-PATH = os.path.dirname(os.path.realpath(__file__))
-PATH = os.path.join(PATH, "..")
-
-def check_queue(bot: Bot, message: Message, table: str):
- conn = sqlite3.connect(os.path.join(PATH, "database.db"))
- c = conn.cursor()
-
- c.execute(
- f"""
- SELECT id, val FROM varvalues WHERE id = 'penta';
- """
- )
- _, val = c.fetchone()
-
- if table == "show":
- msg = f"Peks has gotten {val} pentas!"
-
- tools.smart_privmsg.send(
- bot,
- message,
- msg,
- reply=message.tags["id"],
- )
-
- conn.close()
- return
- if table == "remove":
- val = val - 1
- c.execute(
- f"""
- UPDATE varvalues SET val = ? WHERE id = 'cannon';
- """,
- (val,)
- )
-
- msg = f"Peks has gotten {val} pentas!"
-
- tools.smart_privmsg.send(
- bot,
- message,
- msg,
- reply=message.tags["id"],
- )
- conn.commit()
- conn.close()
- return
- if table == "add":
- val = val + 1
- c.execute(
- f"""
- UPDATE varvalues SET val = ? WHERE id = 'cannon';
- """,
- (val,)
- )
-
- msg = f"Peks has gotten {val} pentas!"
-
- tools.smart_privmsg.send(
- bot,
- message,
- msg,
- reply=message.tags["id"],
- )
- conn.commit()
- conn.close()
- return
-
-
-def parse(query):
- query = query.split()
- try:
- if query[0].lower() == "add":
- return {"--do": "add"}
- if query[0].lower() == "remove":
- return {"--do": "remove"}
- except:
- pass
- return {"--game": "show"}
- d = dict()
- for i in shlex.split(query):
- try:
- d[i.split('=')[0]] = i.split('=')[1]
- except:
- pass
- return d
-
-
-def scrub(table_name):
- return ''.join(chr for chr in table_name if chr.isalnum() or chr == '_')
-
-
-def main(bot: Bot, message: Message):
- args = " ".join(message.value.split(" ")[1:])
- args = parse(args)
- check_queue(bot, message, scrub(args.get("--do", "show")))
+++ /dev/null
-from aptbot.bot import Message, Commands, Bot
-import os
-import logging
-import ttv_api.users
-import sqlite3
-import tools.smart_privmsg
-import random
-import shlex
-
-logger = logging.getLogger(__name__)
-
-PERMISSION = 99
-PREFIX = "?"
-DESCRIPTION = r"Sekiro death counter"
-USER_COOLDOWN = 10
-GLOBAL_COOLDOWN = 5
-
-PATH = os.path.dirname(os.path.realpath(__file__))
-PATH = os.path.join(PATH, "..")
-
-def check_queue(bot: Bot, message: Message, table: str):
- conn = sqlite3.connect(os.path.join(PATH, "database.db"))
- c = conn.cursor()
-
- c.execute(
- f"""
- SELECT id, val FROM varvalues WHERE id = 'quadra';
- """
- )
- _, val = c.fetchone()
-
- if table == "show":
- msg = f"Peks has missed out on {val} pentas!"
-
- tools.smart_privmsg.send(
- bot,
- message,
- msg,
- reply=message.tags["id"],
- )
-
- conn.close()
- return
- if table == "remove":
- val = val - 1
- c.execute(
- f"""
- UPDATE varvalues SET val = ? WHERE id = 'cannon';
- """,
- (val,)
- )
-
- msg = f"Peks has missed out on {val} pentas!"
-
- tools.smart_privmsg.send(
- bot,
- message,
- msg,
- reply=message.tags["id"],
- )
- conn.commit()
- conn.close()
- return
- if table == "add":
- val = val + 1
- c.execute(
- f"""
- UPDATE varvalues SET val = ? WHERE id = 'cannon';
- """,
- (val,)
- )
-
- msg = f"Peks has missed out on {val} pentas!"
-
- tools.smart_privmsg.send(
- bot,
- message,
- msg,
- reply=message.tags["id"],
- )
- conn.commit()
- conn.close()
- return
-
-
-def parse(query):
- query = query.split()
- try:
- if query[0].lower() == "add":
- return {"--do": "add"}
- if query[0].lower() == "remove":
- return {"--do": "remove"}
- except:
- pass
- return {"--game": "show"}
- d = dict()
- for i in shlex.split(query):
- try:
- d[i.split('=')[0]] = i.split('=')[1]
- except:
- pass
- return d
-
-
-def scrub(table_name):
- return ''.join(chr for chr in table_name if chr.isalnum() or chr == '_')
-
-
-def main(bot: Bot, message: Message):
- args = " ".join(message.value.split(" ")[1:])
- args = parse(args)
- check_queue(bot, message, scrub(args.get("--do", "show")))
+++ /dev/null
-from aptbot.bot import Message, Commands, Bot
-import sqlite3
-import os
-
-PERMISSION = 10
-PREFIX = "\\"
-DESCRIPTION = ""
-USER_COOLDOWN = 0
-GLOBAL_COOLDOWN = 0
-
-COMMANDS_PATH = os.path.dirname(os.path.realpath(__file__))
-PATH = os.path.join(COMMANDS_PATH, "..")
-
-
-def main(bot: Bot, message: Message):
- msg = " ".join(message.value.split(" ")[1:])
- command = msg.split(" ")[0]
- command_prefix = command[0]
- command_name = command[1:]
-
- conn = sqlite3.connect(os.path.join(PATH, "database.db"))
- c = conn.cursor()
- c.execute("SELECT value FROM command_values WHERE command = ?", (command_name,))
- command_path = os.path.join(COMMANDS_PATH, f"{command_name}.py")
- hidden_command_path = os.path.join(COMMANDS_PATH, f".{command_name}.py")
- try:
- if not c.fetchone()[0]:
- try:
- os.rename(command_path, hidden_command_path)
- except FileNotFoundError:
- pass
- except TypeError:
- pass
-
- try:
- c.execute(
- "DELETE FROM commands WHERE command = ? AND prefix = ?",
- (
- command_name,
- command_prefix,
- ),
- )
- except sqlite3.IntegrityError:
- bot.send_privmsg(message.channel, f"The command {command_name} doesn't exist.")
- else:
- bot.send_privmsg(message.channel, f"Successfully removed {command_name}.")
- conn.commit()
- conn.close()
+++ /dev/null
-from aptbot.bot import Message, Commands, Bot
-
-PERMISSION = 99
-PREFIX = "?"
-DESCRIPTION = ""
-USER_COOLDOWN = 10
-GLOBAL_COOLDOWN = 10
-
-
-def main(bot: Bot, message: Message):
- msg = message.nick + " you have been scammed KEKW"
- bot.send_privmsg(message.channel, msg)
+++ /dev/null
-from aptbot.bot import Message, Commands, Bot
-import tools.smart_privmsg
-
-PERMISSION = 99
-PREFIX = "?"
-DESCRIPTION = ""
-USER_COOLDOWN = 30
-GLOBAL_COOLDOWN = 15
-
-MAX_LENGTH = 450
-
-
-def main(bot: Bot, message: Message):
- try:
- replied_message = message.tags["reply-parent-msg-body"]
- except KeyError:
- replied_message = None
- if replied_message:
- msg = replied_message
- else:
- msg = " ".join(message.value.split(" ")[1:])
- new_msg = ""
- while len(new_msg) + len(msg) < MAX_LENGTH:
- new_msg += msg + " "
- tools.smart_privmsg.send_safe(bot, message.channel, new_msg)
+++ /dev/null
-from aptbot.bot import Message, Commands, Bot
-import tools.smart_privmsg
-import scripts.translator
-
-PERMISSION = 99
-PREFIX = "?"
-DESCRIPTION = "Translates a message from any language (supported by google translate) into English. How to use: ?t <insert text to translate>"
-USER_COOLDOWN = 15
-GLOBAL_COOLDOWN = 5
-
-
-def main(bot: Bot, message: Message):
- replied_message = message.tags.get("reply-parent-msg-body", None)
- if replied_message:
- msg = replied_message
- replied_msg_id = message.tags["reply-parent-msg-id"]
- else:
- msg = " ".join(message.value.split(" ")[1:])
- replied_msg_id = None
- trans = scripts.translator.translate(msg)
- print(trans)
- tools.smart_privmsg.send(bot, message, trans, reply=replied_msg_id)
+++ /dev/null
-from aptbot.bot import Message, Commands, Bot
-import os
-import logging
-import ttv_api.users
-import sqlite3
-import tools.smart_privmsg
-import shlex
-
-logger = logging.getLogger(__name__)
-
-PERMISSION = 99
-PREFIX = "?"
-DESCRIPTION = r"Check current teams"
-USER_COOLDOWN = 30
-GLOBAL_COOLDOWN = 15
-
-PATH = os.path.dirname(os.path.realpath(__file__))
-PATH = os.path.join(PATH, "..")
-
-
-def teams(bot: Bot, message: Message, table: str):
- conn = sqlite3.connect(os.path.join(PATH, "lol_data.db"))
- c = conn.cursor()
-
- c.execute(
- f"""
- SELECT twitch_id, team FROM {table} WHERE team in (0, 1);
- """
- )
- fetched = c.fetchall()
- blue_team = []
- red_team = []
- for user in fetched:
- if user[1] == 0:
- blue_team.append(user[0])
- elif user[1] == 1:
- red_team.append(user[0])
- else:
- bot.send_privmsg(
- message.channel,
- f"Something VERY WEIRD occured. The user with id: {user[0]} is on team {user[1]}, which is neither blue = 0 or red = 1.",
- reply=message.tags["id"],
- )
-
- users = [x[0] for x in fetched]
- if not users:
- bot.send_privmsg(
- message.channel,
- "No teams have been set yet.",
- reply=message.tags["id"],
- )
- conn.close()
- return
-
- twitch = ttv_api.users.get_users(user_ids=users)
- if not twitch:
- bot.send_privmsg(
- message.channel,
- "There was an issue fetching twitch data. Sadge",
- reply=message.tags["id"],
- )
- conn.close()
- return
- blue_team_users = []
- red_team_users = []
- for twitch_user in twitch:
- if int(twitch_user.user_id) in blue_team:
- blue_team_users.append(twitch_user.display_name)
- elif int(twitch_user.user_id) in red_team:
- red_team_users.append(twitch_user.display_name)
- else:
- bot.send_privmsg(
- message.channel,
- f"Something VERY WEIRD occured. The user with id: {twitch_user.user_id} who has the name {twitch_user.display_name} is not on a team.",
- reply=message.tags["id"],
- )
-
- bot.send_privmsg(
- message.channel,
- [f"Blue team is: {blue_team_users}", f"Red team is: {red_team_users}"],
- reply=message.tags["id"],
- )
-
- conn.close()
-
-
-def parse(query):
- query = query.split()
- try:
- if query[1].lower() in {"ow", "overwatch", "ow2", "overwatch2"}:
- return {"--game": "ow"}
- except:
- pass
- return {"--game": "lol_queue"}
- d = dict()
- for i in shlex.split(query):
- try:
- d[i.split('=')[0]] = i.split('=')[1]
- except:
- pass
- return d
-
-
-def scrub(table_name):
- return ''.join(chr for chr in table_name if chr.isalnum() or chr == '_')
-
-
-def main(bot: Bot, message: Message):
- args = " ".join(message.value.split(" ")[1:])
- args = parse(args)
- teams(bot, message, scrub(args.get("--game", "lol_queue")))
+++ /dev/null
-from aptbot.bot import Message, Commands, Bot
-import os
-import logging
-import sqlite3
-import shlex
-
-logger = logging.getLogger(__name__)
-
-PERMISSION = 10
-PREFIX = "\\"
-DESCRIPTION = r"Change the team size"
-USER_COOLDOWN = 0
-GLOBAL_COOLDOWN = 0
-
-PATH = os.path.dirname(os.path.realpath(__file__))
-PATH = os.path.join(PATH, "..")
-
-
-def team_size(bot: Bot, message: Message, table: str):
- 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(
- f"""
- REPLACE INTO {table}_data (name, data) VALUES ('queuesize', ?)
- """,
- (queue_size,),
- )
- conn.commit()
-
- bot.send_privmsg(
- message.channel,
- f"Successfully changed team size to {queue_size}.",
- reply=message.tags["id"],
- )
-
- conn.close()
-
-
-def parse(query):
- query = query.split()
- try:
- if query[0].lower() in {"ow", "overwatch", "ow2", "overwatch2"}:
- return {"--game": "ow"}
- except:
- pass
- return {"--game": "lol_queue"}
- d = dict()
- for i in shlex.split(query):
- try:
- d[i.split('=')[0]] = i.split('=')[1]
- except:
- pass
- return d
-
-
-def scrub(table_name):
- return ''.join(chr for chr in table_name if chr.isalnum() or chr == '_')
-
-
-def main(bot: Bot, message: Message):
- args = " ".join(message.value.split(" ")[1:])
- args = parse(args)
- team_size(bot, message, scrub(args.get("--game", "lol_queue")))
+++ /dev/null
-from aptbot.bot import Message, Commands, Bot
-import tools.smart_privmsg
-import os
-import random
-
-PERMISSION = 99
-PREFIX = "?"
-DESCRIPTION = ""
-USER_COOLDOWN = 30
-GLOBAL_COOLDOWN = 15
-
-
-COMMANDS_PATH = os.path.dirname(os.path.realpath(__file__))
-PATH = os.path.join(COMMANDS_PATH, "..")
-DATA_PATH = os.path.join(PATH, "data")
-
-
-def main(bot: Bot, message: Message):
- accepted_path = os.path.join(DATA_PATH, "jokes")
- with open(accepted_path, "r") as f:
- jokes = [user_id.rstrip() for user_id in f]
- joke = random.choice(jokes)
-
- tools.smart_privmsg.send(bot, message, f"{joke}", reply=message.tags["id"])
+++ /dev/null
-from aptbot.bot import Message, Commands, Bot
-import os
-import logging
-from tools import smart_privmsg
-
-logger = logging.getLogger(__name__)
-
-
-PERMISSION = 99
-PREFIX = "?"
-DESCRIPTION = ""
-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):
- if message.tags.get("reply-parent-display-name", None):
- smart_privmsg.send(
- bot,
- message,
- f"{message.tags['reply-parent-display-name']}, {message.nick} is UwUing you. Will you UwU back? PauseChamp",
- reply=message.tags["reply-parent-msg-id"],
- )
- return
- try:
- user = message.value.split(" ")[1]
- except IndexError:
- smart_privmsg.send(
- bot, message, f"UwU to you too {message.nick}!", reply=message.tags["id"]
- )
- return
- else:
- smart_privmsg.send(
- bot,
- message,
- f"{user}, {message.nick} is UwUing you. Will you UwU back? PauseChamp",
- )
- return
+++ /dev/null
-from aptbot.bot import Message, Commands, Bot
-import yt_api.videos
-
-PERMISSION = 99
-PREFIX = "?"
-DESCRIPTION = "Get my newest video! Just type ?video"
-USER_COOLDOWN = 15
-GLOBAL_COOLDOWN = 15
-
-CHANNEL_ID = "UCQ7C3NUKY6TSkURdUdVoYFw"
-
-
-def main(bot: Bot, message: Message):
- video = yt_api.videos.get_newest_video(CHANNEL_ID)
- if video:
- video_link = f"https://www.youtube.com/watch?v={video.video_id}"
- msg = f'Watch Peks\' latest video "{video.video_name}" here: {video_link}'
- else:
- msg = f"Check out my youtube channel here -> https://www.youtube.com/channel/{CHANNEL_ID}"
- bot.send_privmsg(message.channel, msg)
+++ /dev/null
-from aptbot.bot import Message, Commands
-import sqlite3
-import os
-import ttv_api.users
-import logging
-
-logger = logging.getLogger(__name__)
-
-PATH = os.path.dirname(os.path.realpath(__file__))
-logger.debug(f"PATH set to: {PATH}")
-
-STREAMER_PATH = os.path.abspath(os.path.join(__file__, ".."))
-logger.debug(f"STREAMER_PATH set to: {STREAMER_PATH}")
-streamer_login = os.path.split(STREAMER_PATH)[1]
-logger.debug(f"streamer_login set to: {streamer_login}")
-
-
-def create_variables_db():
- db_name_var = "variables.db"
- conn = sqlite3.connect(os.path.join(PATH, db_name_var))
- c = conn.cursor()
- logger.info(f"connected to database {db_name_var}")
-
- c.execute(
- """
- CREATE TABLE IF NOT EXISTS variables (
- name TEXT NOT NULL,
- type TEXT NOT NULL,
- value TEXT NOT NULL,
- PRIMARY KEY (name)
- )
- """
- )
- logger.info(f"created table variables")
-
- c.execute(
- """
- CREATE TABLE IF NOT EXISTS methods (
- name TEXT NOT NULL,
- type TEXT NOT NULL,
- input TEXT,
- PRIMARY KEY (name, type)
- )
- """
- )
- logger.info(f"created table methods")
-
- c.execute(
- """
- CREATE TABLE IF NOT EXISTS list_values (
- id INTEGER NOT NULL,
- name TEXT NOT NULL,
- type TEXT NOT NULL,
- value TEXT NOT NULL,
- FOREIGN KEY(name) REFERENCES variables(name)
- PRIMARY KEY (id, name)
- )
- """
- )
- logger.info(f"created table list_values")
-
- conn.commit()
- conn.close()
-
-
-def create_lol_database():
- db_name_database = "lol_data.db"
- conn = sqlite3.connect(os.path.join(PATH, db_name_database))
- c = conn.cursor()
- logger.info(f"connected to database {db_name_database}")
-
- c.execute(
- """
- CREATE TABLE IF NOT EXISTS accounts (
- puuid TEXT NOT NULL,
- summoner_id TEXT NOT NULL,
- account_id TEXT NOT NULL,
- twitch_id INTEGER,
- PRIMARY KEY (puuid)
- )
- """
- )
- logger.info(f"created table accounts")
-
- c.execute(
- """
- CREATE TABLE IF NOT EXISTS lol_queue (
- twitch_id INTEGER NOT NULL,
- position INTEGER NOT NULL,
- available INTEGER NOT NULL,
- last_available INTEGER,
- time_remaining INTEGER NOT NULL,
- team INTEGER,
- priority_queue INTEGER,
- 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")
-
- c.execute(
- """
- CREATE TABLE IF NOT EXISTS ow (
- twitch_id INTEGER NOT NULL,
- position INTEGER NOT NULL,
- available INTEGER NOT NULL,
- last_available INTEGER,
- time_remaining INTEGER NOT NULL,
- team INTEGER,
- priority_queue INTEGER,
- PRIMARY KEY (twitch_id)
- );
- """
- )
- logger.info(f"created table ow")
-
- c.execute(
- """
- CREATE TABLE IF NOT EXISTS ow_data (
- name TEXT NOT NULL,
- data INTEGER NOT NULL,
- PRIMARY KEY (name)
- );
- """
- )
- logger.info(f"created table ow_data")
-
- conn.commit()
- conn.close()
-
-
-def create_database():
- db_name_database = "database.db"
- conn = sqlite3.connect(os.path.join(PATH, db_name_database))
- c = conn.cursor()
- logger.info(f"connected to database {db_name_database}")
-
- c.execute(
- """
- CREATE TABLE IF NOT EXISTS commands (
- command TEXT NOT NULL,
- prefix TEXT NOT NULL,
- permission INTEGER NOT NULL,
- description TEXT,
- user_cooldown INTEGER NOT NULL,
- global_cooldown INTEGER NOT NULL,
- last_used INTEGER NOT NULL,
- PRIMARY KEY (command)
- )
- """
- )
- logger.info(f"created table commands")
-
- c.execute(
- """
- CREATE TABLE IF NOT EXISTS varvalues (
- id TEXT NOT NULL,
- val INTEGER NOT NULL,
- PRIMARY KEY (id)
- )
- """
- )
- logger.info(f"created table varvalues")
-
-
- c.execute(
- """
- CREATE TABLE IF NOT EXISTS clips (
- url TEXT NOT NULL,
- from_user INTEGER NOT NULL,
- PRIMARY KEY (url)
- )
- """
- )
- logger.info(f"created table clips")
-
- c.execute(
- """
- CREATE TABLE IF NOT EXISTS users (
- user_id text NOT NULL,
- permission INTEGER NOT NULL,
- PRIMARY KEY (user_id)
- )
- """
- )
- logger.info(f"created table users")
-
- admin_id = ttv_api.users.get_users(user_logins=["skgyorugo"])
- aptbot_id = ttv_api.users.get_users(user_logins=["murphyai"])
- broadcaster_id = ttv_api.users.get_users(user_logins=[streamer_login])
- if admin_id:
- c.execute("INSERT OR IGNORE INTO users VALUES (?, ?)", (admin_id[0].user_id, 0))
- logger.info(f"inserted user {admin_id[0].user_id} with permission {0}")
- if aptbot_id:
- c.execute(
- "INSERT OR IGNORE INTO users VALUES (?, ?)", (aptbot_id[0].user_id, 0)
- )
- logger.info(f"inserted user {aptbot_id[0].user_id} with permission {0}")
- if broadcaster_id:
- c.execute(
- "INSERT OR IGNORE INTO users VALUES (?, ?)", (broadcaster_id[0].user_id, 1)
- )
- logger.info(f"inserted user {broadcaster_id[0].user_id} with permission {1}")
-
- c.execute(
- """
- CREATE TABLE IF NOT EXISTS cooldowns (
- user_id TEXT NOT NULL,
- command TEXT NOT NULL,
- user_cooldown INTEGER NOT NULL,
- FOREIGN KEY(user_id) REFERENCES users(user_id)
- FOREIGN KEY(command) REFERENCES commands(command)
- PRIMARY KEY (user_id, command)
- )
- """
- )
- logger.info(f"created table cooldowns")
-
- c.execute(
- """
- CREATE TABLE IF NOT EXISTS command_values (
- command TEXT NOT NULL,
- value TEXT NOT NULL,
- FOREIGN KEY(command) REFERENCES commands(command)
- )
- """
- )
- logger.info(f"created table command_values")
-
- c.execute(
- """
- CREATE TABLE IF NOT EXISTS auto_messages (
- name TEXT NOT NULL,
- cooldown INTEGER NOT NULL,
- end_time INTEGER NOT NULL,
- last_used INTEGER NOT NULL,
- PRIMARY KEY (name)
- )
- """
- )
- logger.info(f"created table auto_messages")
-
- c.execute(
- """
- CREATE TABLE IF NOT EXISTS auto_message_values (
- name TEXT NOT NULL,
- value TEXT NOT NULL,
- FOREIGN KEY(name) REFERENCES auto_messages(name)
- )
- """
- )
- logger.info(f"created table auto_message_values")
-
- c.execute(
- """
- CREATE TABLE IF NOT EXISTS stream_info (
- start_stream_ts INTEGER NOT NULL,
- last_checked INTEGER NOT NULL,
- ended INTEGER NOT NULL,
- PRIMARY KEY (start_stream_ts)
- )
- """
- )
- logger.info(f"created table stream_info")
-
- conn.commit()
- conn.close()
-
-
-def update_commands_in_database(modules, commands):
- db_name_database = "database.db"
- conn = sqlite3.connect(os.path.join(PATH, db_name_database))
- c = conn.cursor()
- logger.info(f"connected to database {db_name_database}")
-
- for command in commands:
- command_name = command.split(".")[0]
- command_permission = modules[command_name].PERMISSION
- command_prefix = modules[command_name].PREFIX
- command_description = modules[command_name].DESCRIPTION
- command_user_cooldown = modules[command_name].USER_COOLDOWN
- command_global_cooldown = modules[command_name].GLOBAL_COOLDOWN
- command_last_used = 0
- c.execute(
- "REPLACE INTO commands VALUES (?, ?, ?, ?, ?, ?, ?)",
- (
- command_name,
- command_prefix,
- command_permission,
- command_description,
- command_user_cooldown,
- command_global_cooldown,
- command_last_used,
- ),
- )
- logger.info(f"updating commands command_name: {command_prefix}{command_name}")
- conn.commit()
- conn.close()
-
-
-def add_message_to_chat_history(message: Message):
- if message.command != Commands.PRIVMSG:
- return
- conn = sqlite3.connect(os.path.join(PATH, "chat_history.db"))
- c = conn.cursor()
-
- try:
- bits = message.tags["bits"]
- except KeyError:
- bits = None
- try:
- rp_display_name = message.tags["reply-parent-display-name"]
- rp_msg_body = message.tags["reply-parent-msg-body"]
- rp_msg_id = message.tags["reply-parent-msg-id"]
- rp_user_id = int(message.tags["reply-parent-user-id"])
- rp_user_login = message.tags["reply-parent-user-login"]
- except KeyError:
- rp_display_name = None
- rp_msg_body = None
- rp_msg_id = None
- rp_user_id = None
- rp_user_login = None
-
- c.execute(
- """
- INSERT INTO chat (
- "id",
- "nick",
- "channel",
- "message",
- "tmi-sent-ts",
- "badge-info",
- "badges",
- "bits",
- "color",
- "display-name",
- "first-msg",
- "mod",
- "room-id",
- "user-id",
- "user-type",
- "turbo",
- "subscriber",
- "reply-parent-display-name",
- "reply-parent-msg-body",
- "reply-parent-msg-id",
- "reply-parent-user-id",
- "reply-parent-user-login"
- ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);
- """,
- (
- message.tags["id"],
- message.nick,
- message.channel,
- message.value,
- int(message.tags["tmi-sent-ts"]),
- message.tags["badge-info"],
- message.tags["badges"],
- bits,
- message.tags["color"],
- message.tags["display-name"],
- int(message.tags["first-msg"]),
- int(message.tags["mod"]),
- int(message.tags["room-id"]),
- int(message.tags["user-id"]),
- message.tags["user-type"],
- int(message.tags["turbo"]),
- int(message.tags["subscriber"]),
- rp_display_name,
- rp_msg_body,
- rp_msg_id,
- rp_user_id,
- rp_user_login,
- ),
- )
- conn.commit()
- conn.close()
-
-
-def create_chat_history_database():
- conn = sqlite3.connect(os.path.join(PATH, "chat_history.db"))
- c = conn.cursor()
-
- c.execute(
- """
- CREATE TABLE IF NOT EXISTS "chat" (
- "id" TEXT NOT NULL,
- "nick" TEXT NOT NULL,
- "channel" TEXT NOT NULL,
- "message" TEXT NOT NULL,
- "tmi-sent-ts" INTEGER NOT NULL,
- "badge-info" TEXT NOT NULL,
- "badges" TEXT NOT NULL,
- "bits" TEXT,
- "color" TEXT NOT NULL,
- "display-name" TEXT NOT NULL,
- "first-msg" INTEGER NOT NULL,
- "mod" INTEGER NOT NULL,
- "room-id" INTEGER NOT NULL,
- "user-id" INTEGER NOT NULL,
- "user-type" TEXT NOT NULL,
- "turbo" INTEGER NOT NULL,
- "subscriber" INTEGER NOT NULL,
- "reply-parent-display-name" TEXT,
- "reply-parent-msg-body" TEXT,
- "reply-parent-msg-id" TEXT,
- "reply-parent-user-id" INTEGER,
- "reply-parent-user-login" TEXT,
- PRIMARY KEY("id")
- );
- """
- )
- conn.commit()
- conn.close()
-
-
-def update_auto_messages_in_database(modules, auto_messages):
- conn = sqlite3.connect(os.path.join(PATH, "database.db"))
- c = conn.cursor()
-
- for auto_message in auto_messages:
- auto_message_name = auto_message.split(".")[0]
- auto_message_cooldown = modules[auto_message_name].COOLDOWN
- auto_message_end_time = modules[auto_message_name].END_TIME
- auto_message_last_used = 0
- try:
- c.execute(
- "INSERT INTO auto_messages (name, cooldown, end_time, last_used) VALUES (?, ?, ?, ?)",
- (
- auto_message_name,
- auto_message_cooldown,
- auto_message_end_time,
- auto_message_last_used,
- ),
- )
- except Exception as e:
- c.execute(
- """
- UPDATE auto_messages
- SET
- cooldown = ?,
- end_time = ?
- WHERE
- name = ?
- """,
- (
- auto_message_cooldown,
- auto_message_end_time,
- auto_message_name,
- ),
- )
- conn.commit()
- conn.close()
+++ /dev/null
-import urllib3
-from dataclasses import dataclass
-import os
-import json
-import logging
-from typing import Optional
-
-BASE_URL = "https://euw1.api.riotgames.com"
-
-KEY = os.getenv("LOL_STREAM_HELPER")
-
-HEADER = {"X-Riot-Token": KEY}
+++ /dev/null
-from lol_api import *
-
-logger = logging.getLogger(__name__)
+++ /dev/null
-from lol_api import *
-from typing import Optional
-
-logger = logging.getLogger(__name__)
-
-
-@dataclass
-class BannedChampion:
- pick_turn: int
- 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
- perks: Perks
- profile_icon_id: int
- bot: bool
- team_id: int
- summoner_name: str
- summoner_id: str
- spell1_id: int
- spell2_id: int
-
-
-@dataclass
-class GameInfo:
- game_id: int
- game_type: str
- game_start_time: int
- map_id: int
- game_length: int
- platform_id: str
- game_mode: str
- banned_champions: list[BannedChampion]
- 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
- http = urllib3.PoolManager()
- r = http.request(
- "GET",
- url,
- headers=HEADER,
- )
- if r.status == 404:
- 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}"
- )
- return None
- data = json.loads(r.data.decode("utf-8"))
-
- banned_champions: list[BannedChampion] = []
- for banned in data["bannedChampions"]:
- banned_champions.append(
- BannedChampion(
- banned["pickTurn"],
- banned["championId"],
- banned["teamId"],
- )
- )
-
- participants: list[CurrentGameParticipant] = []
- for participant in data["participants"]:
- perks = Perks(
- [perk_id for perk_id in participant["perks"]["perkIds"]],
- participant["perks"]["perkStyle"],
- participant["perks"]["perkSubStyle"],
- )
- participants.append(
- CurrentGameParticipant(
- participant["championId"],
- perks,
- participant["profileIconId"],
- participant["bot"],
- participant["teamId"],
- participant["summonerName"],
- participant["summonerId"],
- participant["spell1Id"],
- participant["spell2Id"],
- )
- )
-
- return GameInfo(
- data["gameId"],
- data["gameType"],
- data["gameStartTime"],
- data["mapId"],
- data["gameLength"],
- data["platformId"],
- data["gameMode"],
- banned_champions,
- data.get("gameQueueConfigId", None),
- data["observers"]["encryptionKey"],
- participants,
- )
+++ /dev/null
-from lol_api import *
-
-logger = logging.getLogger(__name__)
-
-
-@dataclass
-class Summoner:
- summoner_id: str
- account_id: str
- puuid: str
- name: str
- profile_icon_id: int
- revision_date: int
- summoner_level: int
-
-
-def get_summoner_from_puuid(puuid: str) -> Optional[Summoner]:
- endpoint = f"/lol/summoner/v4/summoners/by-puuid/{puuid}"
- url = BASE_URL + endpoint
- logger.debug(f"url is: {url}")
- http = urllib3.PoolManager()
- r = http.request(
- "GET",
- url,
- headers=HEADER,
- )
- if r.status != 200:
- logger.warning(
- f"Couldn't retrieve summoner with puuid: {puuid}. Status code {r.status}"
- )
- return None
- data = json.loads(r.data.decode("utf-8"))
- return Summoner(
- data["id"],
- data["accountId"],
- data["puuid"],
- data["name"],
- data["profileIconId"],
- data["revisionDate"],
- data["summonerLevel"],
- )
-
-
-def get_summoner_from_name(name: str) -> Optional[Summoner]:
- endpoint = f"/lol/summoner/v4/summoners/by-name/{name}"
- url = BASE_URL + endpoint
- logger.debug(f"url is: {url}")
- http = urllib3.PoolManager()
- r = http.request(
- "GET",
- url,
- headers=HEADER,
- )
- if r.status != 200:
- logger.warning(f"Couldn't retrieve summoner: {name}. Status code {r.status}")
- return None
- data = json.loads(r.data.decode("utf-8"))
- return Summoner(
- data["id"],
- data["accountId"],
- data["puuid"],
- data["name"],
- data["profileIconId"],
- data["revisionDate"],
- data["summonerLevel"],
- )
+++ /dev/null
-from aptbot import Bot, Message, Commands
-import os
-import importlib
-import importlib.util
-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
-import scripts.chatting
-import scripts.chat
-import scripts.crylaugh
-import database_manager
-import analyze_auto_message
-import time
-import logging
-from threading import Event
-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)
-reload(scripts.chatting)
-reload(scripts.chat)
-reload(scripts.crylaugh)
-reload(database_manager)
-reload(analyze_auto_message)
-
-logger = logging.getLogger(__name__)
-
-PATH = os.path.dirname(os.path.realpath(__file__))
-logger.info(f"PATH set to: {PATH}")
-COMMANDS_PATH = os.path.join(PATH, "commands")
-logger.info(f"COMMANDS_PATH set to: {COMMANDS_PATH}")
-AUTO_MESSAGES_PATH = os.path.join(PATH, "auto_messages")
-logger.info(f"AUTO_MESSAGES_PATH set to: {AUTO_MESSAGES_PATH}")
-
-commands_specs = {}
-commands_modules = {}
-
-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))
-]
-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)
- )
-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))
-]
-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)
- )
-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])
- if not commands_specs[spec]:
- continue
- try:
- commands_specs[spec].loader.exec_module(commands_modules[spec])
- except Exception as e:
- logger.critical(traceback.format_exc())
- logger.critical(f"Problem Loading Module: {e}")
-
-for spec in auto_message_specs:
- auto_message_modules[spec] = importlib.util.module_from_spec(
- auto_message_specs[spec]
- )
- if not auto_message_specs[spec]:
- continue
- try:
- auto_message_specs[spec].loader.exec_module(auto_message_modules[spec])
- except Exception as e:
- logger.critical(traceback.format_exc())
- logger.critical(f"Problem Loading Module: {e}")
-
-
-database_manager.create_database()
-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)
-
-
-def start(bot: Bot, message: Message, stop_event: Event):
- i = 0
- wait = 5
- while not stop_event.is_set():
- i += wait
- started = tools.smart_start_stream_time.update_start_stream_timestamp()
- if started == "START":
- bot.send_privmsg(
- message.channel, "/announce Stream has started, you can now use ?join"
- )
- elif started == "END":
- bot.send_privmsg(message.channel, "Stream has ended")
- if i >= 30:
- analyze_auto_message.do_auto_message(bot, message, auto_message_modules)
- i = 0
- time.sleep(wait)
-
-
-def main(bot: Bot, message: Message):
- if message.command == Commands.PRIVMSG:
- database_manager.add_message_to_chat_history(message)
- if message.value[0] in {"?", "\\"}:
- analyze_command.do_command(bot, message, commands_modules)
- scripts.unit_converter.send_metric(bot, message)
- scripts.alwase.alwase(bot, message)
- scripts.chatting.chatting(bot, message)
- scripts.chatting.chatting_annoy(bot, message)
- scripts.chat.chat(bot, message)
- scripts.crylaugh.crylaugh(bot, message)
-
- # if message.command == Commands.PART:
- # if message.nick in {'jelemar', 'flauenn', 'ihaspeks', 'blobin_wobin', 'officiallysp'}:
- # bot.send_privmsg(message.channel, f"/announce {message.nick} has left chat")
- # if message.command == Commands.JOIN:
- # if message.nick in {'jelemar', 'flauenn', 'ihaspeks', 'blobin_wobin', 'officiallysp'}:
- # bot.send_privmsg(message.channel, f"/announce {message.nick} has joined chat")
-
- tools.raid.raid(bot, message)
+++ /dev/null
-beautifulsoup4==4.11.1
-black==22.3.0
-blis==0.7.7
-catalogue==2.0.7
-certifi==2022.5.18.1
-charset-normalizer==2.0.12
-click==8.1.3
-cymem==2.0.6
-deep-translator==1.8.3
-en-core-web-sm @ https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-3.3.0/en_core_web_sm-3.3.0-py3-none-any.whl
-flake8==4.0.1
-flake8-black==0.3.3
-idna==3.3
-Jinja2==3.1.2
-langcodes==3.3.0
-MarkupSafe==2.1.1
-mccabe==0.6.1
-murmurhash==1.0.7
-mypy-extensions==0.4.3
-numpy==1.22.4
-packaging==21.3
-pathspec==0.9.0
-pathy==0.6.1
-platformdirs==2.5.2
-preshed==3.0.6
-pycodestyle==2.8.0
-pydantic==1.8.2
-pyflakes==2.4.0
-pyparsing==3.0.9
-python-dotenv==0.20.0
-requests==2.27.1
-smart-open==5.2.1
-soupsieve==2.3.2.post1
-spacy==3.3.0
-spacy-legacy==3.0.9
-spacy-loggers==1.0.2
-srsly==2.4.3
-thinc==8.0.16
-tomli==2.0.1
-tqdm==4.64.0
-typer==0.4.1
-typing-extensions==4.2.0
-urllib3==1.26.9
-wasabi==0.9.1
-websocket-client==1.3.2
+++ /dev/null
-from aptbot.bot import Bot, Message, Commands
-import tools.smart_privmsg
-import random
-
-
-def alwase(bot: Bot, message: Message):
- if "always" not in message.value.lower():
- return
- try:
- replied_msg_id = message.tags["id"]
- except KeyError:
- replied_msg_id = None
- msgs = [
- "It's ALWASE gigaMadge",
- "Why don't you spell it ALWASE ? gigaMadge",
- "Spell it ALWASE or peepoArriveBan",
- ]
- msg = random.choice(msgs)
- tools.smart_privmsg.send(bot, message, msg, reply=replied_msg_id)
+++ /dev/null
-from aptbot.bot import Message, Commands, Bot
-import tools.smart_privmsg
-import openai
-import os
-
-openai.api_key = os.getenv("OPENAI_API")
-
-def chat(bot: Bot, message: Message):
- if not message.nick in {'skgyorugo', 'ihaspeks'}:
- return
- if not message.value.startswith("# "):
- return
-
- replied_message = message.tags.get("reply-parent-msg-body", None)
- if replied_message:
- msg = replied_message
- replied_msg_id = message.tags["reply-parent-msg-id"]
- else:
- msg = " ".join(message.value.split(" ")[1:])
- replied_msg_id = message.tags['id']
-
- response = openai.Completion.create(
- model="text-davinci-003",
- prompt=msg,
- temperature=1,
- max_tokens=4000,
- top_p=0.3,
- frequency_penalty=0.5,
- presence_penalty=0.5,
- )
-
- if response:
- msg = response["choices"][0]["text"]
- msg = msg.replace("\n", " ")
- else:
- msg = "Sadge nothing was returned"
-
- tools.smart_privmsg.send(bot, message, msg, reply=replied_msg_id)
+++ /dev/null
-from aptbot.bot import Bot, Message, Commands
-import tools.smart_privmsg
-import random
-
-
-def chatting(bot: Bot, message: Message):
- if "Chatting" not in message.value:
- return
- if random.random() > 0.4:
- return
- msg = ""
- if "reply-parent-msg-body" in message.tags:
- if message.value.split(" ")[1] == "Chatting":
- msg = " ".join(message.value.split(" ")[1:])
- else:
- if message.value.split(" ")[0] == "Chatting":
- msg = message.value
- if msg:
- tools.smart_privmsg.send(bot, message, msg)
-
-
-def chatting_annoy(bot: Bot, message: Message):
- nicks = {}
- if message.nick.lower() not in nicks:
- return
- msg = "Chatting " + message.value
- # msg = "Pepelaff " + message.value
- tools.smart_privmsg.send(bot, message, msg)
+++ /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__)
-
-
-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")
- c.execute("DELETE FROM ow")
- conn.commit()
-
- c.execute(
- """
- INSERT INTO lol_queue (
- "twitch_id",
- "position",
- "available",
- "last_available",
- "time_remaining"
- ) VALUES (?, ?, ?, ?, ?);
- """,
- (
- twitch_id,
- 0,
- 1,
- None,
- 9999999,
- ),
- )
- c.execute(
- """
- INSERT INTO ow (
- "twitch_id",
- "position",
- "available",
- "last_available",
- "time_remaining"
- ) VALUES (?, ?, ?, ?, ?);
- """,
- (
- twitch_id,
- 0,
- 1,
- None,
- 9999999,
- ),
- )
- conn.commit()
-
- conn.close()
+++ /dev/null
-import os
-import random
-import sqlite3
-import logging
-from fastapi import FastAPI
-from fastapi.middleware.cors import CORSMiddleware
-
-app = FastAPI()
-
-origins = ["*"]
-
-app.add_middleware(
- CORSMiddleware,
- allow_origins=origins,
- allow_credentials=True,
- allow_methods=["*"],
- allow_headers=["*"],
-)
-
-@app.get("/clip")
-async def root():
- clips = [
- "https://clips-media-assets2.twitch.tv/AT-cm%7CMGyhlrJbd3gtietAgP63LA.mp4",
- "https://clips-media-assets2.twitch.tv/WATxq6O_aQBU1qrftJJ0fQ/AT-cm%7CWATxq6O_aQBU1qrftJJ0fQ.mp4",
- ]
- return random.choice(clips)
-
-# logger = logging.getLogger(__name__)
-
-# PATH = os.path.dirname(os.path.realpath(__file__))
-# logger.debug(f"PATH set to: {PATH}")
-
-
-# def do_command(bot: Bot, message: Message, command_modules: dict):
-# db_name_database = "database.db"
-# conn = sqlite3.connect(os.path.join(PATH, db_name_database))
-# c = conn.cursor()
-# logger.info(f"connected to database {db_name_database}")
+++ /dev/null
-from aptbot.bot import Bot, Message, Commands
-import tools.smart_privmsg
-import random
-
-
-def crylaugh(bot: Bot, message: Message):
- if random.random() > 0.05:
- return
- if "😂" not in message.value:
- return
- try:
- replied_msg_id = message.tags["id"]
- except KeyError:
- replied_msg_id = None
- msg = "Oh 😂 look 😂 at 😂 me 😂 I 😂 use 😂 this 😂 funny 😂 emoji 😂 hahahaha 😂😂😂😂😂 lit 💯 👌"
- tools.smart_privmsg.send(bot, message, msg, reply=replied_msg_id)
+++ /dev/null
-from deep_translator import GoogleTranslator
-
-
-def translate(text: str) -> str:
- trans = GoogleTranslator(source="auto", target="en").translate(text)
- return trans
+++ /dev/null
-from aptbot.bot import Bot, Message, Commands
-import spacy
-import re
-import tools.smart_privmsg
-
-nlp = spacy.load("en_core_web_sm")
-
-
-def send_metric(bot: Bot, message: Message):
- text = ""
- ft_inch, cm = _tometric(message.value)
- for i in range(len(cm)):
- if cm[i] > 230:
- text += f"{ft_inch[i][0]:.1f}ft. and {ft_inch[i][1]:.1f}in. is {cm[i] / 100:.2f}m. | "
- elif cm[i] > 0:
- text += f"{ft_inch[i][0]:.1f}ft. and {ft_inch[i][1]:.1f}in. is {cm[i]:.1f}cm. | "
- if text:
- try:
- replied_msg_id = message.tags["id"]
- except KeyError:
- replied_msg_id = None
- tools.smart_privmsg.send(bot, message, text, reply=replied_msg_id)
-
-
-def _tometric(text: str) -> tuple[list[tuple[int, int]], list[float]]:
- ft_inch: list[tuple] = []
- feet = 0
- inches = 0
- text = text.replace("-", " ")
- text = re.sub(r"([0-9]+(\.[0-9]+)?)", r"\1 ", text)
- text = re.sub(r"\s{2,}", r" ", text)
- doc = nlp(text)
- feet_was_last = False
- next_should_be_double = False
- found_single = False
- for w in doc:
- # print(w.text, w.pos_)
- if w.pos_ in {"AUX", "VERB", "ADP"}:
- if feet_was_last and not next_should_be_double:
- ft_inch.append((feet, 0.0))
- feet = 0
- inches = 0
- if w.like_num or w.pos_ == "NUM":
- # index_of_previous_token = w.i - 1
- # try:
- # prev_token = doc[index_of_previous_token]
- # print(prev_token.lemma_)
- # if prev_token.lemma_ != "be":
- # continue
- # except:
- # pass
- # if "'" in w.text:
- # feet_and_inches = w.text.split("'")
- # try:
- # feet = float(feet_and_inches[0])
- # inches = float(feet_and_inches[1])
- # except:
- # pass
- index_of_next_token = w.i + 1
- try:
- next_token = doc[index_of_next_token]
- if next_token.lemma_ in {"ft", "foot", "'"}:
- if next_token.lemma_ == "'" and not next_should_be_double:
- next_should_be_double = True
- elif next_token.lemma_ == "'":
- feet = 0
- inches = 0
- continue
- if feet_was_last:
- ft_inch.append((feet, 0.0))
- feet = float(w.text)
- feet_was_last = True
- elif next_token.lemma_ in {"inch", '"'}:
- if next_token.lemma_ == '"' and next_should_be_double:
- inches = float(w.text)
- next_should_be_double = False
- elif next_token.lemma_ == '"':
- inches = 0
- elif next_should_be_double:
- feet = 0
- inches = float(w.text)
- else:
- inches = float(w.text)
- ft_inch.append((feet, inches))
- feet = 0
- inches = 0
- feet_was_last = False
- except:
- pass
- if feet_was_last and not next_should_be_double:
- ft_inch.append((feet, 0.0))
- cm: list[float] = []
- for unit in ft_inch:
- cm.append((unit[0] * 12 + unit[1]) * 2.54)
- return (ft_inch, cm)
+++ /dev/null
-import os
-import sqlite3
-
-TOOLS_PATH = os.path.dirname(os.path.realpath(__file__))
-PATH = os.path.join(TOOLS_PATH, "..")
-
-DEFAULT_PERMISSION = 99
-
-
-def get_permission_from_id(user_id: str) -> int:
- conn = sqlite3.connect(os.path.join(PATH, "database.db"))
- c = conn.cursor()
- c.execute("SELECT permission FROM users WHERE user_id = ?", (user_id,))
- fetched_user = c.fetchone()
- if fetched_user:
- return fetched_user[0]
-
- return DEFAULT_PERMISSION
+++ /dev/null
-import ttv_api.channel
-from aptbot.bot import Bot, Message, Commands
-
-
-def raid(bot: Bot, message: Message):
- if message.command == Commands.USERNOTICE and message.tags["msg-id"] == "raid":
- raider_name = message.tags["msg-param-displayName"]
- raider_login = message.tags["msg-param-login"]
- raider_id = message.tags["user-id"]
- raider_channel_info = ttv_api.channel.get_channels(raider_id)
- raider_game = ""
- if raider_channel_info:
- raider_game = raider_channel_info[0].game_name
- viewers = message.tags["msg-param-viewerCount"]
- viewers = f"{viewers} viewer" if viewers == "1" else f"{viewers} viewers"
- msg_reply = f"POGGERS {raider_name} has raided {message.channel} \
- with {viewers}!!! Why don't you check them out at: \
- https://twitch.tv/{raider_login}"
- if raider_game:
- msg_reply += f" they were just playing {raider_game}!"
- bot.send_privmsg(message.channel, msg_reply)
+++ /dev/null
-from aptbot.bot import Bot, Message, Commands
-from typing import Union
-from .. import database_manager
-import time
-
-MAX_LENGTH = 480
-
-
-def _split_message(message: str) -> list[str]:
- split_count = len(message) // MAX_LENGTH + 1
- 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 + " "
-
- 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)):
- 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
- messages[i] = messages[i].replace("always", "alwase")
- messages[i] = messages[i].replace("Always", "Alwase")
- messages[i] = messages[i].replace("ALWAYS", "ALWASE")
- else:
- while True:
- if (
- messages.startswith("/")
- or messages.startswith("!")
- or messages.startswith("\\")
- or messages.startswith("?")
- ):
- messages = messages[1:]
- else:
- break
- messages = messages.replace("always", "alwase")
- messages = messages.replace("Always", "Alwase")
- messages = messages.replace("ALWAYS", "ALWASE")
- 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,
-):
- # 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:])
- message = message.replace("{message}", msg)
- message = message.replace("{nick}", message_data.nick)
- message = message.replace("{channel}", message_data.channel)
-
- messages = _split_message(message)
- for message in messages:
- if reply:
- tags = {"display-name": "MurphyAI", "tmi-sent-ts": int(time.time() * 1000), "user-id": "784114488", "room-id": "169701299", "reply-parent-msg-id": reply}
- database_manager.add_message_tochat_history(
- Message(
- tags=tags,
- nick="murphyai",
- command=Commands.PRIVMSG,
- message_data.channel,
- value=message
- )
- )
- if safe_send:
- send_safe(bot, message_data.channel, messages, reply)
- else:
- bot.send_privmsg(message_data.channel, messages, reply)
+++ /dev/null
-import time
-import os
-import ttv_api.users
-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__)
-
-STREAMER_PATH = os.path.abspath(os.path.join(__file__, "../.."))
-logger.debug(f"STREAMER_PATH set to: {STREAMER_PATH}")
-TOOLS_PATH = os.path.dirname(os.path.realpath(__file__))
-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():
- logger.info(f"{STREAMER_LOGIN} has ended their stream")
- clean_queue.clean_queue()
-
-
-def start_stream():
- logger.info(f"{STREAMER_LOGIN} has started their stream")
- clean_queue.clean_queue()
-
-
-def start_stream_timestamp() -> Optional[int]:
- 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[str]:
- conn = sqlite3.connect(os.path.join(PATH, "database.db"))
- c = conn.cursor()
-
- c.execute("SELECT MAX(last_checked) FROM stream_info")
- max_last_checked = c.fetchone()
- if max_last_checked:
- c.execute(
- """
- SELECT
- start_stream_ts,
- last_checked
- FROM
- stream_info
- WHERE
- last_checked = ?
- AND ended = 0
- """,
- (max_last_checked[0],),
- )
-
- fetched = c.fetchone()
-
- if fetched:
- start_stream_ts, last_checked = fetched
- if time.time() < last_checked + CHECK_STREAMTIME_CD:
- conn.close()
- return
-
- stream_info = ttv_api.stream.get_streams(user_logins=[STREAMER_LOGIN])
- if not stream_info and not fetched:
- conn.close()
- return
-
- if not stream_info:
- start_stream_ts, last_checked = fetched
- if time.time() < last_checked + MAX_OFF_STREAM_MARGIN:
- conn.close()
- return
-
- c.execute(
- "REPLACE INTO stream_info VALUES (?, ?, ?)",
- (
- start_stream_ts,
- last_checked,
- 1,
- ),
- )
- conn.commit()
- conn.close()
- # TODO add hook, streamer ended stream
- end_stream()
- return "END"
-
- if not fetched:
- start_stream_ts = int(stream_info[0].started_at.timestamp())
- current_time = int(time.time())
- c.execute(
- "REPLACE INTO stream_info VALUES (?, ?, ?)",
- (
- start_stream_ts,
- current_time,
- 0,
- ),
- )
- conn.commit()
- conn.close()
- start_stream()
- return "START"
-
- start_stream_ts, last_checked = fetched
- current_time = int(time.time())
- c.execute(
- "REPLACE INTO stream_info VALUES (?, ?, ?)",
- (
- start_stream_ts,
- current_time,
- 0,
- ),
- )
- conn.commit()
- conn.close()
- return
+++ /dev/null
-import os
-import re
-import sqlite3
-
-PATH = os.path.dirname(os.path.realpath(__file__))
-PATH = os.path.join(PATH, "..")
-
-
-class Expression:
- def __init__(self, name: str, list_id: int, method: str, value: str):
- self.name = name
- self.list_id = list_id
- self.method = method
- self.value = value
-
- def eval(self):
- conn = sqlite3.connect(os.path.join(PATH, "variables.db"))
- c = conn.cursor()
-
- if self.list_id:
- # TODO
- c.execute(
- """
- SELECT
- *
- FROM
- list_values
- INNER JOIN methods USING(type)
- WHERE
- list_values.name = ?
- AND list_values.id = ?
- AND methods.name = ?
- """,
- (self.name, self.list_id, self.method),
- )
- conn.close()
- pass
-
- def __repr__(self) -> str:
- print(type(self.list_id))
- return f"Expression('{self.name}', '{self.list_id}', '{self.method}', '{self.value}')"
-
-
-def parse(text: str):
- value = text
- reg_parse = re.compile(r"\$(\w+)\[?(\d+)?\]?\.(\w+)\((.+)?\)")
-
- expressions: list[Expression] = []
- while True:
-
- try:
- name, list_id, method, value = reg_parse.findall(value)[0]
- list_id = int(list_id)
- except IndexError:
- break
- except ValueError:
- list_id = None
- expressions.append(Expression(name, list_id, method, value))
- print(expressions)
- if 2:
- return None
- return ""
-
-
-if __name__ == "__main__":
- # parse(r"$fib[12].set($fib[11].add($fib[10].value()))")
- # parse(r"$quotes[2].set(Hello, world)")
- # parse(r"")
- parse(r"wqe$quotes[].set($quotes[1].value(dw) + fw)")
+++ /dev/null
-import urllib3
-from dataclasses import dataclass
-import os
-import json
-from typing import Optional
-
-URL = "https://www.googleapis.com/youtube/v3/search"
-
-API = os.getenv("YOUTUBE_API")
-CLIENT_ID = os.getenv("YOUTUBE_CLIENT_ID")
-CLIENT_SECRET = os.getenv("YOUTUBE_CLIENT_SECRET")
+++ /dev/null
-from yt_api import *
-import html
-
-
-@dataclass
-class Video:
- video_name: str
- video_id: str
-
-
-def get_newest_video(channel_id: str) -> Optional[Video]:
- get_video_snippets = "?part=snippet"
- get_url = (
- URL
- + get_video_snippets
- + f"&channelId={channel_id}&order=date&type=video"
- + f"&key={API}"
- )
-
- http = urllib3.PoolManager()
- r = http.request(
- "GET",
- get_url,
- )
- if r.status != 200:
- return None
- data = json.loads(r.data.decode("utf-8"))["items"][0]
- video_id = data["id"]["videoId"]
- video_title = html.unescape(data["snippet"]["title"])
-
- return Video(video_title, video_id)