Ejemplo n.º 1
0
def _setup_hypernyms():
    """Initialisation of hypernyms that are extracted from Wikipedia categories using Cat2Ax axioms."""
    if utils.load_cache('wikitaxonomy_hypernyms') is not None:
        return  # only compute hypernyms if they are not existing already
    ccg = category.get_conceptual_category_graph()
    # initialise cat2ax axioms
    cat2ax_axioms = cat_axioms.extract_category_axioms(ccg)
    utils.update_cache('cat2ax_axioms', cat2ax_axioms)
    # initialise wikitaxonomy hypernyms
    wikitaxonomy_hypernyms = hypernymy_util.compute_hypernyms(ccg)
    utils.update_cache('wikitaxonomy_hypernyms', wikitaxonomy_hypernyms)
Ejemplo n.º 2
0
 async def get_meow_url(self):
     """ Gets the url of a random image from aws.random.cat and caches the value """
     json = None
     status_code = 0
     counter = 0
     while status_code != 200 and counter < 100:
         [json, status_code
          ] = await utils.get_json_with_get("http://aws.random.cat/meow")
         self.meow_attempts += 1
         counter += 1
     self.next_meow_url = json['file']
     self.meow_successes += 1
     utils.update_cache(self.bot.dbconn, "meowURL", json['file'])
     utils.update_cache(
         self.bot.dbconn, "meowFailRate",
         "{}/{}".format(self.meow_successes, self.meow_attempts))
Ejemplo n.º 3
0
async def scribble(ctx):
    global scribble_bank
    try:
        (arguments, message) = parse.args(ctx.message.content)
        value = message.lower()

        if "ls" in arguments or len(value) == 0:
            await bot.say(", ".join(scribble_bank))
            return
        if "rm" in arguments:
            if value not in scribble_bank:
                await bot.say("I don't have the term `" + value +
                              "` saved to my list")
            else:
                scribble_bank.remove(value)
                await bot.say("Alright, I removed `" + message +
                              "` from my list")
            return

        if "," not in value:
            value_list = [value]
        else:
            value_list = [i.strip() for i in value.split(",")]

        added = list()
        rejected = list()
        for value in value_list:
            if value in scribble_bank:
                rejected.append(value)
            else:
                scribble_bank.append(value)
                added.append(value)
        utils.update_cache(bot.dbconn, "scribble", ",".join(scribble_bank))
        if len(added) > 0:
            await bot.say("Alright, I recorded " + ", ".join([("`" + i + "`")
                                                              for i in added]))
        if len(rejected) == 1:
            await bot.say("`" + rejected[0] + "` was rejected as a duplicate")
        elif len(rejected) > 2:
            await bot.say(", ".join([("`" + i + "`") for i in rejected]) +
                          " were rejected as duplicates")
    except Exception as e:
        await utils.report(bot, str(e), source="scribble")
Ejemplo n.º 4
0
def extract_wiki_corpus_resources():
    """Crawl the Wikipedia corpus for hearst patterns to retrieve hypernyms and type lexicalisations."""
    if utils.load_cache('wikipedia_type_lexicalisations') is not None:
        return  # only compute hypernyms and type lexicalisations if they are not existing already

    utils.get_logger().info(
        'WIKIPEDIA/NIF: Computing wikipedia hypernyms and type lexicalisations..'
    )
    total_hypernyms = defaultdict(lambda: defaultdict(int))
    total_type_lexicalisations = defaultdict(lambda: defaultdict(int))

    # initialize some caches to reduce the setup time of the individual processes
    dbp_store.get_types('')
    dbp_store.get_inverse_lexicalisations('')
    spacy_util.get_hearst_pairs('')

    with mp.Pool(processes=utils.get_config('max_cpus')) as pool:
        for hypernyms, type_lexicalisations in pool.imap_unordered(
                _compute_counts_for_resource,
                tqdm(_retrieve_plaintexts()),
                chunksize=1000):
            for (sub, obj), count in hypernyms.items():
                total_hypernyms[sub][obj] += count
            for (sub, obj), count in type_lexicalisations.items():
                total_type_lexicalisations[sub][obj] += count

    wikipedia_hypernyms = {
        word: dict(hypernym_counts)
        for word, hypernym_counts in total_hypernyms.items()
    }
    utils.update_cache('wikipedia_hypernyms', wikipedia_hypernyms)

    type_lexicalisations = {
        word: dict(type_counts)
        for word, type_counts in total_type_lexicalisations.items()
        if word not in STOP_WORDS
    }
    utils.update_cache('wikipedia_type_lexicalisations', type_lexicalisations)
