Пример #1
0
def main():
    s = store.Store()
    s.init()
    tw = twitter.Twitter()
    insta = instagram.Instagram()
    ds = discord_service.DiscordService()

    for publisher_name in s.get_publishers():
        p = s.get_publisher(publisher_name)
        if not p.channel:
            continue
        for service in p.services:
            posts = None
            if service.name == 'twitter':
                posts, new_state = tw.get_new_posts(service.username,
                                                    service.state)
            if service.name == 'instagram':
                posts, new_state = insta.get_new_posts(service.username,
                                                       service.state)
            if posts is not None:
                print(publisher_name + ' ' + service.name + ', ' +
                      str(len(posts)) + ' new posts.')
                s.update_state(p.name, service.name, new_state)
                for post in posts:
                    ds.send(p.channel, post)
Пример #2
0
def instagram_download(what_drive):
    print()
    print(
        'Для выгрузки фотографий из Instagram необходимо указать следующие данные:'
    )
    if what_drive == 1:
        token_yandex = input(
            'Введите TOKEN Яндекс диска, для последующей загрузки на него фотографий: '
        )
        print()
    elif what_drive == 2:
        token_yandex = 0
        print(
            """Для работы с Google Drive, необходимо получить json файл от OAuth 2.0 Client IDs(от вашего Desktop client)
    с включённым в проекте API G-Drive. Поместите его в корень папки программы. ВАЖНО!!! 
    Измените название вашего .json файла  на 'client_secret'.Это необходимо для работы программы."""
        )
    else:
        print('Вы указали не корректный вариант.')
        exit()

    access_token = input('Вставьте сюда ваш Instagram "Access token": ')
    print()

    number_of_photo = int(
        input(
            'Введите цифрой количество фотографий, которое необходимо выгрузить: '
        ))
    print('Ожидайте...Выгрузка фотографий началась.')
    send = instagram.Instagram(access_token, token_yandex, number_of_photo)
    print('Выгрузка завершена.')
Пример #3
0
  def test_get_activities_passes_through_access_token(self):
    self.expect_urlopen(
      'https://api.instagram.com/v1/users/self/feed?access_token=asdf',
      json.dumps({'meta': {'code': 200}, 'data': []}))
    self.mox.ReplayAll()

    self.instagram = instagram.Instagram(access_token='asdf')
    self.instagram.get_activities()
Пример #4
0
  def test_preview_comment(self):
    # comment obj doesn't have a url prior to publishing
    to_publish = copy.deepcopy(COMMENT_OBJS[0])
    del to_publish['url']

    self.mox.ReplayAll()
    preview = instagram.Instagram(
      allow_comment_creation=True).preview_create(to_publish)

    self.assertIn('comment', preview.description)
    self.assertIn('this post', preview.description)
    self.assertIn('very cute', preview.content)
Пример #5
0
  def test_create_comment_unauthorized(self):
    # a more realistic test. this is what happens when you try to
    # create comments with the API, with an unapproved app
    self.expect_urlopen(
      'https://api.instagram.com/v1/media/123_456/comments',
      data=urllib.urlencode({'access_token': self.instagram.access_token,
                             'text': COMMENTS[0]['text']}),
      response='{"meta": {"code": 400, "error_type": u"OAuthPermissionsException", "error_message": "This request requires scope=comments, but this access token is not authorized with this scope. The user must re-authorize your application with scope=comments to be granted write permissions."}}',
      status=400)

    self.mox.ReplayAll()
    to_publish = copy.deepcopy(COMMENT_OBJS[0])
    del to_publish['url']

    self.assertRaises(urllib2.HTTPError, instagram.Instagram(
      allow_comment_creation=True).create, to_publish)
Пример #6
0
  def test_create_comment(self):
    self.expect_urlopen(
      'https://api.instagram.com/v1/media/123_456/comments',
      '{"meta":{"status":200}}',
      data=urllib.urlencode({'access_token': self.instagram.access_token,
                             'text': COMMENTS[0]['text']}))

    self.mox.ReplayAll()
    to_publish = copy.deepcopy(COMMENT_OBJS[0])
    del to_publish['url']

    result = instagram.Instagram(allow_comment_creation=True).create(to_publish)
    # TODO instagram does not give back a comment object; not sure how to
    # get the comment id. for now, just check that creation was successful
    # self.assert_equals(source.creation_result(COMMENT_OBJS[0]),
    #                   self.instagram.create(to_publish))
    self.assertTrue(result.content)
    self.assertFalse(result.abort)
Пример #7
0
 def setUp(self):
   super(InstagramTest, self).setUp()
   self.instagram = instagram.Instagram()
