예제 #1
0
파일: quotes.py 프로젝트: Zielmann/FoxBot
def add(ctx):
    """
    Adds a quote from the content of the message to the current quotes

    Parameters:
        ctx: The context of the message

    Returns:
        str: The quote which has been added 
    """
    response = ''
    if ctx.author.is_mod or (settings.vip_quotes_allowed()
                             and util.is_vip(ctx.author.badges)):
        # Puts provided quote into a single string, without including the '!addquote' at the start
        msg = ' '.join(map(str, ctx.content.split()[1:]))
        if msg:
            today = datetime.today()
            date = str(today.day) + '/' + str(today.month) + '/' + str(
                today.year)
            # If no stored quotes, sets first entry as quote number 1. Otherwise adds one to the last key in quotes (the last quote number)
            if len(quotes) == 0:
                number = '1'
            else:
                number = str(int(list(quotes.keys())[-1]) + 1)
            game = util.getGameName(ctx, settings.get_client_id(),
                                    settings.get_client_secret(),
                                    settings.get_channel())
            quote = msg
            # Build dictionary to associate date and game with the quote
            raw_quote = {"date": date, "quote": quote, "game": game}
            quotes[number] = raw_quote
            save_quotes(quotes)
            response = f"{number}: {quotes[number]['quote']} - while streaming {quotes[number]['game']} on {quotes[number]['date']}"
    return response
예제 #2
0
파일: tf.py 프로젝트: Zielmann/FoxBot
def tf(ctx):
    """
    TFs the specified user into either a random or specified animal
    
    Parameters:
        ctx - The context of the message, a second message argument after the 
              @ of the user will specify the animal to tf into

    Returns:
        str: A confirmation of the species the user has been tfed into
    """
    response = ''
    if ctx.author.is_mod and util.validateName(ctx.content):
        # Get name without @
        name = ctx.content.split()[1][1:]
        current_species = new_species = getSpecies(name)
        # Get random species from list
        with open('Data/species.txt') as f:
            all_species = f.read().splitlines()
            while current_species == new_species:
                new_species = random.choice(all_species)
        writeSpeciesToJSON(name, new_species)
        response = name + ' has been TFed into ' + new_species + '!'
    # Check if command sent by streamer and contains name and species
    elif ctx.author.name.lower() == settings.get_channel().lower(
    ) and not util.validateNumParameters(ctx.content, 1):
        name = ctx.content.split()[1][1:]
        species = ctx.content.split()[2:]
        species_str = 'a(n) '
        for thing in species:
            species_str = species_str + thing + ' '
        writeSpeciesToJSON(name, species_str)
        response = name + ' has been TFed into ' + species_str[:-1] + '!'
    return response
예제 #3
0
async def start_periodic_messages():
    """
    Sends messages to chat periodically

    Period (in minutes) is defined in settings
    Checks for recent activity in chat before sending messages (prevents filling an inactive chat)
    If multiple messages are configured, they are distributed evenly across the specified period
    If no messages are configured, periodically checks if message has been added

    Parameters:
        messags: a dict of strings
    """
    global chat_flag
    while True:
        messages = settings.get_periodic_messages().copy()
        ws = bot._ws
        if messages:
            if chat_flag:
                for m in messages:
                    interval = int((60 * int(settings.get_periodic_timer())) /
                                   len(messages))
                    if interval == 0:
                        interval = 1
                    msg = f"({m}) {messages[m]}"
                    await ws.send_privmsg(settings.get_channel(), msg)
                    chat_flag = False
                    await asyncio.sleep(interval)
            else:
                await asyncio.sleep(60)
        else:
            await asyncio.sleep(300)
예제 #4
0
파일: rimworld.py 프로젝트: Zielmann/FoxBot
def item_detail_search(ctx):
    """
    Returns a string containing details about the item specified by the message content

    Parameters:
        ctx: The context of the message

    Returns:
        str: Contains details about the specified item
    """
    response = ''
    if util.validateNumParameters(ctx.content, 2) and util.checkGame(
            ctx, settings.get_client_id(), settings.get_client_secret(),
            settings.get_channel(), 'rimworld'):
        search = ctx.content.split()[1].lower()
        tries = 2
        for i in range(tries):
            try:
                with open(item_file()) as i:
                    items = json.load(i)
                break
            except Exception as e:
                print(e)
                destroy_the_comma()

        for entry in items["items"]:
            if entry["abr"] == search:
                response = 'Item ' + search + ' costs ' + str(
                    entry["price"]
                ) + ' coins. Item category: ' + entry["category"]
    return response
