The simple way of using Imgur.

Overview

PyImgur

The simple way of using Imgur.

You can upload images, download images, read comments, update your albums, message people and more. In fact, you can do almost everything via PyImgur that you can via the webend.

Installation

The recommended way to install is via pip

$ pip install pyimgur

Getting Started

Before we can start using PyImgur, we need to register our application with Imgur. This way, Imgur can see what each application is doing on their site. Go to https://api.imgur.com/oauth2/addclient to register your client. Note that you can't use an application registration for the old v2 version of the Imgur API, which was depreciated December 2012.

When we registered our application we got a client_id and a client_secret. The client_secret is used for authenticating as a user, if we just need access to public or anonymous resources, then we can leave it out. For our first example we're going to get some information about an image already uploaded to image:

import pyimgur
CLIENT_ID = "Your_applications_client_id"
im = pyimgur.Imgur(CLIENT_ID)
image = im.get_image('S1jmapR')
print(image.title) # Cat Ying & Yang
print(image.link) # http://imgur.com/S1jmapR.jpg

The Imgur object keeps the authentication information, changes authentication and is the common way to get objects from Imgur.

Uploading an Image

Let's use another example to show how to upload an image:

import pyimgur

CLIENT_ID = "Your_applications_client_id"
PATH = "A Filepath to an image on your computer"

im = pyimgur.Imgur(CLIENT_ID)
uploaded_image = im.upload_image(PATH, title="Uploaded with PyImgur")
print(uploaded_image.title)
print(uploaded_image.link)
print(uploaded_image.size)
print(uploaded_image.type)

Some methods here one or more arguments with the default value None. For methods modifying existing objects, this mean to keep the already existing value. For methods not modifying existing objects, this mean to use the Imgur default.

Lazy objects

