Example #1
0
def handle_commands(packet: ircp.Packet, shared: dict):
    ''' Handle commands as needed '''
    if not (len(packet.text) > 1 and packet.text[0] == shared['conf']['prefix']):
        return None

    now = time.time()

    if (packet.sender not in shared['cooldown_user'] or
            now > shared['cooldown_user'][packet.sender]):
        stripped_text = packet.text[1:]
        words = irc_argparse.parse(stripped_text)
        if words[0] != '':
            c = words[0].lower()
            commands = shared['commands']
            if c in commands:
                cool = get_cooldown(c, now, shared)
                shared['cooldown_user'][packet.sender] = cool
                reply = commands[c](words, packet, shared)
                shared['stats']['commands_run'] += 1
                return reply
            elif c[0] in ALLOWABLE_START_CHARS:
                return packet.notice('Sorry, but the command {1}{0}{2} '
                                     'does not exist.'.format(c, CLR_HGLT, CLR_RESET))
    else:
        time_left = (shared['cooldown_user'][packet.sender] - int(now))
        return packet.notice('[Cooldown]: You need to wait for {:.1f} seconds '
                             'before you can use a command.'.format(time_left))
Example #2
0
def handle_commands(packet: ircp.Packet, shared: dict):
    ''' Handle commands as needed '''
    if not (len(packet.text) > 1
            and packet.text[0] == shared['conf']['prefix']):
        return None

    now = time.time()

    if (packet.sender not in shared['cooldown_user']
            or now > shared['cooldown_user'][packet.sender]):
        stripped_text = packet.text[1:]
        words = irc_argparse.parse(stripped_text)
        if words[0] != '':
            c = words[0].lower()
            commands = shared['commands']
            if c in commands:
                cool = get_cooldown(c, now, shared)
                shared['cooldown_user'][packet.sender] = cool
                reply = commands[c](words, packet, shared)
                shared['stats']['commands_run'] += 1
                return reply
            elif c[0] in ALLOWABLE_START_CHARS:
                return packet.notice('Sorry, but the command {1}{0}{2} '
                                     'does not exist.'.format(
                                         c, CLR_HGLT, CLR_RESET))
    else:
        time_left = (shared['cooldown_user'][packet.sender] - int(now))
        return packet.notice('[Cooldown]: You need to wait for {:.1f} seconds '
                             'before you can use a command.'.format(time_left))
Example #3
0
def command_list(arg: tuple, packet: ircp.Packet, shared: dict):
    '''
    Lists all commands
    '''
    print('listing commands!')
    all_commands = shared['commands']
    response = [packet.notice('Available commands ({} total)'.format(len(all_commands))),]
    response.extend(packet.notice(c) for c in sorted(all_commands))
    return response
Example #4
0
def say_command(arg: tuple, packet: ircp.Packet, shared: dict):
    """
    Echoes text than an admin tells the bot to
    """
    if len(arg) < 3:
        return packet.notice('Usage - {}:say <channel> <message>'.format(CLR_HGLT))
    else:
        target = arg[1]
        message = packet.text.split(target)[1].lstrip()
        return (packet.notice('Message sent to {}'.format(target)),
                ircp.make_message(message, target))
Example #5
0
def command_list(arg: tuple, packet: ircp.Packet, shared: dict):
    '''
    Lists all commands
    '''
    print('listing commands!')
    all_commands = shared['commands']
    response = [
        packet.notice('Available commands ({} total)'.format(
            len(all_commands))),
    ]
    response.extend(packet.notice(c) for c in sorted(all_commands))
    return response
Example #6
0
def say_command(arg: tuple, packet: ircp.Packet, shared: dict):
    """
    Echoes text than an admin tells the bot to
    """
    if len(arg) < 3:
        return packet.notice(
            'Usage - {}:say <channel> <message>'.format(CLR_HGLT))
    else:
        target = arg[1]
        message = packet.text.split(target)[1].lstrip()
        return (packet.notice('Message sent to {}'.format(target)),
                ircp.make_message(message, target))
Example #7
0
def convert_command(arg: tuple, packet: ircp.Packet, shared: dict):

    if len(arg) < 5:
        return (packet.notice('You need to specify an amount, original current, and output currency!'),
                packet.notice('For example - :convert $50 USD to Pounds'))

    conversion = get_conversion(arg[1:], shared)

    if conversion == '' or conversion is None:
        return None
    else:
        return packet.reply('{}: {}'.format(packet.sender, conversion))
