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
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)
# -*- coding: utf-8 -*- from pytumblr import TumblrRestClient from xml.dom import minidom from os.path import join import time import os if __name__ == "__main__": DATA_DIR = "data" TAGS = ["#selfie", "selfie"] keyDoc = minidom.parse("keys.xml") keys = {} for i in keyDoc.getElementsByTagName("string"): keys[i.attributes["name"].value] = i.childNodes[0].data mTumblr = TumblrRestClient( keys["consumer_key"], keys["consumer_secret"], keys["oauth_token"], keys["oauth_token_secret"] ) for directory in [d for d in os.listdir(DATA_DIR) if os.path.isdir(join(DATA_DIR, d))]: for filename in [ f for f in os.listdir(join(DATA_DIR, directory)) if f.startswith("memememeselfie") and f.endswith(".jpg") ]: fullPath = join(DATA_DIR, directory, filename) print "POSTING %s" % fullPath mTumblr.create_photo(directory, state="published", tags=TAGS, data=fullPath) time.sleep(1) os.remove(fullPath)
import time import os if __name__ == "__main__": DATA_DIR = "data" TAGS = ["#selfie", "selfie"] keyDoc = minidom.parse('keys.xml') keys = {} for i in keyDoc.getElementsByTagName('string'): keys[i.attributes['name'].value] = i.childNodes[0].data mTumblr = TumblrRestClient(keys['consumer_key'], keys['consumer_secret'], keys['oauth_token'], keys['oauth_token_secret']) for directory in [ d for d in os.listdir(DATA_DIR) if os.path.isdir(join(DATA_DIR, d)) ]: for filename in [ f for f in os.listdir(join(DATA_DIR, directory)) if f.startswith("memememeselfie") and f.endswith(".jpg") ]: fullPath = join(DATA_DIR, directory, filename) print "POSTING %s" % fullPath mTumblr.create_photo(directory, state="published", tags=TAGS, data=fullPath) time.sleep(1) os.remove(fullPath)
if not SortByTime: for i in data[1:]: ImagePath = os.path.join(Image_Folder, i.split(FileColumnSeparator)[0]) Caption = i.split(FileColumnSeparator)[1] + " <br> " + exif.get_exif_string(ImagePath) Tags = i.rstrip().split(FileColumnSeparator)[2].split(FileTagsSeparator) # Image_Block = ImageList.append({"Path": ImagePath, "Caption": Caption, "Tags": Tags}) else: for i in data[1:]: ImagePath = os.path.join(Image_Folder, i.split(FileColumnSeparator)[0]) Exif = exif.get_exif_string(ImagePath, True) Caption = i.split(FileColumnSeparator)[1] + "<br>" + Exif[0] Tags = i.rstrip().split(FileColumnSeparator)[2].split(FileTagsSeparator) # Image_Block = ImageList.append([Exif[1], {"Path": ImagePath, "Caption": Caption, "Tags": Tags}]) ImageList = sorted(ImageList, key=itemgetter(0)) temp = [] for i in ImageList: temp.append(i[1]) ImageList = temp for i in ImageList: print "Posting : ", i["Path"] print "Caption : ", i["Caption"] print "Tags : ", i["Tags"] if not BatchProcess: raw_input("Press Enter to Continue") client.create_photo(Keys["blogname"], state="draft", tags=i["Tags"], data=i["Path"], caption=i["Caption"]) print "Done for ", i["Path"] print "-" * 30