def create_tumblr():
    if "TUMBLR_TOKEN_SECRET" in os.environ:
        return pytumblr.TumblrRestClient(
            os.environ.get("TUMBLR_CONSUMER_KEY"),
            os.environ.get("TUMBLR_CONSUMER_SECRET"),
            os.environ.get("TUMBLR_TOKEN"),
            os.environ.get("TUMBLR_TOKEN_SECRET"))
    elif "TUMBLR_CONSUMER_SECRET" in os.environ:
        return pytumblr.TumblrRestClient(
            os.environ.get("TUMBLR_CONSUMER_KEY"),
            os.environ.get("TUMBLR_CONSUMER_SECRET"))
    else:
        return pytumblr.TumblrRestClient(os.environ.get("TUMBLR_CONSUMER_KEY"))
Example #2
0
 def __init__(self):
     config = json.load(open("config.json", "r"))
     self.client = pytumblr.TumblrRestClient(
         config["key"], config["secret"],
         config["oauth_token"], config["oauth_secret"],
     )
     self.dashboard = Dashboard(self.client)
 def private_clients(self) -> List[RateLimitClient]:
     return [
         RateLimitClient.from_tumblr_rest_client(
             pytumblr.TumblrRestClient(*keys), self.blogName
         )
         for keys in self.private_clients_api_keys
     ]
Example #4
0
 def __init__(self):
     self.photo_repository = PhotoRepository("tumblr")
     self.tumblr_client = pytumblr.TumblrRestClient(
         config.get(CONFIG_SECTION, 'TUMBLR_CONSUMER_KEY'),
         config.get(CONFIG_SECTION, 'TUMBLR_CONSUMER_SECRET'),
         config.get(CONFIG_SECTION, 'TUMBLR_ACCESS_KEY'),
         config.get(CONFIG_SECTION, 'TUMBLR_ACCESS_SECRET'))
Example #5
0
def tumblr_it(string, credentials, image, tags, homepage):
    """ Post to Tumblr """
    client = pytumblr.TumblrRestClient(
        credentials["tumblr_consumer_key"],
        credentials["tumblr_consumer_secret"],
        credentials["tumblr_oauth_token"],
        credentials["tumblr_oauth_secret"],
    )

    # Remove None tags
    tags = [tag for tag in tags if tag is not None]

    if args.test:
        print("(Test mode, not actually tumblring)")
    else:
        result = client.create_photo(
            "menubot",
            state="published",
            tags=tags,
            data=str(image),
            caption=str(string),
            link=homepage,
        )
        print(result)

        url = "http://menubot.tumblr.com/post/" + str(result["id"])
        print("Tumblred:\n" + url)
        if not args.no_web:
            webbrowser.open(url, new=2)  # 2 = open in a new tab, if possible
Example #6
0
def buscarfotos(number):
    client = pytumblr.TumblrRestClient(
        '**************************************************')
    ret = []
    tagcounter = 0
    contador = 0
    flag = randomclave()
    while len(ret) == 0:
        contador += 1
        if contador == 20:
            return 'none'
        listafotos = client.tagged(flag, before=randomtime())
        for foto in listafotos:
            tagcounter = 0
            if foto['type'] == 'photo':
                for tag in foto['tags']:
                    for mytag in claves:
                        if tag == mytag and mytag != flag:
                            tagcounter += 1
                            if tagcounter == number:
                                ret.append(foto)
                                break
                    else:
                        continue
                    break

    return ret
Example #7
0
def hello_world():
    user = request.args.get("user").strip()
    tags = request.args.get("tags")
    tags_list = request.args.get("tags", "").split(",")
    posts = None
    if user and bool(len(tags_list)):

        client = pytumblr.TumblrRestClient(settings.TUMBLR_CONSUMER_KEY,
                                           settings.TUMBLR_CONSUMER_SECRET,
                                           settings.TUMBLR_OAUTH_TOKEN,
                                           settings.TUMBLR_OAUTH_SECRET)

        info = client.blog_info(user)
        posts = []
        tags_list.append(user)
        for tag in tags_list:
            tagged_posts = client.posts("{}.tumblr.com".format(user),
                                        "photo",
                                        tag=tag.strip())
            if bool(tagged_posts['total_posts']):
                post_group = {"tag": tag.strip(), "posts": tagged_posts}
                posts.append(post_group)

    return render_template("index.html",
                           user=user,
                           tags=tags,
                           tags_list=tags_list,
                           posts=posts,
                           info=info)
