예제 #1
0
파일: probot.py 프로젝트: camconn/probot
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))
예제 #2
0
파일: probot.py 프로젝트: camconn/probot
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))
예제 #3
0
파일: internal.py 프로젝트: camconn/probot
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
예제 #4
0
파일: internal.py 프로젝트: camconn/probot
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))
예제 #5
0
파일: internal.py 프로젝트: camconn/probot
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
예제 #6
0
파일: internal.py 프로젝트: camconn/probot
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))
예제 #7
0
파일: convert.py 프로젝트: camconn/probot
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))
예제 #8
0
파일: internal.py 프로젝트: camconn/probot
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
예제 #9
0
파일: probot.py 프로젝트: camconn/probot
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
예제 #10
0
파일: internal.py 프로젝트: camconn/probot
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')
예제 #11
0
파일: internal.py 프로젝트: camconn/probot
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
예제 #12
0
파일: internal.py 프로젝트: camconn/probot
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')
예제 #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
예제 #14
0
파일: irctools.py 프로젝트: camconn/probot
 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
예제 #15
0
파일: irctools.py 프로젝트: camconn/probot
 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
예제 #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
예제 #17
0
파일: internal.py 프로젝트: camconn/probot
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
예제 #18
0
파일: internal.py 프로젝트: camconn/probot
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
예제 #19
0
파일: probot.py 프로젝트: camconn/probot
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
예제 #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))
예제 #21
0
파일: internal.py 프로젝트: camconn/probot
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
예제 #22
0
파일: internal.py 프로젝트: camconn/probot
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
예제 #23
0
파일: probot.py 프로젝트: camconn/probot
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
예제 #24
0
파일: probot.py 프로젝트: camconn/probot
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.')
예제 #25
0
파일: probot.py 프로젝트: camconn/probot
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.')
예제 #26
0
파일: linkinfo.py 프로젝트: camconn/probot
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))
예제 #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))
예제 #28
0
파일: probot.py 프로젝트: camconn/probot
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.')
예제 #29
0
파일: probot.py 프로젝트: camconn/probot
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
예제 #30
0
파일: stats.py 프로젝트: camconn/probot
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')
예제 #31
0
파일: stats.py 프로젝트: camconn/probot
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")
예제 #32
0
파일: probot.py 프로젝트: camconn/probot
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.')
예제 #33
0
파일: calc.py 프로젝트: camconn/probot
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.')
예제 #34
0
파일: stats.py 프로젝트: camconn/probot
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
예제 #35
0
파일: convert.py 프로젝트: camconn/probot
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]))
예제 #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.')
예제 #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'))
예제 #38
0
파일: stats.py 프로젝트: camconn/probot
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
예제 #39
0
파일: template.py 프로젝트: camconn/probot
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!')
예제 #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!')
예제 #41
0
파일: probot.py 프로젝트: camconn/probot
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
예제 #42
0
파일: probot.py 프로젝트: camconn/probot
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
예제 #43
0
파일: responses.py 프로젝트: camconn/probot
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))
예제 #44
0
파일: stats.py 프로젝트: camconn/probot
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)
예제 #45
0
파일: stats.py 프로젝트: camconn/probot
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
예제 #46
0
파일: convert.py 프로젝트: camconn/probot
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
예제 #47
0
파일: responses.py 프로젝트: camconn/probot
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))
예제 #48
0
파일: stats.py 프로젝트: camconn/probot
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
예제 #49
0
파일: stats.py 프로젝트: camconn/probot
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)
예제 #50
0
파일: responses.py 프로젝트: camconn/probot
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))
예제 #51
0
파일: responses.py 프로젝트: camconn/probot
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))
예제 #52
0
파일: responses.py 프로젝트: camconn/probot
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))
예제 #53
0
파일: responses.py 프로젝트: camconn/probot
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))