Ejemplo n.º 1
0
async def inrole(text, server, async_send_message):
    """
    [role name] List how many members each role has. Calling it with no role name will list all roles
    """
    role_id = {}
    total_members = 0

    # Map role IDs to usage count
    for user in server.get_users():
        total_members += 1
        for role in user.roles:
            if role.id not in role_id.keys():
                role_id[role.id] = 1
            else:
                role_id[role.id] += 1

    # Map role names to roles for sorting
    alphab_sroles = {}
    for server_role in server.get_roles():
        if server_role.name in ["@everyone", "@here"]:
            continue

        alphab_sroles[server_role.name] = server_role

    # Create string of role names to print
    nice_roles = []

    # If no text was given
    if text == "":
        for srole_name in sorted(alphab_sroles.keys()):
            srole = alphab_sroles[srole_name]

            if srole.id in role_id.keys():
                nice_roles.append("%s: %s" % (srole.name, role_id[srole.id]))
            else:
                nice_roles.append("%s: 0" % (srole.name))
    else:
        for srole_name in sorted(alphab_sroles.keys()):
            if text.lower() not in srole_name.lower():
                continue
            srole = alphab_sroles[srole_name]

            if srole.id in role_id.keys():
                nice_roles.append("%s: %s" % (srole.name, role_id[srole.id]))
            else:
                nice_roles.append("%s: 0" % (srole.name))

    if len(nice_roles) == 0:
        nice_roles = ["Nothing found!"]

    content = paged.element(
        text_list=nice_roles,
        send_func=async_send_message,
        description="Total members: %d" % total_members,
        max_lines=20,
        no_timeout=True,
    )

    await content.get_crt_page()
Ejemplo n.º 2
0
async def urban(text, reply, async_send_message):
    """urban <phrase> [id] -- Looks up <phrase> on urbandictionary.com."""

    headers = {"Referer": "http://m.urbandictionary.com"}

    page = {}
    async with aiohttp.ClientSession(raise_for_status=True) as session:
        if text:
            # clean and split the input
            text = text.lower().strip()
            parts = text.split()

            # fetch the definitions
            try:
                params = {"term": text}
                async with session.get(
                    define_url, params=params, headers=headers
                ) as resp:
                    page = await resp.json()
            except Exception as e:
                reply("Could not get definition: {}".format(e))

        else:
            # get a random definition!
            try:
                async with session.get(random_url, headers=headers) as resp:
                    page = await resp.json()
            except Exception as e:
                reply("Could not get definition: {}".format(e))

    definitions = page["list"]

    defs = []
    for definition in definitions:
        def_text = " ".join(definition["definition"].split())
        def_text = formatting.truncate(def_text, 400)

        name = definition["word"]
        url = definition["permalink"]
        output = "%s: %s - <%s>" % (name, def_text, url)
        defs.append(output)

    if len(defs) == 0:
        reply("No definition found")

    content = paged.element(
        text_list=defs,
        send_func=async_send_message,
        max_lines=1,
        max_line_len=2000,
        no_timeout=True,
        with_quotes=False,
    )

    await content.get_crt_page()
Ejemplo n.º 3
0
    async def get_results(self, async_send_message):
        results = []

        for key, val in self.score.items():
            results.append("%s: %s" % (key, val))

        content = paged.element(
            text_list=results,
            send_func=async_send_message,
            description="Poll results for %s" % self.title,
            max_lines=20,
            no_timeout=True,
        )

        await content.get_crt_page()
Ejemplo n.º 4
0
async def userhistory(text, storage, async_send_message, server):
    """<user> - List confinement reasons for user"""
    def get_reasons(text, storage, user_id):
        if "reasons" not in storage:
            return ["No reasons set"]

        if user_id not in storage["reasons"]:
            return ["No history for given user"]

        rlist = []
        for reason in storage["reasons"][user_id]:
            rtype = "No type given"

            # Skip closed cases
            if "Closed" in reason and reason["Closed"]:
                continue

            # Type may be missing
            if "Type" in reason:
                rtype = reason["Type"]

            rtext = "Case: %s | Type: %s | Date: %s | Author: %s" % (
                reason["Case ID"],
                rtype,
                reason["Date"],
                reason["Author"].split("/")[0],
            )
            rlist.append(rtext)

        return rlist

    try:
        # Get the user
        user_id = dutils.str_to_id(text)

        # Get reasons
        usr_hist = get_reasons(text, storage, user_id)

        # Print as pages
        paged_content = paged.element(usr_hist,
                                      async_send_message,
                                      "User history:",
                                      no_timeout=True)
        await paged_content.get_crt_page()
    except:
        import traceback

        traceback.print_exc()
Ejemplo n.º 5
0
async def grabs(event, storage, async_send_message):
    """
    <expression> - Search for 'expression' in grab texts.
    """
    text = event.msg.clean_content.split(" ", maxsplit=1)[1]
    content = get_data(lambda m: text in m["text"], storage)

    if len(content) == 0:
        content = get_data(lambda m: text == m["id"], storage)

    if len(content) == 0:
        await async_send_message("Nothing found.")
        return
    else:
        paged_content = paged.element(content, async_send_message,
                                      "Grabs containing %s" % text)
        await paged_content.get_crt_page()
Ejemplo n.º 6
0
async def grabl(event, storage, async_send_message, str_to_id, user_id_to_name,
                text):
    """
    <user> - List quotes for user. If no user is specified, it lists everything on the server.
    """
    text = str_to_id(text)
    if text != "":
        content = get_data(lambda m: m["author_id"] == text, storage)
        description = "Grabs for %s:" % user_id_to_name(text)
    else:
        content = get_data(None, storage)
        description = "All server grabs:"

    if len(content) == 0:
        await async_send_message("Nothing found.")
        return
    else:
        paged_content = paged.element(content, async_send_message, description)
        await paged_content.get_crt_page()
Ejemplo n.º 7
0
async def dex(send_message, async_send_message, text):
    """<cuvant> - Cauta definitia pentru un cuvant in DEX"""
    r = requests.get('https://dexonline.ro/definitie/%s/expandat' % text)
    bf = BeautifulSoup(r.content, "html.parser")
    results = bf.find_all('div', {'class': 'defWrapper'})

    if len(results) == 0:
        send_message("n-am gasit boss")
        return

    content = []
    for i in range(len(results)):
        content.append(results[i].find_all('span', {'class': 'def'})[0].text)

    paged_content = paged.element(content,
                                  async_send_message,
                                  "Definitii pentru %s" % text,
                                  max_lines=1,
                                  max_line_len=1800)
    await paged_content.get_crt_page()