Ejemplo n.º 1
0
async def call(message):
    """Queries the UrbanDictionary API and relays the response."""
    entry, search = _parse_args(message.args)
    response = await _make_request(search)
    if response["list"]:
        return trim_message(_get_definition(response, entry), length=400)
    raise BotError(f'Could not find a definition for {search.rstrip(".")}.')
Ejemplo n.º 2
0
async def _substitute(match, message_log):
    flags = _parse_flags(match[2])
    regex = _compile_regex(match[0], flags)

    count = 0 if flags["global"] else 1

    response = await _find_and_replace(message_log, regex, match[1], count)
    return trim_message(response, length=400)
Ejemplo n.º 3
0
async def _relay_push_discord(listener, channel, payload, branch):
    embed = Embed(title=_construct_push_message(payload, branch))
    embed.add_field(name='Compare', value=payload['compare'], inline=False)
    for commit in payload['commits']:
        embed.add_field(
            name=(f'{commit["author"]["username"]} - ' +
                  trim_message(commit["message"])),
            value=commit["url"].replace(commit["id"], commit["id"][:8]),
            inline=False,
        )
    await listener.message(target=channel, message=embed, embed=True)
Ejemplo n.º 4
0
async def _handle_push(listener, payload, cfg):
    branch = payload['ref'].split('/')[2]

    if payload['ref'].split('/')[1] == 'tags':
        logger.info(f'Received tag push event.')
        return await listener.message(
            target=cfg['channel'],
            message=(
                f'New tag {branch} tracking {payload["before"][:8]} pushed '
                f'to {payload["repository"]["name"]}'),
        )

    if cfg['branches'] and branch not in cfg['branches']:
        logger.info(f'Received push event for untracked branch {branch}.')
        return

    def construct_message(payload, branch):
        return (f'{_get_num_commits(payload["commits"])} commit(s) pushed to '
                f'{payload["repository"]["name"]}/{branch} by '
                f'{payload["pusher"]["name"]}')

    def construct_commit_message(commit):
        chash = commit['id'][:8]
        url = commit['url'].replace(commit['id'], chash)
        return (f'{chash} - {commit["author"]["username"]} - '
                f'{trim_message(commit["message"])} - {url}')

    logger.info(f'Received push to branch event.')

    if isinstance(listener, DiscordListener):
        embed = Embed(title=construct_message(payload, branch))
        embed.add_field(name='Compare', value=payload['compare'], inline=False)
        for commit in payload['commits']:
            embed.add_field(
                name=(f'{commit["author"]["username"]} - ' +
                      trim_message(commit["message"])),
                value=commit["url"].replace(commit["id"], commit["id"][:8]),
                inline=False,
            )
        await listener.message(target=cfg['channel'],
                               message=embed,
                               embed=True)
    else:
        await listener.message(target=cfg['channel'],
                               message=construct_message(payload, branch))
        await listener.message(target=cfg['channel'],
                               message=f'Compare - {payload["compare"]}')
        for commit in payload['commits']:
            await listener.message(target=cfg['channel'],
                                   message=construct_commit_message(commit))
Ejemplo n.º 5
0
async def call(message):
    """Queries the Wolfram|Alpha API and relays the response."""
    future = asyncio.get_event_loop().run_in_executor(
        None,
        lambda: requests.get(
            "https://api.wolframalpha.com/v1/result",
            headers={"User-Agent": config["user_agent"]},
            params={
                "appid": config["wolframalpha"]["appid"],
                "i": message.args[0],
            },
            timeout=15,
        ),
    )

    try:
        response = (await future).text
    except requests.RequestException as e:
        logger.error(f"Failed to query Wolfram|Alpha: {e}")
        raise BotError("Failed to query Wolfram|Alpha.")

    return trim_message(response, length=400)
Ejemplo n.º 6
0
async def call(message):
    """Queries the Wolfram|Alpha API and relays the response."""
    future = asyncio.get_event_loop().run_in_executor(
        None,
        lambda: requests.get(
            'https://api.wolframalpha.com/v1/result',
            headers={'User-Agent': config['user_agent']},
            params={
                'appid': config['wolframalpha']['appid'],
                'i': message.args[0],
            },
            timeout=15,
        ),
    )

    try:
        response = (await future).text
    except requests.RequestException as e:
        logger.error(f'Failed to query Wolfram|Alpha: {e}')
        raise BotError('Failed to query Wolfram|Alpha.')

    return trim_message(response, length=400)
Ejemplo n.º 7
0
def test_trim_message(input_, output):
    assert output == trim_message(input_, length=9)