Exemple #1
0
def follow(phenny, input):
    """Follow someone and translate as they speak."""

    # TODO: what if the nick is not present in the channel?
    # phenny possibly informs sender that the nick is not present and continues?

    global follows

    try:
        nick, dir, *extra = input.group(1).split(' ')
        dir = tuple(dir.split('-'))
        _ = dir[1]
    except:
        phenny.reply("Need nick and language pair!")
        return

    if caseless_equal(nick, phenny.config.nick):
        phenny.reply(phenny.config.nick.upper() + " DOES NOT LIKE TO BE FOLLOWED.")
        return

    try:
        apy_url = self.phenny.config.APy_url
    except:
        apy_url = "http://apy.projectjj.com"

    response = json.loads(web.get(apy_url + '/listPairs'))
    pairs = response["responseData"]

    if {"targetLanguage": dir[1], "sourceLanguage": dir[0]} not in pairs:
        try:
            dir[0] = phenny.iso_conversion_data[dir[0]]
            dir[1] = phenny.iso_conversion_data[dir[1]]
        except:
            phenny.reply("That language pair does not exist!")
            return

        if {"targetLanguage": dir[1], "sourceLanguage": dir[0]} not in pairs:
            phenny.reply("That language pair is not supported!")
            return

    # only accept follower paramter if it exists and the nick is admin
    if len(extra) >= 1 and input.admin:
        sender = extra[0]
    else:
        sender = input.nick

    for i in follows:
        if caseless_equal(i.nick, nick) and i.dir == dir and caseless_equal(i.sender, sender):
            phenny.say("%s is already following %s with %s." % (sender, nick, '-'.join(dir)))
            return

    follows.append(Eleda(sender, nick, dir))
    phenny.reply("%s now following %s (%s)." % (sender, nick, '-'.join(dir)))
Exemple #2
0
def checkMessages(phenny, input):  #filter through each message in the channel
    if input.sender in phenny.channels:
        if input.groups()[0][0] == '.' or (
                phenny.nick + ': '
                or phenny.nick + ', ') in input.groups()[0].split(' ')[0]:
            #do not translate if it is a begiak function
            return

        translations = {}
        for i in follows:
            if caseless_equal(i.nick, input.nick):
                if (i.nick, i.dir) not in translations:
                    #this user is being followed, translate them
                    direction = '-'.join(i.dir)
                    translations[(i.nick,
                                  i.dir)] = translate(phenny, input.group(0),
                                                      i.dir[0], i.dir[1])
                    translations[(i.nick,
                                  i.dir)] = translations[(i.nick,
                                                          i.dir)].replace(
                                                              '*', '')
                if translations[(i.nick, i.dir)] != input.group(0):
                    #don't bother sending a notice if the input is the same as the output
                    phenny.msg(
                        i.sender, i.nick + ' (' + '-'.join(i.dir) + '): ' +
                        translations[(i.nick, i.dir)])
Exemple #3
0
def unfollow(phenny, input):  #unfollow a user
    """Stop following someone."""
    global follows

    following = False
    for i in follows:
        if caseless_equal(i.nick,
                          input.groups()[1]) and caseless_equal(
                              i.sender, input.nick):
            #if this person is indeed being followed (and is indeed the creator of the follow)
            follows.remove(i)
            following = True
    if following == True:
        phenny.reply(input.groups()[1] + " is no longer being followed.")
    else:
        phenny.reply("Sorry, you aren't following that user!")
Exemple #4
0
def unfollow(phenny, input):
    """Stop following someone."""

    global follows

    target = input.group(1)

    for i in follows:
        if not (caseless_equal(i.nick, target) and caseless_equal(i.sender, input.nick)):
            continue

        follows.remove(i)
        phenny.reply(target + " is no longer being followed.")
        return

    phenny.reply("Sorry, you aren't following that user!")
Exemple #5
0
def checkMessages(phenny, input):
    '''filter through each message in the channel'''

    if input.sender not in phenny.channels:
        return

    text = input.group(0)

    # don't translate commands
    if text.startswith('.'):
        return

    translations = {}

    for i in follows:
        if not caseless_equal(i.nick, input.nick):
            continue

        # this user is being followed, translate them

        try:
            translation = translations[(i.nick, i.dir)]
        except:
            direction = '-'.join(i.dir)
            translation = apy.translate(phenny, text, i.dir[0], i.dir[1])
            translation = translation.replace('*', '')
            translations[(i.nick, i.dir)] = translation

        # don't send translation if the input is the same as the output
        if translation == text:
            continue

        phenny.msg(i.sender, '%s (%s): %s' % (i.nick, '-'.join(i.dir), translation))
