Giter Site home page Giter Site logo

praw-dev / asyncpraw Goto Github PK

View Code? Open in Web Editor NEW
107.0 4.0 19.0 61.49 MB

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

License: BSD 2-Clause "Simplified" License

Python 99.98% Shell 0.02%
python api oauth reddit reddit-api async asyncpraw praw

asyncpraw's Introduction

Async PRAW: The Asynchronous Python Reddit API Wrapper

Latest Async PRAW Version Supported Python Versions PyPI - Downloads - Monthly GitHub Actions Status Coveralls Coverage OpenSSF Scorecard Contributor Covenant pre-commit Black code style

Async PRAW, an abbreviation for "Asynchronous Python Reddit API Wrapper", is a Python package that allows for simple access to Reddit's API. Async PRAW aims to be easy to use and internally follows all of Reddit's API rules. With Async PRAW there's no need to introduce sleep calls in your code. Give your client an appropriate user agent and you're set.

Installation

Async PRAW is supported on Python 3.8+. The recommended way to install Async PRAW is via pip.

pip install asyncpraw

To install the latest development version of Async PRAW run the following instead:

pip install --upgrade https://github.com/praw-dev/asyncpraw/archive/master.zip

For instructions on installing Python and pip see "The Hitchhiker's Guide to Python" Installation Guides.

Quickstart

Assuming you already have a credentials for a script-type OAuth application you can instantiate an instance of Async PRAW like so:

import asyncpraw

reddit = asyncpraw.Reddit(
    client_id="CLIENT_ID",
    client_secret="CLIENT_SECRET",
    password="PASSWORD",
    user_agent="USERAGENT",
    username="USERNAME",
)

With the reddit instance you can then interact with Reddit:

# Create a submission to r/test
subreddit = await reddit.subreddit("test")
await subreddit.submit("Test Submission", url="https://reddit.com")

# Comment on a known submission
submission = await reddit.submission(
    url="https://www.reddit.com/comments/5e1az9", fetch=False
)
await submission.reply("Super rad!")

# Reply to the first comment of a weekly top thread of a moderated community
subreddit = await reddit.subreddit("mod")
async for submission in subreddit.top(time_filter="week"):
    comments = await submission.comments()
    await comments[0].reply("An automated reply")

# Output score for the first 256 items on the frontpage
async for submission in reddit.front.hot(limit=256):
    print(submission.score)

# Obtain the moderator listing for r/test
subreddit = await reddit.subreddit("test")
async for moderator in subreddit.moderator:
    print(moderator)

Please see Async PRAW's documentation for more examples of what you can do with Async PRAW.

Async PRAW Discussion and Support

For those new to Python, or would otherwise consider themselves a Python beginner, please consider asking questions on the r/learnpython subreddit. There are wonderful people there who can help with general Python and simple Async PRAW related questions.

Otherwise, there are a few official places to ask questions about Async PRAW:

r/redditdev is the best place on Reddit to ask Async PRAW related questions. This subreddit is for all Reddit API related discussion so please tag submissions with [Async PRAW]. Please perform a search on the subreddit first to see if anyone has similar questions.

Real-time chat can be conducted via the PRAW Slack Organization (please create an issue if that invite link has expired).

Please do not directly message any of the contributors via Reddit, email, or Slack unless they have indicated otherwise. We strongly encourage everyone to help others with their questions.

Please file bugs and feature requests as issues on GitHub after first searching to ensure a similar issue was not already filed. If such an issue already exists please give it a thumbs up reaction. Comments to issues containing additional information are certainly welcome.

Note

This project is released with a Contributor Code of Conduct. By participating in this project you agree to abide by its terms.

Documentation

Async PRAW's documentation is located at https://asyncpraw.readthedocs.io/.

History

February 2019: Joel forked PRAW and began work on Async PRAW, an asynchronous compatible version of PRAW.

July 2020: Async PRAW was moved into the praw-dev namespace.

License

Async PRAW's source (v7.1.1+) is provided under the Simplified BSD License.

  • Copyright ©, 2020, Joel Payne

asyncpraw's People

Contributors

