示例#1
0
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)
示例#2
0
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),
    ))
示例#3
0
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
        ),
    ))
示例#4
0
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))
示例#5
0
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'], '')))
示例#6
0
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))
示例#7
0
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'], '')
    ))
示例#8
0
 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)
示例#9
0
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)
示例#10
0
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)
示例#11
0
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)
示例#12
0
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)
示例#13
0
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)
示例#14
0
 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
         )
示例#15
0
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),
        )
    )
示例#16
0
文件: onp.py 项目: swoldanski/grazyna
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)
示例#17
0
文件: google.py 项目: nhlfr/grazyna
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))
示例#18
0
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))
示例#19
0
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)
示例#20
0
def test__bold():
    assert format.bold('socek') == '\x02socek\x02'
示例#21
0
def test_overflow():
    assert str_calc('1024 1024 **') == format.bold('Over 9000!!')
示例#22
0
def test_overflow():
    assert str_calc('1024 1024 **') == format.bold('Over 9000!!')