Example #8
0
def get_tumblr_client():
    # From tumblr API console https://api.tumblr.com/console
    # Authenticate via OAuth
    with open('tumblr_secret.p', 'rb') as f:
        secrets = pickle.load(f)
    client = pytumblr.TumblrRestClient(secrets[0], secrets[1], secrets[2], secrets[3])
    return client
Example #9
0
def submit_to_tumblr(username, video_id):
    ''' Submits the FrameBuzz video to Tumblr asnycronously,
        after we receive feedback that the video upload is fully complete.
        Additionally adds the video to the user's collection. '''
    # Gather credentials.
    tumblr_app = SocialApp.objects.get(provider='tumblr')
    user = User.objects.get(username__iexact=username)
    act = SocialAccount.objects.get(user=user)
    tumblr_user = SocialToken.objects.get(app=tumblr_app, account=act)
    # Connect to Tumblr API.
    client = pytumblr.TumblrRestClient(tumblr_app.client_id, tumblr_app.secret,
                                       tumblr_user.token,
                                       tumblr_user.token_secret)
    # Send video data to Tumblr on behalf of the submitting user.
    v = Video.objects.get(video_id=video_id)
    caption = settings.TUMBLR_POST_TEXT % (v.title, v.formatted_description)
    create_kwargs = encoded_dict({
        'date': datetime.datetime.now(),
        'format': 'html',
        'caption': caption,
        'embed': v.embed_code(),
        'tags': ['#framebuzz']
    })
    # Parse API response from Tumblr.
    response = client.create_video(blogname=act.uid, **create_kwargs)
    post_id = response.get('id', None)
    if post_id:
        # Add new video to collection. Store post link for later.
        v.submit_to_tumblr = True
        v.save()
        uv, created = UserVideo.objects.get_or_create(user=user, video=v)
        uv.tumblr_link = 'http://%s.tumblr.com/post/%s/' % (act.uid, post_id)
        uv.save()
Example #10
0
 def __init__(self):
     self.client = pytumblr.TumblrRestClient(
         ENV['TUMBLR_CONSUMER_KEY'],
         ENV['TUMBLR_CONSUMER_SECRET'],
         ENV['TUMBLR_OAUTH_TOKEN'],
         ENV['TUMBLR_OAUTH_SECRET'],
     )
Example #11
0
 def get_client(self):
     return pytumblr.TumblrRestClient(
         constants.TUMBLR_CONSUMER_KEY,
         constants.TUMBLR_CONSUMER_SECRET,
         constants.OAUTH_TOKEN,
         constants.OAUTH_SECRET,
     )
Example #12
0
 def __init__(self, api):
     self.tumblr = pytumblr.TumblrRestClient(
         consumer_key=api["consumer_key"],
         consumer_secret=api["consumer_secret"],
         oauth_token=api["oauth_token"],
         oauth_secret=api["oauth_secret"]
     )
Example #13
0
 def __init__(self, pif, name='bamca'):
     pif.secure.set_config('tumblr')
     self.name = name
     self.client = pytumblr.TumblrRestClient(pif.secure.oauth,
                                             pif.secure.secret,
                                             pif.secure.key,
                                             pif.secure.value)
Example #14
0
    def authenticate(self):
        self.client = pytumblr.TumblrRestClient(
            self.config.consumer_key,
            self.config.consumer_secret,
            self.config.access_token,
            self.config.access_secret,
        )

        info = self.client.info()
        if info["user"]:
            self.user = info["user"]
            self.blog_name = self.user["blogs"][0]["name"]

        try:
            if "meta" in info:
                if info["meta"]["status"] == 401:
                    self.authenticated = False
                    self.logger.error("Authenication failed: {0}, {1}".format(
                        info["meta"]["status"], info["meta"]["msg"]))
            else:
                self.authenticated = True
                self.logger.info("Successfully authenticated.")

        except Exception as ex:
            self.authenticated = False
            handle_error_with_trace(ex, self.logger)
            raise