Example #8
0
def list_channels(arg: tuple, packet: ircp.Packet, shared: dict):
    ''' List channels that this bot is currently in '''
    output = None
    if packet.sender in shared['auth']:
        output = []
        output.append(packet.notice('I am currently in: '))

        for c in shared['chan']:
            output.append(packet.notice(c))
    else:
        output = packet.notice('You do not have permission to do that. You need to :auth')

    return output
Example #9
0
def list_plugins(arg: tuple, packet: ircp.Packet, shared: dict):
    ''' List all plugins available

    :plugins
    '''
    enabled = ALL_PLUGINS.difference(DISABLED_PLUGINS).difference(FAILED_PLUGINS)

    output = [packet.notice('Enabled plugins ({}): '.format(len(enabled))),
              packet.notice(', '.join(enabled))]
    if len(DISABLED_PLUGINS) > 0:
        output.append(packet.notice('Disabled plugins ({})'.format(len(DISABLED_PLUGINS))))
        output.append(packet.notice(', '.join(DISABLED_PLUGINS)))

    return output
Example #10
0
def log_append_command(arg: tuple, packet: ircp.Packet, shared: dict):
    """ Appends something to text logs

    arg - the text to append to the log

    User syntax is `arg <text>` where `<text>` is a message that will be added
    to the log.
    """
    if len(arg) < 2:
        return packet.notice('You need to put something down for me to add!')

    text = packet.text.split(':log')[1].lstrip()
    write_to_log('{0} LOG-APPEND: {1}'.format(packet.sender, arg))
    return packet.notice('Log written')
Example #11
0
def list_channels(arg: tuple, packet: ircp.Packet, shared: dict):
    ''' List channels that this bot is currently in '''
    output = None
    if packet.sender in shared['auth']:
        output = []
        output.append(packet.notice('I am currently in: '))

        for c in shared['chan']:
            output.append(packet.notice(c))
    else:
        output = packet.notice(
            'You do not have permission to do that. You need to :auth')

    return output
Example #12
0
def log_append_command(arg: tuple, packet: ircp.Packet, shared: dict):
    """ Appends something to text logs

    arg - the text to append to the log

    User syntax is `arg <text>` where `<text>` is a message that will be added
    to the log.
    """
    if len(arg) < 2:
        return packet.notice('You need to put something down for me to add!')

    text = packet.text.split(':log')[1].lstrip()
    write_to_log('{0} LOG-APPEND: {1}'.format(packet.sender, arg))
    return packet.notice('Log written')
Example #13
0
 def restricted_method(args: tuple, packet: ircp.Packet, shared: dict):  # pylint: disable=missing-docstring
     if packet.sender in shared['auth']:
         return callback(args, packet, shared)
     else:
         return packet.notice('You must be an admin to run this command. '
                              'Please login first with :auth')
     return None
Example #14
0
 def public_method(args: tuple, packet: ircp.Packet, shared: dict):  # pylint: disable=missing-docstring
     if packet.msg_public:
         return callback(args, packet, shared)
     else:
         return packet.notice('Sorry, but that command is only available '
                              'through public chat. Try again in a public channel.')
     return None
Example #15
0
 def restricted_method(args: tuple, packet: ircp.Packet, shared: dict):  # pylint: disable=missing-docstring
     if packet.sender in shared['auth']:
         return callback(args, packet, shared)
     else:
         return packet.notice('You must be an admin to run this command. '
                              'Please login first with :auth')
     return None
Example #16
0
 def public_method(args: tuple, packet: ircp.Packet, shared: dict):  # pylint: disable=missing-docstring
     if packet.msg_public:
         return callback(args, packet, shared)
     else:
         return packet.notice(
             'Sorry, but that command is only available '
             'through public chat. Try again in a public channel.')
     return None
Example #17
0
def join_command(arg: tuple, packet: ircp.Packet, shared: dict):
    ''' Make the bot join a channel

        :join <channel> [channel [channel ...]]
    '''
    if len(arg) < 2:
        return packet.notice('You need to specify a channel for me to join.')

    output = []
    for c in arg[1:]:
        if c.find('#') == 0:
            output.append(ircp.join_chan(c))
        else:
            output.append(packet.notice('{} is not a valid channel'.format(c)))

    output.append(packet.notice('Joined!'))
    return output
