Ejemplo n.º 1
0
 async def del_todo(self, ctx, todo_id):
     try:
         todos_collection = get_collection("todos")
         delete_todo(todos_collection, todo_id)
         await ctx.send("The TODO has been deleted.")
     except InvalidId:
         await ctx.send("TODO with such ID simply doesn't exist.")
Ejemplo n.º 2
0
 async def meme_data(self, ctx, *, meme_name):
     memes_collection = get_collection("memes")
     meme = get_meme(memes_collection, meme_name)
     if meme is not None:
         await ctx.send(meme)
     else:
         await ctx.send("No such meme exists. You messed up!")
Ejemplo n.º 3
0
    async def plot_memes(self, ctx, times_used_limit=0):

        memes_collection = get_collection("memes")
        memes_list = get_all_memes(memes_collection)
        memes_to_plot = []
        for meme_document in memes_list:
            times_used = meme_document["times_used"]
            if times_used > times_used_limit:
                name = meme_document["name"]
                memes_to_plot.append((name, times_used))

        # Sort the memes by frequency and capture their names and values into lists
        memes_to_plot = sorted(memes_to_plot, key=lambda meme: meme[1], reverse=True)
        meme_names = [meme[0] for meme in memes_to_plot]
        meme_frequencies = [meme[1] for meme in memes_to_plot]

        # Plot the memes on the graph.
        plt.bar(meme_names, meme_frequencies)
        plt.title("Usage of memes")
        plt.xticks(rotation=90)
        plt.xlabel("Meme names")
        plt.ylabel("Times used")
        plt.savefig("data/memes_chart.png", bbox_inches="tight")
        plt.close()
        await ctx.send(
            "Here's your graph. Enjoy!", file=discord.File("data/memes_chart.png")
        )
Ejemplo n.º 4
0
 async def delete_meme(self, ctx, *, meme_name):
     meme_name = meme_name.lower()
     memes_collection = get_collection("memes")
     meme = get_meme(memes_collection, meme_name)
     if meme is not None:
         delete_meme(memes_collection, meme["_id"])
         await ctx.send("The meme has been removed.")
     else:
         await ctx.send("No such meme exists. You messed up!")
Ejemplo n.º 5
0
 async def reset_api(self, ctx, api_provider):
     try:
         apis_collection = get_collection("apis")
         reset_api(apis_collection, api_provider)
         await ctx.send(
             f"Number of {api_provider} API requests successfully reset to 0."
         )
     except TypeError:
         await ctx.send(
             f"Such API provider isn't registered in the database.")
Ejemplo n.º 6
0
 async def print_api(self, ctx, api_provider):
     try:
         apis_collection = get_collection("apis")
         api = get_api(apis_collection, api_provider)
         requests_count = api["number_of_calls"]
         await ctx.send(
             f"Current number of {api_provider} API requests executed: **{requests_count}**"
         )
     except TypeError:
         await ctx.send(
             f"Such API provider isn't registered in the database.")
Ejemplo n.º 7
0
 async def add_meme(self, ctx, link_to_meme, *, meme_name):
     meme_name = meme_name.lower()
     # If the user tries to overwrite the list of memes, they are prevented..
     if meme_name == "help":
         await ctx.send(
             "You cannot override the list of all the memes, you storming fool!"
         )
         return
     # Add meme to database.
     memes_collection = get_collection("memes")
     insert_meme(memes_collection, meme_name, link_to_meme)
     await ctx.send("The meme has been added.")
Ejemplo n.º 8
0
    async def set_meme_description(self, ctx, meme_name, *, description):
        meme_name = meme_name.lower()
        meme_name = meme_name.replace("-", " ")
        meme_name = meme_name.replace("_", " ")

        memes_collection = get_collection("memes")
        meme = get_meme(memes_collection, meme_name)
        if meme is not None:
            update_meme(memes_collection, meme["_id"], "description",
                        description)
            await ctx.send(
                f"The description of | **{meme_name}** | has been changed to _'{description}'_."
            )
        else:
            await ctx.send("No such meme exists. You messed up!")
Ejemplo n.º 9
0
    async def meme(self, ctx, *, meme_name):
        """Send a meme the user wants to be sent by pasting a hyperlink from shelve database."""
        # Get meme collection
        memes_collection = get_collection("memes")

        meme_name = meme_name.lower()
        if meme_name == "help":
            help_content = get_memes_as_entries(memes_collection)
            await send_with_buffer(ctx, help_content)
            return

        # Get link to a meme which is stored inside the database.
        meme = get_meme(memes_collection, meme_name)
        if meme is not None:
            await ctx.send(meme["url"])
            # Update number of times this meme was used.
            update_meme(memes_collection, meme["_id"], "times_used",
                        meme["times_used"] + 1)
        else:
            await ctx.send("No such meme exists. You messed up!")
Ejemplo n.º 10
0
 async def todo_list(self, ctx):
     todos_collection = get_collection("todos")
     todos = get_todos_as_entries(todos_collection)
     await send_with_buffer(ctx, todos)
Ejemplo n.º 11
0
    async def add_todo(self, ctx, *, todo_content):
        todos_collection = get_collection("todos")
        timestamp = str(datetime.now())
        insert_todo(todos_collection, timestamp, todo_content)

        await ctx.send("The TODO has been added.")
Ejemplo n.º 12
0
    async def search_places(self, ctx, searched_place, city, distance=10):
        await ctx.send(
            f"Searching for {searched_place} in {city}, radius: {distance}..."
        )
        api_provider = "Google"
        # Setup Google Maps API client.
        map_client = googlemaps.Client(GOOGLE_API_TOKEN)
        # Find location data based on search query - in this case: city.
        geocode_result = map_client.geocode(city)
        # Extract latitude and longitude from geocode result.
        coordinates = geocode_result[0]["geometry"]["location"]
        location = (coordinates["lat"], coordinates["lng"])
        # With this variable, track found places.
        places_list = []
        # Convert kilometers to meters
        distance = distance * 1000

        # Read current number of API requests already executed into variable.
        apis_collection = get_collection("apis")
        api = get_api(apis_collection, api_provider)
        requests_count = api["number_of_calls"]

        # Perform the search.
        response = map_client.places_nearby(
            location=location, keyword=searched_place, radius=distance
        )
        # Count the number of requests.
        requests_count += 1

        places_list += response.get("results")
        # This token is neeeded to track our position on the search list.
        # Google Maps allows for max. 20 results on one page.
        next_page_token = response.get("next_page_token")

        # Call API for more places results as long as there are any.
        while next_page_token:
            time.sleep(2)
            response = map_client.places_nearby(
                location=location,
                keyword=searched_place,
                radius=distance,
                page_token=next_page_token,
            )
            requests_count += 1
            places_list += response.get("results")
            next_page_token = response.get("next_page_token")

        # Update document in database.
        update_api(apis_collection, api_provider, requests_count)

        df = pd.DataFrame(places_list)
        # Store Google Maps url with the given place.
        df["url"] = "www.google.com/maps/place/?q=place_id:" + df["place_id"]
        # Remove closed locations.
        df.drop(df[df.business_status != "OPERATIONAL"].index, inplace=True)
        # Remove low rating locations.
        df.drop(df[df.rating <= 3.5].index, inplace=True)

        # Reduce data frame to the most important columns.
        df = df[["name", "rating", "vicinity", "url"]]
        df_rows = df.to_string(index=False).split(sep="\n")
        await send_with_buffer(ctx, df_rows, separator="\n\n")