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
Automatically updates the twitter banner with the images of 5 latest followers, using tweepy python

Auto twitter banner Automatically updates the twitter banner every few seconds with follower profile pics on it Here's how it looks! Installation git

Dhravya Shah 7 Jul 04, 2022
A Telegram bot for personal utilities

Aqua Aqua is a Telegram bot for personal utilities. Installation Prerequisites: Install Poetry for managing dependencies and fork/clone the repository

Guilherme Vasconcelos 2 Mar 30, 2022
Gnosis-py includes a set of libraries to work with Ethereum and Gnosis projects

Gnosis-py Gnosis-py includes a set of libraries to work with Ethereum and Gnosis projects: EthereumClient, a wrapper over Web3.py Web3 client includin

Gnosis 93 Dec 23, 2022
Pdisk Uploader Bot

pdisk-bot pdisk uploader telegram bot How To Use Configs TG_BOT_TOKEN - Get bot token from @BotFather API_ID - From my.telegram.org API_HASH - From my

lokaman chendekar 25 Oct 21, 2022
For specific function. For my own convenience. Remind owner to share data to another DITO user.

For specific function. For my own convenience. Remind owner to share data to another DITO user.

Meigo 1 Dec 14, 2021
Image Tooᥣs Bot I specialize for logo design Services with Amazing logo Creator Platform and more tools

Image Tooᥣs Bot I specialize for logo design Services with Amazing logo Creator Platform and more tools

Sz Team Bots <sz/>✌️ 10 Oct 21, 2022
LimitatiBot - A simple telegram bot to establish a conversation with a user without having to use private chats

🤖 LimitatiBot [0.2] LimitatiBot is a simple telegram bot to establish a convers

xMrPente 9 Dec 27, 2022
Latest Open Source Code for Playing Music in Telegram Video Chat. Made with Pyrogram and Pytgcalls 💖

MusicPlayer_TG Latest Open Source Code for Playing Music in Telegram Video Chat. Made with Pyrogram and Pytgcalls 💖 Requirements 📝 FFmpeg NodeJS nod

Abhijith Sudhakaran 2 Feb 04, 2022
Telegram Reporter

[Telegram Reporter v.3 ] 🇮🇷 AliCybeRR 🇮🇷 [ AliCybeRR.Reporter feature ] Login Your Telegram account 👽 support Termux ❕ No Limits ⚡ Secure 🔐 Free

AliCybeRR 1 Jun 08, 2022
Desafio de projeto sobre Git/Github

Maçã ou Laranja? 🤔 Desafio Projeto Dio para Git/Github 🔶 Para esse primeiro repositório, decidir adicionar o primeiro algoritmo de inteligência arti

José Filipe 2 Oct 23, 2022
Python based Spotify account generator.

Spotify Account Generator Python based Spotify account generator. Installation Download the latest release, open command prompt in the folder, run pip

polo 5 Dec 27, 2022
Discord music bot using discord.py, slash commands, and yt-dlp.

bop Discord music bot using discord.py, slash commands, and yt-dlp. Features Play music from YouTube videos and playlists Queue system with shuffle Sk

Hizkia Felix 3 Aug 11, 2022
An Unofficial API for 1337x, Piratebay, Nyaasi, Torlock, Torrent Galaxy, Zooqle, Kickass, Bitsearch, and MagnetDL

An Unofficial API for 1337x, Piratebay, Nyaasi, Torlock, Torrent Galaxy, Zooqle, Kickass, Bitsearch, and MagnetDL

Neeraj Kumar 130 Dec 27, 2022
QuickStart specific rules for cfn-python-lint

AWS Quick Start cfn-lint rules This repo provides CloudFormation linting rules specific to AWS Quick Start guidelines, for more information see the Co

AWS Quick Start 12 Jul 30, 2022
A Telegram Video Merge Bot by @AbirHasan2005

VideoMerge-Bot This is very simple Telegram Videos Merge Bot by @AbirHasan2005. Using FFmpeg for Merging Videos. Features: Merge Multiple Videos. User

Abir Hasan 57 Nov 12, 2022
Simple contact bot for telegram, written in python.

🔗 | Install Install the requirements with pip install -r requirements.txt 📋 | Setup Get your token from BotFather Get your UserId with Nicegram or w

Stehack 3 Dec 10, 2022
Tubee is a web application, which runs actions when your subscribed channel upload new videos

Tubee is a web application, which runs actions when your subscribed channel upload new videos, think of it as a better IFTTT but built specifically for YouTube with many enhancements.

Tomy Hsieh 11 Jan 01, 2023
This is a python wrapper for "the best api in the world"

This is a python wrapper for my api api_url = "https://api.dhravya.me/" This wrapper now has async support, its basically the same except it uses asyn

Dhravya Shah 3 Dec 21, 2021
Easy to use API Wrapper for somerandomapi.ml.

Overview somerandomapi is an API Wrapper for some-random-api.ml Examples Asynchronous from somerandomapi import Animal import asyncio async def main

Myxi 1 Dec 31, 2021
Deploy a STAC API and a dynamic mosaic tiler API using AWS CDK.

Earth Observation API Deploy a STAC API and a dynamic mosaic tiler API using AWS CDK.

Development Seed 39 Oct 30, 2022