def apertium_generate(phenny, input): """Use Apertium APY's generate functionality""" lang, text = input.groups() opener = urllib.request.build_opener() opener.addheaders = headers constructed_url = APIanalyseURL + '/generate?lang=' + web.quote(lang) constructed_url += '&q=' + web.quote(text.strip()) try: response = opener.open(constructed_url).read() except urllib.error.HTTPError as error: response = error.read() jobj = json.loads(response.decode('utf-8')) if 'explanation' in jobj: phenny.say('The following error occurred: ' + jobj['explanation']) else: phenny.say('An error occurred: ' + str(error)) return jobj = json.loads(response.decode('utf-8')) messages = [] for generation, original in jobj: messages.append(original + " → " + generation) more.add_messages(input.nick, phenny, "\n".join(messages), break_up=lambda x, y: x.split('\n'))
def apertium_generate(phenny, input): '''Use Apertium APy's generate functionality''' cmd, cmd_error = strict_check(r'(' + langRE + r')\s+(.*)', input.group(1), apertium_generate) if cmd_error: phenny.say(cmd_error) return opener = urllib.request.build_opener() opener.addheaders = headers try: response = opener.open('{:s}/generate?lang={:s}&q={:s}'.format( phenny.config.APy_analyseURL, web.quote(cmd.group(1)), web.quote(cmd.group(2).strip()))).read() except urllib.error.HTTPError as error: handle_error(error) jobj = json.loads(response.decode('utf-8')) messages = [] for generation, original in jobj: messages.append(original + ' → ' + generation) more.add_messages(phenny, input.nick, messages)
def apertium_identlang(phenny, input): '''Identify the language for a given input.''' text, text_error = strict_check(r'.*', input.group(1), apertium_identlang) text = text.group(0) if text_error: phenny.say(text_error) return opener = urllib.request.build_opener() opener.addheaders = headers try: response = opener.open('{:s}/identifyLang?q={:s}'.format( phenny.config.APy_url, web.quote(text.strip()))).read() jsdata = json.loads(response.decode('utf-8')) except urllib.error.HTTPError as error: handle_error(error) messages = [] for key, value in jsdata.items(): messages.append(key + ' = ' + str(value)) more.add_messages(phenny, input.nick, messages)
def randquote_fetcher(phenny, topic, to_user): # create opener opener = urllib.request.build_opener() opener.addheaders = [ ('User-agent', web.Grab().version), ('Referer', "http://quotes.firespeaker.org/"), ] try: url = "http://quotes.firespeaker.org/random.php" if topic: url += "?topic=%s" % web.quote(topic) req = opener.open(url) data = req.read().decode('utf-8') data = json.loads(data) except (HTTPError, IOError, ValueError) as e: raise GrumbleError("Firespeaker.org down? Try again later.") from e if len(data) == 0: phenny.say("No results found") return #result = data['list'][0] #url = 'http://www.urbandictionary.com/define.php?term={0}'.format(web.quote(word)) # #response = "{0} - {1}".format(result['definition'].strip()[:256], url) if data['quote'] != None: quote = data['quote'].replace('</p>', '').replace('<p>', '').replace('<em>', '_').replace('</em>', '_').replace('—', '—') response = data['short_url'] + ' - ' + quote else: phenny.say("Sorry, no quotes returned!") return more.add_messages(phenny, to_user, response.split('\n'))
def suggest(phenny, input): ''' Shows first 10 results from Google Suggestion API.''' if not input.group(1): return phenny.reply("No query term.") query = input.group(1) answer = requests.get(suggest_uri + query) suggestions = answer.json()[1][:10] phenny.reply(suggestions[0]) phenny.reply('Check PM for more.') more.add_messages(phenny, input.nick, suggestions[1:])
def apertium_identlang(phenny, input): '''Identify the language for a given input.''' text = strict_check(r'.*', input.group(2), apertium_identlang).group(0) opener = urllib.request.build_opener() opener.addheaders = headers try: response = opener.open('{:s}/identifyLang?q={:s}'.format( phenny.config.APy_url, web.quote(text.strip()))).read() jsdata = json.loads(response.decode('utf-8')) except urllib.error.HTTPError as error: handle_error(error) messages = [] for key, value in jsdata.items(): messages.append(key + ' = ' + str(value)) more.add_messages(input.nick, phenny, '\n'.join(messages), break_up=lambda x, y: x.split('\n'))
def apertium_generate(phenny, input): '''Use Apertium APy's generate functionality''' cmd = strict_check(r'(' + langRE + r')\s+(.*)', input.group(2), apertium_generate) opener = urllib.request.build_opener() opener.addheaders = headers try: response = opener.open('{:s}/generate?lang={:s}&q={:s}'.format( phenny.config.APy_analyseURL, web.quote(cmd.group(1)), web.quote(cmd.group(2).strip()))).read() except urllib.error.HTTPError as error: handle_error(error) jobj = json.loads(response.decode('utf-8')) messages = [] for generation, original in jobj: messages.append(original + ' → ' + generation) more.add_messages(input.nick, phenny, '\n'.join(messages), break_up=lambda x, y: x.split('\n'))
def check_mail(phenny): found = False mail = login(phenny) if not mail: return mail.select('inbox') rc, data = mail.uid('search', None, 'UNSEEN') unseen_mails = data[0].split() messages = {} for uid in unseen_mails: rc, data = mail.uid('fetch', uid, '(RFC822)') e = email.message_from_string(data[0][1].decode('utf8')) for name, (address, channels) in phenny.config.mailing_lists.items(): if address in recipients(e): found = True message = format_email(e, name) if type(channels) is str: channels = [channels] for channel in channels: if not channel in messages: messages[channel].append(message) else: messages[channel] = [message] rc, data = mail.uid('store', uid, '+FLAGS', '(\\Seen)') for channel in messages.keys(): more.add_messages(phenny, channel, messages[channel]) mail.logout() phenny.mailing_list_timer = threading.Timer(60 * 5, check_mail, (phenny, )) phenny.mailing_list_timer.start() return found
def topics(phenny, input): if not is_up('https://api.duckduckgo.com'): return phenny.say('Sorry, DuckDuckGo API is down.') if not input.group(1): return phenny.reply('.topics about what?') query = input.group(1) r = requests.get(ddg_uri + query, timeout=REQUEST_TIMEOUT).json() topics = r['RelatedTopics'] if len(topics) == 0: return phenny.say('Sorry, no topics found.') topics_list = [] counter = 0 for topic in r['RelatedTopics'][:10]: try: topics_list.append(topic['Text'] + ' - ' + topic['FirstURL']) except KeyError: continue phenny.say(topics_list[0]) phenny.reply('Check PM for more topics.') more.add_messages(phenny, input.nick, topics_list[1:])
def apertium_analyse(phenny, input): '''Analyse text using Apertium APy''' cmd = strict_check(r'(' + langRE + r')\s+(.*)', input.group(1), apertium_analyse) opener = urllib.request.build_opener() opener.addheaders = headers try: response = opener.open('{:s}/analyse?lang={:s}&q={:s}'.format( phenny.config.APy_analyseURL, web.quote(cmd.group(1)), web.quote(cmd.group(2).strip()))).read() except urllib.error.HTTPError as error: handle_error(error) jobj = json.loads(response.decode('utf-8')) messages = [] for analysis, original in jobj: messages.append(original + ' → ' + analysis) more.add_messages(phenny, input.nick, messages)
def check_mail(phenny): found = False mail = login(phenny) if not mail: return mail.select('inbox') rc, data = mail.uid('search', None, 'UNSEEN') unseen_mails = data[0].split() messages = {} for uid in unseen_mails: rc, data = mail.uid('fetch', uid, '(RFC822)') e = email.message_from_string(data[0][1].decode('utf8')) for name, (address, channels) in phenny.config.mailing_lists.items(): if address in recipients(e): found = True message = format_email(e, name) if type(channels) is str: channels = [channels] for channel in channels: messages.setdefault(channel, []).append(message) rc, data = mail.uid('store', uid, '+FLAGS', '(\\Seen)') for channel in messages.keys(): more.add_messages(phenny, channel, messages[channel]) mail.logout() phenny.mailing_list_timer = threading.Timer(60*5, check_mail, (phenny,)) phenny.mailing_list_timer.start() return found
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 q.split(':')[0] == raw.nick and 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 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 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, 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)
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!')
def do_POST(self): '''Handles POST requests for all hooks.''' receive_time = time.time() try: # read and decode data logger.debug('payload received; headers: ' + str(self.headers)) length = int(self.headers['Content-Length']) indata = self.rfile.read(length) post_data = urllib.parse.parse_qs(indata.decode('utf-8')) if len(post_data) == 0: post_data = indata.decode('utf-8') if "payload" in post_data: data = json.loads(post_data['payload'][0]) else: data = json.loads(post_data) except Exception as error: logger.error('Error 400 (no valid payload)') logger.error(str(error)) # 400 Bad Request self.send_response(400) self.end_headers() for channel in self.phenny.config.channels: self.phenny.msg(channel, 'Webhook received malformed payload') return try: result = self.do_POST_unsafe(data) except Exception as error: logger.error(str(error)) result = None if result: status = 200 # OK else: status = 500 # Internal Server Error self.send_response(status) self.end_headers() self.finish() self.connection.close() send_time = time.time() respond_time = send_time - receive_time logger.debug("responded '{:}' in {:.2f}s".format(status, respond_time)) if result: # post all messages to all channels channels, messages = result for channel in channels: more.add_messages(self.phenny, channel, messages) return logger.error(str(data)) try: commits = [commit['url'] for commit in data['commits']] logger.error('Internal Error (commits were ' + ', '.join(commits) + ')') except: logger.error('Internal Error (commits unknown or malformed)') for channel in self.phenny.config.channels: self.phenny.msg(channel, 'Webhook received problematic payload')
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 q.split(':')[0] == raw.nick and 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 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 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, 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)
def do_POST(self): '''Handles POST requests for all hooks.''' receive_time = time.time() try: # read and decode data logger.debug('payload received; headers: '+str(self.headers)) length = int(self.headers['Content-Length']) indata = self.rfile.read(length) post_data = urllib.parse.parse_qs(indata.decode('utf-8')) if len(post_data) == 0: post_data = indata.decode('utf-8') if "payload" in post_data: data = json.loads(post_data['payload'][0]) else: data = json.loads(post_data) except Exception as error: logger.error('Error 400 (no valid payload)') logger.error(str(error)) # 400 Bad Request self.send_response(400) self.end_headers() for channel in self.phenny.config.channels: self.phenny.msg(channel, 'Webhook received malformed payload') return try: result = self.do_POST_unsafe(data) except Exception as error: logger.error(str(error)) result = None if result: status = 200 # OK else: status = 500 # Internal Server Error self.send_response(status) self.end_headers() self.finish() self.connection.close() send_time = time.time() respond_time = send_time - receive_time logger.debug("responded '{:}' in {:.2f}s".format(status, respond_time)) if result: # post all messages to all channels channels, messages = result for channel in channels: more.add_messages(self.phenny, channel, messages) return logger.error(str(data)) try: commits = [commit['url'] for commit in data['commits']] logger.error('Internal Error (commits were ' + ', '.join(commits) + ')') except: logger.error('Internal Error (commits unknown or malformed)') for channel in self.phenny.config.channels: self.phenny.msg(channel, 'Webhook received problematic payload')
def create_messages(self, target, num, tag='test'): more.add_messages(self.phenny, target, self.messages[:num], tag=tag)
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!')