def events(irc_protocol, plugin, config): try: data = yield from github_action('issues/events', plugin, config) except POSSIBLE_EXCEPTIONS: return issue = data['issue'] state = data['event'] state_color = state_colors.get(state, color.black) assignee = issue['assignee'] assignee_login = assignee['login'] if assignee is not None else None msg = ("‼ {issue} {labels} '{title}' by {user} " "{assignee} {state} {url}").format( issue=bold('ISSUE'), labels=' '.join('[%s]' % label['name'] for label in issue['labels']), title=strip(issue['title']), state=bold(color(' %s ' % state, color.white, state_color)), user=issue['user']['login'], assignee="assigned to %s" % assignee_login if assignee_login else '', url=issue['html_url'], ) for chan in config['channels'].split(','): irc_protocol.say(chan.strip(), msg)
def where_i_am(bot): level = bot.plugin.temp['world'].actual_level bot.say('{name}{type} dirs: {dirs}'.format( name=format.bold(level.name), type=format.bold( format.color( ' (%s)' % level.type.name if level.name else level.type.name, format.color.white)), dirs=' '.join( format.color(direction.value, format.color.light_green) for direction in level.directions), ))
def where_i_am(bot): level = bot.plugin.temp['world'].actual_level bot.say('{name}{type} dirs: {dirs}'.format( name=format.bold(level.name), type=format.bold(format.color( ' (%s)' % level.type.name if level.name else level.type.name, format.color.white )), dirs=' '.join( format.color(direction.value, format.color.light_green) for direction in level.directions ), ))
def google(bot, query): """get first result of google query""" params = dict( key=bot.config['key'], cx=bot.config['cx'], prettyPrint=False, q=query, ) response = yield from request('GET', GOOGLE_URL, params=params) json_data = yield from response.json() error = json_data.get('error') if error: bot.say('err: %s' % error['message']) items = json_data.get('items', []) try: result = items[0] except IndexError: bot.reply('not found') return title = result['title'] url = result['link'] bot.say('{}: {}'.format(format.bold(title[:50]), url))
def weather(bot, city, day=None): dt = check_and_return_datetime(day) timestamp = dt.replace(tzinfo=timezone.utc).timestamp() delta_days = (dt - datetime.now()).days is_long_forecast = (delta_days > 5) if not is_long_forecast: response = yield from request('GET', URL_API, params={ 'q': city, 'units': 'metric', 'lang': 'pl', 'APPID': bot.config.get('app_id'), }) else: response = yield from request('GET', URL_API_LONG, params={ 'q': city, 'units': 'metric', 'lang': 'pl', 'cnt': min(delta_days, 16), 'APPID': bot.config.get('app_id'), }) try: json_data = yield from response.json() finally: response.close() if json_data.get('cod') == 401: return data_list = json_data.get("list") if data_list is None: bot.reply('404 lol') return data = sorted(data_list, key=lambda x: abs(x['dt'] - timestamp))[0] try: weather = data['weather'][0] except IndexError: weather = {'description': '', 'icon': ''} if not is_long_forecast: temperature = data['main']['temp'] else: if dt.hour < 6: period = 'night' elif dt.hour < 10: period = 'morn' elif dt.hour < 18: period = 'day' elif dt.hour < 22: period = 'eve' else: period = 'night' temperature = data['temp'][period] bot.reply('{city}: {temp} °C {icon} {desc}'.format( city=format.bold(city), temp=temperature, desc=weather['description'], icon=ICON_TO_UTF.get(weather['icon'], '')))
def show_command_help(bot, importer, name): plugin, func = importer.find_command(name) if func is None: return bot.reply('cmd not found') cmd = func.cmd.format(**importer.get_plugin_cfg(plugin.name)) doc = re.sub('\s+', ' ', func.__doc__) if func.__doc__ else 'help not found' bot.say('{}: {}'.format(format.bold(cmd), doc))
def weather(bot, city, day=None): dt = check_and_return_datetime(day) timestamp = dt.replace(tzinfo=timezone.utc).timestamp() delta_days = (dt - datetime.now()).days is_long_forecast = (delta_days > 5) if not is_long_forecast: response = yield from request('GET', URL_API, params={ 'q': city, 'units': 'metric', 'lang': 'pl', 'APPID': bot.config.get('app_id'), }) else: response = yield from request('GET', URL_API_LONG, params={ 'q': city, 'units': 'metric', 'lang': 'pl', 'cnt': min(delta_days, 16), 'APPID': bot.config.get('app_id'), }) try: json_data = yield from response.json() finally: response.close() if json_data.get('cod') == 401: return data_list = json_data.get("list") if data_list is None: bot.reply('404 lol') return data = sorted(data_list, key=lambda x: abs(x['dt'] - timestamp))[0] try: weather = data['weather'][0] except IndexError: weather = {'description': '', 'icon': ''} if not is_long_forecast: temperature = data['main']['temp'] else: if dt.hour < 6: period = 'night' elif dt.hour < 10: period = 'morn' elif dt.hour < 18: period = 'day' elif dt.hour < 22: period = 'eve' else: period = 'night' temperature = data['temp'][period] bot.reply('{city}: {temp} °C {icon} {desc}'.format( city=format.bold(city), temp=temperature, desc=weather['description'], icon=ICON_TO_UTF.get(weather['icon'], '') ))
def _execute_func(self, func, bot, args, user, channel): try: yield from func(bot, **args) except Exception: traceback.print_exc(file=sys.stdout) tb = traceback.format_exc().split('\n')[-4:-1] self.protocol.reply( user.nick, '{} {} {}'.format( format.bold('ERR:'), tb[2], format.color(tb[0], format.color.red), ), channel)
def commits(irc_protocol, plugin, config): try: data = yield from github_action('commits', plugin, config) except POSSIBLE_EXCEPTIONS: return msg = "‼ {commit} '{msg}' by {committer} {url}".format( commit=bold('COMMIT'), msg=strip(data['commit']['message']), committer=data['commit']['author']['name'], url=data['html_url']) for chan in config['channels'].split(','): irc_protocol.say(chan.strip(), msg)
def commits(irc_protocol, plugin, config): try: data = yield from github_action('commits', plugin, config) except POSSIBLE_EXCEPTIONS: return msg = "‼ {commit} '{msg}' by {committer} {url}".format( commit=bold('COMMIT'), msg=strip(data['commit']['message']), committer=data['commit']['author']['name'], url=data['html_url'] ) for chan in config['channels'].split(','): irc_protocol.say(chan.strip(), msg)
def comments(irc_protocol, plugin, config): try: data = yield from github_action('issues/comments', plugin, config) except POSSIBLE_EXCEPTIONS: return msg = "‼ {issue} by {nick} '{msg}' {url}".format( issue=bold('COMMENT'), msg=strip(data['body']), nick=data['user']['login'], url=data['html_url'], ) for chan in config['channels'].split(','): irc_protocol.say(chan.strip(), msg)
def _execute_func(self, func, bot, args, user, channel): try: yield from func(bot, **args) except Exception: traceback.print_exc(file=sys.stdout) tb = traceback.format_exc().split('\n')[-4:-1] self.protocol.reply( user.nick, '{} {} {}'.format( format.bold('ERR:'), tb[2], format.color(tb[0], format.color.red), ), channel )
def cmd_args(bot, name): """show args""" importer = bot.protocol.importer plugin, func = importer.find_command(name) if func is None: return bot.reply('cmd not found') cmd = func.cmd.format(**importer.get_plugin_cfg(plugin.name)) argspec = getfullargspec(func) args = argspec.args[1:] defaults = argspec.defaults kwonlyargs = argspec.kwonlyargs bot.say( '{cmd}: {args} {optional} {very_optional}'.format( cmd=format.bold(cmd), args=' '.join(args[:-len(defaults)]), optional=' '.join('[%s]' % a for a in args[-len(defaults):]), very_optional=' '.join('[%s]' % a for a in kwonlyargs), ) )
def execute(op, buffer): try: len_args, func = operator_funcs[op] except KeyError: return 'WTF - %s is not a good operator' % op if len_args > 0: args = buffer[-len_args:] if len(args) != len_args: return "WTF" del buffer[-len_args:] else: args = [] try: value = func(*args) except OverflowError: return format.bold("Over 9000!!") else: buffer.append(value)
def google(bot, query): """get first result of google query""" response = yield from request('GET', GOOGLE_URL, params={ 'q': query, 'v': '1.0' }) json_data = yield from response.json() data = json_data['responseData'] if data is None: bot.reply(response['responseDetails']) return try: result = data['results'][0] except IndexError: bot.reply('not found') return title = result['titleNoFormatting'] url = result['url'] bot.say('{}: {}'.format(format.bold(title), url))
def google(bot, query): """get first result of google query""" response = yield from request('GET', GOOGLE_URL, params={ 'q': query, 'v': '1.0' }) json_data = yield from response.json() data = json_data['responseData'] if data is None: bot.reply(json_data['responseDetails']) return try: result = data['results'][0] except IndexError: bot.reply('not found') return title = result['titleNoFormatting'] url = result['url'] bot.say('{}: {}'.format(format.bold(title), url))
def execute(op, buffer): try: len_args, func = operator_funcs[op] except KeyError: return 'WTF - %s is not a good operator' % op if len_args > 0: args = buffer[-len_args:] if len(args) != len_args: return "WTF" del buffer[-len_args:] else: args = [] try: value = func(*args) except ZeroDivisionError: return float('nan') except OverflowError: return format.bold("Over 9000!!") else: buffer.append(value)
def test__bold(): assert format.bold('socek') == '\x02socek\x02'
def test_overflow(): assert str_calc('1024 1024 **') == format.bold('Over 9000!!')