A Python Library to interface with Tumblr v2 REST API & OAuth

Overview

Tumblpy

https://pypip.in/d/python-tumblpy/badge.png

Tumblpy is a Python library to help interface with Tumblr v2 REST API & OAuth

Features

  • Retrieve user information and blog information
  • Common Tumblr methods
    • Posting blog posts
    • Unfollowing/following blogs
    • Edit/delete/reblog posts
    • And many more!!
  • Photo Uploading
  • Transparent Python 3 Support!

Installation

Installing Tumbply is simple:

$ pip install python-tumblpy

Usage

Importing

from tumblpy import Tumblpy

Authorization URL

t = Tumblpy(YOUR_CONSUMER_KEY, YOUR_CONSUMER_SECRET)

auth_props = t.get_authentication_tokens(callback_url='http://michaelhelmick.com')
auth_url = auth_props['auth_url']

OAUTH_TOKEN_SECRET = auth_props['oauth_token_secret']

print 'Connect with Tumblr via: %s' % auth_url

Once you click "Allow" be sure that there is a URL set up to handle getting finalized tokens and possibly adding them to your database to use their information at a later date.

Handling the Callback

# OAUTH_TOKEN_SECRET comes from the previous step
# if needed, store those in a session variable or something

# oauth_verifier and OAUTH_TOKEN are found in your callback url querystring
# In Django, you'd do something like
# OAUTH_TOKEN = request.GET.get('oauth_token')
# oauth_verifier = request.GET.get('oauth_verifier')


t = Tumblpy(YOUR_CONSUMER_KEY, YOUR_CONSUMER_SECRET,
            OAUTH_TOKEN, OAUTH_TOKEN_SECRET)

authorized_tokens = t.get_authorized_tokens(oauth_verifier)

final_oauth_token = authorized_tokens['oauth_token']
final_oauth_token_secret = authorized_tokens['oauth_token_secret']

# Save those tokens to the database for a later use?

Getting some User information

# Get the final tokens from the database or wherever you have them stored

t = Tumblpy(YOUR_CONSUMER_KEY, YOUR_CONSUMER_SECRET,
            OAUTH_TOKEN, OAUTH_TOKEN_SECRET)

# Print out the user info, let's get the first blog url...
blog_url = t.post('user/info')
blog_url = blog_url['user']['blogs'][0]['url']

Getting posts from a certain blog

# Assume you are using the blog_url and Tumblpy instance from the previous section
posts = t.get('posts', blog_url=blog_url)
print posts
# or you could use the `posts` method
audio_posts = t.posts(blog_url, 'audio')
print audio_posts
all_posts = t.posts(blog_url)
print all_posts

Creating a post with a photo

# Assume you are using the blog_url and Tumblpy instance from the previous sections

photo = open('/path/to/file/image.png', 'rb')
post = t.post('post', blog_url=blog_url, params={'type':'photo', 'caption': 'Test Caption', 'data': photo})
print post  # returns id if posted successfully

Posting an Edited Photo (This example resizes a photo)

# Assume you are using the blog_url and Tumblpy instance from the previous sections

# Like I said in the previous section, you can pass any object that has a
# read() method

# Assume you are working with a JPEG

from PIL import Image
from StringIO import StringIO

photo = Image.open('/path/to/file/image.jpg')

basewidth = 320
wpercent = (basewidth / float(photo.size[0]))
height = int((float(photo.size[1]) * float(wpercent)))
photo = photo.resize((basewidth, height), Image.ANTIALIAS)

image_io = StringIO.StringIO()
photo.save(image_io, format='JPEG')

image_io.seek(0)

try:
    post = t.post('post', blog_url=blog_url, params={'type':'photo', 'caption': 'Test Caption', 'data': photo})
    print post
except TumblpyError, e:
    # Maybe the file was invalid?
    print e.message

Following a user

# Assume you are using the blog_url and Tumblpy instance from the previous sections
try:
    follow = t.post('user/follow', params={'url': 'tumblpy.tumblr.com'})
except TumblpyError:
    # if the url given in params is not valid,
    # Tumblr will respond with a 404 and Tumblpy will raise a TumblpyError

Get a User Avatar URL (No need for authentication for this method)

t = Tumblpy()
avatar = t.get_avatar_url(blog_url='tumblpy.tumblr.com', size=128)
print avatar['url']

