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
Marketplace for self published books

Nile API API for the imaginary Nile marketplace for self published books. This is a project created to try out FastAPI as the post promising ASGI serv

Matt de Young 1 Jan 31, 2022
One version package to rule them all, One version package to find them, One version package to bring them all, and in the darkness bind them.

AwesomeVersion One version package to rule them all, One version package to find them, One version package to bring them all, and in the darkness bind

Joakim Sørensen 39 Dec 31, 2022
Drop-in Replacement of pychallonge

pychal Pychal is a drop-in replacement of pychallonge with some extra features and support for new Python versions. Pychal provides python bindings fo

ZED 29 Nov 28, 2022
Based Telegram Bot and Userbot To Play Music in Your Telegram Groups With Some Cool Extra Features! 🥰

CallMusicPlus69 This Repo base on! 🤗️ A CallsMusic Based Telegram Bot and Userbot To Play Music in Your Telegram Groups With Some Cool Extra Features

brut✘⁶⁹ // ユスフ 6 Jun 26, 2022
Replace sequence_IDs in gff3 based on given genome.fasta

gff-rename Replace the sequence IDs in a gff3 file with a set of provided sequence IDs from a genom.fasta. This is useful when a gff3 file is retrieve

tolkit 1 Nov 12, 2021
Shellkg-py - A temporary Repository to rewrite of shellpkg in python

Shellkg-py - A temporary Repository to rewrite of shellpkg in python

2 Jan 26, 2022
pyDuinoCoin is a simple python integration for the DuinoCoin REST API, that allows developers to communicate with DuinoCoin Master Server

PyDuinoCoin PyDuinoCoin is a simple python integration for the DuinoCoin REST API, that allows developers to communicate with DuinoCoin Main Server. I

BackrndSource 6 Jul 14, 2022
🤖 A discord bot for Dota2 community

BOTA BOT-A is a free Discord Dota 2 bot which provides comprehensive Information of every Dota 2 characters and exciting features for the community. P

Bendang 23 Jun 29, 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
Um script simples para consultar dados, com API's simples.

Info sobre o Script Esta é uma das mais simples ferramentas para consultar dados. Daqui um tempo eu farei um UPGRADE no painel, irei adicionar um banc

Crowley 6 Apr 11, 2022
Simple Bot With Python 3.8+ For Converstaion Your Media

Media-Conversation Simple Bot With Python 3.8+ For Converstaion Your Media

Farzin 2 Dec 06, 2021
A Telegram Bot for searching any channel messages from Inline by @AbirHasan2005

Message-Search-Bot A Telegram Bot for searching any channel messages from Inline by @AbirHasan2005. I made this for @AHListBot. You can use this for s

Abir Hasan 44 Dec 27, 2022
Thread-safe Python RabbitMQ Client & Management library

AMQPStorm Thread-safe Python RabbitMQ Client & Management library. Introduction AMQPStorm is a library designed to be consistent, stable and thread-sa

Erik Olof Gunnar Andersson 167 Nov 20, 2022
Automated endpoint management for Amazon Aurora Global Database

This sample code can be used to manage Aurora global database endpoints. After failover the global database writer endpoints swap from one region to the other. This solution automates creation and ma

AWS Samples 13 Dec 08, 2022
Community-based extensions for the python-telegram-bot library.

Community-based extensions for the python-telegram-bot library. Table of contents Introduction Installing Getting help Contributing License Introducti

74 Dec 24, 2022
ABACUS Aroio API for Webinterfaces and App-Connections

ABACUS Aroio API for Webinterfaces and App-Connections Setup Start virtual python environment if you don't have python3 running setup: $ python3 -m ve

Abacus Aroio Developer Team 1 Apr 01, 2021
A Python library to access Instagram's private API.

Instagram Private API A Python wrapper for the Instagram private API with no 3rd party dependencies. Supports both the app and web APIs. Overview I wr

2.6k Jan 05, 2023
Random-backlog-tweet - Pick a page from a sitemap at random and prep a tweet button for it

Random-backlog-tweet - Pick a page from a sitemap at random and prep a tweet button for it

Paul O'Leary McCann 0 Dec 01, 2022
Discovery is an open-source Discord Bot with the main features Tickets, Moderation, Giveaways and Reaction roles.

Discovery is an open-source Discord Bot with the main features Tickets, Moderation, Giveaways and Reaction roles.

1 Dec 29, 2021
Easy Discord Webhook Token Grabber!

Easy Discord Webhook Token Grabber!

†† 27 Jun 01, 2022