Example #18
0
def join_command(arg: tuple, packet: ircp.Packet, shared: dict):
    ''' Make the bot join a channel

        :join <channel> [channel [channel ...]]
    '''
    if len(arg) < 2:
        return packet.notice('You need to specify a channel for me to join.')

    output = []
    for c in arg[1:]:
        if c.find('#') == 0:
            output.append(ircp.join_chan(c))
        else:
            output.append(packet.notice('{} is not a valid channel'.format(c)))

    output.append(packet.notice('Joined!'))
    return output
Example #19
0
def plugin_info_command(arg: tuple, packet: ircp.Packet, shared: dict):
    '''
    Does stuff to plugins
    '''
    if len(arg) < 2:
        return packet.notice('You need to specify a plugin to inspect!')

    name = arg[1].lower()

    if name not in ALL_PLUGINS:
        return packet.notice('{} is not a valid plugin name'.format(name))

    is_enabled = not (name in DISABLED_PLUGINS or name in FAILED_PLUGINS)

    module = None
    full_name = 'plugins.{}'.format(name)
    for plug in PLUGIN_LIST:
        if plug.__name__ == full_name:
            module = plug
            break

    output = []
    enabled_text = (lambda x: 'ENABLED' if x else 'DISABLED')(is_enabled)
    output.append(packet.notice('{} is {}'.format(name, enabled_text)))
    if module:
        if '__plugin_description__' in dir(module):
            output.append(packet.notice(module.__plugin_description__))
        if '__plugin_author__' in dir(module):
            output.append(packet.notice('Author: {}'.format(module.__plugin_author__)))
        if '__plugin_version__' in dir(module):
            output.append(packet.notice('Version: {}'.format(module.__plugin_version__)))
        if '__plugin_type__' in dir(module):
            output.append(packet.notice('Plugin Type: {}'.format(module.__plugin_type__)))

    return output
Example #20
0
def sub_replace(match, packet: ircp.Packet, shared: dict) -> str:
    """
    Naive substitution regular expression on previous message.
    """
    global_flag = False

    parts = match.group(0).split('/')
    old, new = None, None
    
    old = parts[1]
    new = parts[2]
    if len(parts) >= 4:
        if parts[3].lower() == 'g':
            global_flag = True

    
    # Now, find the last message in the same channel that
    # contains `old`
    orig_packet = None
    output = ''

    print('looking for "{}"'.format(old))
    for p in reversed(shared['recent_messages']):
        if p.target == packet.target:
            if p.msg_public and (p.text.find(old) != -1):
                output = str(p.text)
                orig_packet = p
                break
    else:
        return packet.reply('Could not find a suitable substitution target.')


    print('replacing "{}" with "{}"'.format(old, new))
    print('original: "{}"'.format(output))
    # patch in italics
    new = CLR_ITLCS + new + CLR_RESET


    if global_flag:
        output = output.replace(old, new)
    else:
        output = output.replace(old, new, 1)

    return packet.reply('<{}> {}'.format(orig_packet.sender, output))
Example #21
0
def part_command(arg: tuple, packet: ircp.Packet, shared: dict):
    ''' Make the bot part a channel

        :part <channel> [channel [channel ...]]
    '''
    output = None
    if len(arg) < 2:
        return packet.notice('You need to specify a channel for me to leave.')

    output = []
    for c in arg[1:]:
        if c in shared['chan']:
            output.append(ircp.leave_chan(c))
            shared['chan'].remove(c)
        else:
            output.append(packet.notice('I am currently not in {}'.format(c)))

    output.append(packet.notice('Done PARTing'))
    return output
Example #22
0
def part_command(arg: tuple, packet: ircp.Packet, shared: dict):
    ''' Make the bot part a channel

        :part <channel> [channel [channel ...]]
    '''
    output = None
    if len(arg) < 2:
        return packet.notice('You need to specify a channel for me to leave.')

    output = []
    for c in arg[1:]:
        if c in shared['chan']:
            output.append(ircp.leave_chan(c))
            shared['chan'].remove(c)
        else:
            output.append(packet.notice('I am currently not in {}'.format(c)))

    output.append(packet.notice('Done PARTing'))
    return output