Ejemplo n.º 5
0
async def claire():
    global last_colton, daily_colton, total_colton
    try:
        total_colton += 1
        now = datetime.now()
        if last_colton.day != now.day:
            daily_colton = 1
            timestoday = ", which makes this his first time today"
        else:
            daily_colton += 1
            timestoday = ", which makes this " + str(
                daily_colton) + " times today alone!"
        await bot.say(
            "Wow! Claire has now mentioned being forever alone {} times!\n"
            "The last time he mentioned being forever alone was **{}**".format(
                total_colton, last_colton.strftime("%c")) + timestoday)
        last_colton = now
        utils.update_cache(bot.dbconn, "lastColton",
                           last_colton.strftime("%s"))
        utils.update_cache(bot.dbconn, "dailyColton", str(daily_colton))
        utils.update_cache(bot.dbconn, "totalColton", str(total_colton))
    except Exception as e:
        await utils.report(bot, str(e), source="!claire command")
Ejemplo n.º 6
0
async def dev(ctx):
    global currently_playing
    try:
        if ctx.message.author.id not in AUTHORIZED_IDS:
            await bot.say("You are not authorized to use these commands")
            return

        [func, parameter] = parse.func_param(ctx.message.content)

        if func in ["help", ""]:
            title = "`!dev` User Guide"
            description = "A list of features useful for "
            helpdict = {
                "channelid":
                "Posts the ID of the current channel",
                "colton":
                "Check the `!colton` data",
                "dump":
                "A debug command for the bot to dump a variable into chat",
                "flag":
                "Tests the `flag` function",
                "load":
                "Loads an extension",
                "playing":
                "Sets the presence of the bot (what the bot says it's currently playing)",
                "reload":
                "Reloads an extension",
                "report":
                "Tests the `report` function",
                "serverid":
                "Posts the ID of the current channel",
                "swears":
                "Find out who swears the most",
                "test":
                "A catch-all command for inserting code into the bot to test",
            }
            await bot.say("`!dev` User Guide",
                          embed=embedfromdict(helpdict,
                                              title=title,
                                              description=description))

        elif func == "channelid":
            await bot.say("Channel ID: " + ctx.message.channel.id)

        elif func == "colton":
            await bot.say(
                "Colton has mentioned being forever alone {} times.\n"
                "The last time he mentioned being forever alone was **{}**".
                format(total_colton, last_colton.strftime("%c")))

        elif func == "dump":
            await bot.say("AT THE DUMP")

        elif func == "flag":
            await bot.say("Triggering flag...")
            await utils.flag(bot,
                             "Test",
                             description="This is a test of the flag ability",
                             ctx=ctx)

        elif func == "load":
            """Loads an extension."""
            try:
                bot.load_extension("cogs." + parameter)
            except (AttributeError, ImportError) as e:
                await utils.report(bot,
                                   "```py\n{}: {}\n```".format(
                                       type(e).__name__, str(e)),
                                   source="Loading extension (!dev)",
                                   ctx=ctx)
                return
            await bot.say("`` {} `` loaded.".format(parameter))

        elif func == "nick":
            try:
                if ctx.message.server is None:
                    await bot.say("I can't do that here")
                    return
                newnick = parameter
                if newnick == "":
                    newnick = None
                botmember = ctx.message.server.get_member(
                    "340287898433748993")  # Gets the bot's own member object
                await bot.change_nickname(botmember, newnick)
            except Exception as e:
                await utils.report(bot, str(e), source="!dev nick", ctx=ctx)

        elif func == "playing":
            try:
                currently_playing = parameter
                await bot.change_presence(game=discord.Game(
                    name=currently_playing))
                utils.update_cache(bot.dbconn, "currPlaying",
                                   currently_playing)
                await bot.say("I'm now playing `" + parameter + "`")
            except discord.InvalidArgument as e:
                await utils.report(bot,
                                   "Failed to change presence to `" +
                                   parameter + "`\n" + str(e),
                                   source="dev playing",
                                   ctx=ctx)

        elif func == "serverid":
            await bot.say("Server ID: " + ctx.message.server.id)

        elif func == "swears":
            sortedlist = sorted(list(swear_tally.items()),
                                key=lambda user_tally: user_tally[1][2],
                                reverse=True)
            message = ""
            for i, user in enumerate(sortedlist):
                message += ("**" + str(i + 1) + ".** " + bot.users[user[0]] +
                            " - " + str(round(user[1][2] * 100, 2)) + "%\n")
            if len(message) > 0:
                await bot.say(utils.trimtolength(message, 2000))

        elif func == "reload":
            bot.unload_extension(parameter)
            await bot.say("`` {} `` unloaded.".format(parameter))
            try:
                bot.load_extension("cogs." + parameter)
            except (AttributeError, ImportError) as e:
                await utils.report(bot,
                                   "```py\n{}: {}\n```".format(
                                       type(e).__name__, str(e)),
                                   source="Loading extension (!dev)",
                                   ctx=ctx)
                return
            await bot.say("`` {} `` loaded.".format(parameter))

        elif func == "report":
            await bot.say("Triggering report...")
            await utils.report(bot,
                               "This is a test of the report system",
                               source="dev report command",
                               ctx=ctx)

        elif func == "test":
            try:
                await bot.say("hello")
            except Exception as e:
                await utils.report(bot, str(e), source="dev test", ctx=ctx)

        elif func == "unload":
            """ Unoads an extension """
            bot.unload_extension(parameter)
            await bot.say("`` {} `` unloaded.".format(parameter))

        else:
            await bot.say("I don't recognize the command `" + func +
                          "`. You can type `!dev` for a list of " +
                          "available functions")
    except Exception as e:
        await utils.report(bot, str(e), source="dev command", ctx=ctx)
