0

I'm developing a discord bot in Python which will get random image from a subreddit on Reddit, and send it to my discord channel whenever I type a specific phrase. I use PRAW to get data from Reddit, and discord.py to work with discord.

My problem is, when I type the phrase on discord, the bot sometime response absolute, but sometime it take 3-5s or even 10-20s to response. Here are two video for more detailed comparison. Slow Response - Fast Response

I've done some debug show I find out the problem is in the code section below:

def get_image_reddit(sub_name):
    global reddit
    sub = reddit.subreddit(sub_name)
    random_post = sub.random()

    #bellow if in case the response link is a gallery
    if random_post.url.startswith('https://www.reddit.com/gallery'):
        post_galleries = reddit.submission(url=random_post.url)
    gallery = []
        for i in post_galleries.media_metadata.items():
            url = i[1]['p'][0]['u']
            url = url.split("?")[0].replace("preview", 'i')
            gallery.append(url)
        return gallery

    output = []
    output.append(random_post.url)
    return output

Can someone help me to solve this problem? Thank you, have a nice day!

Cuong Do
  • 1
  • 2
  • I had this problem too! Check [this](https://stackoverflow.com/questions/67101891/discord-py-meme-command-takes-a-lot-of-time) out. – ChaoticNebula Dec 20 '21 at 15:46
  • thank you! Can you tell me why you put async along with your function? – Cuong Do Dec 20 '21 at 16:28
  • Discord bot development is done in an ```async``` environment. Read more about it [here](https://towardsdatascience.com/introduction-to-asynchronous-programming-in-python-3cd190748cd5). – ChaoticNebula Dec 21 '21 at 04:10

0 Answers0