Exemple #6
0
def get_queue(queue_data, queue_name, nick):
    lower_names = {k.casefold(): k for k in queue_data.keys()}
    if queue_name.casefold() in lower_names:
        n = lower_names[queue_name.casefold()]
        return n, queue_data[n]
    elif nick.casefold() + ':' + queue_name.casefold() in lower_names:
        n = lower_names[nick.casefold() + ':' + queue_name.casefold()]
        return n, queue_data[n]
    else:
        for i in lower_names:
            if caseless_equal(queue_name, i.split(':')[1]):
                n = lower_names[i.casefold()]
                return n, queue_data[n]
    return None, None
Exemple #7
0
def get_queue(queue_data, queue_name, nick):
    lower_names = {k.casefold(): k for k in queue_data.keys()}

    if queue_name.casefold() in lower_names:
        n = lower_names[queue_name.casefold()]
        return n, queue_data[n]
    elif nick.casefold()  + ':' + queue_name.casefold() in lower_names:
        n = lower_names[nick.casefold() + ':' + queue_name.casefold()]
        return n, queue_data[n]

    for i in lower_names:
        if caseless_equal(queue_name, i.split(':')[1]):
            n = lower_names[i.casefold()]
            return n, queue_data[n]

    return None, None
Exemple #8
0
def queue(phenny, raw):
    """.queue- queue management."""
    if raw.group(1):
        command = raw.group(1)
        if command.lower() == 'display':
            search = raw.group(2)
            if search:
                queue_names = disambiguate_name(phenny.queue_data, search)
                if type(queue_names) is str:
                    #there was only one possible queue
                    more.add_messages(
                        raw.nick, phenny,
                        print_queue(queue_names,
                                    phenny.queue_data[queue_names]))
                elif len(queue_names) > 0:
                    queue_exact = list(queue_names)
                    for q in queue_names:
                        if caseless_equal(q.split(':')[0],
                                          raw.nick) and caseless_equal(
                                              q[len(raw.nick) + 1:], search):
                            #current user owns queue with exact name
                            more.add_messages(
                                raw.nick, phenny,
                                print_queue(q, phenny.queue_data[q]))
                            return
                        elif q[q.find(':') + 1:] != search:
                            #filter queues with exact name
                            queue_exact.remove(q)
                    if len(queue_exact) == 1:
                        #only one user owns queue with exact name
                        more.add_messages(
                            raw.nick, phenny,
                            print_queue(queue_exact[0],
                                        phenny.queue_data[queue_exact[0]]))
                    elif len(queue_exact) > 1:
                        #more users own queues with exact name
                        phenny.reply('Did you mean: ' +
                                     ', '.join(queue_exact) + '?')
                    else:
                        #the name was ambiguous, show a list of queues
                        phenny.reply('Did you mean: ' +
                                     ', '.join(queue_names) + '?')
                else:
                    phenny.reply('No queues found.')
            else:
                #there was no queue name given, display all of their names
                if phenny.queue_data:
                    phenny.reply('Avaliable queues: ' +
                                 ', '.join(sorted(phenny.queue_data.keys())))
                else:
                    phenny.reply('There are no queues to display.')

        elif command.lower() == 'new':
            if raw.group(2):
                queue_name = raw.nick + ':' + raw.group(2)
                owner = raw.nick
                if queue_name not in phenny.queue_data:
                    if raw.group(3):
                        queue = raw.group(3).split(',')
                        queue = list(map(lambda x: x.strip(), queue))
                        phenny.queue_data[queue_name] = {
                            'owner': owner,
                            'queue': queue
                        }
                        write_dict(filename(phenny), phenny.queue_data)
                        phenny.reply('Queue {} with items {} created.'.format(
                            queue_name, ', '.join(queue)))
                    else:
                        phenny.queue_data[queue_name] = {
                            'owner': owner,
                            'queue': []
                        }
                        write_dict(filename(phenny), phenny.queue_data)
                        phenny.reply(
                            'Empty queue {} created.'.format(queue_name))
                else:
                    phenny.reply(
                        'You already have a queue with that name! Pick a new name or delete the old one.'
                    )
            else:
                phenny.reply('Syntax: .queue new <name> <item1>, <item2> ...')

        elif command.lower() in ['delete', 'remove', 'del', 'rm']:
            if raw.group(2):
                queue_name, queue = get_queue(phenny.queue_data, raw.group(2),
                                              raw.nick)
                if type(queue_name) is str:
                    if caseless_equal(raw.nick, queue['owner']) or raw.admin:
                        phenny.queue_data.pop(queue_name)
                        write_dict(filename(phenny), phenny.queue_data)
                        phenny.reply('Queue {} deleted.'.format(queue_name))
                    else:
                        phenny.reply('You aren\'t authorized to do that!')
                else:
                    phenny.reply('That queue wasn\'t found!')
            else:
                phenny.reply('Syntax: .queue delete <name>')

        elif get_queue(phenny.queue_data, raw.group(1), raw.nick)[0]:
            #queue-specific commands
            queue_name, queue = get_queue(phenny.queue_data, raw.group(1),
                                          raw.nick)
            if raw.group(2):
                command = raw.group(2).lower()
                if caseless_equal(queue['owner'], raw.nick) or raw.admin:
                    if command == 'add':
                        if raw.group(3):
                            new_queue = raw.group(3).split(',')
                            new_queue = list(
                                map(lambda x: x.strip(), new_queue))
                            queue['queue'] += new_queue
                            write_dict(filename(phenny), phenny.queue_data)
                            more.add_messages(raw.nick.lower(), phenny,
                                              print_queue(queue_name, queue))
                        else:
                            phenny.reply(
                                'Syntax: .queue <name> add <item1>, <item2> ...'
                            )
                    elif command == 'swap':
                        if raw.group(3):
                            indices = raw.group(3).split(',')
                            try:
                                id1, id2 = tuple(
                                    map(lambda x: int(x.strip()), indices))[:2]
                            except ValueError:
                                q1, q2 = tuple(
                                    map(lambda x: x.strip(), indices))[:2]
                                id1 = search_queue(queue['queue'], q1)
                                if id1 is None:
                                    phenny.reply('{} not found in {}'.format(
                                        indices[0].strip(), queue_name))
                                    return
                                id2 = search_queue(queue['queue'], q2)
                                if id2 is None:
                                    phenny.reply('{} not found in {}'.format(
                                        indices[1].strip(), queue_name))
                                    return
                            queue['queue'][id1], queue['queue'][id2] = queue[
                                'queue'][id2], queue['queue'][id1]
                            write_dict(filename(phenny), phenny.queue_data)
                            more.add_messages(raw.nick, phenny,
                                              print_queue(queue_name, queue))
                        else:
                            phenny.reply(
                                'Syntax: .queue <name> swap <index/item1>, <index/item2>'
                            )
                    elif command in ['move', 'mv']:
                        if raw.group(3) and ',' in raw.group(3):
                            indices = raw.group(3).split(',')
                            try:
                                id1, id2 = tuple(
                                    map(lambda x: int(x.strip()), indices))[:2]
                            except ValueError:
                                q1, q2 = tuple(
                                    map(lambda x: x.strip(), indices))[:2]
                                id1 = search_queue(queue['queue'], q1)
                                if id1 is None:
                                    phenny.reply('{} not found in {}'.format(
                                        indices[0].strip(), queue_name))
                                    return
                                id2 = search_queue(queue['queue'], q2)
                                if id2 is None:
                                    phenny, reply('{} not found in {}'.format(
                                        indices[1].strip(), queue_name))
                                    return
                            #queue['queue'][id2 + (-1 if id1 < id2 else 0)] = queue['queue'].pop(id1)
                            queue['queue'].insert(id2, queue['queue'].pop(id1))
                            write_dict(filename(phenny), phenny.queue_data)
                            more.add_messages(raw.nick, phenny,
                                              print_queue(queue_name, queue))
                        else:
                            phenny.reply(
                                'Syntax: .queue <name> move <source_index/item>, <target_index/item>'
                            )
                    elif command == 'replace':
                        if raw.group(3) and ',' in raw.group(3):
                            old, new = raw.group(3).split(',')
                            old = old.strip()
                            try:
                                old_id = int(old)
                            except ValueError:
                                old_id = search_queue(queue['queue'], old)
                                if old_id is None:
                                    phenny.reply('{} not found in {}'.format(
                                        old, queue_name))
                                    return
                            queue['queue'][old_id] = new.strip()
                            write_dict(filename(phenny), phenny.queue_data)
                            more.add_messages(raw.nick, phenny,
                                              print_queue(queue_name, queue))
                        else:
                            phenny.reply(
                                'Syntax: .queue <name> replace <index/item>, <new_item>'
                            )
                    elif command in ['remove', 'delete', 'del', 'rm']:
                        if raw.group(3):
                            item = raw.group(3)
                            if item in queue['queue']:
                                queue['queue'].remove(item)
                                write_dict(filename(phenny), phenny.queue_data)
                                more.add_messages(
                                    raw.nick, phenny,
                                    print_queue(queue_name, queue))
                            elif search_queue(queue['queue'], item):
                                queue['queue'].pop(
                                    search_queue(queue['queue'], item))
                                write_dict(filename(phenny), phenny.queue_data)
                                more.add_messages(
                                    raw.nick, phenny,
                                    print_queue(queue_name, queue))
                            else:
                                phenny.reply('{} not found in {}'.format(
                                    item, queue_name))
                        else:
                            phenny.reply('Syntax: .queue <name> remove <item>')
                    elif command == 'pop':
                        try:
                            queue['queue'].pop(0)
                            write_dict(filename(phenny), phenny.queue_data)
                            more.add_messages(raw.nick, phenny,
                                              print_queue(queue_name, queue))
                        except IndexError:
                            phenny.reply('That queue is already empty.')
                    elif command == 'random':
                        mphenny.reply('%s is the lucky one.' %
                                      repr(random.choice(queue['queue'])))
                    elif command == 'reassign':
                        if raw.group(3):
                            new_owner = raw.group(3)
                            new_queue_name = new_owner + queue_name[
                                queue_name.index(':'):]
                            phenny.queue_data.pop(queue_name)
                            phenny.queue_data[new_queue_name] = {
                                'owner': new_owner,
                                'queue': queue['queue']
                            }
                            write_dict(filename(phenny), phenny.queue_data)
                            more.add_messages(
                                raw.nick, phenny,
                                print_queue(new_queue_name, queue))
                        else:
                            phenny.reply(
                                'Syntax: .queue <name> reassign <nick>')
                    elif command.lower() in ['rename', 'ren']:
                        if raw.group(3):
                            new_queue_name = queue['owner'] + ':' + raw.group(
                                3)
                            phenny.queue_data[
                                new_queue_name] = phenny.queue_data.pop(
                                    queue_name)
                            write_dict(filename(phenny), phenny.queue_data)
                            more.add_messages(
                                raw.nick, phenny,
                                print_queue(new_queue_name, queue))
                        else:
                            phenny.reply(
                                'Syntax: .queue <name> rename <new_name>')
                elif command == 'random':
                    phenny.reply('%s is the lucky one.' %
                                 repr(random.choice(queue['queue'])))
                else:
                    phenny.reply('You aren\'t the owner of this queue!')
            else:
                more.add_messages(raw.nick, phenny,
                                  print_queue(queue_name, queue))
        else:
            if raw.group(3):
                phenny.reply('That\'s not a command. Commands: ' + commands)
            else:
                phenny.reply('That queue wasn\'t found!')
    else:
        phenny.reply('Commands: ' + commands)