# OR

avatar = t.get('avatar', blog_url='tumblpy.tumblr.com', extra_endpoints=['128'])
print avatar['url']

Catching errors

try:
    t.post('user/info')
except TumbplyError, e:
    print e.message
    print 'Something bad happened :('

Thanks for using Tumblpy!

Comments
  • 0.6.1

    0.6.1

    This changes a few things:

    • Allows for numbers and boolean params to be sent to Tumblr's API.
      • Examples: Under /posts, limit is a Number and reblog_info is a Boolean.
    • Include default_params consisting of the api_key, like before. If not, /posts requests don't work.
    • In the event that the api_key that is sent in the params is wrong/expired, throw an AuthError.
    • Allow the user to manipulate urllib3's maxsize via request's pool_maxsize for multi-threaded applications.
    • Updated t.get_access_token to t.get_authorized_tokens in the README.
    opened by joaquincasares 20
  • Handle empty/ 404 responses

    Handle empty/ 404 responses

    The Tumblr API returns and empty list (and not a dict) in some cases, e. g. if a blog was not found (404). In these case, calling content.get() raises an AttributeError. This commit fixes it.

    Example for a 404 response: http://api.tumblr.com/v2/blog/cocofuckedchanel.tumblr.com/posts/

    opened by mkai 18
  • oauth issue

    oauth issue

    tried to use your python package but got below error...how can i fix this issue?

    Traceback (most recent call last): File "test.py", line 4, in auth_props = t.get_authentication_tokens(callback_url='http://www.xyz.com/somecallbackurl/index.php') File "/opt/.softroot/python-tumblpy/tumblpy/api.py", line 61, in get_authentication_tokens raise TumblpyAuthError('Seems something couldn't be verified with your OAuth junk. Error: %s, Message: %s' % (response.status_code, response.content)) tumblpy.exceptions.TumblpyAuthError: Seems something couldn't be verified with your OAuth junk. Error: 401, Message: oauth_timestamp is too far away; we believe it is now 1390665118, you sent 1390643508, 21610 seconds away

    opened by srinivasuk 8
  • fixed problem with post requests

    fixed problem with post requests

    Post requests didn't include the type parameter, so they would fail. For instance, the example in the readme for posting an image didn't work.

    I'm not sure if this is the best way to solve the problem, but it makes it so I can submit post requests to the api.

    opened by royhodgman 8
  • Posting to secondary blog

    Posting to secondary blog

    Is it possible to use this library to post something to secondary blog?

    I authorized the app and I took a look at Tumblr console where I picked up all the keys from. I have noticed that I can successfully post to my primary blog, but not on secondary (getting {TumblpyError} 404 'There was an error making your request.' error all the time).

    This is my current code:

    from tumblpy import Tumblpy
    
    
    def post_tumblr(
            url,
            comment='',
            tags='',
            **kwargs
    ):
        t = Tumblpy(
            APP_KEY, APP_SECRET,
            OAUTH_TOKEN, OAUTH_TOKEN_SECRET
        )
    
        blog_url = t.post('user/info')
        blog_url = blog_url['user']['blogs'][0]['url']  # POSTING TO PRIMARY BLOG WORKS
        # blog_url = blog_url['user']['blogs'][1]['url']  # CANNOT POST TO SECONDARY BLOG?
    
        post_url = t.post(
            'post',
            blog_url=blog_url,
            params={
                'type': 'video',
                'embed': url,
                'caption': comment,
                'tags': tags,
            }
        )
    
        return True
    
    opened by bomb-on 7
  • Posting error while posting Images.

    Posting error while posting Images.

    'Error: 401, Message: {"meta":{"status":401,"msg":"Not Authorized"},"response":[]}' while posting an image using "data" parameter. I followed your example and that's the error I got. Is this a bug?

    opened by satya10x 7
  • Error 401

    Error 401

    I'm getting the next error everytime I try to post something:

    File "C:\Python27\lib\site-packages\tumblpy.py", line 259, in post extra_endpoints=extra_endpoints, params=params) File "C:\Python27\lib\site-packages\tumblpy.py", line 222, in request raise TumblpyAuthError('Error: %s, Message: %s' % (response.status_code, response.content)) tumblpy.TumblpyAuthError: 'Error: 401, Message: {"meta":{"status":401,"msg":"Not Authorized"},"response":[]}'

    I don't know if is from my code or if is from the library.

    opened by jupazave 7
  • Error making post

    Error making post

    Hello,

    Trying to use the post method for a text post.

    t = Tumblpy(TUMBLR_CONSUMER_KEY, TUMBLR_CONSUMER_SECRET,
                TUMBLR_ACCESS_KEY, TUMBLR_ACCESS_SECRET)
    
            blog_url = t.post('user/info')
            blog_url = blog_url['user']['blogs'][0]['url']
            blog_url = blog_url.replace('http://', '')
            blog_url = blog_url.replace('/', '')
            print(blog_url)
    
            try:
                if image:
                    #Create a photo post using a local filepath
                    post = t.post('post', blog_url=blog_url, params={'type':'photo', 'caption': text, 'data': image})
                elif url:
                    #Create a link post
                    post = t.post('post', blog_url=blog_url, params={'type':'link', 'url': url, 'description': text})
                else:
                    print('im definitely text')
                    #Create a text post
                    post = t.post('post', blog_url=blog_url, params={'type':'text', 'body': text})
            except Exception as e:
                import pdb; pdb.set_trace()
                print(e)
    
            return HttpResponse(status=200)
    

    The text is just a normal string. I'm using Pythin 3.4.

    Error is tumblpy.exceptions.TumblpyError: There was an error making your request. and error_code is 404

    Any ideas why this isn't working? Thanks!

    opened by amanthei 6
  • Fully Converting over to requests_oauthlib

    Fully Converting over to requests_oauthlib

    Everything seems to be working now, though lacking tests, it's hard to know specifically if it's working, but it's working for my follower tracker that I'm working on.

    opened by graysonarts 5
  • Can't Reblog Posts

    Can't Reblog Posts

    Using the following:

    t.post('post/reblog', params={'id':someid,'reblog_key':somereblog_key})
    

    I get:

    Invalid ID or reblog_key specified
    

    I have double checked the reblog key on the post and the id, these are correct, however no matter what I do I get that result, I even built my own module to reblog posts in request_oauthlib!

    opened by agieocean 4
  • Decode fix

    Decode fix

    Fix issues with GET requests in get_authentication_tokens and get_authorized_tokens returns value in bytes and needed to be decoded before response data can be worked with.

    The response.content would return an dict with the keys and values encoded;

    {b'oauth_token': b'Yh...token...EQ', b'oauth_token_secret': b'YH...token...gO', b'oauth_callback_confirmed': b'true'}
    
    opened by wmantly 4
  • Tumblr can return error responses that aren't handled correctly

    Tumblr can return error responses that aren't handled correctly

    It appears that when Tumblr is having issues, error responses can be different than expected.

    I got the error: AttributeError: 'str' object has no attribute 'get'

    Sentry recorded that content was a str instead of a dict. The status code was 504.

    Relevant line: https://github.com/michaelhelmick/python-tumblpy/blob/master/tumblpy/api.py#L165

    It seems like the easiest fix would be to check if the response was a str and if it was, use that for the error_message. Also, in looking at that code, it appears error_message gets written over for every error instead of being appended to. This seems like it could be fixed by ', '.join(content['errors']) instead of the loop.

    If these seems like reasonable fixes, I'm happy to open a PR for them.

    opened by Syfaro 2
