Ejemplo n.º 1
0
    def postJson(self, blog_url, tags, params):
        # Get the final tokens from the database or wherever you have them stored
        t = Tumblpy(self.YOUR_CONSUMER_KEY, self.YOUR_CONSUMER_SECRET,
                    self.OAUTH_TOKEN, self.OAUTH_TOKEN_SECRET)

        # let's get the first blog url...
        blog_url = t.post('user/info')
        blog_url = blog_url['user']['blogs'][0]['url']

        print blog_url
        dict_params = json.loads(params)

        print 'Posts length: ' + str(len(dict_params))

        for i in range(0, len(dict_params)):
            try:
                source = dict_params[i]['post']['source']
                caption = dict_params[i]['post']['caption']
                params = {
                    'type': 'photo',
                    'state': 'published',
                    'caption': caption,
                    'source': source,
                    'data': '',
                    'tags': tags + ',' + caption
                }

                post = t.post('post', blog_url=blog_url, params=params)
                raw_input("Downloading....")
            except Exception as e:
                print '------------------------------------------'
                print(e)
                print source

        return post
Ejemplo n.º 2
0
def post_images(status):
    """
    画像を作品のタグと引用付きで Tumblr に Post する
    :param status: Tweepy の status オブジェクト
    :return: なし
    """
    BLOG_URL = "mangatime-kirara.tumblr.com"
    caption = status.full_text + "\n\n" + "Source: https://" + status.extended_entities[
        "media"][0]["display_url"]
    tags = "manga,manga time kirara,まんがタイムきらら," + extract_titles(status)
    params = {
        "type": "photo",
        "caption": caption,
        "tags": tags,
    }

    image_urls = []
    for i, entry in enumerate(status.extended_entities["media"]):
        image_urls.append(entry["media_url"] + ":orig")  # original size

    for i, url in enumerate(image_urls):
        params["data[{}]".format(i)] = urllib.request.urlopen(url)

    with open("tumblr_config.txt", "r") as f:
        ck, cs, token, token_secret = f.read().strip().split()

    t = Tumblpy(ck, cs, token, token_secret)
    t.post('post', blog_url=BLOG_URL, params=params)
Ejemplo n.º 3
0
def post():
    YOUR_CONSUMER_KEY = ''
    YOUR_CONSUMER_SECRET = ''
    OAUTH_TOKEN = ''
    OAUTH_TOKEN_SECRET = ''

    # 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']
    print blog_url

    # Assume you are using the blog_url and Tumblpy instance from the previous sections
    source = 'http://www.factslides.com/imgs/lion2.jpg'
    state = 'published'
    type = 'photo'
    caption = 'TESSSTT CAPP'
    tags = ' "yay", "bay" '

    post = t.post('post',
                  blog_url=blog_url,
                  params={
                      'type': type,
                      'state': state,
                      'caption': caption,
                      'source': source,
                      'tags': tags
                  })
    print post
    return post
Ejemplo n.º 4
0
def post(request):
    user = request.user
    # check access token. If no access token, redirect to Oauth page.
    try:
        token = TumblrToken.objects.get(user=user,
                                        apikey=settings.TUMBLR_CONSUMER_KEY)
    except TumblrToken.DoesNotExist:
        return HttpResponseRedirect(reverse("tumblr_auth"))

    final_oauth_token, final_oauth_token_secret = token.get_oauth_token()

    t = Tumblpy(app_key=settings.TUMBLR_CONSUMER_KEY,
                app_secret=settings.TUMBLR_SECRET_KEY,
                oauth_token=final_oauth_token,
                oauth_token_secret=final_oauth_token_secret)
    try:
        # get default blog url.
        blog_url = t.post('user/info')
        blog_url = blog_url['user']['blogs'][0]['url']

        # post blog
        post = t.post('post',
                      blog_url=blog_url,
                      params={
                          'title': 'A new blog',
                          'body': 'This is blog content.'
                      })
    except TumblpyAuthError:
        return HttpResponseRedirect(reverse("tumblr_auth"))

    return HttpResponse("Blog post successfully.")
Ejemplo n.º 5
0
def do_post(path):
  print "Posting..."
  t = Tumblpy("","",
      "","")
  tbuff = textview.get_buffer()
  article_text = ""
  if isWeather.get_active():
    article_text = get_date_desc() + weatherProvider.get_weather()
  article_text = article_text + tbuff.get_text(tbuff.get_start_iter(), tbuff.get_end_iter())
  blog_url = t.post('user/info')
  blog_url = blog_url['user']['blogs'][1]['url']
  if path.get_text() !="No image":
    photo = open(path.get_text(), 'rb')
    ephoto = open(path.get_text(), 'rb')
    tags = "catumblr , "+ platform.node()
    etags = exifread.process_file(ephoto)
    if etags.has_key('Image Model'):
      tags = "catumblr , "+ platform.node() + ", " + str(etags['Image Model'])
    p_params = {'type':'photo', 'caption': article_text, 'data': photo, 'tags':tags}
    ephoto.close()
  else:
    tags = "catumblr , "+ platform.node()
    time_caption = strftime("%Y-%m-%d %H:%M:%S", gmtime())
    p_params = {'type':'text', 'body': article_text, 'caption': time_caption, 'tags':tags}

  post = t.post('post', blog_url=blog_url, params=p_params)
  print post  # returns id if posted successfully
Ejemplo n.º 6
0
    def post(self, blog_url, params):
        # Get the final tokens from the database or wherever you have them stored
        t = Tumblpy(self.YOUR_CONSUMER_KEY, self.YOUR_CONSUMER_SECRET,
                    self.OAUTH_TOKEN, self.OAUTH_TOKEN_SECRET)

        # let's get the first blog url...
        blog_url = t.post('user/info')
        blog_url = blog_url['user']['blogs'][0]['url']

        post = t.post('post', blog_url=blog_url, params=params)
        return post