Пример #8
0
def main():
    if PARAMS['command'] is None:
        utils.print_message("Error: Empty command. Exit.")
        return

    login, password = utils.read_login_pwd()
    insta = instagram.Instagram(login, password)

    #statistic
    inserted_posts = 0
    successfuly_posted = 0
    new_accounts = 0
    posted_comments = 0

    utils.print_message("Command: '{}'".format(PARAMS['command']))
    if PARAMS['command'].lower() == "insert_posts":
        for post in PARAMS["posts"]:
            utils.print_message("Inserted {} of {} rows".format(
                inserted_posts, len(PARAMS["posts"])),
                                2,
                                end="\r")
            try:
                inserted_posts += 1 if db_utils.add_post(post[0],
                                                         post[1]) else 0
            except:
                utils.print_message(traceback.format_exc())
                pass
        utils.print_message("Inserted rows {}. In control file {} {}".format(
            inserted_posts, len(PARAMS["posts"]), " " * 20))
        db_utils.commit()
    elif PARAMS['command'].lower() == "posting":
        utils.print_message("Processing...")
        posts = db_utils.get_not_posted_posts(PARAMS["posts_count"])
        for post_num, post in enumerate(posts):
            id, fname, descr = post
            try:
                if insta.post_photo(fname, descr):
                    db_utils.set_posted(id)
                    successfuly_posted += 1
                if post_num < len(posts) - 1:
                    for seconds in range(PARAMS['timeout']):
                        utils.print_message(
                            "Sleep {} seconds...".format(PARAMS['timeout'] -
                                                         seconds),
                            2,
                            end="\r")
                        time.sleep(1)
                utils.print_message(" " * 25, 2, end="\r")
            except:
                utils.print_message(traceback.format_exc())
                pass
        db_utils.commit()
        utils.print_message("Total new photos posted: {} {}".format(
            successfuly_posted, " " * 25))
    elif PARAMS['command'].lower() == "username2id":
        utils.print_message("Processing...")
        for user_num, username in enumerate(PARAMS["usernames"]):
            utils.print_message(
                "Get info about account #{} '{}' ({} total)...".format(
                    user_num + 1, username, len(PARAMS["usernames"])),
                2,
                end="\r")
            try:
                user_id = insta.API.username_info(username)["user"]["pk"]
                utils.print_message(
                    "Insert new account '{}' in database... {}".format(
                        username, " " * 10),
                    2,
                    end="\r")
                new_accounts += 1 if db_utils.add_user(username,
                                                       user_id) else 0
                utils.print_message(
                    "Info about account '{}' inserted in database{}".format(
                        username, " " * 25), 2)
            except:
                utils.print_message(traceback.format_exc())
                utils.print_message(
                    "Hasn't info about account '{}' {}".format(
                        username, " " * 25), 2)
        utils.print_message("Inserted new accounts in database: {} {}".format(
            new_accounts, " " * 25))
        db_utils.commit()
    elif PARAMS['command'].lower() == "spam":
        if PARAMS['mode'].lower() in ("users", "all"):
            utils.print_message("Spam comments to users posts...")
            posted_comments += insta.spam_in_users_comments([
                info[2]
                for info in db_utils.select_users(PARAMS['users_count'])
            ], PARAMS['text'], PARAMS['comments_count'])
        if PARAMS['mode'].lower() in ("feedline", "all"):
            utils.print_message("Spam comments to feedline posts...")
            posted_comments += insta.spam_in_timeline_comments(
                PARAMS['text'], PARAMS['comments_count'])
        utils.print_message("Posted spam comments: {} {}".format(
            posted_comments, " " * 25))
Пример #9
0
modified_date = datetime.datetime.fromtimestamp(
    os.stat(__file__).st_mtime).strftime("%Y%m%d")
VERSION = "1_%s" % modified_date

import web
#from web.wsgiserver import CherryPyWSGIServer
import subprocess
import re
import configparser
import shutil
import instagram
import printer

CWD = os.path.dirname(os.path.abspath(__file__))

insta = instagram.Instagram()
lp = printer.Printer()
logfile = "shrine.log"

configobj = configparser.ConfigParser()
configobj.read("server.ini")
config = configobj['shrine']


def config_write():
    with open("server.ini", 'w') as f:
        configobj.write(f)


ADMIN_PASSWORD = config.get('admin_password')
UPLOAD_ALLOWED = config.getboolean('upload_allowed')
Пример #10
0
    def test_single_account(self):

        crawler = instagram.Instagram()
        post_list = crawler.crawl("dsschoolkr")

        self.assertEqual(len(post_list), 2)