praw-dev / asyncpraw

Async PRAW, an abbreviation for "Asynchronous Python Reddit API Wrapper", is a python package that allows for simple access to Reddit's API.

Home Page:https://asyncpraw.readthedocs.io

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Trying to fetch or load attribute causes error.

MrTransparentBox opened this issue · comments

Whenever I try to load or fetch the author part of a submission (in order to get the "icon_img") for my discord.py bot, it gives an error. Interestingly the other parts are available without using .load(), but it wants me to fetch (or use .load()) in order to access author.icon_img or it says that icon_img doesn't exist.

To Reproduce
Steps to reproduce the behaviour:

  1. Add that command to a discord bot
  2. Run the "meme" command
  3. Wait for the command to process
  4. IndexError: list index out of range

Expected behavior
Allows me to get any information I wanted about the author. The submission info works, and most of the author info works, it's just the icon_img that is broken. It complains that attribute doesn't exist and suggests using .load(). When I do that it then gives an IndexError, the same occurs if I use fetch=True.

Code/Logs
CODE:

@bot.command(name="meme", 
                    aliases=["funny", "memes"],
                    description="""Grabs a random meme from the top posts in r/memes and r/dankmemes subreddits. May take a second.
Parametres:
'From last' timephrase: specify the possible age of available selections. E.g. if equal to 'day' it gets one of the top memes of the day.; Default = week""",
                    brief="Gets you some memes.",
                    usage="<'From last' timephrase [hour, day, week, month, year, all] = week>")
async def meme(ctx, time="week"):
    if time not in ("hour", "day", "week", "month", "year", "all"):
        await ctx.send("Time phrase given is not valid. Should be: 'hour', 'day', 'week', 'month', 'year' or 'all'")
        return
    submissions = []
    async with ctx.typing():
        sub = random.choice(["dankmemes", "memes"])
        subr = await reddit.subreddit(sub)
        async for item in subr.top(time):
            submissions.append(item)
        submission = random.choice(submissions)
        author = await reddit.redditor(name=submission.author.name)
        await author.load()
        emb = discord.Embed(title=submission.title, url=f"https://www.reddit.com{submission.permalink}", description="", color=discord.Colour.random())
        emb.set_image(url=submission.url)
        emb.set_author(name=author.name, url=f"https://www.reddit.com/user/{author.name}", icon_url=author.icon_img)
        emb.set_footer(text=f"{emoji.emojize(':+1:', True)} {submission.score}  ||  {emoji.emojize(':speech_balloon:', True)} {submission.num_comments}  ||  Posted by {author.name}")
    await ctx.send(embed=emb)

LOGS:

Ignoring exception in command meme:
Traceback (most recent call last):
  File "D:\PropertyOfName\VisualStudioProjects\Python\Environments\discordBotEnv\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "D:\PropertyOfName\VisualStudioProjects\Python\discordTest\discordTest\discordTest.py", line 53, in meme
    await author.load()
  File "_pydevd_bundle/pydevd_cython.pyx", line 1216, in _pydevd_bundle.pydevd_cython.SafeCallWrapper.__call__
  File "_pydevd_bundle/pydevd_cython.pyx", line 300, in _pydevd_bundle.pydevd_cython.PyDBFrame.trace_exception
  File "_pydevd_bundle/pydevd_cython.pyx", line 187, in _pydevd_bundle.pydevd_cython.is_unhandled_exception
  File "c:\program files (x86)\microsoft visual studio\2019\community\common7\ide\extensions\microsoft\python\core\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_collect_bytecode_info.py", line 167, in collect_try_except_info
    def collect_try_except_info(co, use_func_first_line=False):
IndexError: list index out of range

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "D:\PropertyOfName\VisualStudioProjects\Python\Environments\discordBotEnv\lib\site-packages\discord\ext\commands\bot.py", line 902, in invoke
    await ctx.command.invoke(ctx)
  File "D:\PropertyOfName\VisualStudioProjects\Python\Environments\discordBotEnv\lib\site-packages\discord\ext\commands\core.py", line 864, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "D:\PropertyOfName\VisualStudioProjects\Python\Environments\discordBotEnv\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: IndexError: list index out of range
The program 'python.exe' has exited with code 0 (0x0).

System Info

  • OS: Windows 10, version 20H2
  • Python: 3.7.8
  • Async PRAW Version: 7.1.1

Maybe it's my mistake but can someone help.

I tried the following code and was not able to reproduce this.

import random
import discord
    