Example #23
0
def list_plugins(arg: tuple, packet: ircp.Packet, shared: dict):
    ''' List all plugins available

    :plugins
    '''
    enabled = ALL_PLUGINS.difference(DISABLED_PLUGINS).difference(
        FAILED_PLUGINS)

    output = [
        packet.notice('Enabled plugins ({}): '.format(len(enabled))),
        packet.notice(', '.join(enabled))
    ]
    if len(DISABLED_PLUGINS) > 0:
        output.append(
            packet.notice('Disabled plugins ({})'.format(
                len(DISABLED_PLUGINS))))
        output.append(packet.notice(', '.join(DISABLED_PLUGINS)))

    return output
Example #24
0
def auth_command(arg: tuple, packet: ircp.Packet, shared: dict):
    ''' Authenticate yourself

    :auth <password>
    '''
    if len(arg) < 2:
        return packet.notice('You must specify a password!')

    passphrase = arg[1]

    if passphrase == shared['conf']['adminpass']:
        if packet.sender in shared['auth']:
            return packet.notice('You are already logged in!')
        else:
            shared['auth'].add(packet.sender)
            print('{} successfully authenticated.'.format(packet.sender))
            return packet.notice('Authentication success!')
    else:
        return packet.notice('Authentication failure. Try again later.')
Example #25
0
def auth_command(arg: tuple, packet: ircp.Packet, shared: dict):
    ''' Authenticate yourself

    :auth <password>
    '''
    if len(arg) < 2:
        return packet.notice('You must specify a password!')

    passphrase = arg[1]

    if passphrase == shared['conf']['adminpass']:
        if packet.sender in shared['auth']:
            return packet.notice('You are already logged in!')
        else:
            shared['auth'].add(packet.sender)
            print('{} successfully authenticated.'.format(packet.sender))
            return packet.notice('Authentication success!')
    else:
        return packet.notice('Authentication failure. Try again later.')
Example #26
0
def matched_url(match, packet: ircp.Packet, shared: dict):
    ''' Match the url regex '''
    # At the moment this only cares about the first link in a message
    matched = match.group(0)
    print('matched url: {}'.format(matched))
    try:
        title = link_info(matched)
        if title is not None:
            return packet.reply(title)
    except Exception:
        print('Failed to parse link: {}'.format(matched))
Example #27
0
def sub_replace(match, packet: ircp.Packet, shared: dict) -> str:
    """
    Naive substitution regular expression on previous message.
    """
    global_flag = False

    parts = match.group(0).split('/')
    old, new = None, None

    old = parts[1]
    new = parts[2]
    if len(parts) >= 4:
        if parts[3].lower() == 'g':
            global_flag = True

    # Now, find the last message in the same channel that
    # contains `old`
    orig_packet = None
    output = ''

    print('looking for "{}"'.format(old))
    for p in reversed(shared['recent_messages']):
        if p.target == packet.target:
            if p.msg_public and (p.text.find(old) != -1):
                output = str(p.text)
                orig_packet = p
                break
    else:
        return packet.reply('Could not find a suitable substitution target.')

    print('replacing "{}" with "{}"'.format(old, new))
    print('original: "{}"'.format(output))
    # patch in italics
    new = CLR_ITLCS + new + CLR_RESET

    if global_flag:
        output = output.replace(old, new)
    else:
        output = output.replace(old, new, 1)

    return packet.reply('<{}> {}'.format(orig_packet.sender, output))
Example #28
0
def plugin_toggle(arg: tuple, packet: ircp.Packet, shared: dict):
    ''' Enable or disable plugins

    :enable <plugin>
    :disable <plugin>
    '''
    if len(arg) < 2:
        return packet.notice('You need to specify a plugin to disable')
    if len(arg) > 2:
        return packet.notice('Too many arguments! The command only uses 1 argument.')

    command = arg[0].lower()
    name = arg[1].lower()

    if command == 'enable':
        if not (name in DISABLED_PLUGINS or name in FAILED_PLUGINS):
            return packet.notice('Plugin is already enabled. Doing nothing.')

        if name in DISABLED_PLUGINS:
            DISABLED_PLUGINS.remove(name)
        if name in FAILED_PLUGINS:
            FAILED_PLUGINS.remove(name)

        return packet.notice('Plugin is now enabled.')
    elif command == 'disable':
        if name in DISABLED_PLUGINS:
            return packet.notice('Plugin is already disabled!')
        else:
            DISABLED_PLUGINS.add(name)
            # TODO: Reload plugins to get rid of leftovers
            return packet.notice('Plugin is now disabled!')
    else:
        print('You screwed up.')