Exemple #9
0
def follow(phenny, input):  #follow a user
    """Follow someone and translate as they speak."""
    # TODO: what if the nick is not present in the channel?
    # phenny possibly informs sender that the nick is not present and continues?

    global follows

    if input.groups()[1] != None:
        data = input.group(2).split(' ')
        nick = data[0]

        if caseless_equal(nick, phenny.config.nick):
            phenny.reply(phenny.config.nick.upper() +
                         " DOES NOT LIKE TO BE FOLLOWED.")
            return

        try:
            dir = data[1].split('-')
            dir[1] = dir[1]
        except:
            phenny.reply("Need language pair!")
            return

        pairs = {}
        if hasattr(phenny.config, 'translate_url'):
            pairs = json.loads(
                get_page(self.phenny.config.translate_url, '/listPairs'))
        else:
            pairs = json.loads(
                get_page('apy.projectjj.com', '/listPairs', port=2737))
        if {
                "targetLanguage": dir[1],
                "sourceLanguage": dir[0]
        } not in pairs["responseData"]:
            if (not (phenny.iso_conversion_data.get(dir[0]))
                    or not (phenny.iso_conversion_data.get(dir[1])) or
                {
                    "targetLanguage": phenny.iso_conversion_data.get(dir[1]),
                    "sourceLanguage": phenny.iso_conversion_data.get(dir[0])
                } not in pairs["responseData"]):
                phenny.reply("That language pair does not exist!")
                return
            else:
                dir[0] = phenny.iso_conversion_data[dir[0]]
                dir[1] = phenny.iso_conversion_data[dir[1]]

        if len(data) in [2, 3]:
            sender = input.nick
            if len(data) == 3 and input.admin == True:
                #only accept follower paramter if it exists and the nick is admin
                sender = data[2]
        else:
            phenny.reply("Unexpected error.")
            return

        for i in follows:
            if caseless_equal(i.nick,
                              nick) and i.dir == tuple(dir) and caseless_equal(
                                  i.sender, sender):
                phenny.say(sender + " is already following " + nick +
                           " with " + '-'.join(dir) + '.')
                return

        follows.append(Eleda(sender, nick, dir))
        phenny.reply(sender + " now following " + nick + " (" + '-'.join(dir) +
                     ").")
    else:
        phenny.reply("Need nick and language pair!")