def fetch_tumblr():
    
    # From pytumblr API https://github.com/tumblr/pytumblr
    # Create a credentials.json file as follows
    # {
    #  "consumer_key": "XXXXXXXXXXXX7YSB5dYM3F3IpcSPPO4MkLg",
    #  "consumer_secret": "XXXXXXXXXXXXOSpC648SoZ3u0IUUwTARFc",
    #  "oauth_token": "XXXXXXXXXXXXXXXXXdOo2iBRbY",
    #  "oauth_secret": "XXXXXXXXXXXXXX60Xkbh5BcFrmP85zDsWCFSdM4YF"
    # }
    client = pytumblr.TumblrRestClient(credentials['consumer_key'], credentials['consumer_secret'], credentials['oauth_token'], credentials['oauth_secret']);

    result = []
    r = range(9)
    for off in r:
        posts = client.posts('accidental-art.tumblr.com', limit=20, offset=off, notes_info=True, filter='text')
        for p in posts['posts']:
            d = {};
            d['url'] = p['photos'][0]['alt_sizes'][0]['url'];
            d['filename'] = d['url'].strip().split('/')[-1].strip()
            d['text'] = p['summary'];
            d['source'] = 'tumblr';
            d['post_url'] = p['post_url'];
            full_path = os.path.join(os.getcwd(), OUTPUT_IMAGES_DIR)
            if(os.path.isfile(full_path)):
                print(full_path, "already downloaded")
            else:
                download(d['url'], d['filename'], full_path)
                time.sleep(2)
            result.append(d);
    return result
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("folder", help="folder to save liked photos")
    parser.add_argument("consumer_key",
                        help="consumer key for the Tumblr blog")
    parser.add_argument("consumer_secret",
                        help="consumer secret for the Tumblr blog")
    parser.add_argument("oauth_token", help="oauth token for the Tumblr blog")
    parser.add_argument("oauth_token_secret",
                        help="oauth token secret for the Tumblr blog")
    parser.add_argument(
        "--unlike",
        help=
        "unlikes processed likes, saves restore information to unliked.txt",
        action="store_true")
    parser.add_argument("--like",
                        help="likes unliked posts stored in unliked.txt",
                        action="store_true")
    args = parser.parse_args()

    colorama.init()
    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

    client = pytumblr.TumblrRestClient(args.consumer_key, args.consumer_secret,
                                       args.oauth_token,
                                       args.oauth_token_secret)

    if args.like:
        like(client, "{}\\unliked.txt".format(args.folder))
        return

    likes = save_photo_likes(client, args.folder)
    if (args.unlike):
        unlike(client, likes, "{}\\unliked.txt".format(args.folder))
def main():
    blogname = sys.argv[1]
    num_sources = int(sys.argv[2])
    depth = int(sys.argv[3])
    filename = sys.argv[4]

    # load tumblr auth from file
    with open('tumblr_config.json', 'rb') as f:
        conf = json.loads(f.read())

    client = pytumblr.TumblrRestClient(
        conf['consumer_key'],
        conf['consumer_secret'],
        conf['oauth_token'],
        conf['oauth_secret']
    )

    # build the graph
    graph = graphviz.Digraph(format='svg')
    build_graph(client, graph, blogname, num_sources, depth)

    # style the graph
    graph.graph_attr.update({'fontcolor': 'white', 'bgcolor': '#333333',
                             'rankdir': 'BT', 'fontsize': '12',})
    graph.node_attr.update({'fontname': 'Helvetica', 'fontsize': '14',
                            'fontcolor': 'white', 'color': 'white',
                            'style': 'filled', 'fillcolor': '#006699',})
    graph.edge_attr.update({'style': 'dashed', 'color': 'white',
                            'arrowhead': 'open', 'fontname': 'Courier',
                            'fontsize': '12', 'fontcolor': 'white'})
    graph.render(filename)
    return
Example #18
0
def main():
    args = docopt(__doc__)
    oldblog = args.get('OLDBLOG',False) or "log.shackspace.de"
    newblog = args.get('NEWBLOG',False) or "shackspace.tumblr.com"
    client = pytumblr.TumblrRestClient(
          consumer_key
        , consumer_secret
        , token
        , token_secret
    )
    postnum = int(args['--end']) if args['--end'] else int(client.posts(oldblog)['blog']['total_posts'])
    limit = int(args['--limit'])
    begin = int(args['--begin'])
    print('from:{} to:{} begin:{} end:{} limit:{}'.format(oldblog,newblog,begin,postnum,limit))

    for offset in reversed(range(begin,postnum,limit)):
        print("current offset: {}".format(offset))
        for post in reversed(client.posts(oldblog,limit=limit,offset=offset)['posts']):

            ident = post['id']
            summary = post['summary']
            reblogkey = post['reblog_key']
            print('moving post: {} ({} {})'.format(summary,ident,reblogkey))
            ret = client.reblog(newblog, id=ident, reblog_key=reblogkey)
            print('Return code {} - {}'.format(ret['meta']['status'],ret['meta']['msg']))
            if ret['meta']['status'] == 400:
                print("got 400 error from tumblr ....")
                pprint(ret)
                sys.exit()
 def __init__(self):
     self.client = pytumblr.TumblrRestClient(
         config.thumblr['consumer_key'],
         config.thumblr['consumer_secret'],
         config.thumblr['oauth_token'],
         config.thumblr['oauth_secret'],
     )