13steinj avatar abaisero avatar bakonydraco avatar bboe avatar crackedp0t avatar d0cr3d avatar damgaard avatar deimos avatar diceroll123 avatar eleweek avatar jamiemagee avatar jarhill0 avatar julian avatar kaif-00z avatar kungming2 avatar leviroth avatar lilspazjoekp avatar liudvikam avatar maybenetwork avatar michael-lazar avatar nemec avatar nmtake avatar pyprohly avatar pythoncoderas avatar sprt avatar tmelz avatar vallard192 avatar voussoir avatar watchful1 avatar zhifuge avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

asyncpraw's Issues

asyncpraw uses update_checker which isn't async

Describe the solution you'd like

update_checker is a PyPi package that appears to be used by this library, and is imported here:

from update_checker import update_check

The package itself appears to be using requests to do the actual checking when the Reddit class is instanced, and this isn't async. This goes against the whole purpose of this library, in that all web requests are to be done in an asynchronous way. Please consider either dropping it as a requirement, or using some other library for this purpose. Alternatively, version check could be done "manually" from asyncpraw itself.

Describe alternatives you've considered

Since there's a check for that package being installed, one can just uninstall the package. Having to uninstall it after every update is quite terrible from the design perspective though, I'd like not to be forced to use a library that handles requests in a non-async way.

Additional context

No response

subreddit.flair() generator not working as intended

Describe the bug
To get a list of users and flairs on a subreddit, you can use the subreddit.flair() generator. When looping through this generator without specifying the redditor argument, it should return the listings of ALL users and their flairs. Instead, it only returns the listing of the reddit user "None".

To Reproduce
On a subreddit in which you have the correct flair permissions, loop through the list of users and their flairs.

reddit = Reddit(...)
sub = await reddit.subreddit("subreddit_goes_here")

async for flair in sub.flair():
  print(flair)

Expected behavior
A list of users and their flairs on the subreddit to be printed.

Code/Logs
Problem seems to be here in this file on line 1696.

Subreddit._safely_add_arguments(generator_kwargs, "params", name=str(redditor))
generator_kwargs.setdefault("limit", None)
url = API_PATH["flairlist"].format(subreddit=self.subreddit)
return ListingGenerator(self.subreddit._reddit, url, **generator_kwargs)

If redditor is None, it will be converted to the string 'None' and be treated as if you were literally searching for the flair of the user "None". This makes it impossible to call this generator without having the redditor argument added to generator_kwargs. It should just be:

Subreddit._safely_add_arguments(generator_kwargs, "params", name=redditor)
generator_kwargs.setdefault("limit", None)
url = API_PATH["flairlist"].format(subreddit=self.subreddit)
return ListingGenerator(self.subreddit._reddit, url, **generator_kwargs)

without explicitly casting redditor to a string. This bug only affects the async version of the library and behavior is working as intended in the main library.

Cannot submit image posts with 7.6 onwards

Describe the Bug

My Discord bot happily posts image submissions with asyncpraw 7.5.0, but in 7.6.0 onwards it does not work.

Desired Result

An image submission

Relevant Logs