Exemple #10
0
def queue(phenny, input):
    """.queue- queue management."""

    command = input.group(1).lower()

    if not command:
        phenny.reply('Commands: ' + '; '.join(commands))
        return

    if command == 'display':
        search = input.group(2)

        if not search:
            # there was no queue name given, display all of their names
            if phenny.queue_data:
                phenny.reply('Avaliable queues: ' + ', '.join(sorted(phenny.queue_data.keys())))
            else:
                phenny.reply('There are no queues to display.')
            return

        queue_names = disambiguate_name(phenny.queue_data, search)

        if not queue_names:
            phenny.reply('No queues found.')
            return

        if len(queue_names) == 1:
            # there was only one possible queue
            queue_name = queue_names[0]
            queue = phenny.queue_data[queue_name]
            more.add_messages(phenny, input.sender, print_queue(queue_name, queue))
            return

        for q in queue_names:
            if caseless_equal(q.split(':')[0], input.nick) and caseless_equal(q[len(input.nick)+1:], search):
                # current user owns queue with exact name
                more.add_messages(phenny, input.sender, print_queue(q, phenny.queue_data[q]))
                return
            elif q[q.find(':')+1:] != search:
                # filter queues with exact name
                queue_names.remove(q)

        if len(queue_names) == 1:
            # only one user owns queue with exact name
            queue_name = queue_names[0]
            queue = phenny.queue_data[queue_name]
            more.add_messages(phenny, input.sender, print_queue(queue_name, queue))
        else:
            # the name was ambiguous, show a list of queues
            phenny.reply('Did you mean: ' + ', '.join(queue_names) + '?')

    elif command == 'new':
        if not input.group(2):
            phenny.reply('Syntax: .queue new <name> <item1>, <item2> ...')

        queue_name = input.nick + ':' + input.group(2)
        owner = input.nick

        if queue_name in phenny.queue_data:
            phenny.reply('You already have a queue with that name! Pick a new name or delete the old one.')
            return

        if input.group(3):
            queue = input.group(3).split(',')
            queue = list(map(lambda x: x.strip(), queue))
            phenny.queue_data[queue_name] = {'owner': owner, 'queue': queue}
            write_db(phenny, 'queue', phenny.queue_data)
            phenny.reply('Queue {} with items {} created.'.format(
                queue_name, ', '.join(queue)))
        else:
            phenny.queue_data[queue_name] = {'owner': owner, 'queue': []}
            write_db(phenny, 'queue', phenny.queue_data)
            phenny.reply('Empty queue {} created.'.format(queue_name))

    elif command in ['delete', 'remove', 'del', 'rm']:
        if not input.group(2):
            phenny.reply('Syntax: .queue delete <name>')

        queue_name, queue = get_queue(phenny.queue_data, input.group(2), input.nick)

        if not queue_name:
            phenny.reply('That queue wasn\'t found!')
            return

        if not (caseless_equal(input.nick, queue['owner']) or input.admin):
            phenny.reply('You aren\'t authorized to do that!')
            return

        phenny.queue_data.pop(queue_name)
        write_db(phenny, 'queue', phenny.queue_data)
        phenny.reply('Queue {} deleted.'.format(queue_name))

    elif get_queue(phenny.queue_data, input.group(1), input.nick)[0]:
        # queue-specific commands
        command = input.group(2).lower()
        queue_name, queue = get_queue(phenny.queue_data, input.group(1), input.nick)

        if not command:
            more.add_messages(phenny, input.sender, print_queue(queue_name, queue))
            return

        if command == 'random':
            phenny.reply('%s is the lucky one.' % repr(random.choice(queue['queue'])))
            return

        if not (caseless_equal(queue['owner'], input.nick) or input.admin):
            phenny.reply('You aren\'t the owner of this queue!')
            return

        if command == 'add':
            if not input.group(3):
                phenny.reply('Syntax: .queue <name> add <item1>, <item2> ...')
                return

            new_queue = input.group(3).split(',')
            new_queue = list(map(lambda x: x.strip(), new_queue))
            queue['queue'] += new_queue
            write_db(phenny, 'queue', phenny.queue_data)
            more.add_messages(phenny, input.sender, print_queue(queue_name, queue))
        elif command == 'swap':
            if not input.group(3):
                phenny.reply('Syntax: .queue <name> swap <index/item1>, <index/item2>')
                return

            try:
                id1, id2 = get_indices(phenny, input.group(3), queue_name, queue)
            except ValueError:
                return

            queue['queue'][id1], queue['queue'][id2] = queue['queue'][id2], queue['queue'][id1]
            write_db(phenny, 'queue', phenny.queue_data)
            more.add_messages(phenny, input.sender, print_queue(queue_name, queue))
        elif command in ['move', 'mv']:
            if not (input.group(3) and ',' in input.group(3)):
                phenny.reply('Syntax: .queue <name> move <source_index/item>, <target_index/item>')
                return

            try:
                id1, id2 = get_indices(phenny, input.group(3), queue_name, queue)
            except ValueError:
                return

            queue['queue'].insert(id2, queue['queue'].pop(id1))
            write_db(phenny, 'queue', phenny.queue_data)
            more.add_messages(phenny, input.sender, print_queue(queue_name, queue))
        elif command == 'replace':
            if not (input.group(3) and ',' in input.group(3)):
                phenny.reply('Syntax: .queue <name> replace <index/item>, <new_item>')
                return

            old, new = input.group(3).split(',')
            old = old.strip()

            try:
                old_id = int(old)
            except ValueError:
                old_id = search_queue(queue['queue'], old)
                if old_id is None:
                    phenny.reply('{} not found in {}'.format(old, queue_name))
                    return

            queue['queue'][old_id] = new.strip()
            write_db(phenny, 'queue', phenny.queue_data)
            more.add_messages(phenny, input.sender, print_queue(queue_name, queue))
        elif command in ['remove', 'delete', 'del', 'rm']:
            if not input.group(3):
                phenny.reply('Syntax: .queue <name> remove <item>')
                return

            item = input.group(3)

            if item in queue['queue']:
                queue['queue'].remove(item)
                write_db(phenny, 'queue', phenny.queue_data)
                more.add_messages(phenny, input.sender, print_queue(queue_name, queue))
            elif search_queue(queue['queue'], item):
                queue['queue'].pop(search_queue(queue['queue'], item))
                write_db(phenny, 'queue', phenny.queue_data)
                more.add_messages(phenny, input.sender, print_queue(queue_name, queue))
            else:
                phenny.reply('{} not found in {}'.format(item, queue_name))
        elif command == 'pop':
            try:
                queue['queue'].pop(0)
                write_db(phenny, 'queue', phenny.queue_data)
                more.add_messages(phenny, input.sender, print_queue(queue_name, queue))
            except IndexError:
                phenny.reply('That queue is already empty.')
        elif command == 'reassign':
            if not input.group(3):
                phenny.reply('Syntax: .queue <name> reassign <nick>')
                return

            phenny.queue_data.pop(queue_name)
            new_owner = input.group(3)
            queue_name = new_owner + queue_name[queue_name.index(':'):]
            phenny.queue_data[queue_name] = {'owner': new_owner, 'queue': queue['queue']}
            write_db(phenny, 'queue', phenny.queue_data)
            more.add_messages(phenny, input.sender, print_queue(queue_name, queue))
        elif command in ['rename', 'ren']:
            if not input.group(3):
                phenny.reply('Syntax: .queue <name> rename <new_name>')
                return

            phenny.queue_data.pop(queue_name)
            queue_name = queue['owner'] + ':' + input.group(3)
            phenny.queue_data[queue_name] = queue
            write_db(phenny, 'queue', phenny.queue_data)
            more.add_messages(phenny, input.sender, print_queue(queue_name, queue))
    else:
        if input.group(3):
            phenny.reply('That\'s not a command. Commands: ' + '; '.join(commands))
        else:
            phenny.reply('That queue wasn\'t found!')