Releases(1.1.4)
Owner
Mike Helmick
Mike Helmick
Python based Discord Bot with a simple music player

C32 Discord Bot Discord bot that plays music Table Of Contents About the Project Built With Acknowledgements About The Project Play music using the !p

Christopher Burwell 2 Oct 17, 2021
An API serving data on all creatures, monsters, materials, equipment, and treasure in The Legend of Zelda: Breath of the Wild

Hyrule Compendium API An API serving data on all creatures, monsters, materials, equipment, and treasure in The Legend of Zelda: Breath of the Wild. B

Aarav Borthakur 116 Dec 01, 2022
Python binding for Terraform.

Python libterraform Python binding for Terraform. Installation $ pip install libterraform NOTE Please install version 0.3.1 or above, which solves the

Prodesire 28 Dec 29, 2022
Upload comma-delimited files to biglocalnews.org in your GitHub Action

Upload comma-delimited files to biglocalnews.org in your GitHub Action Inputs api-key: Your biglocalnews.org API token. project-id: The identifier of

biglocalnews 1 Apr 20, 2022
A crashbot for Discord

Description A Effective crash bot code How to use Setup First, we need to install the library: pip install discord or (for linux users): pip3 install

3 Sep 17, 2021
GUI Pancakeswap V2 and Uniswap V3 trading client (and bot) MOST ADVANCE TRADING BOT SUPPORT WINDOWS LINUX MAC (BUY TOKEN ON LAUNCH)

