0

I am currently programming a Discord Bot using Discord.py, aiohttp and asyncpraw to work with Reddit API requests. My problem is that every request takes a long time to respond. Do you have any solutions how to improve speed of my code / API request?

When using the /gif Command this function is getting called:

# Function for a GIF from r/gifs
async def _init_command_gif_response(interaction: Interaction):
    """A function to send a random gif using reddit api"""

    # Respond in the console that the command has been ran
    print(f"> {interaction.guild} : {interaction.user} used the gif command.")

    # Tell Discord that Request takes some time
    await interaction.response.defer()

    try:
        submission = await _reddit_api_request(interaction, "gifs")
        await interaction.followup.send(submission.url)
    except Exception:
        print(f" > Exception occured processing gif: {traceback.print_exc()}")
        return await interaction.followup.send(f"Exception occured processing gif. Please contact <@164129430766092289> when this happened.")

Which is calling this function to start a Reddit API request:

# Reddit API Function
async def _reddit_api_request(interaction: Interaction, subreddit_string: str):
    try:
        #async with aiohttp.ClientSession(trust_env=True) as session:
        async with aiohttp.ClientSession() as session:
            reddit = asyncpraw.Reddit(
                client_id = config_data.get("reddit_client_id"),
                client_secret = config_data.get("reddit_client_secret"),
                redirect_uri = config_data.get("reddit_redirect_uri"),
                requestor_kwargs = {"session": session},
                user_agent = config_data.get("reddit_user_agent"),
                check_for_async=False)
            reddit.read_only = True

            # Check if Subreddit exists
            try:
                subreddit = [sub async for sub in reddit.subreddits.search_by_name(subreddit_string, exact=True)]
            except asyncprawcore.exceptions.NotFound:
                print(f" > Exception: Subreddit \"{subreddit_string}\" not found")
                await interaction.followup.send(f"Subreddit \"{subreddit_string}\" does not exist!")
                raise
            except asyncprawcore.exceptions.ServerError:
                print(f" > Exception: Reddit Server not reachable")
                await interaction.followup.send(f"Reddit Server not reachable!")
                raise

            # Respond with content from reddit
            return await subreddit[0].random()
    except Exception:
        raise

My goal is to increase speed of the discord response. Every other function that is not using Reddit API is snappy. So it must be something with my _reddit_api_request Function.

Full Source Code can be found on Github

Popeye
  • 11
  • 2
  • Note: https://stackoverflow.com/questions/4544784/how-can-you-get-the-call-tree-with-python-profilers – Popeye Jan 17 '23 at 10:22

0 Answers0