Ejemplo n.º 7
0
    def demoPost():
        t = Tumblpy(app_key = APP_KEY,
                    app_secret = APP_SECRET,
                    oauth_token = OAUTH_TOKEN,
                    oauth_token_secret = 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']

        # Assume you are using the blog_url and Tumblpy instance from the previous sections
        post = t.post('post', blog_url=blog_url, params={'type':'text', 'state':'private', 'title':'titulo', 'body':'<p>This is a body</p>'})
        print post  # returns id if posted successfully
Ejemplo n.º 8
0
    def hidePosts():
        t = Tumblpy(app_key = APP_KEY,
                    app_secret = APP_SECRET,
                    oauth_token = OAUTH_TOKEN,
                    oauth_token_secret = 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']
        print "url: %s" % blog_url
        # Assume you are using the blog_url and Tumblpy instance from the previous section
        posts = t.get('posts', blog_url=blog_url, params={'tag':"JustMigrate"})
        for post in posts['posts']:
            print "%s %s" % (post['date'],post['post_url'])
            id = post['id']
            post = t.post('edit', blog_url=blog_url, params={'id':id,'state':'private'})
            print "ahora está en estado %s" % post['state']
Ejemplo n.º 9
0
    def deletePosts(tag):
        t = Tumblpy(app_key = APP_KEY,
                    app_secret = APP_SECRET,
                    oauth_token = OAUTH_TOKEN,
                    oauth_token_secret = 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']
        print "url: %s" % blog_url
        # Assume you are using the blog_url and Tumblpy instance from the previous section
        posts = t.get('posts', blog_url=blog_url, params={'tag':tag})
        for post in posts['posts']:
            print "%s %s" % (post['date'],post['post_url'])
            id = post['id']
            post = t.post('post/delete', blog_url=blog_url, params={'id':id})
            print "post deleted!!"
Ejemplo n.º 10
0
    def postInTumblr(self,title,date,body):
        t = Tumblpy(app_key = APP_KEY,
                    app_secret = APP_SECRET,
                    oauth_token = OAUTH_TOKEN,
                    oauth_token_secret = OAUTH_TOKEN_SECRET)

        # Assume you are using the blog_url and Tumblpy instance from the previous sections
        photo = open('/Users/xmanoel/Documents/Development/posterous-verter/gotasdechuva.jpg', 'rb')
        post = t.post('post', blog_url=BLOG_URL, params={'type':'text', 'state':STATE, 'title':title, 'body':body, 'date':date, 'tags':TAGS})
        print post  # returns id if posted successfully
Ejemplo n.º 11
0
def load_config():
    config = utils.load_config('tumbl_config')
    consumer_key = config[':consumer_key'] 
    consumer_secret = config[':consumer_secret'] 
    token = config[':token'] 
    token_secret = config[':token_secret'] 
    default_n = config[':default_n']
    t = Tumblpy(consumer_key,consumer_secret, token, token_secret)
    blog_url = t.post('user/info')['user']['blogs'][0]['url']
    return t, default_n, blog_url
Ejemplo n.º 12
0
def f_post(skrizz, trigger):
    """Post to the bots tumblr account"""
    post_content = trigger.group(2)

    t = Tumblpy(consumer_key, consumer_secret, access_token, access_token_secret)

    blog_info = t.post('user/info')
    blog_url = blog_info['user']['blogs'][0]['url']
    blog_title = str(blog_info['user']['blogs'][0]['title'])
    blog_desc = str(blog_info['user']['blogs'][0]['description'])
    blog_posts = str(blog_info['user']['blogs'][0]['posts'])

    if post_content.startswith('info'):
        skrizz.say('[TUMBLR] Title: ' + blog_title + ' | Address: ' + str(blog_url) + ' | Description: ' + blog_desc + ' | Posts: ' + blog_posts)
        return

    if post_content.startswith('that'):
        if trigger.sender not in skrizz.memory['last_seen_url']:
            skrizz.say('I haven\'t seen any URL\'s lately...')
            return
        post_url = skrizz.memory['last_seen_url'][trigger.sender]
        post_caption = post_content.replace("that","",1)
        if not post_caption and skrizz.memory['last_seen_url_title'][trigger.sender]:
            post_caption = skrizz.memory['last_seen_url_title'][trigger.sender]
        elif not post_caption:
            post_caption = "I was too lazy to come up with a clever caption."
        post_content = post_url + " " + post_caption

    post, meta = build_post(post_content)

    if not post:
        skrizz.say("Error: No URL Specified to post.")
        return

    try:
        t.post('post', blog_url=blog_url, params=post)
    except TumbplyError, e:
        skrizz.say(e.message)
        skrizz.say('Something super sad happened :(')
Ejemplo n.º 13
0
def post_to_tumblr():
  # Collect them all
  CONSUMER_KEY = environ['tumblr_consumer_key']
  CONSUMER_SECRET = environ['tumblr_consumer_secret']
  OAUTH_TOKEN = environ['tumblr_auth_token']
  OAUTH_TOKEN_SECRET = environ['tumblr_auth_token_secret']

  # Authenticate dat
  t = Tumblpy(CONSUMER_KEY, CONSUMER_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)

  # Load the photo and post to Tumblr
  photo = open('pic.jpg', 'rb')
  post = t.post('post', blog_url='http://meyow-me.tumblr.com', params={'type':'photo', 'caption': 'Test Caption', 'data': photo})
Ejemplo n.º 14
0
def _post_to_tumblr():
    """
    Handles the POST to Tumblr.
    """
    def clean(string):
        """
        Formats a string all pretty.
        """
        return string.replace('-', ' ').replace("id ", "I'd ").replace("didnt", "didn't").replace('i ', 'I ')

    # Request is a global. Import it down here where we need it.
    from flask import request

    def strip_html(value):
        """
        Strips HTML from a string.
        """
        return re.compile(r'</?\S([^=]*=(\s*"[^"]*"|\s*\'[^\']*\'|\S*)|[^>])*?>', re.IGNORECASE).sub('', value)

    def strip_breaks(value):
        """
        Converts newlines, returns and other breaks to <br/>.
        """
        value = re.sub(r'\r\n|\r|\n', '\n', value)
        return value.replace('\n', '<br />')

    caption = u"<p class='intro'>Dear Mr. President,</p><p class='voted' data-vote-type='%s'>%s.</p><p class='message'>%s</p><p class='signature-name'>Signed,<br/>%s from %s</p><p class='footnote'>What do <em>you</em> want President Obama to remember in his second term? Share your message at <a href='http://inauguration2013.tumblr.com/'>NPR's Dear Mr. President</a>.</p>" % (
        request.form['voted'],
        clean(request.form['voted']),
        strip_breaks(strip_html(request.form['message'])),
        strip_html(request.form['signed_name']),
        strip_html(request.form['location'])
    )

    t = Tumblpy(
        app_key=app_config.TUMBLR_KEY,
        app_secret=os.environ['TUMBLR_APP_SECRET'],
        oauth_token=os.environ['TUMBLR_OAUTH_TOKEN'],
        oauth_token_secret=os.environ['TUMBLR_OAUTH_TOKEN_SECRET'])

    try:
        tumblr_post = t.post('post', blog_url=app_config.TUMBLR_URL, params={
            'type': 'photo',
            'caption': caption,
            'tags': u"%s" % request.form['voted'].replace('-', ''),
            'data': request.files['image']
        })
    except:
        return 'Sorry, we\'re probably over capacity. Please try again later.'

    return redirect(u"http://%s/%s#posts" % (app_config.TUMBLR_URL, tumblr_post['id']), code=301)
Ejemplo n.º 15
0
    def getPosts():
        t = Tumblpy(app_key = APP_KEY,
                    app_secret = APP_SECRET,
                    oauth_token = OAUTH_TOKEN,
                    oauth_token_secret = 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']
        print "url: %s" % blog_url
        # Assume you are using the blog_url and Tumblpy instance from the previous section
        posts = t.get('posts', blog_url=blog_url)
        for post in posts['posts']:
            print "%s %s" % (post['date'],post['post_url'])
Ejemplo n.º 16
0
def write_mr_president_test_posts():
    """
    Writes test posts to our test blog as defined by app_config.py
    """

    # This is how many posts will be written.
    TOTAL_NUMBER = 15

    def clean(string):
        """
        Formats a string all pretty.
        """
        return string.replace('-', ' ').replace("id ", "I'd ").replace("didnt", "didn't").replace('i ', 'I ')

    t = Tumblpy(
            app_key=app_config.TUMBLR_KEY,
            app_secret=os.environ['TUMBLR_APP_SECRET'],
            oauth_token=os.environ['TUMBLR_OAUTH_TOKEN'],
            oauth_token_secret=os.environ['TUMBLR_OAUTH_TOKEN_SECRET'])

    tags = ['ivotedforyou', 'idrathernotsayhowivoted', 'ididntvoteforyou', 'ididntvote']

    images = ['data/images/1.png', 'data/images/2.png', 'data/images/3.png', 'data/images/4.png']

    n = 0
    while n < TOTAL_NUMBER:
        tag = choice(tags)
        caption = u"""<p class='intro'>Dear Mr. President,</p>
        <p class='voted' data-vote-type='%s'>%s.</p>
        <p class='message'>This is a test post.</p>
        <p class='signature-name'>Signed,<br/>Test from Test, Test</p>""" % (
            tag,
            clean(tag),
        )

        filename = choice(images)

        with open(filename, 'rb') as f:
            tumblr_post = t.post('post', blog_url=app_config.TUMBLR_URL, params={
                'type': 'photo',
                'caption': caption,
                'tags': tag,
                'data': f
            })

        print n, tumblr_post['id']

        n += 1
Ejemplo n.º 17
0
def get_connection_values(response, **kwargs):
    if not response:
        return None

    t = Tumblpy(app_key=config["consumer_key"], app_secret=config["consumer_secret"],
        oauth_token=response['oauth_token'],oauth_token_secret=response['oauth_token_secret'])

    blog_url = t.post('user/info')
    return dict(
        provider_id=config['id'],
        provider_user_id=str(blog_url["user"]["name"]),
        access_token=response['oauth_token'],
        secret=response['oauth_token_secret'],
        #display_name='%s %s' %(profile.first_name, profile.last_name) ,
        profile_url="N/A",
        image_url= ""
    )
Ejemplo n.º 18
0
class Client(object):
    name = "tumblr"

    def __init__(self, config):
        self.client = Tumblpy(config['consumer_key'],
                              config['consumer_secret'], config['token'],
                              config['token_secret'])
        self.blog_id = config['blog_id']
        self.log = logger.get(__name__)

    def send(self, picture):
        "Post a post. `picture` is a `Result` object from `picdescbot.common`"

        post_text = TEMPLATE.format(description=picture.caption,
                                    source=picture.source_url)

        tags = DEFAULT_TAGS + filter_tags(picture.tags)

        params = {
            'caption': post_text,
            'source': picture.url,
            'tags': ','.join(tags)
        }
        params.update(DEFAULT_PARAMS)

        retries = 0
        post = None
        while retries < 3 and post is None:
            if retries > 0:
                self.log.info('retrying...')
            try:
                post = self.client.post("post",
                                        blog_url=self.blog_id,
                                        params=params)
            except tumblpy.exceptions.TumblpyError as e:
                self.log.error("Error when sending tumblr post: %s" % e)
                retries += 1
                if retries >= 3:
                    raise
                else:
                    time.sleep(5)
        return post['id']
Ejemplo n.º 19
0
def write_test_posts():
    """
    Writes test posts to our test blog as defined by app_config.py
    """

    # This is how many posts will be written.
    TOTAL_NUMBER = 9

    secrets = app_config.get_secrets()

    t = Tumblpy(app_key=secrets['TUMBLR_APP_KEY'],
                app_secret=secrets['TUMBLR_APP_SECRET'],
                oauth_token=secrets['TUMBLR_OAUTH_TOKEN'],
                oauth_token_secret=secrets['TUMBLR_OAUTH_TOKEN_SECRET'])

    tags = ['featured', '']

    images = [
        'http://media.npr.org/assets/img/2013/04/24/habitablezones_custom-fa87578c6e6a97788b92a0ecac956b9098607aa6-s40.jpg',
        'http://media.npr.org/assets/img/2013/04/24/ocpack-32260770b4090f86ddeb7502175a631d50c3b4a1-s51.jpg',
        'http://media.npr.org/assets/img/2013/04/24/dalrymple-c-karoki-lewis-4c9bd790639c870d51c670cbecbca4b802b82b1a-s51.jpg',
        'http://media.npr.org/assets/img/2013/04/24/ap111231019469-46289d097a45801ed2ca3464da14b13be40e5adb-s51.jpg'
    ]

    n = 0
    while n < TOTAL_NUMBER:
        image = choice(images)
        tag = choice(tags)
        caption = u"<p class='intro'>Introduction,</p><p class='message'>This is a test post.</p><p class='signature-name'>Sincerely,<br/>Test from Test, Test</p>"
        tumblr_post = t.post('post',
                             blog_url=app_config.TUMBLR_URL,
                             params={
                                 'type': 'photo',
                                 'caption': caption,
                                 'tags': tag,
                                 'source': image
                             })

        print n, tumblr_post['id']

        n += 1
Ejemplo n.º 20
0
def write_test_posts():
    """
    Writes test posts to our test blog as defined by app_config.py
    """

    # This is how many posts will be written.
    TOTAL_NUMBER = 9

    secrets = app_config.get_secrets()

    t = Tumblpy(
        app_key=secrets['TUMBLR_APP_KEY'],
        app_secret=secrets['TUMBLR_APP_SECRET'],
        oauth_token=secrets['TUMBLR_OAUTH_TOKEN'],
        oauth_token_secret=secrets['TUMBLR_OAUTH_TOKEN_SECRET'])

    tags = ['featured', '']

    images = [
        'http://media.npr.org/assets/img/2013/04/24/habitablezones_custom-fa87578c6e6a97788b92a0ecac956b9098607aa6-s40.jpg',
        'http://media.npr.org/assets/img/2013/04/24/ocpack-32260770b4090f86ddeb7502175a631d50c3b4a1-s51.jpg',
        'http://media.npr.org/assets/img/2013/04/24/dalrymple-c-karoki-lewis-4c9bd790639c870d51c670cbecbca4b802b82b1a-s51.jpg',
        'http://media.npr.org/assets/img/2013/04/24/ap111231019469-46289d097a45801ed2ca3464da14b13be40e5adb-s51.jpg'
    ]

    n = 0
    while n < TOTAL_NUMBER:
        image = choice(images)
        tag = choice(tags)
        caption = u"<p class='intro'>Introduction,</p><p class='message'>This is a test post.</p><p class='signature-name'>Sincerely,<br/>Test from Test, Test</p>"
        tumblr_post = t.post('post', blog_url=app_config.TUMBLR_URL, params={
            'type': 'photo',
            'caption': caption,
            'tags': tag,
            'source': image
        })

        print n, tumblr_post['id']

        n += 1
Ejemplo n.º 21
0
class Client(object):
    name = "tumblr"

    def __init__(self, config):
        self.client = Tumblpy(config['consumer_key'], config['consumer_secret'],
                              config['token'], config['token_secret'])
        self.blog_id = config['blog_id']

    def send(self, picture):
        "Post a post. `picture` is a `Result` object from `picdescbot.common`"

        post_text = TEMPLATE.format(description=picture.caption,
                                    source=picture.source_url)

        tags = DEFAULT_TAGS + filter_tags(picture.tags)

        params = {'caption': post_text,
                  'source': picture.url,
                  'tags': ','.join(tags)}
        params.update(DEFAULT_PARAMS)

        retries = 0
        post = None
        while retries < 3 and post is None:
            if retries > 0:
                print('retrying...')
            try:
                post = self.client.post("post", blog_url=self.blog_id,
                                        params=params)
            except tumblpy.exceptions.TumblpyError as e:
                print("Error when sending tumblr post: %s" % e)
                retries += 1
                if retries >= 3:
                    raise
                else:
                    time.sleep(5)
        return post['id']
Ejemplo n.º 22
0
class Reddit2Tumblr():
    def __init__(
        self,
        consumer_key,
        consumer_secret,
        oauth_token,
        oauth_secret,
        subreddit,
        site_link,
    ):
        self.client = Tumblpy(consumer_key, consumer_secret, oauth_token,
                              oauth_secret)
        self.blog_url = self.client.post('user/info')
        self.blog_url = self.blog_url['user']['blogs'][0]['url']
        self.agent = 'PyEng version: ' + str(randrange(1, 200, 1))
        self.r = praw.Reddit(user_agent=self.agent)
        self.subreddit = self.r.get_subreddit(subreddit)
        self.site_link = site_link

    def watch(self, count):
        for submission in self.subreddit.get_hot(limit=10):
            try:
                # print(submission.title)
                # print(submission.url)
                # print(submission.selftext)
                if "This Sub" or "Text" not in submission.title:

                    if "Article" in submission.title:
                        print("Article")
                        print("Title Article: ",
                              submission.title.replace("[Article]", "", 1))
                        print("Url: ", submission.url)
                        text = submission.title.replace(
                            "[Article]", "", 1) + ' ' + self.site_link
                        print("Text: ", text)
                        post = self.client.post('post',
                                                blog_url=self.blog_url,
                                                params={
                                                    'type': 'link',
                                                    'caption': text,
                                                    'source': submission.url
                                                })
                        print(post)

                    if ("youtube"
                            not in submission.url) and ('youtu.be'
                                                        not in submission.url):
                        if ("jpg" or "png" or "gif" or "jpeg") and (
                                'reddit.com'
                                or "redd.it") not in submission.url:
                            if "imgur" not in submission.url:
                                print("Article")
                                print(
                                    "Title Article: ",
                                    submission.title.replace(
                                        "[Article]", "", 1))
                                print("Url: ", submission.url)
                                text = submission.title.replace(
                                    "[Article]", "", 1) + ' ' + self.site_link
                                print("Text: ", text)
                                post = self.client.post('post',
                                                        blog_url=self.blog_url,
                                                        params={
                                                            'type':
                                                            'link',
                                                            'caption':
                                                            text,
                                                            'source':
                                                            submission.url
                                                        })
                                print(post)
                        else:
                            pass

                    if ("Video" in submission.title) or (
                            "youtube"
                            in submission.url) or ('youtu.be'
                                                   in submission.url):
                        print("Video")
                        print("Title Article: ",
                              submission.title.replace("[Video]", "", 1))
                        print("Url: ", submission.url)
                        print("Text: ", submission.selftext)
                        text = submission.title.replace(
                            "[Video]", "", 1) + ' ' + self.site_link
                        print("Text: ", text)
                        post = self.client.post('post',
                                                blog_url=self.blog_url,
                                                params={
                                                    'type': 'video',
                                                    'caption': text,
                                                    'embed': submission.url
                                                })
                        print(post)

                    if ("jpg" or "png" or "gif" or "jpeg") in submission.url:
                        print("Image")
                        print("Title: ",
                              submission.title.replace("[Image]", "", 1))
                        print("Image Url: ", submission.url)
                        text = submission.title.replace(
                            "[Image]", "", 1) + ' ' + self.site_link
                        print("Text: ", text)
                        post = self.client.post('post',
                                                blog_url=self.blog_url,
                                                params={
                                                    'type': 'photo',
                                                    'caption': text,
                                                    'source': submission.url
                                                })
                        print(post)
            except:
                pass
        else:
            pass

    def follower(self, count):
        tc = requests.session()
        tc.verify = False
        tbrowser = RoboBrowser(session=tc)
        tbrowser.open('https://www.tumblr.com/tagged/trending-topics')
        links = tbrowser.find_all("a", {"class": "post_info_link"})
        for link in links:
            try:
                self.client.post('user/follow', params={'url': link['href']})
                print("following " + link['href'] + "On account: " +
                      self.blog_url)
            except:
                print("boo")
Ejemplo n.º 23
0
def _post_to_tumblr():

    """
    Handles the POST to Tumblr.
    """
    def clean(string):
        """
        Formats a string all pretty.
        """
        return string.replace('-', ' ').replace("id ", "I'd ").replace("didnt", "didn't").replace('i ', 'I ')

    # Request is a global. Import it down here where we need it.
    from flask import request

    def strip_html(value):
        """
        Strips HTML from a string.
        """
        return re.compile(r'</?\S([^=]*=(\s*"[^"]*"|\s*\'[^\']*\'|\S*)|[^>])*?>', re.IGNORECASE).sub('', value)

    def strip_breaks(value):
        """
        Converts newlines, returns and other breaks to <br/>.
        """
        value = re.sub(r'\r\n|\r|\n', '\n', value)
        return value.replace('\n', '<br />')

    try:
        caption = "<p class='message'>%s</p><p class='signature-name'>Initialed,<br/>%s from %s</p><p class='footnote'>Dinner is hard. We want to know what's on your family's table, and why. Share yours at <a href='http://%s/'>NPR's Dinnertime Confessional</a>.</p>" % (
            strip_breaks(strip_html(request.form['message'])),
            strip_html(request.form['signed_name']),
            strip_html(request.form['location']),
            app_config.TUMBLR_URL
        )

        t = Tumblpy(
            app_key=app_config.TUMBLR_KEY,
            app_secret=os.environ['TUMBLR_APP_SECRET'],
            oauth_token=os.environ['TUMBLR_OAUTH_TOKEN'],
            oauth_token_secret=os.environ['TUMBLR_OAUTH_TOKEN_SECRET'])

        file_path = '/upload/%s/%s_%s' % (
            'family-meal',
            str(time.mktime(datetime.datetime.now().timetuple())).replace('.', ''),
            secure_filename(request.files['image'].filename.replace(' ', '-'))
        )

        with open('/tmp%s' % file_path, 'w') as f:
            f.write(request.files['image'].read())

        params = {
            "type": "photo",
            "caption": caption,
            "tags": "food,dinner,plate,confession,crunchtime,npr",
            "source": "http://%s%s" % (app_config.SERVERS[0], file_path)
        }

        try:
            tumblr_post = t.post('post', blog_url=app_config.TUMBLR_URL, params=params)
            tumblr_url = u"http://%s/%s" % (app_config.TUMBLR_URL, tumblr_post['id'])
            logger.info('200 %s' % tumblr_url)

            return redirect('%s#posts' % tumblr_url, code=301)

        except TumblpyError, e:
            logger.error('%s %s' % (e.error_code, e.msg))
            return 'TUMBLR ERROR'

        return redirect('%s#posts' % tumblr_url, code=301)
Ejemplo n.º 24
0
class TumblrManager(object):
    following_users = set()

    def __init__(self,
                 consumer_key=None,
                 consumer_secret=None,
                 oauth_token=None,
                 oauth_token_secret=None):
        if consumer_key is None or consumer_secret is None or oauth_token is None or oauth_token_secret is None:
            self.t = Tumblpy()
        else:
            self.t = Tumblpy(consumer_key, consumer_secret, oauth_token,
                             oauth_token_secret)

    def fetch_urls(self, LIM=4):
        """
        Fetch urls from user's likes.
        If you want more urls, increase LIM range 1 to 50 (default 4).
        :return a list: including urls
        """
        post_urls = []
        for cnt in range(LIM):
            try:
                likes = self.t.post('user/likes', params={"offset": 20 * cnt})
            except:
                continue

            liked_posts = likes["liked_posts"]
            for liked_post in liked_posts:
                post_url = liked_post["post_url"]
                post_urls.append(self.format_url(post_url))

        return post_urls

    def fetch_all_following_users(self):
        # seek total_blogs
        following = self.t.post("user/following", params={"limit": 1})
        total_blogs = following["total_blogs"]

        users = set()
        for i in range(total_blogs // 20 + 2):
            blogs = self.fetch_blogs(offset=20 * i)
            for user in blogs:
                users.add(user)

        return users

    def fetch_blogs(self, offset=0):
        try:
            following = self.t.post("user/following",
                                    params={"offset": offset})
        except:
            return []
        blogs = following["blogs"]
        ret = [blog["name"] for blog in blogs]
        return ret

    def format_url(self, url):
        """
        :return str: formated url
        """
        try:
            p = url.find("post/")
            front = url[:p + 18]
            back = url[p + 18:]
            return_url = front + urllib.parse.quote_plus(back,
                                                         encoding="utf-8")
            return return_url
        except:
            return ""

    def is_following(self, user):
        if not self.following_users:
            self.following_users = self.fetch_all_following_users()
        return user in self.following_users

    def is_valid_id(self, id):
        """ Return True if id is following a rule of user name.  """
        alnum_reg = re.compile(r'^[a-zA-Z0-9-]+$')
        return alnum_reg.match(id) is not None
Ejemplo n.º 25
0
def _post_to_tumblr():
    """
    Handles the POST to Tumblr.
    """
    def clean(string):
        """
        Formats a string all pretty.
        """
        return string.replace('-', ' ').replace("id ", "I'd ").replace(
            "didnt", "didn't").replace('i ', 'I ')

    # Request is a global. Import it down here where we need it.
    from flask import request

    def strip_html(value):
        """
        Strips HTML from a string.
        """
        return re.compile(
            r'</?\S([^=]*=(\s*"[^"]*"|\s*\'[^\']*\'|\S*)|[^>])*?>',
            re.IGNORECASE).sub('', value)

    def strip_breaks(value):
        """
        Converts newlines, returns and other breaks to <br/>.
        """
        value = re.sub(r'\r\n|\r|\n', '\n', value)
        return value.replace('\n', '<br />')

    try:
        caption = "<p class='message'>%s</p><p class='signature-name'>Initialed,<br/>%s from %s</p><p class='footnote'>Dinner is hard. We want to know what's on your family's table, and why. Share yours at <a href='http://%s/'>NPR's Dinnertime Confessional</a>.</p>" % (
            strip_breaks(strip_html(request.form['message'])),
            strip_html(request.form['signed_name']),
            strip_html(request.form['location']), app_config.TUMBLR_URL)

        t = Tumblpy(app_key=app_config.TUMBLR_KEY,
                    app_secret=os.environ['TUMBLR_APP_SECRET'],
                    oauth_token=os.environ['TUMBLR_OAUTH_TOKEN'],
                    oauth_token_secret=os.environ['TUMBLR_OAUTH_TOKEN_SECRET'])

        file_path = '/upload/%s/%s_%s' % (
            'family-meal', str(time.mktime(
                datetime.datetime.now().timetuple())).replace('.', ''),
            secure_filename(request.files['image'].filename.replace(' ', '-')))

        with open('/tmp%s' % file_path, 'w') as f:
            f.write(request.files['image'].read())

        params = {
            "type": "photo",
            "caption": caption,
            "tags": "food,dinner,plate,confession,crunchtime,npr",
            "source": "http://%s%s" % (app_config.SERVERS[0], file_path)
        }

        try:
            tumblr_post = t.post('post',
                                 blog_url=app_config.TUMBLR_URL,
                                 params=params)
            tumblr_url = u"http://%s/%s" % (app_config.TUMBLR_URL,
                                            tumblr_post['id'])
            logger.info('200 %s' % tumblr_url)

            return redirect('%s#posts' % tumblr_url, code=301)

        except TumblpyError, e:
            logger.error('%s %s' % (e.error_code, e.msg))
            return 'TUMBLR ERROR'

        return redirect('%s#posts' % tumblr_url, code=301)
Ejemplo n.º 26
0
    t = Tumblpy(
        app_key=secrets['TUMBLR_APP_KEY'],
        app_secret=secrets['TUMBLR_APP_SECRET'],
        oauth_token=secrets['TUMBLR_OAUTH_TOKEN'],
        oauth_token_secret=secrets['TUMBLR_OAUTH_TOKEN_SECRET'])

    params = {
        "type": "photo",
        "caption": caption,
        "tags": app_config.TUMBLR_TAGS,
        "source": "http://%s%s" % (app_config.SERVERS[0], png_path)
    }

    try:
        tumblr_post = t.post('post', blog_url=app_config.TUMBLR_URL, params=params)
        tumblr_url = u"http://%s/%s" % (app_config.TUMBLR_URL, tumblr_post['id'])
        logger.info('200 %s reader(%s) (times in EST)' % (tumblr_url, name))

        if app_config.ZAZZLE_ENABLE:
            zazzlify_png(png_path, tumblr_post['id'], name, location)

        return redirect(tumblr_url, code=301)

    except TumblpyError, e:
        logger.error('%s %s http://%s%s reader(%s) (times in EST)' % (
            e.error_code, e.msg, app_config.SERVERS[0], svg_path, name))
        context = {}
        context['title'] = 'Tumblr error'
        context['message'] = '%s\n%s' % (e.error_code, e.msg)
Ejemplo n.º 27
0
    print('Connect with Tumblr via: {}'.format(auth_url))

    oauth_token = raw_input('OAuth Token (from callback url): ')
    oauth_verifier = raw_input('OAuth Verifier (from callback url): ')

    t = Tumblpy(key, 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']

    print('OAuth Token: {}'.format(final_oauth_token))
    print('OAuth Token Secret: {}'.format(final_oauth_token_secret))
else:
    final_oauth_token = raw_input('OAuth Token: ')
    final_oauth_token_secret = raw_input('OAuth Token Secret: ')

t = Tumblpy(key, secret, final_oauth_token, final_oauth_token_secret)

blog_url = t.post('user/info')
blog_url = blog_url['user']['blogs'][0]['url']

print('Your blog url is: {}'.format(blog_url))

posts = t.posts(blog_url)

print('Here are some posts this blog has made:', posts)

# print t.post('post', blog_url=blog_url, params={'type':'text', 'title': 'Test', 'body': 'Lorem ipsum.'})
Ejemplo n.º 28
0
def _post_to_tumblr():
    """
    Handles the POST to Tumblr.
    """

    def strip_html(value):
        """
        Strips HTML from a string.
        """
        return re.compile(r'</?\S([^=]*=(\s*"[^"]*"|\s*\'[^\']*\'|\S*)|[^>])*?>', re.IGNORECASE).sub('', value)

    def strip_breaks(value):
        """
        Converts newlines, returns and other breaks to <br/>.
        """
        value = re.sub(r'\r\n|\r|\n', '\n', value)
        return value.replace('\n', do_mark_safe('<br/>'))

    # Request is a global. Import it down here where we need it.
    from flask import request

    message = strip_html(request.form.get('message', None))
    message = escape(message)
    message = strip_breaks(message)

    name = strip_html(request.form.get('signed_name', None))
    email = strip_html(request.form.get('email', None))

    context = {
        'message': message,
        'name': name,
        'email': email,
        'app_config': app_config
    }

    caption = render_template('caption.html', **context)

    t = Tumblpy(
        app_key=os.environ['TUMBLR_CONSUMER_KEY'],
        app_secret=os.environ['TUMBLR_APP_SECRET'],
        oauth_token=os.environ['TUMBLR_OAUTH_TOKEN'],
        oauth_token_secret=os.environ['TUMBLR_OAUTH_TOKEN_SECRET'])

    file_path = '/uploads/%s/%s_%s' % (
        app_config.PROJECT_SLUG,
        str(time.mktime(datetime.datetime.now().timetuple())).replace('.', ''),
        secure_filename(request.files['image'].filename.replace(' ', '-'))
    )

    with open('/var/www%s' % file_path, 'w') as f:
        f.write(request.files['image'].read())

    params = {
        "type": "photo",
        "caption": caption,
        "tags": app_config.TUMBLR_TAGS,
        "source": "http://%s%s" % (app_config.SERVERS[0], file_path)
    }

    try:
        tumblr_post = t.post('post', blog_url=app_config.TUMBLR_URL, params=params)
        tumblr_url = u"http://%s/%s" % (app_config.TUMBLR_URL, tumblr_post['id'])
        logger.info('200 %s reader(%s %s) (times in EST)' % (tumblr_url, name, email))

        return redirect(tumblr_url, code=301)

    except TumblpyError, e:
        logger.error('%s %s http://%s%s reader(%s %s) (times in EST)' % (
            e.error_code, e.msg, app_config.SERVERS[0], file_path, name, email))
        return 'TUMBLR ERROR'
Ejemplo n.º 29
0
while True:
	quote = makeGif(random.randint(4,6), 0, rand=True, frames=20)
	quote = ' '.join(quote)

	# reduce amount of colors, because tumblr sucks
	subprocess.call(['convert',
					'star_wars.gif',
					'-layers',
					'Optimize',
					'-colors',
					'64',
					'star_wars.gif'])
	while(os.path.getsize('star_wars.gif') > 1048576):
		subprocess.call(['convert',
						'star_wars.gif',
						'-resize',
						'90%',
						'-coalesce',
						'-layers',
						'Optimize',
						'star_wars.gif'])

	photo = open('star_wars.gif', 'rb')

	post = t.post('post', blog_url='http://starwarsgifsasaservice.tumblr.com', params={'type':'photo', 'caption': quote, 'data': photo, 'tags': 'star wars, gif'})

	print "sleeping..."
	# sleep 12 hours
	time.sleep(43200)
Ejemplo n.º 30
0
t = Tumblpy(
    CONSUMER_KEY,
    CONSUMER_SECRET,
    OAUTH_TOKEN,
    OAUTH_TOKEN_SECRET,
)

while True:
    quote = makeGif(random.randint(4, 6), 0, rand=True)
    quote = ' '.join(quote)

    while (os.path.getsize('star_wars.gif') > 1048576):
        subprocess.call([
            'convert', 'star_wars.gif', '-resize', '90%', '-coalesce',
            '-layers', 'optimize', 'star_wars.gif'
        ])

    photo = open('star_wars.gif', 'rb')

    post = t.post('post',
                  blog_url='http://starwarsgifsasaservice.tumblr.com',
                  params={
                      'type': 'photo',
                      'caption': quote,
                      'data': photo,
                      'tags': 'star wars, gif'
                  })

    print "sleeping..."
    # sleep 12 hours
    time.sleep(43200)
Ejemplo n.º 31
0
def _post_to_tumblr():
    """
    Handles the POST to Tumblr.
    """

    def strip_html(value):
        """
        Strips HTML from a string.
        """
        return re.compile(r'</?\S([^=]*=(\s*"[^"]*"|\s*\'[^\']*\'|\S*)|[^>])*?>', re.IGNORECASE).sub('', value)

    def strip_breaks(value):
        """
        Converts newlines, returns and other breaks to <br/>.
        """
        value = re.sub(r'\r\n|\r|\n', '\n', value)
        return value.replace('\n', do_mark_safe('<br/>'))

    # Request is a global. Import it down here where we need it.
    from flask import request

    # These should match the form fields.
    message = strip_html(request.form.get('message', None))
    message = escape(message)
    message = strip_breaks(message)

    name = strip_html(request.form.get('signed_name', None))
    email = strip_html(request.form.get('email', None))

    context = {
        'message': message,
        'name': name,
        'email': email,
        'app_config': app_config
    }

    caption = render_template('caption.html', **context)

    secrets = app_config.get_secrets()
    t = Tumblpy(
        app_key=secrets['TUMBLR_APP_KEY'],
        app_secret=secrets['TUMBLR_APP_SECRET'],
        oauth_token=secrets['TUMBLR_OAUTH_TOKEN'],
        oauth_token_secret=secrets['TUMBLR_OAUTH_TOKEN_SECRET'])

    file_path = '/uploads/%s/%s_%s' % (
        app_config.PROJECT_SLUG,
        str(time.mktime(datetime.datetime.now().timetuple())).replace('.', ''),
        secure_filename(request.files['image'].filename.replace(' ', '-'))
    )

    with open('/var/www%s' % file_path, 'w') as f:
        f.write(request.files['image'].read())

    params = {
        "type": "photo",
        "caption": caption,
        "tags": app_config.TUMBLR_TAGS,
        "source": "http://%s%s" % (app_config.SERVERS[0], file_path)
    }

    try:
        tumblr_post = t.post('post', blog_url=app_config.TUMBLR_URL, params=params)
        tumblr_url = u"http://%s/%s" % (app_config.TUMBLR_URL, tumblr_post['id'])
        logger.info('200 %s reader(%s %s) (times in EST)' % (tumblr_url, name, email))

        return redirect(tumblr_url, code=301)

    except TumblpyError, e:
        logger.error('%s %s http://%s%s reader(%s %s) (times in EST)' % (
            e.error_code, e.msg, app_config.SERVERS[0], file_path, name, email))
        return 'TUMBLR ERROR'
Ejemplo n.º 32
0
    quote = makeGif(random.choice(slug), frames=20)
    quote = ' '.join(quote)

    # reduce amount of colors, because tumblr sucks
    subprocess.call([
        'convert', 'barbarella.gif', '-layers', 'optimize', '-colors', '64',
        '-loop', '0', 'barbarella.gif'
    ])

    while (os.path.getsize('barbarella.gif') > 1048576):
        subprocess.call([
            'convert', 'barbarella.gif', '-resize', '90%', '-coalesce',
            '-layers', 'optimize', '-loop', '0', 'barbarella.gif'
        ])

    photo = open('barbarella.gif', 'rb')

    post = t.post(
        'post',
        #blog_url='http://barbarellagifs.tumblr.com',
        params={
            'type': 'photo',
            'caption': quote,
            'data': photo,
            'tags': 'barbarella, gif'
        })

    print "sleeping..."
    # sleep 12 hours
    time.sleep(43200)
Ejemplo n.º 33
0
def main():

    print('###################')
    print('#     Glitchr     #')
    print('###################')
    print('\n')
    print(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
    args, config = parseArgs()
    consumerKey = config.get('consumer', 'key')
    consumerSecret = config.get('consumer', 'secret')
    oauthToken = config.get('oauth', 'key')
    oauthSecret = config.get('oauth', 'secret')

    blogurl = config.get('blog', 'url')

    print('Sorting out Tumblr OAuth')
    tumblr = Tumblpy(consumerKey, consumerSecret, oauthToken, oauthSecret)

    tags = config.get('misc', 'tags').split(',')
    if tags:
        tag = choice(tags)
    else:
        tag = None

    print('Getting images with %s tag' % tag)

    cacheFileName = '%s-%s' % (config.get('cache', 'posts'), tag)
    postCache = BasicCache(cacheFileName)
    postCache.loadCache()

    blogs = open(args.blogs).read().splitlines()
    print('Searching %d blogs' % len(blogs))

    allPhotos = getBlogPhotos(tumblr, blogs, postCache, tag)

    postCache.saveCache()

    print('Sleeping for a few seconds')
    print('This seems to stop errors with posting the image\n')
    sleep(5)

    photo = getRandomPhoto(allPhotos)
    printPhotoInfoLogMessage(photo)

    params = {'type': 'photo',
              'caption': createCaption(photo),
              'tags': 'Glitchr, glitch, generative, random'
              }

    glitchPhoto(photo)

    if args.testing:
        print('Only testing, not posting images')
    else:
        try:
            resp = tumblr.post('post',
                               'http://%s' % blogurl,
                               params=params,
                               files=photo['fp'])
            # Print a URL to the post we just made
            print('Image posted:')
            print('    http://%s/post/%s' % (blogurl, resp['id']))
        except AttributeError as e:
            print('Bugger, something went wrong!')
            print(e)

    print('\n')
    print('###################')
    print('#    All done!    #')
    print('###################')
    print('\n\n')
Ejemplo n.º 34
0
	def get_tumblr_table(self):
	    t = Tumblpy("sYKNnjJRqbxWWlg19sY8WYnZyQi6wURbilnE4k3vsyqX4vc4ER","n8mtWzKieR8qgTdwUWNhF3OYZVIsvMZXvVr9DKPlCGI6wE2VLV",
	    "PyvcruFPx1YqhdAOkCWjCPWMBIYx3fUJaiFzjhxpkwUwps0VjC","Zjwmi2wYA83rtIdoL82BcWcj5sxm5QrI1MEnZX4DzFQHWydx1C")
	    
	    blog_url = t.post('user/info')
	    blog_url = blog_url['user']['blogs'][1]['url']
	    
	    posts = t.get('posts', blog_url=blog_url)
	    posts_count = posts["total_posts"]
	    #print posts
	    table = gtk.Table(posts_count, 1, False)
	    
	    # set the spacing to 10 on x and 10 on y
	    table.set_row_spacings(10)
	    table.set_col_spacings(10)
	    
	    # pack the table into the scrolled window
	    i = 0
	    for cur_post in posts["posts"]:
			buffer = ""
			cur_image_fac = catImageBox.catImageBox("http://www.linux.org.ru/tango/img/opensource-logo.png", 50, 50)

			if cur_post["type"] == "text":
				buffer = cur_post["body"]
			
			if cur_post["type"] == "photo":
				j = len(cur_post["photos"][0]["alt_sizes"]) -1 
				img_url = cur_post["photos"][0]["alt_sizes"][j]["url"]
				
				cur_image_fac = catImageBox.catImageBox(img_url, 75, 75)
				buffer = cur_post["caption"]
				
			s = MLStripper()
			s.feed(buffer)	
			label = gtk.Label(s.get_data())
			label.set_line_wrap(True)
			label.set_justify(gtk.JUSTIFY_LEFT)
			label.set_width_chars(30)
			label.show()
			
			#date box
			date_box = gtk.HBox(True, 1)
			date_icon = gtk.Image()
			date_icon.set_from_file("resources/cal.png")
			date_icon.show()
			cur_image = cur_image_fac.image
			cur_image.show()
			fdate = cur_post["date"]
			date_label = gtk.Label(fdate.split(" ")[0])
			date_label.set_line_wrap(True)
			date_label.show()
			#date_box.pack_start(date_icon, True, True, 1)
			date_box.pack_start(cur_image, True, True, 1)
			
			date_box.pack_end(date_label, True, True, 1)
			date_box.show()
			
			#tag box
			tag_box = gtk.HBox(True, 1)
			tag_icon = gtk.Image()
			tag_icon.set_from_file("resources/tag.png")
			tag_icon.show()
			ftags = ""
			for cur_tag in cur_post["tags"]:
				ftags += cur_tag + " "
				
			
			tag_label = gtk.Label(ftags)
			tag_label.set_line_wrap(True)
			tag_label.show()
			tag_box.pack_start(tag_icon, True, True, 1)
			tag_box.pack_end(tag_label, True, True, 1)
			tag_box.show()
			
			separator = gtk.HSeparator()
			separator.show()
			
			box = gtk.VBox(True, 1)
			box.pack_start(date_box, True, True, 1)
			if cur_post["tags"].count > 0:
				box.pack_start(tag_box, True, True, 1)
			box.pack_start(label, True, True, 0)
			box.pack_end(separator, True,  True, 0)
			box.show()
			table.attach(box, 1, 2, i, i+1)
			i = i+1
	    return  table
Ejemplo n.º 35
0
gif = '%s/%s' % (GIF_DIR, tweet_gif)
gif = gif.replace('\n', '')
api.update_with_media(gif)

# Post to Tumblr Too
# Load tumblr credentials for this bot from config file
BOTCRED_FILE = '%s/.twurlrc' % os.path.expanduser('~')
with open(BOTCRED_FILE, 'r') as credfile:
    full_config = yaml.load(credfile)
    api_key = api_key = full_config['profiles']['twinpeaksdiarytumblr'].keys(
    )[0]
    bot_creds = full_config['profiles']['twinpeaksdiarytumblr'][api_key]

from tumblpy import Tumblpy
TUMBLR_CONSUMER_KEY = bot_creds['consumer_key']
TUMBLR_CONSUMER_SECRET = bot_creds['consumer_secret']
OAUTH_TOKEN = bot_creds['token']
OAUTH_TOKEN_SECRET = bot_creds['secret']

t = Tumblpy(TUMBLR_CONSUMER_KEY, TUMBLR_CONSUMER_SECRET, OAUTH_TOKEN,
            OAUTH_TOKEN_SECRET)
blog_url = t.post('user/info')
blog_url = blog_url['user']['blogs'][0]['url']
photo = open(gif, 'rb')
post = t.post('post',
              blog_url=blog_url,
              params={
                  'type': 'photo',
                  'data': photo
              })