def bancount(text, bot): """<user> - gets a count of <user>'s minecraft bans from fishbans""" user = text.strip() headers = {"User-Agent": bot.user_agent} try: request = requests.get(api_url.format(quote_plus(user)), headers=headers) request.raise_for_status() except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError) as e: return "Could not fetch ban data from the Fishbans API: {}".format(e) try: json = request.json() except ValueError: return "Could not fetch ban data from the Fishbans API: Invalid Response" if not json["success"]: return "Could not fetch ban data for {}.".format(user) user_url = "http://fishbans.com/u/{}/".format(user) services = json["stats"]["service"] out = [] for service, ban_count in list(services.items()): if ban_count != 0: out.append("{}: \x02{}\x02".format(service, ban_count)) else: pass if not out: return "The user \x02{}\x02 has no bans - {}".format(user, user_url) else: return "Bans for \x02{}\x02: {} - {}".format(user, formatting.get_text_list(out, "and"), user_url)
def namegen(text, bot, notice): """[generator|list] - generates some names using the chosen generator, or lists all generators if 'list' is specified :type bot: ralybot.bot.Ralybot """ # clean up the input inp = text.strip().lower() # get a list of available name generators files = os.listdir(os.path.join(bot.data_dir, "name_files")) all_modules = [os.path.splitext(i)[0] for i in files if os.path.splitext(i)[1] == ".json"] all_modules.sort() # command to return a list of all available generators if inp == "list": message = "Available generators: " message += formatting.get_text_list(all_modules, 'and') notice(message) return if inp: selected_module = inp.split()[0] else: # make some generic fantasy names selected_module = "fantasy" # check if the selected module is valid if selected_module not in all_modules: return "{} is not a valid name generator.".format(inp) # load the name generator path = os.path.join(bot.data_dir, "name_files", "{}.json".format(selected_module)) with codecs.open(path, encoding="utf-8") as f: try: generator = get_generator(f.read()) except ValueError as error: return "Unable to read name file: {}".format(error) # time to generate some names name_list = generator.generate_strings(10) # and finally return the final message :D return "Some names to ponder: {}.".format(formatting.get_text_list(name_list, 'and'))
def poll(text, conn, nick, chan, message, reply): """<title> <items> -- Creates a poll with the specified <title> and <items>. <items> are split via a comma.""" global polls # get poll ID uid = ":".join([conn.name, chan, nick]).lower() if text.lower() == "close": if uid not in polls.keys(): return "You have no active poll to close." p = polls.get(uid) reply("Your poll has been closed. Final results for \x02\"{}\"\x02:".format(p.question, p.creator)) message(p.format_results()) del polls[uid] return if uid in polls.keys(): return "You already have an active poll in this channel, you must close it before you can create a new one." if ':' in text: question, options = text.strip().split(':') c = findall(r'([^,]+)', options) if len(c) == 1: c = findall(r'(\S+)', options) options = list(set(x.strip() for x in c)) _poll = Poll(question, nick, options) else: question = text.strip() _poll = Poll(question, nick) # store poll in list polls[uid] = _poll option_str = get_text_list([option.title for option in _poll.options.values()], "and") message('Created poll \x02\"{}\"\x02 with the following options: {}'.format(_poll.question, option_str)) message("Use {}vote {} <option> to vote on this poll!".format(conn.config["command_prefix"], nick.lower()))
def test_get_text_list(): assert get_text_list(['a', 'b', 'c', 'd']) == 'a, b, c or d' assert get_text_list(['a', 'b', 'c'], 'and') == 'a, b and c' assert get_text_list(['a', 'b'], 'and') == 'a and b' assert get_text_list(['a']) == 'a' assert get_text_list([]) == ''
def networks(text, bot): """Displays the list of networks that the bot is currently connected to.""" networks = list(bot.connections.keys()) return "Networks: " + formatting.get_text_list(networks, last_word="and")
def format_time(seconds, count=3, accuracy=6, simple=False): """ Takes a length of time in seconds and returns a string describing that length of time. This function has a number of optional arguments that can be combined: SIMPLE: displays the time in a simple format >> format_time(SECONDS) 1 hour, 2 minutes and 34 seconds >> format_time(SECONDS, simple=True) 1h 2m 34s COUNT: how many periods should be shown (default 3) >> format_time(SECONDS) 147 years, 9 months and 8 weeks >> format_time(SECONDS, count=6) 147 years, 9 months, 7 weeks, 18 hours, 12 minutes and 34 seconds """ if simple: periods = [ ('c', 60 * 60 * 24 * 365 * 100), ('de', 60 * 60 * 24 * 365 * 10), ('y', 60 * 60 * 24 * 365), ('m', 60 * 60 * 24 * 30), ('d', 60 * 60 * 24), ('h', 60 * 60), ('m', 60), ('s', 1) ] else: periods = [ (('century', 'centuries'), 60 * 60 * 24 * 365 * 100), (('decade', 'decades'), 60 * 60 * 24 * 365 * 10), (('year', 'years'), 60 * 60 * 24 * 365), (('month', 'months'), 60 * 60 * 24 * 30), (('day', 'days'), 60 * 60 * 24), (('hour', 'hours'), 60 * 60), (('minute', 'minutes'), 60), (('second', 'seconds'), 1) ] periods = periods[-accuracy:] strings = [] i = 0 for period_name, period_seconds in periods: if i < count: if seconds > period_seconds: period_value, seconds = divmod(seconds, period_seconds) i += 1 if simple: strings.append("{}{}".format(period_value, period_name)) else: if period_value == 1: strings.append("{} {}".format(period_value, period_name[0])) else: strings.append("{} {}".format(period_value, period_name[1])) else: break if simple: return " ".join(strings) else: return formatting.get_text_list(strings, "and")
def process(self, event): """ :type event: Event """ run_before_tasks = [] tasks = [] command_prefix = event.conn.config.get('command_prefix', '.') # Raw IRC hook for raw_hook in self.plugin_manager.catch_all_triggers: # run catch-all coroutine hooks before all others - TODO: Make this a plugin argument if not raw_hook.threaded: run_before_tasks.append( self.plugin_manager.launch(raw_hook, Event(hook=raw_hook, base_event=event))) else: tasks.append(self.plugin_manager.launch(raw_hook, Event(hook=raw_hook, base_event=event))) if event.irc_command in self.plugin_manager.raw_triggers: for raw_hook in self.plugin_manager.raw_triggers[event.irc_command]: tasks.append(self.plugin_manager.launch(raw_hook, Event(hook=raw_hook, base_event=event))) # Event hooks if event.type in self.plugin_manager.event_type_hooks: for event_hook in self.plugin_manager.event_type_hooks[event.type]: tasks.append(self.plugin_manager.launch(event_hook, Event(hook=event_hook, base_event=event))) if event.type is EventType.message: # Commands if event.chan.lower() == event.nick.lower(): # private message, no command prefix command_re = r'(?i)^(?:[{}]?|{}[,;:]+\s+)(\w+)(?:$|\s+)(.*)'.format(command_prefix, event.conn.nick) else: command_re = r'(?i)^(?:[{}]|{}[,;:]+\s+)(\w+)(?:$|\s+)(.*)'.format(command_prefix, event.conn.nick) cmd_match = re.match(command_re, event.content) if cmd_match: command = cmd_match.group(1).lower() if command in self.plugin_manager.commands: command_hook = self.plugin_manager.commands[command] command_event = CommandEvent(hook=command_hook, text=cmd_match.group(2).strip(), triggered_command=command, base_event=event) tasks.append(self.plugin_manager.launch(command_hook, command_event)) else: potential_matches = [] for potential_match, plugin in self.plugin_manager.commands.items(): if potential_match.startswith(command): potential_matches.append((potential_match, plugin)) if potential_matches: if len(potential_matches) == 1: command_hook = potential_matches[0][1] command_event = CommandEvent(hook=command_hook, text=cmd_match.group(2).strip(), triggered_command=command, base_event=event) tasks.append(self.plugin_manager.launch(command_hook, command_event)) else: event.notice("Possible matches: {}".format( formatting.get_text_list([command for command, plugin in potential_matches]))) # Regex hooks for regex, regex_hook in self.plugin_manager.regex_hooks: if not regex_hook.run_on_cmd and cmd_match: pass else: regex_match = regex.search(event.content) if regex_match: regex_event = RegexEvent(hook=regex_hook, match=regex_match, base_event=event) tasks.append(self.plugin_manager.launch(regex_hook, regex_event)) # Run the tasks yield from asyncio.gather(*run_before_tasks, loop=self.loop) yield from asyncio.gather(*tasks, loop=self.loop)