Example #20
0
    def setUp(self):
        configPath = os.path.join(basePath, 'config', 'tumblr-config.json')
        try:
            with open(configPath, 'rb') as f:
                s = json.loads(f.read())
        except:
            raise SkipTest("Could not access Tumblr configuration file.")

        self.params = s['tumblrText']

        self.client = pytumblr.TumblrRestClient(
            self.params['key'],
            self.params['secret'],
            self.params['token'],
            self.params['token_secret'],
        )

        self.randText = ''.join(
            [random.choice(string.letters) for i in range(10)])

        self.apiParams = {}
        self.apiParams['filter'] = 'raw'

        from sneakers.channels.tumblrText import Tumblrtext

        self.chan = Tumblrtext()
        self.chan.params['sending'] = self.params
        self.chan.params['receiving'] = self.params
Example #21
0
def readMessage():
    # Authenticate via OAuth
    client = pytumblr.TumblrRestClient(C_KEY, C_SECRET, O_TOKEN, O_SECRET)

    message = client.submission(USERNAME)['posts'][0]['question']

    return message
Example #22
0
    def handle(self, *args, **kwargs):
        CONSUMER_KEY = settings.TWITTER_API_KEY
        CONSUMER_SECRET = settings.TWITTER_API_SECRET
        ACCESS_KEY = settings.TWITTER_OAUTH_TOKEN
        ACCESS_SECRET = settings.TWITTER_OAUTH_VERIFIER

        auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
        auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
        api = tweepy.API(auth)

        twitter_hashtag_search(api, settings.HASHTAG)

        tumblr_client = pytumblr.TumblrRestClient(
            settings.TUMBLR_CONSUMER_KEY,
            settings.TUMBLR_CONSUMER_SECRET,
            settings.TUMBLR_OAUTH_TOKEN,
            settings.TUMBLR_OAUTH_SECRET,
        )
        tumblr_hashtag_search(tumblr_client)

        tries = 0
        captured_exception = None
        while tries < self.max_tries:
            try:
                my_posts_scrape()
                instagram_hashtag_scrape()
                return
            except Exception as e:
                tries += 1
                time.sleep(2**tries)
                captured_exception = e
        raise captured_exception
    def initialize(self):
        """
        Performs necessary setup things
        """
        logging.info("Logging in to Tumblr...")

        #Check if token or token-secret are blank, if so, tell user to visit https://api.tumblr.com/console and login to get token
        if self.config.token == "" or self.config.token_secret == "":
            logging.warning(
                "  -> Need to authorise the Tumblr app with your account first. Visit https://api.tumblr.com/console and login to get token and secret, then add to .config file"
            )
            quit()

        self.tumblr_client = pytumblr.TumblrRestClient(
            self.config.key, self.config.secret, self.config.token,
            self.config.token_secret)

        #Test the user has logged in
        client_details = self.tumblr_client.info()
        if 'user' in client_details:
            self.logger.info("  -> Logged in as user [%s]" %
                             client_details['user']['name'])
        else:
            self.logger.warning("  -> Error logging in: %s" % client_details)
            quit()

        logging.info("Initialisation complete!")
def main():
    client = pytumblr.TumblrRestClient(
        config.consumer_key,
        config.consumer_secret,
        config.oauth_token,
        config.oauth_secret
    )

    while True:
        mode = input('select mode (0:get post / 1:get my likes) : ')
        try:
            mode = int(mode)
        except:
            print('type it again')
            continue

        if mode == 0 or mode == 1:
            break
        else:
            print('type it again')

    if mode == 0:
        blog_name = input('blog name : ')
        get_blog_media(client, blog_name)
    else:
        get_my_likes(client)
Example #25
0
    def __init__(self) -> None:

        TumblrApi.authenticate()

        consumer_key = get_api_key('Tumblr', 'consumer_key')
        consumer_secret = get_api_key('Tumblr', 'consumer_secret')
        auth_token = get_api_key('Tumblr', 'auth_token')
        auth_token_secret = get_api_key('Tumblr', 'auth_token_secret')

        self.client = pytumblr.TumblrRestClient(
            consumer_key,
            consumer_secret,
            auth_token,
            auth_token_secret,
        )

        info = self.client.info()

        self.blogs: dict = {}
        self.current_blog_name = ''

        if 'blogs' in info:
            # get a list of all blog names
            self.blogs = info['blogs']

            # set first blog name to blog_name
            self.current_blog_name = self.blogs[0].name
