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
Semplice pagina di informazione per sapere se e quando è uscito Joypad, il podcast a tema videoludico di Matteo Bordone (Corri!), Francesco Fossetti (Salta!) e Alessandro Zampini (Spara! per finta).

È uscito Joypad? Semplice pagina di informazione per sapere se e quando è uscito Joypad, il podcast a tema videoludico di Matteo Bordone (Corri!), Fra

Paolo Donadeo 32 Jan 02, 2023
JAKYM, Just Another Konsole YouTube-Music. A command line based Youtube music player written in Python with spotify and youtube playlist support

Just Another Konsole YouTube-Music Overview I wanted to create this application so that I could use the command line to play music easily. I often pla

Mayank Jha 73 Jan 01, 2023
52pojie 吾爱破解论坛 签到 支持云函数/服务器等Py3环境运行

52pojie-Checkin 52pojie 吾爱破解论坛 签到 Py3单程序 支持云函数/服务器等Py3环境运行 只需要Cookie即可运行 新版说明 依赖包请用项目 https://github.com/BlueSkyXN/requirements-serverless 需要填写的参数有 co

BlueSkyXN 22 Sep 15, 2022
Bringing Ethereum Virtual Machine to StarkNet at warp speed!

Warp Warp brings EVM compatible languages to StarkNet, making it possible to transpile Ethereum smart contracts to Cairo, and use them on StarkNet. Ta

Nethermind 700 Dec 26, 2022
Python client for numerbay.ai - the Numerai community marketplace

NumerBay Python API Programmatic interaction with numerbay.ai - the Numerai community marketplace. If you encounter a problem or have suggestions, fee

Numerai Council of Elders 5 Nov 30, 2022
A Telegram Music Bot with proper functions written in Python with Pyrogram and Py-Tgcalls.

⭐️ Yukki Music Bot ⭐️ A Telegram Music Bot written in Python using Pyrogram and Py-Tgcalls Ready to use method A Support Group and ready-to-use runnin

Shikhar Kumar 1000 Jan 03, 2023
This is a Telegram Bot that tracks packages from the Brazilian Mail Service.

RastreioBot About Setup Run Contribute Contact About This is a Telegram Bot that tracks packages from the Brazilian Mail Service. It runs on Python 3

Gabriel R F 320 Dec 22, 2022
A Telegram Bot which notifies the user when a vaccine is available on CoWin Platform.

Cowin Vaccine Availability Notifier Telegram Bot A bot that notifies the available vaccines at given district in realtime. Introduction • Requirements

Arham Shah 7 Jul 31, 2021
A multifunctional bot for Discord

Um bot multifuncional e divertido para Discord Estive desenvolvendo o BotDaora desde o começo de outubro de 2021 e agora ele é open-source! tomei essa

Ruan 4 Dec 28, 2021
A telegram bot script for generating session string using pyrogram and telethon on Telegram bot

String-session-Bot Telegram Bot to generate Pyrogram and Telethon String Session. A star ⭐ from you means a lot to us! Usage Deploy to Heroku Tap on a

Wahyusaputra 8 Oct 28, 2022
Flask extension that provides integration with Azure Storage

Flask-Azure-Storage A Flask extension that provides integration with Azure Storage Table of Contents Flask-Azure-Storage Install Usage Examples Create

Alejo Arias 17 Nov 14, 2021
Asynchronous wrapper for wttr.in weather forecast.

aiopywttr Asynchronous wrapper for wttr.in weather forecast. Synchronous version here. Installation pip install aiopywttr Example This example prints

Almaz 4 Dec 24, 2022
Advanced telegram link in a message attach bot

Attach-Bot-V2 An advanced telegram attach bot Made with Python3 (C) @FayasNoushad Copyright permission under MIT License License - https://github.com

Fayas Noushad 8 Oct 21, 2022
A python package to fetch results of various national examinations done in Tanzania.

Necta-API Get a formated data of examination results scrapped from necta results website. Note this is not an official NECTA API and is still in devel

vincent laizer 16 Dec 23, 2022
A telegram bot that messages you available vaccine appointments in the Veneto region

Serenissimo, domande frequenti Chi sei? Sono Alberto Granzotto, libero professionista a Berlino. Mi occupo di servizi software, privacy, decentralizza

vrde 31 Sep 30, 2022
Ap lokit lokit

🎵 FANDA MUSIC BOT Fanda Music adalah proyek bot telegram yang memungkinkan Anda memutar musik di obrolan suara grup telegram. a href="https://www.py

Fatur 2 Nov 18, 2021
Rock API is an API that allows you to view rocks and find the ratings on them

Rock API The best Rock API What is Rock API? Rock API is an API that allows you to view rocks and find the ratings on them. However, this isn't a regu

Conos 21 Sep 21, 2022
Information about the weather in a city written using Python

Information about the weather in a city Enter the desired city Climate information of the target city This program is written using Python programming

Amir Hussein Sharifnezhad 4 Nov 17, 2021
Python SDK for the Buycoins API.

This library provides easy access to the Buycoins API using the Python programming language. It provides all the feature of the API so that you don't need to interact with the API directly. This libr

Musa Rasheed 48 May 04, 2022
A python to scratch API connector. Can fetch data from the API and send it back in cloud variables.

Scratch2py Scratch2py or S2py is a easy to use, versatile tool to communicate with the Scratch API Based of scratchclient by Raihan142857 Installation

20 Jun 18, 2022