예제 #5
0
파일: rimworld.py 프로젝트: Zielmann/FoxBot
def event_search(ctx):
    """
    Searches the users Rimworld installation for events containing the message content
    
    Parameters:
        ctx: The context of the message

    Returns:
        str: Containins up to 500 characters of matching events
    """
    response = ''
    if util.validateNumParameters(ctx.content, 2) and util.checkGame(
            ctx, settings.get_client_id(), settings.get_client_secret(),
            settings.get_channel(), 'rimworld'):
        search = ctx.content.split()[1].lower()
        with open(event_file()) as e:
            events = json.load(e)

        # Follows same logic as item search
        for field in events["incitems"]:
            if search in field["abr"]:
                response = response + field["abr"] + ':' + str(
                    field["price"]) + ', '
        if len(response) > 500:
            response = response[0:495] + ' ...  '
        response = response[:-2]
    return response
예제 #6
0
async def event_ready():
    """
    Called once when the bot goes online.

    Sends a greeting message to the chat and then kicks off periodic messages, if any
    Periodic messages are defined in settings.xml
    """
    print(f"{settings.get_bot_account()} is online!")
    ws = bot._ws  # this is only needed to send messages within event_ready
    await ws.send_privmsg(settings.get_channel(), f"/me is alive!")
    await start_periodic_messages()
예제 #7
0
파일: rimworld.py 프로젝트: Zielmann/FoxBot
def mod_list(ctx):
    """
    Creates response containing rimworld mods

    Returns:
        str: Mod list, as entered in settings.xml
    """
    response = ''
    if util.checkGame(ctx, settings.get_client_id(),
                      settings.get_client_secret(), settings.get_channel(),
                      'rimworld'):
        response = settings.get_rimworld_mods()
    return response
예제 #8
0
def get_uptime():
    """
    Returns a string of the current uptime

    Returns:
        str: Contains the current amount of uptime for the channel
    """
    # Set up twitch API call and get stream info
    client = TwitchHelix(client_id=settings.get_client_id(),
                         client_secret=settings.get_client_secret())
    client.get_oauth()
    stream = client.get_streams(user_logins=settings.get_channel())._queue[0]
    # Get stream start time (API sends UTC time) and calculate uptime
    start_time = stream["started_at"]
    uptime = datetime.utcnow() - start_time
    return str(uptime).split(".")[0]
예제 #9
0
파일: rimworld.py 프로젝트: Zielmann/FoxBot
def item_search(ctx):
    """
    Searches the users Rimworld installation for items matching the message content

    Parameters:
        ctx: The context of the message

    Returns:
        str: Contains up to 500 characters of matching items
    """
    response = ''
    if util.validateNumParameters(ctx.content, 2) and util.checkGame(
            ctx, settings.get_client_id(), settings.get_client_secret(),
            settings.get_channel(), 'rimworld'):
        # Get item to search from message
        search = ctx.content.split()[1].lower()
        tries = 2
        # Allows for a retry if the items file had to have the extraneous comma removed to fix the json formatting
        for _ in range(tries):
            try:
                with open(item_file()) as f:
                    items_json = json.load(f)
                break
            except Exception as e:
                print(e)
                destroy_the_comma()  # Kill it.

        # Find all items containing search term and append to response string
        for field in items_json["items"]:
            if search in field["abr"]:
                response = response + field["abr"] + ':' + str(
                    field["price"]) + ', '

        # Trim response below 500ch max if necessary
        if len(response) > 500:
            response = response[0:495] + ' ...  '
        # Cut trailing ', ' from response
        response = response[:-2]
    return response
예제 #10
0
파일: rimworld.py 프로젝트: Zielmann/FoxBot
def event_detail_search(ctx):
    """
    Returns a string containing details about the event specified by the message content

    Parameters:
        ctx: The context of the message

    Returns:
        str: Contains details about the specified event
    """
    response = ''
    if util.validateNumParameters(ctx.content, 2) and util.checkGame(
            ctx, settings.get_client_id(), settings.get_client_secret(),
            settings.get_channel(), 'rimworld'):
        search = ctx.content.split()[1].lower()
        with open(event_file()) as e:
            events = json.load(e)
        for entry in events["incitems"]:
            if entry["abr"] == search:
                response = 'Event ' + search + ' costs ' + str(
                    entry["price"]
                ) + ' coins. Karma type: ' + entry["karmatype"]
    return response