Example #29
0
def reload_command(_: tuple, packet: ircp.Packet, shared: dict):
    '''
    Reloads all plugins as well as their data files
    '''
    print('Reload command called')
    load_plugins(shared)
    if len(FAILED_PLUGINS) + len(DISABLED_PLUGINS) == 0:
        return packet.notice('All {} plugins reloaded!'.format(
            len(PLUGIN_LIST)))

    response = [
        packet.notice('{} plugins were reloaded.'.format(len(PLUGIN_LIST))),
        packet.notice('The following were NOT loaded: ')
    ]

    if len(FAILED_PLUGINS) > 0:
        response.append(
            packet.notice('Fail to Load:  ' + ', '.join(FAILED_PLUGINS)))
    if len(DISABLED_PLUGINS) > 0:
        response.append(
            packet.notice('Disabled: ' + ', '.join(DISABLED_PLUGINS)))

    response.append(
        packet.notice('Please check your logs for further information.'))

    return response
Example #30
0
def memory_obj(args: tuple, packet: ircp.Packet, ___: dict):
    """ Print the biggest memory hogs """
    if not _IS_TRACING:
        return packet.notice(
            'Sorry, but tracing is currently disabled. '
            'Please restart probot with the "PYTHONTRACEMALLOC=NFRAME" '
            'environment variable.')

    snapshot = tracemalloc.take_snapshot()
    top_stats = snapshot.statistics('filename')

    num = 0
    if len(args) >= 2:
        try:
            num = int(args[1])
        except ValueError:
            return packet.notice('Your argument must be an integer')
    else:
        return packet.notice('You must specify an object to inspect!')

    if len(top_stats) >= num:
        output = [packet.notice('Memory hog #{}'.format(num))]
        obj = top_stats[num]
        trace = tracemalloc.get_object_traceback(obj)
        for line in trace:
            output.append(packet.notice(line))
        return output
    else:
        return packet.notice('Sorry, but that object does not exist')
Example #31
0
def memory_obj(args: tuple, packet: ircp.Packet, ___: dict):
    """ Print the biggest memory hogs """
    if not _IS_TRACING:
        return packet.notice(
            "Sorry, but tracing is currently disabled. "
            'Please restart probot with the "PYTHONTRACEMALLOC=NFRAME" '
            "environment variable."
        )

    snapshot = tracemalloc.take_snapshot()
    top_stats = snapshot.statistics("filename")

    num = 0
    if len(args) >= 2:
        try:
            num = int(args[1])
        except ValueError:
            return packet.notice("Your argument must be an integer")
    else:
        return packet.notice("You must specify an object to inspect!")

    if len(top_stats) >= num:
        output = [packet.notice("Memory hog #{}".format(num))]
        obj = top_stats[num]
        trace = tracemalloc.get_object_traceback(obj)
        for line in trace:
            output.append(packet.notice(line))
        return output
    else:
        return packet.notice("Sorry, but that object does not exist")
Example #32
0
def plugin_toggle(arg: tuple, packet: ircp.Packet, shared: dict):
    ''' Enable or disable plugins

    :enable <plugin>
    :disable <plugin>
    '''
    if len(arg) < 2:
        return packet.notice('You need to specify a plugin to disable')
    if len(arg) > 2:
        return packet.notice(
            'Too many arguments! The command only uses 1 argument.')

    command = arg[0].lower()
    name = arg[1].lower()

    if command == 'enable':
        if not (name in DISABLED_PLUGINS or name in FAILED_PLUGINS):
            return packet.notice('Plugin is already enabled. Doing nothing.')

        if name in DISABLED_PLUGINS:
            DISABLED_PLUGINS.remove(name)
        if name in FAILED_PLUGINS:
            FAILED_PLUGINS.remove(name)

        return packet.notice('Plugin is now enabled.')
    elif command == 'disable':
        if name in DISABLED_PLUGINS:
            return packet.notice('Plugin is already disabled!')
        else:
            DISABLED_PLUGINS.add(name)
            # TODO: Reload plugins to get rid of leftovers
            return packet.notice('Plugin is now disabled!')
    else:
        print('You screwed up.')