Ejemplo n.º 7
0
async def dev(ctx):
    global currently_playing
    try:
        if ctx.message.author.id not in AUTHORIZED_IDS:
            await bot.say("You are not authorized to use these commands")
            return

        [func, parameter] = parse.func_param(ctx.message.content)

        if func in ["help", ""]:
            title = "`!dev` User Guide"
            description = "A list of features useful for "
            helpdict = {
                "channelid":
                "Posts the ID of the current channel",
                "dump":
                "A debug command for the bot to dump a variable into chat",
                "flag":
                "Tests the `flag` function",
                "load":
                "Loads an extension",
                "playing":
                "Sets the presence of the bot (what the bot says it's currently playing)",
                "reload":
                "Reloads an extension",
                "report":
                "Tests the `report` function",
                "serverid":
                "Posts the ID of the current channel",
                "test":
                "A catch-all command for inserting code into the bot to test",
            }
            await bot.say("`!dev` User Guide",
                          embed=embedfromdict(helpdict,
                                              title=title,
                                              description=description))

        elif func == "channelid":
            await bot.say("Channel ID: " + ctx.message.channel.id)

        elif func == "dump":
            await bot.say("hello")

        elif func == "flag":
            await bot.say("Triggering flag...")
            await utils.flag(bot,
                             "Test",
                             description="This is a test of the flag ability",
                             ctx=ctx)

        elif func == "load":
            """Loads an extension."""
            try:
                bot.load_extension("cogs." + parameter)
            except (AttributeError, ImportError) as e:
                await utils.report(bot,
                                   "```py\n{}: {}\n```".format(
                                       type(e).__name__, str(e)),
                                   source="Loading extension (!dev)",
                                   ctx=ctx)
                return
            await bot.say("`` {} `` loaded.".format(parameter))

        elif func == "nick":
            try:
                if ctx.message.server is None:
                    await bot.say("I can't do that here")
                    return
                new_nick = parameter
                if new_nick == "":
                    new_nick = None
                bot_member = ctx.message.server.get_member(tokens["CLIENT_ID"])
                await bot.change_nickname(bot_member, new_nick)
            except Exception as e:
                await utils.report(bot, str(e), source="!dev nick", ctx=ctx)

        elif func == "playing":
            try:
                currently_playing = parameter
                await bot.change_presence(game=discord.Game(
                    name=currently_playing))
                utils.update_cache(bot.dbconn, "currPlaying",
                                   currently_playing)
                await bot.say("I'm now playing `" + parameter + "`")
            except discord.InvalidArgument as e:
                await utils.report(bot,
                                   "Failed to change presence to `" +
                                   parameter + "`\n" + str(e),
                                   source="dev playing",
                                   ctx=ctx)

        elif func == "serverid":
            await bot.say("Server ID: " + ctx.message.server.id)

        elif func == "reload":
            bot.unload_extension(parameter)
            await bot.say("`` {} `` unloaded.".format(parameter))
            try:
                bot.load_extension("cogs." + parameter)
            except (AttributeError, ImportError) as e:
                await utils.report(bot,
                                   "```py\n{}: {}\n```".format(
                                       type(e).__name__, str(e)),
                                   source="Loading extension (!dev)",
                                   ctx=ctx)
                return
            await bot.say("`` {} `` loaded.".format(parameter))

        elif func == "report":
            await bot.say("Triggering report...")
            await utils.report(bot,
                               "This is a test of the report system",
                               source="dev report command",
                               ctx=ctx)

        elif func == "test":
            try:
                await bot.say("hello")
            except Exception as e:
                await utils.report(bot, str(e), source="dev test", ctx=ctx)

        elif func == "unload":
            """ Unoads an extension """
            bot.unload_extension(parameter)
            await bot.say("`` {} `` unloaded.".format(parameter))

        else:
            await bot.say("I don't recognize the command `" + func +
                          "`. You can type `!dev` for a list of " +
                          "available functions")
    except Exception as e:
        await utils.report(bot, str(e), source="dev command", ctx=ctx)