async def main():
    submissions = []
    reddit = asyncpraw.Reddit(**settings)
    sub = random.choice(["dankmemes", "memes"])
    subr = await reddit.subreddit(sub)
    async for item in subr.top("hour"):
        submissions.append(item)
    submission = random.choice(submissions)
    author = await reddit.redditor(name=submission.author.name)
    await author.load()
    emb = discord.Embed(title=submission.title, url=f"https://www.reddit.com{submission.permalink}", description="", color=discord.Color.random())
    emb.set_image(url=submission.url)
    emb.set_author(name=author.name, url=f"https://www.reddit.com/user/{author.name}", icon_url=author.icon_img)
    emb.set_footer(text=f"{':+1:'} {submission.score}  ||  {':speech_balloon:'} {submission.num_comments}  ||  Posted by {author.name}")

if __name__ == "__main__":
    loop.run_until_complete(main())

Could this be a problem with discord.py?

Could this be a problem with discord.py?

Possibly, some strange things are occurring when using async praw, that don't happen with the non-async version. E.g. I copied out the code you used for your test (obviously changing Reddit init, etc.) and began to get this error

Traceback (most recent call last):
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "c:\program files (x86)\microsoft visual studio\2019\community\common7\ide\extensions\microsoft\python\core\debugpy\__main__.py", line 45, in <module>
    cli.main()
  File "c:\program files (x86)\microsoft visual studio\2019\community\common7\ide\extensions\microsoft\python\core\debugpy/..\debugpy\server\cli.py", line 430, in main
    run()
  File "c:\program files (x86)\microsoft visual studio\2019\community\common7\ide\extensions\microsoft\python\core\debugpy/..\debugpy\server\cli.py", line 267, in run_file
    runpy.run_path(options.target, run_name=compat.force_str("__main__"))
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\runpy.py", line 263, in run_path
    pkg_name=pkg_name, script_name=fname)
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\runpy.py", line 96, in _run_module_code
    mod_name, mod_spec, pkg_name, script_name)
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "D:\PropertyOfName\VisualStudioProjects\Python\PythonTest\PythonTest\PythonTest.py", line 82, in <module>
    main()
  File "D:\PropertyOfName\VisualStudioProjects\Python\PythonTest\PythonTest\PythonTest.py", line 80, in main
    loop.run_until_complete(meme())
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\asyncio\base_events.py", line 587, in run_until_complete
    return future.result()
  File "D:\PropertyOfName\VisualStudioProjects\Python\PythonTest\PythonTest\PythonTest.py", line 68, in meme
    await author.load()
  File "_pydevd_bundle/pydevd_cython.pyx", line 1216, in _pydevd_bundle.pydevd_cython.SafeCallWrapper.__call__
  File "_pydevd_bundle/pydevd_cython.pyx", line 300, in _pydevd_bundle.pydevd_cython.PyDBFrame.trace_exception
  File "_pydevd_bundle/pydevd_cython.pyx", line 196, in _pydevd_bundle.pydevd_cython.is_unhandled_exception
  File "c:\program files (x86)\microsoft visual studio\2019\community\common7\ide\extensions\microsoft\python\core\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_collect_bytecode_info.py", line 26, in is_line_in_try_block
    def is_line_in_try_block(self, line):
TypeError: '<=' not supported between instances of 'int' and 'NoneType'

I used this code:

async def meme():
    submissions=[]
    reddit = asyncpraw.Reddit(client_id="xxx", client_secret="xxx", user_agent=f"Python3:ReginaldBot:{appVersion} (by u/MrTransparentBox)", username="xxx", password="xxx")
    sub = random.choice(["memes", "dankmemes"])
    subr = await reddit.subreddit(sub)
    s = subr.top()
    async for i in s:
        submissions.append(i)

    submission = random.choice(submissions)
    author = await reddit.redditor(name=submission.author.name)
    await author.load()
    print(submission.title)
    print(submission.permalink)
    print(submission.url)
    print(author.name)
    print(author.icon_img)
    await asyncio.sleep(2)
    print("slept well")
    await asyncio.sleep(2)
def main():
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    loop.run_until_complete(meme())

main()

Although I've used discord.py for a while, using things in async is quite new to me, so I might have made a lot of mistakes.
Thanks for all your help @LilSpazJoekp.

I am not able to reproduce this bug with this environment:

System Info

  • OS: macOS 11.1 (20C69)
  • Python: 3.7.8
  • Async PRAW Version: 7.1.1

This appears to be an issue with Microsoft Visual Studio. I have a couple of things you could try:

  • You appear to be running it in debug mode, try executing the script normally.
  • Try with Visual Studio Code.
  • Try with the latest version of Python.

I'm going to close this issue due to inactivity. If you still need help feel free to comment or reopen this issue.