GUI Pancakeswap 2 and Uniswap 3 SNIPER BOT 🏆 🥇 (MOST ADVANCE TRADING BOT SUPPORT WINDOWS LINUX MAC) (AUTO BUY TOKEN ON LAUNCH AFTER ADD LIQUIDITY) S

HYDRA 16 Dec 22, 2021
Documentation and Samples for the Official HN API

Hacker News API Overview In partnership with Firebase, we're making the public Hacker News data available in near real time. Firebase enables easy acc

Y Combinator Hacker News 9.6k Jan 03, 2023
This is a very simple botnet with a CnC server, made by me. Feel free to change anything

This is a very simple botnet with a CnC server, made by me. Feel free to change anything

8 Nov 12, 2022
Access LeetCode problems via id

LCid - access LeetCode problems via id Introduction As a world's leading online programming learning platform, LeetCode is quite popular among program

bunnyxt 14 Oct 08, 2022
:electric_plug: Generating short urls with python has never been easier

pyshorteners A simple URL shortening API wrapper Python library. Installing pip install pyshorteners Documentation https://pyshorteners.readthedocs.i

Ellison 351 Jan 03, 2023
Telegram Link Shortener Bot (With 20 Shorteners)

Telegram ShortenerBot ShortenerBot: 🇬🇧 Telegram Link Shortener Bot (11 + 9 Shorteners) 🇹🇷 Telegram Link Kısaltıcı Bot (11 + 9 Kısaltıcı) All suppo

Hüzünlü Artemis [HuzunluArtemis] 10 May 24, 2022
A powerfull SMS Bomber for Bangladesh . NO limite .Unlimited SMS Spaming

RedBomberBD A powerfull SMS Bomber for Bangladesh . NO limite .Unlimited SMS Spaming Installation Install my-tool on termux by using thoes commands pk

Abdullah Al Redwan 3 Feb 16, 2022
Public Mirror of Team 15's Code and Reports for RBE 3002 B21

RBE3002 Team 15 Lab Repository Team 15's Repository for all code written for RBE 3002 using the Robotis TurtleBot3 Written By Matthew Haahr, Leo Morri

Matthew Haahr 3 Mar 21, 2022
Match-making API for OpenSanctions

OpenSanctions Match-making API This directory contains code and a Docker image for running an API to match data against OpenSanctions. It is intended

OpenSanctions.org 26 Dec 15, 2022
An information scroller Twitter trends, news, weather for raspberry pi and Pimoroni Unicorn Hat Mini and Scroll Phat HD.

uticker An information scroller Twitter trends, news, weather for raspberry pi and Pimoroni Unicorn Hat Mini and Scroll Phat HD. Features include: Twi

Tansu Şenyurt 1 Nov 28, 2021
a small cli to generate AWS Well Architected Reports on the road

well-architected-review This repo intends to publish some scripts related to Well Architected Reviews. war.py extracts in txt & xlsx files all the WAR

4 Mar 18, 2022
Fortnite Dumper for anyone's Save the World profiles.

Anyone's Fortnite Save the World Profile Dumper This program allows you to dump anyone's Fortnite Save the World Profiles. How to use it? After starti

PRO100KatYT 6 Apr 13, 2022
A community made discord bot coded in Python and running on AWS.

Pogbot Project Open Group Discord This is an open source community ran project. Join the discord for more information on how to participate. Coded in

Project Open Group 2 Jul 27, 2022
Powerful Telegram Members Scraping and Adding Toolkit

🔥 Genisys V2.1 Powerful Telegram Members Scraping and Adding Toolkit 🔻 Features 🔺 ADDS IN BULK[by user id, not by username] Scrapes and adds to pub

The Cryptonian 16 Mar 01, 2022
Huan Xu 1.6k Jan 04, 2023