def get_client(appinfo, authinfo): client = TumblrRestClient( appinfo.consumer_key, appinfo.consumer_secret, authinfo.token, authinfo.secret ) user = client.info().get('user') logger.debug( 'connect to account %s with %d followings and %d likes', user.get('name'), user.get('following'), user.get('likes') ) return client
class TumblrClient: def __init__(self, **kwargs): self.client = TumblrRestClient(**kwargs) self.dummy = { 'likes': { 'liked_posts': [] }, 'following': { 'blogs': [] }, 'posts': { 'total_posts': 0, 'posts': [] } } def info(self): return self.client.info() def posts(self, **kwargs): retry = MAX_RETRY while retry: try: return self.client.posts(**kwargs) except RequestException: retry -= 1 return self.dummy['posts'] def following(self, **kwargs): retry = MAX_RETRY while retry: try: return self.client.following(**kwargs) except RequestException: retry -= 1 return self.dummy['following'] def likes(self, **kwargs): retry = MAX_RETRY while retry: try: return self.client.likes(**kwargs) except RequestException: retry -= 1 return self.dummy['likes']
class Blog(object): def __init__(self, conf): self.log = getLogger(__name__) self.conf = conf self.__info = None self.client = TumblrRestClient(self.conf.tumblr_consumer_key, self.conf.tumblr_consumer_secret, self.conf.tumblr_oauth_token, self.conf.tumblr_oauth_secret) self.log.debug('%s init done', __name__) @property def info(self): if self.__info is None: self.log.debug('request blog info for "%s"', self.conf.tumblr_blog_name) self.__info = [ blog for blog in self.client.info()['user']['blogs'] if blog['name'] == self.conf.tumblr_blog_name ][-1] return self.__info def log_post(self, post, text): self.log.info('\n '.join([ 'tumblr post ->', text, '\n', pformat(post.get('posts')), ])) def post_photo(self, source, *, title, caption, public, tags=[]): post = self.client.create_photo( self.info['name'], caption=caption, format='markdown', slug=title, source=source, state=('published' if public else 'draft'), tags=tags) self.log_post(post, 'photo') return self.client.posts(self.info['name'], id=post['id']).get('posts', [None])[0] def post_video(self, embed, *, title, caption, public, tags=[]): post = self.client.create_video( self.info['name'], caption=caption, embed=embed, format='markdown', slug=title, state=('published' if public else 'draft'), tags=tags) self.log_post(post, 'video') return self.client.posts(self.info['name'], id=post['id']).get('posts', [None])[0] def pull_photos(self): for offset in range(0, self.info['total_posts'], 20): for post in self.client.posts(self.info['name'], type='photo', offset=offset, limit=20)['posts']: yield post
Username: {blog_name} Date: {date} Post type: {type} :: {title} :: {body} Tags: {tags} Notes: {note_count} URL: {post_url} """ for i in query.execute("$.posts"): print(post.format(**i)) client = TumblrRestClient( consumer_key='iWpkjxQeBaFBpIvHTB0RbP7G5ozicNZ5FQtiMkkoKFkiJ4Cfjb', consumer_secret='JfmKt6EJWOPdNs155kBrVC7AC8YO3V9RVJt73PcuU85E7buGsq', oauth_token='ZoegVG4B9pTAFm3lI86bSueW8KVlr0PKOkxNsh4CqmwIMnLRcE', oauth_secret='AkuR2qM8QNvEm62dQ8JbldxYicQJMvpxdOhfBQPALgsBWLrc7G', ) dashboard = client.dashboard(type="text") query = Query(dashboard) user_info = client.info() print("--- Welcome to the InstaCommander prototype. ---\n") print("-"*15, "\nStart using the `client` object\n", "\n", "username:"******"\n", "url:", user_info['user']['blogs'][0]['url']) show_dashboard()
class Queues(): #Either blog name or url def __init__(self, *args): self.api = TumblrRestClient(tumblrLogin["consumerkey"], tumblrLogin["consumersecret"], tumblrLogin["oauthtoken"], tumblrLogin["oauthtokensecret"]) self.clientInfo = self.api.info() self.blogs = self.clientInfo['user']['blogs'] for arg in args: if arg.find("http", 0, len(arg)) != -1: self.blog = self.findBlog(arg, True) else: self.blog = self.findBlog(arg, False) self.queue = [] self.batch = [] self.state = "draft" self.number = 0 self.name = "" def findBlog(self, arg, url): blogNumber = 0 read = True while read == True: try: if url: if self.blogs[blogNumber]['url'] == arg: return self.blogs[blogNumber]['name'] else: if self.blogs[blogNumber]['name'] == arg: return self.blogs[blogNumber]['name'] blogNumber = blogNumber + 1 except IndexError: read = False print("Blog not found, check your URL or name") #Add CSV to queue def csvQueue(self, csvFile): with open(csvFile, newline='', encoding='utf-8') as csvfile: reader = reader(csvfile, delimiter=',', quotechar='|') for row in reader: if row == "": print("Skipping Empty Row") else: self.addImages(row[0]) self.numberImages = self.numberImages + 1 def addImages(self, overwrite=False, *args, **kwargs): for arg in args: if isinstance(arg, pixivImage): if overwrite: self.queue = [arg] else: self.queue.append(arg) for kwarg in kwargs.keys(): self.csvQueue(kwargs[kwarg]) #Adds caption text, or keyworded text to be added when posted def link(self, text, link): return "<a href={}>{}</a>".format(link, text) #Takes dictionary or csv as {"trigger":"Tag to be added when triggered"} def tagTriggers( self, triggers, csv=False, overwrite=False, batch=None, ): tempTags = [] if batch == None: batch = self.queue if csv: with open(triggers, newline='', encoding='utf-8') as csvfile: csvReader = reader(csvfile, delimiter=',', quotechar='|') triggers = {} for row in csvReader: triggers[row[0]] = row[1] for image in batch: image.importIllustJSON() totaltags = image.tags for tag in image.userTags: totaltags.append(tag) for trigger in triggers.keys(): for tag in totaltags: if trigger == tag: tempTags.append(triggers[tag]) if overwrite: image.setCustomTags(tempTags) else: for tag in image.userTags: tempTags.append(tag) image.setCustomTags(tempTags) #Adds default caption def addCaption(self): for image in self.queue: image.setCaption("{} by {}".format( self.link(image.title, image.URL), self.link(image.name, image.user_URL))) def formatCaptions(self, text, *args): caption_format = args for image in self.queue: try: print(text) print(caption_format) print(text.format(caption_format)) image.setCaption(text.format(caption_format)) except AttributeError: try: self.getArtist(pixivImage) image.setCaption(text.format(caption_format)) except: print("Invalid arguments for caption") #Manually artist information for pixivImage def getArtistWebsite(self, pixivImage): website = pixivImage.webpage if website.find("twittee") != -1: return "https://twitter.com/intent/follow?user_id=" + pixivImage.twitter_id elif website.find("tumblr") != -1: username = self.api.blog_info(website)['name'] return "https://www.tumblr.com/follow/" + username else: pass def postList(self, images, blogName, state): rowcurrent = 0 rowsum = len(images) for image in images: rowcurrent = rowcurrent + 1 try: imageCaption = image.caption except AttributeError: imageCaption = "" print("({}/{}) Downloading: {} by {}".format( rowcurrent, rowsum, image.title, image.name)) if image.directories == []: image.download() print("Posting to " + blogName + " as " + state) print("Caption: " + imageCaption) print("Tags: " + str(image.userTags)) self.api.create_photo(blogName, state=state, format="markdown", tags=image.userTags, caption=str(image.caption), data=image.directories) print("") if rowcurrent == rowsum: print("Done!") def postAll(self, state): self.postList(self.queue, self.blog, state)
from time import sleep from auth import ( consumer_key, consumer_secret, oauth_token, oauth_secret ) client = TumblrRestClient( consumer_key, consumer_secret, oauth_token, oauth_secret ) info = client.info() try: username = info["user"]["name"] except KeyError: raise RuntimeError("Could not connect to Tumblr. Check auth keys.") PHOTOS_DIR = '/home/pi/photos' def take_picture(): with PiCamera() as camera: timestamp = datetime.now().isoformat() photo_path = '%s/%s.jpg' % (PHOTOS_DIR, timestamp) camera.capture(photo_path) return photo_path