Praxis_Bot/twitch_script.py
Alex Orid 659fe444d6 Added Configs
Added configs to either block or force functions to do or not do something.
2021-01-21 03:12:46 -05:00

192 lines
8.2 KiB
Python

from typing import Sequence
import random
import re
import utilities_script as utilities
import twitch
import twitch.chat
import config as config
import db
import tts
import commands.loader as command_loader
import credentials
from commands.command_base import AbstractCommand
from cooldowns import Cooldown_Module
class Twitch_Module():
def __init__(self):
super().__init__()
self.twitchCredential: credentials.Twitch_Credential
self.dbCredential: credentials.DB_Credential
self.db_manager: db.db_module = db.db_module()
self.chat: twitch.Chat
self.commands = command_loader.load_commands_new(AbstractCommand.CommandType.TWITCH)
self.tts_enabled: bool = False
self.tts_whitelist_enabled: bool = False
self.links_allowed: bool = True
self.whitelisted_users: list = ["thecuriousnerd"]
# don't freak out, this is *merely* a regex for matching urls that will hit just about everything
self._urlMatcher = re.compile(
"(https?:(/{1,3}|[a-z0-9%])|[a-z0-9.-]+[.](com|net|org|edu|gov|mil|aero|asia|biz|cat|coop|info|int|jobs|mobi|museum|name|post|pro|tel|travel|xxx|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|cy|cz|dd|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|Ja|sk|sl|sm|sn|so|sr|ss|st|su|sv|sx|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw))")
# Default Twitch Chat limit is 20 per 30 seconds
# If Mod or Op, Twitch Chat limit is 100 per 30 seconds
self.cooldownModule:Cooldown_Module = Cooldown_Module()
self.cooldownModule.setupCooldown("twitchChat", 20, 32)
def join_channel(self, credential: credentials.Twitch_Credential, channel_name:str):
channel_name = "#" + channel_name
print("Connecting to Channel: " + channel_name + "...")
if credential is None:
credential = self.twitchCredential
self.chat = twitch.Chat(
channel = channel_name,
nickname = credential.username,
oauth = credential.oauth,
# LIBRARY UPDATE BROKE THE FOLLOWING LINE [FIX THIS]
#helix = twitch.Helix(credential.helix, use_cache=True)
)
self.chat.subscribe(self.twitch_chat)
print("Connected to Channel: ", channel_name)
def leave_channel(self):
print("Leaving Channel", self.chat.channel)
self.chat.irc.leave_channel(self.chat.channel)
self.chat.irc.socket.close()
def send_message(self, message):
isBlocked = self.isChannel_inConfigList(self.chat.channel, config.block_TwitchChannelsMessaging)
#print("isBlocked: " + str(isBlocked) + " for: " + self.chat.channel)
if self.cooldownModule.isCooldownActive("twitchChat") == False and not isBlocked and not config.blockAll_TwitchChatChannelsMessaging:
self.chat.send(message)
#print("Sent ChatMSG")
self.cooldownModule.actionTrigger("twitchChat")
def send_whisper(self, user, message):
pass
# This reacts to messages
def twitch_chat(self, message: twitch.chat.Message) -> None:
print("[#" + message.channel + "](" + message.sender + ")> " + message.text)
if not self.isSenderBot(message):
if self.cooldownModule.isCooldownActive("twitchChat") == False:
print("Pre Eval")
self.eval_commands(message)
self.tts_message(message)
def eval_commands(self, message: twitch.chat.Message):
print("evaling command")
# containsURL: bool = self.contains_url(message)
try:
#first_space_idx = message.text.index(' ')
# This fixes a error where if you send a command without arguments it fails because
# it cant find the substring.
if message.text.find(" ") != -1:
first_space_idx = message.text.index(' ')
else:
first_space_idx = -1
command_text = ' '
if first_space_idx > -1:
command_text = message.text[0:first_space_idx]
else:
command_text = message.text
command = self.commands[command_text]
if command is not None and command.command_type is AbstractCommand.CommandType.TWITCH:
print("running command")
command.do_command(self, message)
except Exception as e:
# Undo the following for debug stuff
#print(e)
print("failed command")
pass # we don't care
def tts_message(self, message: twitch.chat.Message):
isBlocked = self.isChannel_inConfigList(self.chat.channel, config.block_TwitchChannelsTTS)
isForced = (self.isChannel_inConfigList(self.chat.channel, config.force_TwitchChannelsTTS) and not config.blockAll_TwitchChatChannelsTTS)
if (not self.contains_slur(message)):
if self.tts_enabled and not isBlocked and not config.blockAll_TwitchChatChannelsTTS or isForced or config.forceAll_TwitchChatChannelsTTS:
if not message.text.startswith('!'):
text_to_say: str = "%s says, %s" % (message.sender, message.text)
channel_text = "%s user msg" % message.channel
tts.tts(text_to_say)
def contains_url(self, message: twitch.chat.Message):
containsURL = re.search(self._urlMatcher, message.text.lower()) is not None
if containsURL:
print("<{ link detected! }> " + " [#" + message.channel + "](" + message.sender + ") sent a link in chat")
return containsURL
# Checks if Sender is bot.
def isSenderBot(self, message: twitch.chat.Message):
isBot = False
for bot in config.botList:
if message.sender.lower() == bot.lower():
isBot = True
print("<{ bot detected! }> " + " [#" + message.channel + "](" + message.sender + ") is a bot")
return isBot
# Checks for basic slurs.
def contains_slur(self, message: twitch.chat.Message):
containsSlur: bool = False
parsedMessage = message.text.split(" ")
for word in parsedMessage:
for slur in config.slurList:
if word.lower() == slur:
containsSlur = True
break # we want to immediately escape if we found a slur
if containsSlur:
break
if containsSlur:
print("<{ slur detected! }> " + " [#" + message.channel + "](" + message.sender + ") used a slur in chat")
return containsSlur
def isChannel_inConfigList(self, selectedChannel, selectedList):
#print(channel)
#print(selectedList)
is_Self = False
for twitchChannel in selectedList:
if twitchChannel == selectedChannel:
is_Self = True
#if is_Self:
# print("Is Self")
#if not is_Self:
# print("Is Not Self")
return is_Self
# This is a old function used prior to the creation of the Twitch_Module class above.
# I need to make a new one for the class.
def main_chat_commands_check(channel, sender, text):
response = db.basic_command_trigger(channel, sender, text)
if response == "$$None$$":
pass
else:
print("Curious Nerd Response Function:")
print(response)
if __name__ == "__main__":
testModule = Twitch_Module()
credentials_manager = credentials.Credentials_Module()
credentials_manager.load_credentials()
testModule.twitchCredential = credentials_manager.find_Twitch_Credential(config.credentialsNickname)
testModule.dbCredential = credentials_manager.find_DB_Credential(config.credentialsNickname)
for twitchChannel in config.autojoinTwitchChannels:
testModule.join_channel(None, twitchChannel)