Exemple #11
0
def queue(phenny, input):
    """.queue- queue management."""

    if not input.group(1):
        phenny.reply('Commands: ' + '; '.join(commands))
        return

    command = input.group(1).lower()

    if command == 'display':
        search = input.group(2)

        if not search:
            # there was no queue name given, display all of their names
            if phenny.queue_data:
                phenny.reply('Avaliable queues: ' + ', '.join(sorted(phenny.queue_data.keys())))
            else:
                phenny.reply('There are no queues to display.')
            return

        queue_names = disambiguate_name(phenny.queue_data, search)

        if not queue_names:
            phenny.reply('No queues found.')
            return

        if len(queue_names) == 1:
            # there was only one possible queue
            queue_name = queue_names[0]
            queue = phenny.queue_data[queue_name]
            more.add_messages(phenny, input.sender, print_queue(queue_name, queue))
            return

        for q in queue_names:
            if caseless_equal(q.split(':')[0], input.nick) and caseless_equal(q[len(input.nick)+1:], search):
                # current user owns queue with exact name
                more.add_messages(phenny, input.sender, print_queue(q, phenny.queue_data[q]))
                return
            elif q[q.find(':')+1:] != search:
                # filter queues with exact name
                queue_names.remove(q)

        if len(queue_names) == 1:
            # only one user owns queue with exact name
            queue_name = queue_names[0]
            queue = phenny.queue_data[queue_name]
            more.add_messages(phenny, input.sender, print_queue(queue_name, queue))
        else:
            # the name was ambiguous, show a list of queues
            phenny.reply('Did you mean: ' + ', '.join(queue_names) + '?')

    elif command == 'new':
        if not input.group(2):
            phenny.reply('Syntax: .queue new <name> <item1>, <item2> ...')
            return

        queue_name = input.nick + ':' + input.group(2)
        owner = input.nick

        if queue_name in phenny.queue_data:
            phenny.reply('You already have a queue with that name! Pick a new name or delete the old one.')
            return

        if input.group(3):
            queue = input.group(3).split(',')
            queue = list(map(lambda x: x.strip(), queue))
            phenny.queue_data[queue_name] = {'owner': owner, 'queue': queue}
            write_db(phenny, 'queue', phenny.queue_data)
            phenny.reply('Queue {} with items {} created.'.format(
                queue_name, ', '.join(queue)))
        else:
            phenny.queue_data[queue_name] = {'owner': owner, 'queue': []}
            write_db(phenny, 'queue', phenny.queue_data)
            phenny.reply('Empty queue {} created.'.format(queue_name))

    elif command in ['delete', 'remove', 'del', 'rm']:
        if not input.group(2):
            phenny.reply('Syntax: .queue delete <name>')
            return

        queue_name, queue = get_queue(phenny.queue_data, input.group(2), input.nick)

        if not queue_name:
            phenny.reply('That queue wasn\'t found!')
            return

        if not (caseless_equal(input.nick, queue['owner']) or input.admin):
            phenny.reply('You aren\'t authorized to do that!')
            return

        phenny.queue_data.pop(queue_name)
        write_db(phenny, 'queue', phenny.queue_data)
        phenny.reply('Queue {} deleted.'.format(queue_name))

    elif get_queue(phenny.queue_data, input.group(1), input.nick)[0]:
        # queue-specific commands
        command = input.group(2).lower()
        queue_name, queue = get_queue(phenny.queue_data, input.group(1), input.nick)

        if not command:
            more.add_messages(phenny, input.sender, print_queue(queue_name, queue))
            return

        if command == 'random':
            phenny.reply('%s is the lucky one.' % repr(random.choice(queue['queue'])))
            return

        if not (caseless_equal(queue['owner'], input.nick) or input.admin):
            phenny.reply('You aren\'t the owner of this queue!')
            return

        if command == 'add':
            if not input.group(3):
                phenny.reply('Syntax: .queue <name> add <item1>, <item2> ...')
                return

            new_queue = input.group(3).split(',')
            new_queue = list(map(lambda x: x.strip(), new_queue))
            queue['queue'] += new_queue
            write_db(phenny, 'queue', phenny.queue_data)
            more.add_messages(phenny, input.sender, print_queue(queue_name, queue))
        elif command == 'swap':
            if not input.group(3):
                phenny.reply('Syntax: .queue <name> swap <index/item1>, <index/item2>')
                return

            try:
                id1, id2 = get_indices(phenny, input.group(3), queue_name, queue)
            except ValueError:
                return

            queue['queue'][id1], queue['queue'][id2] = queue['queue'][id2], queue['queue'][id1]
            write_db(phenny, 'queue', phenny.queue_data)
            more.add_messages(phenny, input.sender, print_queue(queue_name, queue))
        elif command in ['move', 'mv']:
            if not (input.group(3) and ',' in input.group(3)):
                phenny.reply('Syntax: .queue <name> move <source_index/item>, <target_index/item>')
                return

            try:
                id1, id2 = get_indices(phenny, input.group(3), queue_name, queue)
            except ValueError:
                return

            queue['queue'].insert(id2, queue['queue'].pop(id1))
            write_db(phenny, 'queue', phenny.queue_data)
            more.add_messages(phenny, input.sender, print_queue(queue_name, queue))
        elif command == 'replace':
            if not (input.group(3) and ',' in input.group(3)):
                phenny.reply('Syntax: .queue <name> replace <index/item>, <new_item>')
                return

            old, new = input.group(3).split(',')
            old = old.strip()

            try:
                old_id = int(old)
            except ValueError:
                old_id = search_queue(queue['queue'], old)
                if old_id is None:
                    phenny.reply('{} not found in {}'.format(old, queue_name))
                    return

            queue['queue'][old_id] = new.strip()
            write_db(phenny, 'queue', phenny.queue_data)
            more.add_messages(phenny, input.sender, print_queue(queue_name, queue))
        elif command in ['remove', 'delete', 'del', 'rm']:
            if not input.group(3):
                phenny.reply('Syntax: .queue <name> remove <item>')
                return

            item = input.group(3)

            if item in queue['queue']:
                queue['queue'].remove(item)
                write_db(phenny, 'queue', phenny.queue_data)
                more.add_messages(phenny, input.sender, print_queue(queue_name, queue))
            elif search_queue(queue['queue'], item):
                queue['queue'].pop(search_queue(queue['queue'], item))
                write_db(phenny, 'queue', phenny.queue_data)
                more.add_messages(phenny, input.sender, print_queue(queue_name, queue))
            else:
                phenny.reply('{} not found in {}'.format(item, queue_name))
        elif command == 'pop':
            try:
                queue['queue'].pop(0)
                write_db(phenny, 'queue', phenny.queue_data)
                more.add_messages(phenny, input.sender, print_queue(queue_name, queue))
            except IndexError:
                phenny.reply('That queue is already empty.')
        elif command == 'reassign':
            if not input.group(3):
                phenny.reply('Syntax: .queue <name> reassign <nick>')
                return

            phenny.queue_data.pop(queue_name)
            new_owner = input.group(3)
            queue_name = new_owner + queue_name[queue_name.index(':'):]
            phenny.queue_data[queue_name] = {'owner': new_owner, 'queue': queue['queue']}
            write_db(phenny, 'queue', phenny.queue_data)
            more.add_messages(phenny, input.sender, print_queue(queue_name, queue))
        elif command in ['rename', 'ren']:
            if not input.group(3):
                phenny.reply('Syntax: .queue <name> rename <new_name>')
                return

            phenny.queue_data.pop(queue_name)
            queue_name = queue['owner'] + ':' + input.group(3)
            phenny.queue_data[queue_name] = queue
            write_db(phenny, 'queue', phenny.queue_data)
            more.add_messages(phenny, input.sender, print_queue(queue_name, queue))
    else:
        if input.group(3):
            phenny.reply('That\'s not a command. Commands: ' + '; '.join(commands))
        else:
            phenny.reply('That queue wasn\'t found!')