Discord bot not fetching memes from Reddit API

I’m trying to make a Discord bot that gets random memes from Reddit. I followed a tutorial but it’s not working as expected; the main script runs fine yet nothing appears in the logs.

Here’s my main script:

import discord
from discord.ext import commands, tasks
import os
import asyncio
from itertools import cycle

bot = commands.Bot(command_prefix='!', intents=discord.Intents.all())

status_list = cycle(['Online', 'Meme Time', 'Having fun'])

@tasks.loop(seconds=10)
async def update_status():
    await bot.change_presence(activity=discord.Game(next(status_list)))

@bot.event
async def on_ready():
    print('Bot is up!')
    update_status.start()

with open('secret.txt') as f:
    bot_token = f.read().strip()

async def load_cogs():
    for file in os.listdir('./extensions'):
        if file.endswith('.py'):
            await bot.load_extension(f'extensions.{file[:-3]}')

async def run_bot():
    async with bot:
        await load_cogs()
        await bot.start(bot_token)

asyncio.run(run_bot())

And here’s the Reddit script:

import discord
from discord.ext import commands
from random import choice
import asyncpraw as praw

class MemeFeeder(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.reddit = praw.Reddit(client_id='HIDDEN', client_secret='HIDDEN', user_agent='bot:meme_feeder:v1 (by u/HIDDEN)')

    @commands.Cog.listener()
    async def on_ready(self):
        print(f'{self.__class__.__name__} is ready!')

    @commands.command()
    async def funny(self, ctx: commands.Context):
        subreddit = await self.reddit.subreddit('dankmemes')
        meme_collection = []

        async for post in subreddit.hot(limit=30):
            if not post.over_18 and post.author and post.url.endswith(('.png', '.jpg', '.jpeg', '.gif')):
                meme_collection.append((post.url, post.author.name))

        if meme_collection:
            chosen_meme = choice(meme_collection)
            embed = discord.Embed(title='Random Meme', description='Fresh from r/dankmemes', color=discord.Color.green())
            embed.set_author(name=f'Requested by {ctx.author}', icon_url=ctx.author.avatar)
            embed.set_image(url=chosen_meme[0])
            embed.set_footer(text=f'Posted by u/{chosen_meme[1]}')
            await ctx.send(embed=embed)
        else:
            await ctx.send('No memes found. Try again later.')

    def cog_unload(self):
        self.bot.loop.create_task(self.reddit.close())

async def setup(bot):
    await bot.add_cog(MemeFeeder(bot))

I suspect the issue lies in the ‘funny’ function. I’m fairly new to coding, so I’m not sure how to resolve it. Any insights?

I’ve encountered similar issues before. One potential problem could be rate limiting by the Reddit API. Try implementing a delay between requests or using a different Reddit wrapper like PRAW instead of asyncpraw. Also, ensure your bot has the proper intents enabled in the Discord Developer Portal. It might be worth adding some error handling and logging in your ‘funny’ function to pinpoint where exactly it’s failing. If you’re still stuck, consider using Discord.py’s debug mode to get more detailed error information. Lastly, double-check that your Reddit API credentials are correct and that you’ve properly set up your Discord bot token. Keep at it!

hey there! i had a similar issue. Make sure ur bot has the necessary permissions in discord. Also, check if ur reddit credentials r correct and not expired. Try adding some print statements in the ‘funny’ function to see where it might be failing. good luck!

Hey there! I’ve been through this rodeo before. One thing that jumps out at me is your use of asyncpraw. While it’s great for asynchronous programming, it can be finicky. Have you considered using the regular PRAW library instead? It might simplify things.

Also, I noticed you’re not handling exceptions in your ‘funny’ function. That could be why you’re not seeing any errors in your logs. Try wrapping your Reddit API calls in a try-except block. Something like:

try:
    async for post in subreddit.hot(limit=30):
        # Your existing code here
except Exception as e:
    print(f'Error fetching memes: {e}')
    await ctx.send('Oops! Something went wrong. Try again later.')

This way, if there’s an issue with the API call, you’ll at least see it in your console. Hope this helps! Let me know if you need any more pointers.