Example #33
0
def calc_command(arg: tuple, packet: ircp.Packet, shared: dict) -> str:
    ''' Evaluate a mathematical expression

    usage:
    :calc <expression>
    :calc 1 + 1 == 2
    :calc 3^3
    '''
    problem = (''.join(arg[1:])).replace('^', '**')
    print('solving for {}'.format(problem))
    try:
        result = evaluate_expression(problem)
        if result is None:
            raise ValueError('Invalid result')

        reply = 'Result: {}'.format(result)
        return packet.reply(reply)
    except ZeroDivisionError as e:
        return packet.notice('Error: Divide by zero.')
    except Exception as e:
        print(e)
        return packet.notice('Sorry, but that expression was invalid. Please try again.')
Example #34
0
def memory_command(args: tuple, packet: ircp.Packet, ___: dict):
    """ Print the biggest memory hogs """
    if not _IS_TRACING:
        return packet.notice(
            'Sorry, but tracing is currently disabled. '
            'Please restart probot with the "PYTHONTRACEMALLOC=NFRAME" '
            'environment variable.')

    snapshot = tracemalloc.take_snapshot()
    top_stats = snapshot.statistics('filename')

    num = 15
    if len(args) >= 2:
        try:
            num = int(args[1])
        except ValueError:
            num = 15

    output = [packet.notice('Top {} biggest memory hogs:'.format(num))]
    for num, stat in enumerate(top_stats[:num]):
        output.append(packet.notice('{}: {}'.format(num, stat)))

    return output
Example #35
0
def whatis_command(arg: tuple, packet: ircp.Packet, shared: dict):
    if len(arg) < 2:
        return ircp.make_notice('You must specify a type of currency!', packet.sender)

    orig_currency = (' '.join(arg[1:]))
    currency = str(orig_currency).upper()

    if currency in ALIASES:
        currency = ALIASES[currency]

    if currency not in CURRENCIES:
        return ircp.make_notice('I don\'t know what "{}" is!'.format(currency), packet.sender)
    else:
        return packet.reply('{} is {}'.format(orig_currency, CURRENCIES[currency]))
Example #36
0
def calc_command(arg: tuple, packet: ircp.Packet, shared: dict) -> str:
    ''' Evaluate a mathematical expression

    usage:
    :calc <expression>
    :calc 1 + 1 == 2
    :calc 3^3
    '''
    problem = (''.join(arg[1:])).replace('^', '**')
    print('solving for {}'.format(problem))
    try:
        result = evaluate_expression(problem)
        if result is None:
            raise ValueError('Invalid result')

        reply = 'Result: {}'.format(result)
        return packet.reply(reply)
    except ZeroDivisionError as e:
        return packet.notice('Error: Divide by zero.')
    except Exception as e:
        print(e)
        return packet.notice(
            'Sorry, but that expression was invalid. Please try again.')
Example #37
0
def fortune_command(arg: tuple, packet: ircp.Packet, shared: dict) -> str:
    ''' Tells the user a fortune (maybe via cowsay)

    :fortune - tells the user a fortune
    :cowsay - tells the user a fortune via cowsay
    :moo - alias of cowsay
    '''
    command = None
    user_command = arg[0].lower()
    if user_command == 'fortune':
        command = '{} -a'.format(shared['fortune.path'])
    elif user_command == 'cowsay' or user_command == 'moo':
        if 'fortune.cowsay' in shared:
            command = '{} -a | {}'.format(shared['fortune.path'], shared['fortune.cowsay'])
        else:
            return packet.notice('This machine does not have cowsay installed. '
                                 'Please install cowsay, then reload this plugin.')

    # rstrip to remove trailing newline
    ps = check_output(command, shell=True, universal_newlines=True).rstrip()
    print(ps)

    return (packet.notice(line) for line in ps.split('\n'))
Example #38
0
def memory_command(args: tuple, packet: ircp.Packet, ___: dict):
    """ Print the biggest memory hogs """
    if not _IS_TRACING:
        return packet.notice(
            "Sorry, but tracing is currently disabled. "
            'Please restart probot with the "PYTHONTRACEMALLOC=NFRAME" '
            "environment variable."
        )

    snapshot = tracemalloc.take_snapshot()
    top_stats = snapshot.statistics("filename")

    num = 15
    if len(args) >= 2:
        try:
            num = int(args[1])
        except ValueError:
            num = 15

    output = [packet.notice("Top {} biggest memory hogs:".format(num))]
    for num, stat in enumerate(top_stats[:num]):
        output.append(packet.notice("{}: {}".format(num, stat)))

    return output