To reduce the load on Imgur, PyImgur only requests the data it needs. This means each object has the attribute _has_fetched which if True` has fetched all the data it can, if False it can fetch more information.

Whenever we request an attribute that hasn't been loaded the newest information will be requested from Imgur and all the object attributes will be updated to the newest values. We can also use the method refresh() to force a call to Imgur, that will update the object with the latest values:

import pyimgur
CLIENT_ID = "Your_applications_client_id"
im = pyimgur.Imgur(CLIENT_ID)
gallery_image = im.get_gallery_image('JiAaT')
author = gallery_image.author
print(author._has_fetched) # False ie. it's a lazily loaded object
print(author.reputation)
print(author._has_fetched) # True ie. all values have now been retrieved.

Introspection

Remember that as usual you can use the dir, vars and help builtin functions to introspect objects to learn more about them and how they work.

Mashape API

Imgur supports commercial use via Mashape, which uses a different endpoint and some additional authentication. You can enable this easily by providing your Mashape key on initialization of the Imgur object:

import pyimgur
CLIENT_ID = "Your_applications_client_id"
MASHAPE_KEY = "Your_mashape_api_key"
im = pyimgur.Imgur(CLIENT_ID, mashape_key=MASHAPE_KEY)

More information on Mashape's API and Pricing can be found on the Mashape website.

Support

If you find an bug, have any questions about how to use PyImgur or have suggestions for improvements then feel free to file an issue on the Github project page.

Documentation

PyImgur's full documentation is located on ReadTheDocs.

License

All of the code contained here is licensed by the GNU GPLv3.

Comments
  • pip install errors on Linux

    pip install errors on Linux

    Just opening this as a clean issue thread. Problem is that PyImgur package can not be installed on Linux through PyPI.

    Full debug is as follows.

    (env)james@blackbox:/tmp/test$ pip install pyimgur-0.3.2.tar.gz --verbose
    Unpacking ./pyimgur-0.3.2.tar.gz
      Running setup.py egg_info for package from file:///tmp/test/pyimgur-0.3.2.tar.gz
        Traceback (most recent call last):
          File "<string>", line 14, in <module>
          File "/tmp/pip-t98d8G-build/setup.py", line 10, in <module>
            INIT = open(os.path.join(HERE, PACKAGE_NAME, '__init__.py')).read()
        IOError: [Errno 2] No such file or directory: '/tmp/pip-t98d8G-build/pyimgur/__init__.py'
        Complete output from command python setup.py egg_info:
        Traceback (most recent call last):
    
      File "<string>", line 14, in <module>
    
      File "/tmp/pip-t98d8G-build/setup.py", line 10, in <module>
    
        INIT = open(os.path.join(HERE, PACKAGE_NAME, '__init__.py')).read()
    
    IOError: [Errno 2] No such file or directory: '/tmp/pip-t98d8G-build/pyimgur/__init__.py'
    
    ----------------------------------------
    Command python setup.py egg_info failed with error code 1 in /tmp/pip-t98d8G-build
    Exception information:
    Traceback (most recent call last):
      File "/tmp/test/env/lib/python2.7/site-packages/pip-1.1-py2.7.egg/pip/basecommand.py", line 104, in main
        status = self.run(options, args)
      File "/tmp/test/env/lib/python2.7/site-packages/pip-1.1-py2.7.egg/pip/commands/install.py", line 245, in run
        requirement_set.prepare_files(finder, force_root_egg_info=self.bundle, bundle=self.bundle)
      File "/tmp/test/env/lib/python2.7/site-packages/pip-1.1-py2.7.egg/pip/req.py", line 1009, in prepare_files
        req_to_install.run_egg_info()
      File "/tmp/test/env/lib/python2.7/site-packages/pip-1.1-py2.7.egg/pip/req.py", line 225, in run_egg_info
        command_desc='python setup.py egg_info')
      File "/tmp/test/env/lib/python2.7/site-packages/pip-1.1-py2.7.egg/pip/__init__.py", line 256, in call_subprocess
        % (command_desc, proc.returncode, cwd))
    InstallationError: Command python setup.py egg_info failed with error code 1 in /tmp/pip-t98d8G-build
    

    pip.log contains the same info. Some previous discussion is here #5

    opened by jamescooke 13
  • Fetching title and link based on ID.

    Fetching title and link based on ID.

    Hello, I'm currently writing a little script that will pull imgur links from a IRC channel and store them in a database. I would also like to print the title to the channel.

    Problem is, imgur's IDs are pretty ambiguous. An ID can represent several things: a image, an album, a gallery, a picture in a gallery or even a gallery album. It seems like you can go to imgur.com/[id here] and it will happily show you whatever thing that exists on that ID, whether it's an album, a image and so on.

    So, apart from doing multiple try/except blocks to get the title and link (which are the only things I'm interested in), are there any nice ways of doing this with PyImgur? It would be terrific if I could just do one request that would get all the things that IDs may have in common, where title and link is from what I gather among those.

    opened by ToJa92 7
  • get_subreddit_gallery raising 404

    get_subreddit_gallery raising 404

    This snippet of code: picgallery = im.get_subreddit_gallery("pics") is raising this error: requests.exceptions.HTTPError: 404 Client Error: Not Found

    I'm following the documentation perfectly, so I'm puzzled as to why this isn't working.

    opened by lukepfjo 4
  • PyPI package broken

    PyPI package broken

    The source of __ init __.py served from https://pypi.python.org/packages/source/p/pyimgur/pyimgur-0.5.2.tar.gz is different than the source from here. In the package from PyPI is a bug that doesn't let me fetch a gallery.

    opened by screendriver 3
  • Attribute Error

    Attribute Error

    I'm trying the basic example to upload a picture to imgur, but whenever I get to the attributes like data, url, link, i get AttributeError: Image instance has no attribute 'date'.

    Here is the code I have

    import pyimgur
    CLIENT_ID = ""
    PATH = "/Users/jacksongeller/Desktop/imgur/sample.png"
    
    
    
    
    im = pyimgur.Imgur(CLIENT_ID)
    uploaded_image = im.upload_image(PATH, title="Uploaded with PyImgur")
    print(uploaded_image.title)
    print(uploaded_image.date)
    print(uploaded_image.url)
    print(uploaded_image.link)
    

    here is the error

    $ python main.py
    Uploaded with PyImgur
    Traceback (most recent call last):
      File "main.py", line 11, in <module>
        print(uploaded_image.date)
      File "/Library/Python/2.7/site-packages/pyimgur/__init__.py", line 70, in __getattr__
        (type(self).__name__, attribute))
    AttributeError: Image instance has no attribute 'date'
    

    Am I missing something basic? or a syntax error? I cannot seem to figure it out. Thanks in advance. great module by the way

    opened by jaxgeller 3
  • b64encode, image_upload input

    b64encode, image_upload input

    There is actually no need to encode an image into b64, it will increase the picture size.

    I've added new argument to upload_image funtion, to directly push an image without opening a file

    patch: http://paste.org/66501

    opened by ghost 3
  • An issue when importing the library

    An issue when importing the library

      File "C:\Users\Jason\Documents\Programming\e-card-websocket\socket.py", line 4, in <module>
        from pyimgur import Imgur
      File "C:\Users\Jason\AppData\Local\Programs\Python\Python36\lib\site-packages\pyimgur\__init__.py", line 45, in <module>
        import requests  # NOQA
      File "C:\Users\Jason\AppData\Local\Programs\Python\Python36\lib\site-packages\requests\__init__.py", line 43, in <module>
        import urllib3
      File "C:\Users\Jason\AppData\Local\Programs\Python\Python36\lib\site-packages\urllib3\__init__.py", line 8, in <module>
        from .connectionpool import (
      File "C:\Users\Jason\AppData\Local\Programs\Python\Python36\lib\site-packages\urllib3\connectionpool.py", line 7, in <module>
        from socket import error as SocketError, timeout as SocketTimeout
    ImportError: cannot import name 'error'
    

    I get this. I don't know how to fix it.

    opened by SharpBit 2
  • 400 Status Code

    400 Status Code

    I keep getting a 400 error, with the following code:

    img = pyimgur.upload_image('screenshot.png', title='Screenshot', api_key='76c8c84eaa7c685')
    

    It says when parameters are out of bounds or image upload fails, but I manually uploaded the exact image and it worked fine. Not sure what is going on.

    opened by shannonrothe 2
  • Can't add images to an anonymous album using delete hashes.

    Can't add images to an anonymous album using delete hashes.

    Hello, I'm trying to add some images to an album anonymously, using the images delete hashes. Since I'm doing this without the use of an account, I have no need to authenticate with an access code, and therefore can't add these images. Can checks be added to see if the user is doing things anonymously, because this is really breaking my project.

    opened by Aidgigi 1
  • pyimgur.__init__.User.getalbums() and getImages() returns 400

    pyimgur.__init__.User.getalbums() and getImages() returns 400

    I am trying to access all albums from my authenticated user as below(python=2.7). Other pyimgur.User methods such as get_statistics() ran without issue.

    import pyimgur
    
    CLIENT_ID = "**********"
    CLIENT_SECRET = "****************"  
    
    im = pyimgur.Imgur(CLIENT_ID, CLIENT_SECRET, refresh_token="***********")
    im.refresh_access_token()
    #album=im.create_album("An authorized album", "Cool stuff!")
    user=im.get_user("************")
    print(user)
    print(user.get_images())
    
    
    Traceback (most recent call last):
      File "main.py", line 15, in <module>
        print(user.get_images())  File "/home/runner/.local/share/virtualenvs/python2/lib/python2.7/site-packages/pyimgur/__init__.py", line 1347, in get_images
        resp = self._imgur._send_request(url, limit=limit)  File "/home/runner/.local/share/virtualenvs/python2/lib/python2.7/site-packages/pyimgur/__init__.py", line 731, in _send_request
        result = request.send_request(url, verify=self.verify, **kwargs)  File "/home/runner/.local/share/virtualenvs/python2/lib/python2.7/site-packages/pyimgur/request.py", line 102, in send_request
        resp.raise_for_status()  File "/home/runner/.local/share/virtualenvs/python2/lib/python2.7/site-packages/requests/models.py", line 940, in raise_for_status
        raise HTTPError(http_error_msg, response=self)requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://api.imgur.com/3/account/NeverLucky135/images/%7B%7D
    
    
    opened by hzhou0 1
  • How do I get a user's notification?

    How do I get a user's notification?

    I got client_id, client_secret, access_token, and refresh_token just fine. Other user functions like user.name or user.get_comments() etc work fine but when I call user.get_notifications() it throws this error File "/Library/Python/2.7/site-packages/pyimgur/__init__.py", line 1353, in get_notifications com_dict in resp['replies']] UnboundLocalError: local variable 'msg_dict' referenced before assignment

    opened by 8bitgentleman 1
  • Commercial Usage now requires RapidAPI Key, not Mashape_Key

    Commercial Usage now requires RapidAPI Key, not Mashape_Key

    I am trying to use this API for commercial usage, so I followed the steps in the readme.md: https://github.com/Damgaard/PyImgur#mashape-api

    I then get this error: HTTPSConnectionPool(host='imgur-apiv3.p.mashape.com', port=443): Max retries exceeded with url: /3/image (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f7cb9afb430>: Failed to establish a new connection: [Errno -2] Name or service not known'))

    The problem is occurring because imgur switched from using mashape to using rapidapi for commercial usage (see new docs here

    The solution is to replace the endpoint with imgur-apiv3.p.rapidapi.com and the mashape_key with the X-RapidAPI-Key.

    opened by jbh2155 0
  • "Invalid client_id"

    Potentially I'm just being dumb, but I'm running into this weird situation where the PyImgur is able to upload 2 or so images and then it starts complaining that I have the wrong client ID. I tried slowing it down thinking I was hitting Imgur's API limit, but even at 10 second delays, it still pops up. I don't see any warning from Imgur that my client ID is bad, so I'm not sure what's going on...

    Traceback (most recent call last): File "", line 76, in main() File "", line 70, in main link = ImgurBatch(files) File "", line 57, in ImgurBatch links.append(imgurupload(item)) File "", line 24, in imgurupload uploaded_image = im.upload_image(PATH, title="") File "C:\Users\Bram\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pyimgur_init_.py", line 1150, in upload_image resp = self._send_request(self.base_url + "/3/image", File "C:\Users\Bram\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pyimgur_init.py", line 731, in _send_request result = request.send_request(url, verify=self.verify, **kwargs) File "C:\Users\Bram\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pyimgur\request.py", line 102, in send_request resp.raise_for_status() File "C:\Users\Bram\AppData\Local\Programs\Python\Python38-32\lib\site-packages\requests\models.py", line 941, in raise_for_status raise HTTPError(http_error_msg, response=self) requests.exceptions.HTTPError: 403 Client Error: Permission Denied for url: https://api.imgur.com/3/image

    opened by bramnet 2
  • Replace printing exception with actual exception

    Replace printing exception with actual exception

    Really makes no sense to have in here. Makes it impossible for me to catch rate limit/file size errors. Additionally breaks my curses screen and forces me to restart the program.

    Using an Exception here instead of print makes it possible to catch the error, and to be honest just makes more sense.

    Fixes Issue #19

    opened by CalicoCatalyst 0
  • Page number parameter for get_subreddit_gallery

    Page number parameter for get_subreddit_gallery

    In Imgur's documentation, you are able to specify the an integer that represents the number of the paginated gallery. PyImgur does not offer an argument for the page number, and I'm in need of this functionality at the moment.

    https://api.imgur.com/endpoints/gallery#subreddit

    Perhaps update the function like so:

    def get_subreddit_gallery(self, subreddit, sort='time', window='top',
                                limit=None, page=0):
        """
        Return a list of gallery albums/images submitted to a subreddit.
        A subreddit is a subsection of the website www.reddit.com, where users
        can, among other things, post images.
        :param subreddit: A valid subreddit name.
        :param sort: time | top - defaults to top.
        :param window: Change the date range of the request if the section is
            "top", day | week | month | year | all, defaults to day.
        :param limit: The number of items to return.
        :param page: The page number of the gallery
        """
        url = (self._base_url + "/3/gallery/r/{0}/{1}/{2}/{3}".format(
                subreddit, sort, window, page))
        resp = self._send_request(url, limit=limit)
        return [_get_album_or_image(thing, self) for thing in resp]
    
    opened by alexwohlbruck 0
Owner
Andreas Damgaard Pedersen
Andreas Damgaard Pedersen
A simple way to create a request to the coinpayment API with a valid HMAC using your private key and command

Coinpayments Verify TXID Created for Astral Discord bot A simple way to create a request to the coinpayment API with a valid HMAC using your private k

HellSec 1 Nov 7, 2022
A simple Telegram bot which handles images in whole different way

zeroimagebot thezeroimagebot ?? I Can Edit Dimension Of An image which is required by @stickers ?? I Can Extract Text From An Image ?? !!! New Updates

RAVEEN KUMAR 4 Jul 1, 2021
Fairstructure - Structure your data in a FAIR way using google sheets or TSVs

Fairstructure - Structure your data in a FAIR way using google sheets or TSVs. These are then converted to LinkML, and from there other formats

Linked data Modeling Language 23 Dec 1, 2022
Python JIRA Library is the easiest way to automate JIRA. Support for py27 was dropped on 2019-10-14, do not raise bugs related to it.

Jira Python Library This library eases the use of the Jira REST API from Python and it has been used in production for years. As this is an open-sourc

PyContribs 1.7k Jan 6, 2023
Easy way to use Telegram bot to hide your identity.

telegram-support-bot Easy way to use Telegram bot to hide your identity. Useful for support, anonymous channel management. Free clone of Livegram Bot.

Daniil Okhlopkov 197 Dec 23, 2022
A Python Client to View F1TV Content the right way

F1Hub is a terminal application running directly on your computer -- no connection to the website needed* *In theory. As of now, the F1TV website is needed for some content

kodos 3 Jun 14, 2022
Python linting made easy. Also a casual yet honorific way to address individuals who have entered an organization prior to you.

pysen What is pysen? pysen aims to provide a unified platform to configure and run day-to-day development tools. We envision the following scenarios i

Preferred Networks, Inc. 452 Jan 5, 2023
A really easy way to display your spotify listening status on spotify.

Spotify playing README A really easy way to display your spotify listening status on READMEs and Websites too! Demo Here's the embed from the site. Cu

Sunrit Jana 21 Nov 6, 2022
A way to export your saved reddit posts to a Notion table.

reddit-saved-to-notion A way to export your saved reddit posts and comments to a Notion table.Uses notion-sdk-py and praw for interacting with Notion

null 19 Sep 12, 2022
Manage AWS Secrets the easy way

AWStanding Easily load variables from AWS Parameter store into environment variables. Why to AWStanding? Because it handles AWS pagination so the amou

Juan Ignacio Sánchez Sampayo 13 Dec 30, 2022
A library that revolutionizes the way people interact with NextDNS.

NextDNS-API An awesome way to interface with your NextDNS account - via Python! Explore the docs » Report Bug . Request Feature Table Of Contents Abou

null 34 Dec 7, 2022
A python script to acquire multiple aws ec2 instances in a forensically sound-ish way

acquire_ec2.py The script acquire_ec2.py is used to automatically acquire AWS EC2 instances. The script needs to be run on an EC2 instance in the same

Deutsche Telekom Security GmbH 31 Sep 10, 2022
The easiest way to deploy this Bot

How To Host The easiest way to deploy this Bot Update Channe

Isekai Reszz 1 Jan 23, 2022
A quick way to verify your Climate Hack.AI (2022) submission locally!

Climate Hack.AI (2022) Submission Validator This repository contains code that allows you to quickly validate your Climate Hack.AI (2022) submission l

Jeremy 3 Mar 3, 2022
Simple-nft-tutorial - A simple tutorial on making nft/memecoins on algorand

nft/memecoin Tutorial on Algorand Let's make a simple NFT/memecoin on the Algora

null 2 Feb 5, 2022
A simple Python script using Telethon to log all (or some) messages a user or bot account can see on Telegram.

telegram-logger A simple Python script using Telethon to log all (or some) messages a user or bot account can see on Telegram. Requirements Python 3.6

Richard 13 Oct 6, 2022
A simple waybar module to display the status of the ICE you are currently in using the ICE Portals JSON API.

waybar-iceportal A simple waybar module to display the status of the ICE you are currently in using the ICE Portals JSON API. Installation Ensure pyth

Moritz 7 Aug 26, 2022
Simple script to ban bots at Twitch chats using a text file as a source.

AUTOBAN ???? English version Simple script to ban bots at Twitch chats using a text file as a source. How to use Windows Go to releases for further in

And Paiva 5 Feb 6, 2022
A simple anti-ghostping python bot made using diskord.

Anti Ghostping A simple Anti-Ghostping python bot made with ❤ using Diskord Requirements No one will use this but, all you need for this bot is: Pytho

RyZe 2 Sep 12, 2022