Example #26
0
def to_tumblr():
    post = Blogpost.objects.filter(
        category__exact="Raaky's World").order_by('-published_date')[0]

    if (post.tumblr_uri):
        log_to_file(
            "Did not post to tumblr - tumblr URI alraedy exists! " +
            post.tumblr_uri, SOCIAL_LOG)
        return

    post_info = _fetch_post_info(post)

    #I removed these keys too
    client = pytumblr.TumblrRestClient(
        'redacted',
        'classified',
        'very classified',
        'private',
    )

    response = client.create_photo("raaky-draws",
                                   state="published",
                                   tags=post_info['tag_list'],
                                   caption=post_info['description'],
                                   data=post_info['absolute_file_path'])

    tumblr_uri = TUMBLR_BLOG_URI + "post/" + str(response['id']) + "/"
    post.tumblr_uri = tumblr_uri
    post.save()

    print(response)
Example #27
0
 def __init__(self):
     self.t = pytumblr.TumblrRestClient(
         config.get('tumblr', 'consumerKey'),
         config.get('tumblr', 'consumerSecret'),
         config.get('tumblr', 'oauthToken'),
         config.get('tumblr', 'oauthSecret'))
     self.blogName = config.get('tumblr', 'blogName')
Example #28
0
    def save_csv(self,csv_dir):
        client = pytumblr.TumblrRestClient(
            'dSzyxGsJ72cXUkoobt1TVug8wag6AzVCKlbrccBhWb2kbavKCO',
            '10JMaTu2eglGJCzEpeQI6Vt4gcVySRvdyVUBk0iVLqbkVALc0v',
            '5bTiJMhYd7UPN0fEXNgNvtR4xvco8JmV5TCtvFZjTpOGIeNgAd',
            'CLKCx31ljxzIw5QZqsszvd1tjjGOvLLwBYXjJ5CXEQzmyMGS6s'
        )

        # Make the request
        print(client.info())

        before = 1500000000
        delta_limit = 10000000

        tags = ['Happy', 'Calm', 'Sad', 'Scared', 'Bored', 'Angry', 'Annoyed', 'Love', 'Excited', 'Surprised',
                'Optimistic', 'Amazed', 'Ashamed', 'Disgusted', 'Pensive']
        title = ['id', 'post_url', 'type', 'timestamp', 'date', 'tags', 'liked', 'note_count', 'photo', 'caption',
                 'search_query']

        for tag in tags:
            posts = self.extract_tumblr_posts(client, 500, tag, before, delta_limit)
            print('length', len(posts))
            csv_path = os.path.join(csv_dir, tag + '.csv')
            csvFile = open(csv_path, 'w', newline='', encoding='utf-8')  # 设置newline,否则两行之间会空一行
            writer = csv.writer(csvFile)
            writer.writerow(title)
            for post in posts:
                writer.writerow(post)
            csvFile.close()
 def dashboard_clients(self) -> List[RateLimitClient]:
     return [
         RateLimitClient.from_tumblr_rest_client(
             pytumblr.TumblrRestClient(*keys), self.dash_blogName
         )
         for keys in self.dashboard_clients_api_keys
     ]
Example #30
0
def setup(val=False):
    yaml_path = os.path.expanduser('~') + '/.tumblr'

    if (val == True and os.path.exists(yaml_path)):
        os.remove(yaml_path)

    if not os.path.exists(yaml_path):
        try:
            tokens = new_oauth(yaml_path)
        except:
            exit("Unknown error occurred! Couldn't fetch tokens")
    else:
        yaml_file = open(yaml_path, "r")
        tokens = yaml.safe_load(yaml_file)
        yaml_file.close()

    # check availability of all tokens
    if (len(tokens) != TOTAL_TOKENS):
        try:
            tokens = new_oauth(yaml_path)
        except:
            exit("Unknown error occurred! Couldn't fetch tokens")

    client = pytumblr.TumblrRestClient(tokens['consumer_key'],
                                       tokens['consumer_secret'],
                                       tokens['oauth_token'],
                                       tokens['oauth_token_secret'])

    global key
    key = tokens['consumer_key']
    helpers.default_blog = tokens['default_blog']

    return client