Example #39
0
def hello_world(arg: tuple, packet: ircp.Packet, shared: dict):
    ''' Hello, world!

    This is an example template command

    arg - the tuple of keywords
    packet - the packet object to receive
    shared - the shared data dictionary
    '''

    # arg[0] is always the command name (in this case 'hello', or 'h').
    # You can use this to assign multiple commands to the same function.
    # Different indexes are parsed similarly to how sys.argv is parsed,
    # paying attention to quotes and backslash-escapes.
    print(arg)

    return packet.reply('Hello, there!')
Example #40
0
def hello_world(arg: tuple, packet: ircp.Packet, shared: dict):
    ''' Hello, world!

    This is an example template command

    arg - the tuple of keywords
    packet - the packet object to receive
    shared - the shared data dictionary
    '''

    # arg[0] is always the command name (in this case 'hello', or 'h').
    # You can use this to assign multiple commands to the same function.
    # Different indexes are parsed similarly to how sys.argv is parsed,
    # paying attention to quotes and backslash-escapes.
    print(arg)

    return packet.reply('Hello, there!')
Example #41
0
def plugin_info_command(arg: tuple, packet: ircp.Packet, shared: dict):
    '''
    Does stuff to plugins
    '''
    if len(arg) < 2:
        return packet.notice('You need to specify a plugin to inspect!')

    name = arg[1].lower()

    if name not in ALL_PLUGINS:
        return packet.notice('{} is not a valid plugin name'.format(name))

    is_enabled = not (name in DISABLED_PLUGINS or name in FAILED_PLUGINS)

    module = None
    full_name = 'plugins.{}'.format(name)
    for plug in PLUGIN_LIST:
        if plug.__name__ == full_name:
            module = plug
            break

    output = []
    enabled_text = (lambda x: 'ENABLED' if x else 'DISABLED')(is_enabled)
    output.append(packet.notice('{} is {}'.format(name, enabled_text)))
    if module:
        if '__plugin_description__' in dir(module):
            output.append(packet.notice(module.__plugin_description__))
        if '__plugin_author__' in dir(module):
            output.append(
                packet.notice('Author: {}'.format(module.__plugin_author__)))
        if '__plugin_version__' in dir(module):
            output.append(
                packet.notice('Version: {}'.format(module.__plugin_version__)))
        if '__plugin_type__' in dir(module):
            output.append(
                packet.notice('Plugin Type: {}'.format(
                    module.__plugin_type__)))

    return output
Example #42
0
def reload_command(_: tuple, packet: ircp.Packet, shared: dict):
    '''
    Reloads all plugins as well as their data files
    '''
    print('Reload command called')
    load_plugins(shared)
    if len(FAILED_PLUGINS) + len(DISABLED_PLUGINS) == 0:
        return packet.notice('All {} plugins reloaded!'.format(len(PLUGIN_LIST)))

    response = [packet.notice('{} plugins were reloaded.'.format(len(PLUGIN_LIST))),
                packet.notice('The following were NOT loaded: ')]

    if len(FAILED_PLUGINS) > 0:
        response.append(packet.notice('Fail to Load:  ' + ', '.join(FAILED_PLUGINS)))
    if len(DISABLED_PLUGINS) > 0:
        response.append(packet.notice('Disabled: ' + ', '.join(DISABLED_PLUGINS)))

    response.append(packet.notice('Please check your logs for further information.'))

    return response
Example #43
0
def respond_bad(matched, packet: ircp.Packet, shared: dict) -> str:
    ''' Respond to an ugly, mean message '''
    return packet.reply('F**k you too, {1}{0}{2}!'.format(packet.sender, CLR_NICK, CLR_RESET))
Example #44
0
def uptime_command(__: tuple, packet: ircp.Packet, shared: dict):
    """ Print current uptime """
    start_time = shared["stats"]["starttime"]
    uptime = _uptime(start_time)

    return packet.reply(uptime)