예제 #11
0
if __name__ == '__main__':
    #try:
        query_type = sys.argv[1]
        query = sys.argv[2]
        if query_type == 'search_games':
            search_games(query)
        elif query_type == "streams_by_game":
            get_streams_by_game(query)
        elif query_type == "top_games":
            get_top_games()
        elif query_type == "all_followed_channels":
            get_followed_channels()
        elif query_type == 'online_followed_channels':
            get_active_followed_channels()
        elif query_type == "vods":
            get_videos(settings.get_channel(query))
        elif query_type == "search_streams":
            try:
                search_streams(query)
            except:
                workflow.output_items([workflow.create_item()])
        elif query_type == "favorite_streams":
            items = []
            items.append(workflow.create_item(
                arg = "http://www.twitch.tv/%s" % query,
                title = "View Stream for %s" % query,
                subtitle = "Command+Click for VODs"))
            for channel in settings.match_channels(query):
                items.append(workflow.create_item(
                    arg = "http://www.twitch.tv/%s" % channel,
                    title = "%s" % channel,
예제 #12
0
if __name__ == '__main__':
    #try:
    query_type = sys.argv[1]
    query = sys.argv[2]
    if query_type == 'search_games':
        search_games(query)
    elif query_type == "streams_by_game":
        get_streams_by_game(query)
    elif query_type == "top_games":
        get_top_games()
    elif query_type == "all_followed_channels":
        get_followed_channels()
    elif query_type == 'online_followed_channels':
        get_active_followed_channels()
    elif query_type == "vods":
        get_videos(settings.get_channel(query))
    elif query_type == "search_streams":
        try:
            search_streams(query)
        except:
            workflow.output_items([workflow.create_item()])
    elif query_type == "favorite_streams":
        items = []
        items.append(
            workflow.create_item(arg="http://www.twitch.tv/%s" % query,
                                 title="View Stream for %s" % query,
                                 subtitle="Command+Click for VODs"))
        for channel in settings.match_channels(query):
            items.append(
                workflow.create_item(arg="http://www.twitch.tv/%s" % channel,
                                     title="%s" % channel,
livestream_url = sys.argv[1]
livestreamer = 'livestreamer'

potential_livestream_locations = [
	'/usr/bin/livestreamer',
	'/usr/local/bin/livestreamer',
	'/opt/bin/livestreamer',
	'/opt/local/bin/livestreamer']

for location in potential_livestream_locations:
	if os.path.isfile(location):
		livestreamer = location
		break

if 'livestreamer' in user_settings:
	livestreamer = user_settings['livestreamer']

quality = "best"
if 'quality' in user_settings:
	quality = user_settings['quality']

extra_settings = []
if 'extra_settings' in user_settings:
	extra_settings = user_settings['extra_settings'].split(' ')

channel = settings.get_channel(livestream_url)
settings.add_channel(channel)


import subprocess
subprocess.Popen([livestreamer, livestream_url, quality] + extra_settings)
예제 #14
0
user_settings = settings.get_settings()
livestream_url = sys.argv[1]
livestreamer = 'livestreamer'

potential_livestream_locations = [
    '/usr/bin/livestreamer', '/usr/local/bin/livestreamer',
    '/opt/bin/livestreamer', '/opt/local/bin/livestreamer'
]

for location in potential_livestream_locations:
    if os.path.isfile(location):
        livestreamer = location
        break

if 'livestreamer' in user_settings:
    livestreamer = user_settings['livestreamer']

quality = "best"
if 'quality' in user_settings:
    quality = user_settings['quality']

extra_settings = []
if 'extra_settings' in user_settings:
    extra_settings = user_settings['extra_settings'].split(' ')

channel = settings.get_channel(livestream_url)
settings.add_channel(channel)

import subprocess
subprocess.Popen([livestreamer, livestream_url, quality] + extra_settings)
예제 #15
0
# Set up basic logging handler
if settings.get_logging().lower() == 'debug':
    logLevel = logging.DEBUG
else:
    logLevel = logging.CRITICAL

logging.basicConfig(filename='FoxBot_log.txt',
                    level=logLevel,
                    format='%(asctime)s - %(levelname)s - %(message)s')

# Initialize twitchio command bot
bot = commands.Bot(irc_token=settings.get_app_token(),
                   client_id=settings.get_client_id(),
                   nick=settings.get_bot_account(),
                   prefix=settings.get_prefix(),
                   initial_channels=[settings.get_channel()])


#---------------------------------------------------#
async def start_periodic_messages():
    """
    Sends messages to chat periodically

    Period (in minutes) is defined in settings
    Checks for recent activity in chat before sending messages (prevents filling an inactive chat)
    If multiple messages are configured, they are distributed evenly across the specified period
    If no messages are configured, periodically checks if message has been added

    Parameters:
        messags: a dict of strings
    """