Traceback (most recent call last):
      File "C:\Users\jon\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 414, in _scheduled_task
        await item.callback(interaction)
      File [...] line 1939, in callback
        image_post = await rfcoc.submit_image(
      File "C:\Users\jon\AppData\Local\Programs\Python\Python310\lib\site-packages\asyncpraw\util\deprecate_args.py", line 51, in wrapped
        return await _wrapper(*args, **kwargs)
      File "C:\Users\jon\AppData\Local\Programs\Python\Python310\lib\site-packages\asyncpraw\models\reddit\subreddit.py", line 1330, in submit_image
        image_url, websocket_url = await self._upload_media(
      File "C:\Users\jon\AppData\Local\Programs\Python\Python310\lib\site-packages\asyncpraw\models\reddit\subreddit.py", line 763, in _upload_media
        response = await self._read_and_post_media(media_path, upload_url, upload_data)
      File "C:\Users\jon\AppData\Local\Programs\Python\Python310\lib\site-packages\asyncpraw\models\reddit\subreddit.py", line 705, in _read_and_post_media
        response = await self._reddit._core._requestor._http.post(
      File "C:\Users\jon\AppData\Local\Programs\Python\Python310\lib\site-packages\aiohttp\client.py", line 950, in post
        self._request(hdrs.METH_POST, url, data=data, **kwargs)
    TypeError: ClientSession._request() got an unexpected keyword argument 'files'

Code to reproduce the bug

rfcoc = await reddit.subreddit('fcoc')
image_post = await rfcoc.submit_image(title=self.trip.reddit_header,image_path=self.trip.reddit_img,flair_id=flair_departure,timeout=10)

My code example does not include the Reddit() initialization to prevent credential leakage.

Yes

This code has previously worked as intended.

Yes

Operating System/Environment

Debian 10

Python Version

Python 10

Async PRAW Version

7.6

Asyncprawcore Version

2.3

Anything else?

Neither 7.6 nor 7.6.1 works but 7.5 does.

Bump aiofiles dependency

Describe the solution you'd like

Some months ago I PRed #181 to support newer version of aiofiles. Since then they switched from normal versioning to versioning which includes the year eg. 22.1.0 .

I'm not fully sure how they handle breaking changes, but it would be nice to implement some solution which allows users to use newer aiofiles version.

Describe alternatives you've considered

No response

Additional context

No response

subreddit.submit flair_text, flair_id returns 400 error if used.

Describe the bug
When attempting to use attributes "flair_text" or "flair_id" reddit returns "received 400 HTTP response". This was done under a moderator account. Was not tested on a non-moderator account. Works fine with removal of these attributes and then using submission.mod.flair() to flair these posts under the same account with the same text.

To Reproduce
Steps to reproduce the behavior:

  1. Submit post to subreddit you moderator with "flair_text" or "flair_id" used. In the example "flair_text="FlairText"" was used.

Expected behavior
Submission of post using flair_text and flair_id given.

Code/Logs

subreddit = await reddit.subreddit("YourSubredditHere")
await subreddit.submit(title="Test Post", selftext="Test Post Body", flair_text="FlairText"))

System Info

  • OS: Windows
  • Python: 3.7.8
  • Async PRAW Version: asyncpraw 7.1.1.dev0
    asyncprawcore 1.5.1

Add a function that allows someone to get an image/video URL, raises error if not retrievable.

I'd like something like submission.viewable_URL which returns a url if it's an image/video and raises an error if it doesn't exist. I see a way of doing this with

import aiohttp

Responses = f'https://www.reddit.com/{POST-ID-GOES-HERE}/.json'
    async with aiohttp.ClientSession() as session:
        async with session.get(Responses) as r:
            if r.status == 200:
                js = await r.json()
                try:
                    return js[0]['data']['children'][0]['data']['url_overridden_by_dest']
                except KeyError:
                    #raise an error or whatever

Praw streaming and blocked users comments

Describe the Bug

I am getting the AttributeError: 'NoneType' object has no attribute 'name' when streaming the comments. I first chalked it off to people commenting and deleting immediately, but that is not the case.

Desired Result

comment.author should not be None if the comment is not deleted or removed

Code to reproduce the bug

main_logger.info(f"Logged into {await reddit_instance.user.me()} Account.")
    pcm_subreddit = await reddit_instance.subreddit("PoliticalCompassMemes")
    async for comment in pcm_subreddit.stream.comments(skip_existing=True):  # Comment
        if comment.author.name.lower() in [getenv("REDDIT_USERNAME", "basedcount_bot").lower(), "flair-checking-bot"]:
           ^^^^^^^^^^^^^^ throws attribute error

The Reddit() initialization in my code example does not include the following parameters to prevent credential leakage:

client_secret, password, or refresh_token.

  • Yes

Relevant Logs

Traceback (most recent call last):
  File "/root/basedcount_bot/basedcount_bot.py", line 39, in wrapper
    await func(reddit_instance, mongo_client)
  File "/root/basedcount_bot/basedcount_bot.py", line 250, in read_comments
    if comment.author.name.lower() in [getenv("REDDIT_USERNAME", "basedcount_bot").lower(), "flair-checking-bot"]:
AttributeError: 'NoneType' object has no attribute 'name'

This code has previously worked as intended.

Yes

Operating System/Environment

Ubuntu 20.04.5 LTS

Python Version

3.10.7

Async PRAW Version

7.6.1

Asyncprawcore Version

2.3.0

Anything else?

Now technically speaking, I could check if the author is None and skip the comment, but as I mentioned, it is giving an error for comments which should have the author info. If I go the skip route, I might skip over normal comments.

Get warnings when exiting program

Describe the bug

When I exit my Discord bot, I get a lot of ResourceWarnings from unclosed sessions.

To Reproduce
Steps to reproduce the behavior:

  1. Make reddit instance
  2. Await a sleep.
  3. Handle KeyboardInterrupt and instantiate new instance
  4. Hit Ctrl + C
  5. Wait 5 seconds
  6. Hit Ctrl + C again

Expected behavior

Program exits without any warnings.

Code/Logs

Code:

import asyncpraw
import asyncio

reddit = asyncpraw.Reddit(<login info>)

async def main():
    await reddit.submission("asdfgh")
    await asyncio.sleep(1000)

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    try:
        loop.run_until_complete(main())
    except:
        reddit = asyncpraw.Reddit(<login info>)
        try:
            loop.run_until_complete(main())
        except:
            pass

Output:

Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x10c4f0c10>
Unclosed connector
connections: ['[(<aiohttp.client_proto.ResponseHandler object at 0x10c5346a0>, 0.68580921)]']
connector: <aiohttp.connector.TCPConnector object at 0x10c4f0c40>

System Info

  • OS: Mac OS 10.15.6
  • Python: 3.8.5
  • Async PRAW Version: 7.1.0

aiofiles version is locked to <1

Describe the solution you'd like

I ran down into issues with poetry while trying to install this library. I use a library that depends on latest version of aiofiles (^23.*), but in setup.py asyncpraw is locked down to aiofiles <1:

   install_requires=[
        "aiofiles <1",

Which turns into dependency conflict. Then, the only available <1 version is 0.8.0, which was released in 2021. So I just wanted to ask if this is a typo or intended to be like that?

Describe alternatives you've considered

No response

Additional context

No response

Add option to sort submissions from oldest to newest

Describe the solution you'd like

I have a python script that looks at new posts to a subreddit and determines if the user is posting too soon (they only allow one post per week). I'm currently using async for submission in subreddit.new(limit=max_posts) but it appears that your ListingGenerator feeds me the newest posts first. I'd prefer to see the oldest posts (within the limit) first. This will help me catch someone who posts, then posts again quickly. Basically, it's comparing submission.created_utc to the same attribute of the previous post (stored in my db). Currently, the previous post time is greater than the currently evaluated time since it's looking at the newer posts first.

What would be ideal would be the option to do something like this:
async for submission in subreddit.new(limit=max_posts, reverse=True)
or
async for submission in subreddit.new(limit=max_posts, oldest_first=True)

Describe alternatives you've considered

One option would be to consume the generator and just store each submission in a new list, then loop through the list in reverse order, but that kinda defeats the purpose of async for. Currently, I don't see a way of going through the submissions, oldest to newest, without seriously increasing execution time.

Additional context

No response

Uploading snoo/icon fails with IMAGE_ERROR

Describe the bug
Trying to upload a new Snoo or icon to a subreddit fails with an asyncpraw.exceptions.RedditAPIException: IMAGE_ERROR: 'Invalid image or general image error'

To Reproduce
Steps to reproduce the behavior:

  1. Create the subreddit object
  2. Call the upload_header/upload_mobile_icon on the subreddit moderation stylesheet with the path given

Expected behavior
The expected behavior is that the image would be uploaded and applied to the subreddit styling.

Code/Logs
Log:

Traceback (most recent call last):
  File "C:\Users\User\Documents\Git\bot\cogs\reddit_tools.py", line 312, in update_image_executor
    await sub.stylesheet.upload_mobile_icon(path_to_image)
  File "C:\Users\User\AppData\Roaming\Python\Python38\site-packages\asyncpraw\models\reddit\subreddit.py", line 3831, in upload_mobile_icon
    return await self._upload_image(image_path, {"upload_type": "icon"})
  File "C:\Users\User\AppData\Roaming\Python\Python38\site-packages\asyncpraw\models\reddit\subreddit.py", line 3486, in _upload_image
    raise RedditAPIException([[error_type, error_value, None]])
asyncpraw.exceptions.RedditAPIException: IMAGE_ERROR: 'Invalid image or general image error'
async def update_image_executor(self, ctx, path_to_image):
    sub = await self.areddit.subreddit(SUBREDDIT)
    await sub.stylesheet.upload_mobile_icon(path_to_image)
    ## Equivalent praw code that works with the same parameters given
    # sub = self.reddit.subreddit(SUBREDDIT)
    # sub.stylesheet.upload_mobile_icon(path_to_image)

System Info

  • OS: Windows 10 2004
  • Python: 3.8.6
  • Async PRAW Version: 7.1.1

subreddit.banned.add BAD_NUMBER exception if duration is None

Describe the bug
When trying to permanently ban a user from a subreddit by either passing None to duration or omitting the aforementioned optional parameter an asyncpraw.exceptions.RedditAPIException: BAD_NUMBER: "that number isn't in the right range (1 to 999)" on field 'duration' exception is thrown.

To Reproduce
Steps to reproduce the behavior:

  1. Create a subreddit object
  2. Call the add coroutine on the banned subreddit relationship

Expected behavior
The expected behavior is banning the user passed to the coroutine permanently from the subreddit. This behavior would be in line with praw.

Code/Logs
Code:

    @commands.command(name='ban')
    async def ban_user(self, ctx, user_name: str, ban_duration: int, ban_reason: str, ban_note: str, ban_message: Optional[str]):
        "Command to ban a user. Duration 0 = permanent"
        subreddit = await self.areddit.subreddit(SUBREDDIT)
        try:
            if ban_duration == 0:
                await subreddit.banned.add(user_name, ban_reason=ban_reason, ban_message=ban_message, note=ban_note)
            else:
                await subreddit.banned.add(user_name, ban_reason=ban_reason, ban_message=ban_message, duration=ban_duration, note=ban_note)
            await ctx.send(f"I've banned {user_name} {'permanently' if ban_duration == 0 else f'for {ban_duration} days'} for you.")
        except:
            await ctx.send(f"```{traceback.format_exc()}```")

Logs:

Traceback (most recent call last):
  File "/home/user/discord_bot/cogs/reddit_tools.py", line 293, in ban_user
    await subreddit.banned.add(user_name, ban_reason=ban_reason, ban_message=ban_message, note=ban_note)
  File "/home/user/.local/lib/python3.8/site-packages/asyncpraw/models/reddit/subreddit.py", line 2599, in add
    await self.subreddit._reddit.post(url, data=data)
  File "/home/user/.local/lib/python3.8/site-packages/asyncpraw/reddit.py", line 676, in post
    return await self._objectify_request(
  File "/home/user/.local/lib/python3.8/site-packages/asyncpraw/reddit.py", line 584, in _objectify_request
    return self._objector.objectify(
  File "/home/user/.local/lib/python3.8/site-packages/asyncpraw/objector.py", line 180, in objectify
    raise RedditAPIException(errors)
asyncpraw.exceptions.RedditAPIException: BAD_NUMBER: "that number isn't in the right range (1 to 999)" on field 'duration'

System Info

  • OS: Ubuntu 18.04
  • Python: 3.8.0
  • Async PRAW Version: 7.1.0

subreddit.stream.submissions() stops after an hour or so

Describe the bug
subreddit.stream.submissions() stops after an hour or so

To Reproduce
Steps to reproduce the behavior:

  1. Create an submissions stream
  2. Run for a couple of hours
  3. Observe

Expected behavior
submissions.stream() never stops

Code/Logs

        subreddit = await reddit.subreddit("dankmemes+memes+okbuddyretard+specialsnowflake+pewdiepiesubmissions")
        
        async for submission in subreddit.stream.submissions(skip_existing=True):
            keywords = DataBase.get_keywords()
            matching = [s for s in keywords if s[0].lower() in submission.title.lower()]
            if matching:
                await self.send_notification(submission, matching[0])

It reaches the end of the for loop before just dying, so I'm not expecting there being a blocking method that may be causing this

System Info

  • OS: Ubuntu 18.04.5 LTS x86_64
  • Python: 3.8.3
  • Async PRAW Version: 7.1.0

Missing RedditorListingMixin for endpoint "overview"

Describe the solution you'd like

The api prescribes an "overview" endpoint for users which shows combined comments plus submissions, as shown on the user overview page. I don't know enough about the asyncpraw code to competently make this function, but I suspect it'd look like this:

@cachedproperty
def overview(self) -> SubListing:
    return SubListing(self._reddit, self._path, "overview")

And it would ultimately be used like this:

redditor = await reddit.redditor("spez")
redditor.overview.hot()

Describe alternatives you've considered

Fetch the comments and submissions for the redditor separately, then combine them in a list sorted by created_utc.

Additional context

No response

Trying to fetch or load attribute causes error.

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

Add py.typed marker

Describe the solution you'd like

Add py.typed marker according to https://peps.python.org/pep-0561/
As far as I know if you're using inline types adding empty py.typed file should work

Describe alternatives you've considered

No response

Additional context

No response

comment.submission is not loaded or awaitable.

Describe the bug

When calling comment.submission.title, an AttributeError is thrown due to it not being fetched.

To Reproduce
Steps to reproduce the behavior:

  1. Get a comment, for example comment = await reddit.comment("dkk4qjd")
  2. Try to get a field from the comments subreddit field, e.g. print(comment.submission.title
  3. Observe AttibuteError: AttributeError: 'Submission' object has no attribute 'title'. 'Submission' object has not been fetched, did you forget to execute '.load()'?

Expected behavior
I would expect either the Submission object to be loaded, the Comment object return a coroutine that loads the Submission, or the submission.title call to be awaitable.

Maybe this is expected behaviour, but it feels a little off to have to manually call the .load().

Maybe it's just because the Comment API returns enough data, but it's strange that I can do comment.author.name but not comment.submission.title.

Even if this is working as intended, it would be nice to document this on the Comment doc to say that the submission attribute must be manually loaded to make it clear this is expected.

Metaclass error import asyncpraw

Been having this issue for a while, it just showed up and it tirggers on the import itself.

Ive tried uninstalling and reinstalling but nothing.

File "discordbot.py", line 4, in <module>
import asyncpraw
File "/usr/local/lib/python3.8/site-packages/asyncpraw/init.py", line 14, in <module>
from .reddit import Reddit # NOQA
File "/usr/local/lib/python3.8/site-packages/asyncpraw/reddit.py", line 22, in <module>
from asyncprawcore import (
File "/usr/local/lib/python3.8/site-packages/asyncprawcore/init.py", line 4, in <module>
from .auth import ( # noqa
File "/usr/local/lib/python3.8/site-packages/asyncprawcore/auth.py", line 5, in <module>
import aiohttp
File "/usr/local/lib/python3.8/site-packages/aiohttp/init.py", line 6, in <module>
from .client import (
File "/usr/local/lib/python3.8/site-packages/aiohttp/client.py", line 35, in <module>
from . import hdrs, http, payload
File "/usr/local/lib/python3.8/site-packages/aiohttp/http.py", line 7, in <module>
from .http_parser import (
File "/usr/local/lib/python3.8/site-packages/aiohttp/http_parser.py", line 15, in <module>
from .helpers import NO_EXTENSIONS, BaseTimerContext
File "/usr/local/lib/python3.8/site-packages/aiohttp/helpers.py", line 48, in <module>
from typing_extensions import Protocol
File "/usr/local/lib/python3.8/site-packages/typing_extensions.py", line 962, in <module>
class OrderedDict(collections.OrderedDict, typing.MutableMapping[KT, VT],
TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases```

some attributes of Redditor is not defined.

Describe the Bug

some attributes of Redditor is not defined. like .is_gold , .link_karma , .comment_karma and more. https://github.com/praw-dev/asyncpraw/blob/master/asyncpraw/models/reddit/redditor.py#L55

Desired Result

not error!

Relevant Logs

File "/home/Kaif/.local/lib/python3.10/site-packages/asyncpraw/models/reddit/base.py", line 34, in __getattr__
    raise AttributeError(
AttributeError: 'Redditor' object has no attribute 'link_karma'. 'Redditor' object has not been fetched, did you forget to execute '.load()'?

Code to reproduce the bug

print((await reddit.user.friends())[0].link_karma)

My code example does not include the Reddit() initialization to prevent credential leakage.

Yes

This code has previously worked as intended.

No

Operating System/Environment

Ubuntu 20 lts

Python Version

Python3.10.4

Async PRAW Version

7.4.0

Asyncrawcore Version

2.3.0

Anything else?

add that attributes .

Fetching comment parent clears children comments

Describe the bug

If I refresh a comment, then it loads in the comment replies. However, if I fetch the parent, then it clears the replies.

To Reproduce
Steps to reproduce the behavior:

  1. Make comment from URL
  2. Refresh comment and check for replies
  3. Fetch parent
  4. Check for replies

Expected behavior

The children should not be cleared.

Code/Logs

url = "https://www.reddit.com/r/anime/comments/il7y3i/rezero_kara_hajimeru_isekai_seikatsu_season_2/g3q1k1m/?utm_source=share&utm_medium=ios_app&utm_name=iossmf"
comment = await reddit.comment(url=url)
print(len(comment.replies))
await comment.refresh()
print(len(comment.replies))
await comment.parent()
print(len(comment.replies))

Output:

0
6
0

System Info

  • OS: Mac OS 10.15.6
  • Python: 3.8.5
  • Async PRAW Version: 7.1.0

AttributeError: 'Redditor' object has no attribute 'icon_img'.

Describe the bug
Almost all Submission.author attributes dont work.

To Reproduce
Steps to reproduce the behavior:

  1. Get a sub post using asyncpraw
  2. Try and fetch anything author related except name and a few others.
  3. And it should say "AttributeError: 'Redditor' object has no attribute 'icon_img'. 'Redditor' object has not been fetched, did you forget to execute '.load()'?"

Expected behavior
asyncpraw should properly fetch author (Redditor) attributes.

Code/Logs
subreddit = await reddit.subreddit(config["Reddit"].get("sub_name"))
async for submission in subreddit.stream.submissions(skip_existing=True):
print(submission.author.icon_img)

System Info

  • OS: Windows 10 1809
  • Python: 3.7
  • Async PRAW Version: 7.1.0

New release for stream fix

It would be nice to have a new release for new people installing asyncpraw through pip that patched some of the recent changes. I'm thinking of this issue in particular, which patches the timeout of the stream function. The function is even highlighted through one of the only tutorials in the docs, which will actually experience a similar time out without the patch that was submitted by @cmays90. It has been almost a year since the last release, so many people aren't getting access to these patches, and pulling bleeding-edge versions of the code through a requirements.txt or pip install is inconvenient. I don't know what the current timeline is for the project, but a new release soon would be helpful.

Allow stylesheet.upload() to take a BytesIO object

Describe the solution you'd like

Allow passing of BytesIO objects instead of a str representing the path to the upload= argument.

Describe alternatives you've considered

Current workflow workaround is to write the file to disk first, then pass that file's path to upload.

This is rather counterintuitive though.

Additional context

In my use case, a discord bot, Files are uploaded by subreddit moderators via discord and the /sidebar slash command, and the work flow is currently:

image: Attachment

image.save(os.pathLike('temp'))
stylesheet.upload('sidebar', 'temp')

Which is pretty wasteful

Can't iterate user comments.

I'm getting this error:

asyncprawcore.exceptions.RequestException: error with request Timeout context manager should be used inside a task

When trying to iterate through a user's comments like this:

async def print_comments(username):
    redditor = await reddit.redditor(username)
    #print(redditor.id)

    try:
        redditor.name
    except:
        return -1

    engine = create_async_engine("mysql+aiomysql://xxxx:xxxx@localhost/dbname?charset=utf8mb4")
    async with engine.begin() as conn:
        print("We're going to list comments from "+redditor.name)
        async for comment in redditor.comments.new(limit=None):
            print(comment.body())
.........

The print right before the loop is working fine and shows the redditor username, but the loop is not working...

Also if I try to print the redditor.id as in the commented line I get this other error:
AttributeError: 'Redditor' object has no attribute 'id'. 'Redditor' object has not been fetched, did you forget to execute '.load()'?

Sidebar Fails to Update with subreddit.mod.update(description=x) Coroutine

Describe the bug
Trying to edit a subreddit's sidebar via the subreddit.mod.update() coroutine fails silently.

To Reproduce
Steps to reproduce the behavior:

  1. Create the subreddit object
  2. Call the update coroutine on subreddit moderation with the description parameter
  3. Check subreddit to see that the sidebar hasn't changed.

Expected behavior
The expected behavior is that the sidebar would be updated to the text passed as a parameter. Editing the wiki page at config/sidebar works as a workaround.

Code/Logs

@commands.command(name='edit_sidebar')
async def edit_sidebar_links(self, ctx, post_id: str):
    new_link = f'https://redd.it/{post_id}'
    sub = await self.reddit.subreddit(SUBREDDIT)
    await sub.load()

    description = sub.description
    description = re.sub(r'(?<=\[Meta Thread here\]\().*?(?=\))', new_link, description)
    await sub.mod.update(description=description)

System Info

  • OS: Ubuntu 18.04
  • Python: 3.8.0
  • Async PRAW Version: 7.1.1

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.