Example #45
0
def stats_command(__: tuple, packet: ircp.Packet, shared: dict):
    """ Print statistical data about this bot """
    stats = shared["stats"]
    uptime = _uptime(shared["stats"]["starttime"])

    import resource

    mem_usage = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
    tracing_status = (lambda x: "enabled" if x else "disabled")(_IS_TRACING)
    from platform import platform, python_version

    output = (
        packet.notice("Current uptime: {}".format(uptime)),
        packet.notice("Available plugins: {}".format(stats["plugins.available"])),
        packet.notice("Disabled plugins: {}".format(stats["plugins.disabled"])),
        packet.notice("Failed plugins: {}".format(stats["plugins.failed"])),
        packet.notice("Parsed messages: {}".format(stats["num_messages"])),
        packet.notice("Commands run: {}".format(stats["commands_run"])),
        packet.notice("Regex Matches: {}".format(stats["regex_matches"])),
        packet.notice("Probot memory usage: {} KB".format(mem_usage)),
        packet.notice("Bot admins online: {}".format(len(shared["auth"]))),
        packet.notice("Memory tracing is {}".format(tracing_status)),
        packet.notice("Cows: {}:moo{}".format(CLR_HGLT, CLR_RESET)),
        packet.notice("Platform: {}".format(platform())),
        packet.notice("Running on Python {}".format(python_version())),
    )

    return output
Example #46
0
def list_currencies(arg: tuple, packet: ircp.Packet, shared: dict):
    c_list = [packet.notice('Available currencies: ({} total)'.format(len(CURRENCIES)))]
    c_list.extend(packet.notice(c) for c in sorted(CURRENCIES))
    return c_list
Example #47
0
def respond_good(matched, packet: ircp.Packet, shared: dict) -> str:
    ''' Respond to a good message '''
    return packet.reply('Thanks, {1}{0}{2}!'.format(packet.sender, CLR_NICK,
                                                    CLR_RESET))
Example #48
0
def stats_command(__: tuple, packet: ircp.Packet, shared: dict):
    """ Print statistical data about this bot """
    stats = shared['stats']
    uptime = _uptime(shared['stats']['starttime'])

    import resource
    mem_usage = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
    tracing_status = (lambda x: 'enabled' if x else 'disabled')(_IS_TRACING)
    from platform import platform, python_version

    output = (packet.notice('Current uptime: {}'.format(uptime)),
              packet.notice('Available plugins: {}'.format(
                  stats['plugins.available'])),
              packet.notice('Disabled plugins: {}'.format(
                  stats['plugins.disabled'])),
              packet.notice('Failed plugins: {}'.format(
                  stats['plugins.failed'])),
              packet.notice('Parsed messages: {}'.format(
                  stats['num_messages'])),
              packet.notice('Commands run: {}'.format(stats['commands_run'])),
              packet.notice('Regex Matches: {}'.format(
                  stats['regex_matches'])),
              packet.notice('Probot memory usage: {} KB'.format(mem_usage)),
              packet.notice('Bot admins online: {}'.format(len(
                  shared['auth']))),
              packet.notice('Memory tracing is {}'.format(tracing_status)),
              packet.notice('Cows: {}:moo{}'.format(CLR_HGLT, CLR_RESET)),
              packet.notice('Platform: {}'.format(platform())),
              packet.notice('Running on Python {}'.format(python_version())))

    return output
Example #49
0
def uptime_command(__: tuple, packet: ircp.Packet, shared: dict):
    """ Print current uptime """
    start_time = shared['stats']['starttime']
    uptime = _uptime(start_time)

    return packet.reply(uptime)
Example #50
0
def respond_greeting(matched, packet: ircp.Packet, shared: dict) -> str:
    ''' Respond to a nice greeting '''
    return packet.reply('Hello to you too, {1}{0}{2}!'.format(
        packet.sender, CLR_NICK, CLR_RESET))
Example #51
0
def respond_greeting(matched, packet: ircp.Packet, shared: dict) -> str:
    ''' Respond to a nice greeting '''
    return packet.reply('Hello to you too, {1}{0}{2}!'.format(packet.sender, CLR_NICK, CLR_RESET))
Example #52
0
def respond_bad(matched, packet: ircp.Packet, shared: dict) -> str:
    ''' Respond to an ugly, mean message '''
    return packet.reply('F**k you too, {1}{0}{2}!'.format(
        packet.sender, CLR_NICK, CLR_RESET))
Example #53
0
def respond_good(matched, packet: ircp.Packet, shared: dict) -> str:
    ''' Respond to a good message '''
    return packet.reply('Thanks, {1}{0}{2}!'.format(packet.sender, CLR_NICK, CLR_RESET))