Beispiel #1
0
def main():
    arguments = docopt(__doc__)
    quiet = arguments['--quiet']
    username = arguments['--username']
    if arguments['--password'] is None:
        password = getpass('Password:'******'--password']
    path = arguments['<path>']

    if not os.path.isdir(path):
        print('No such directory: {0}'.format(arguments['<path>']))
        sys.exit(1)

    s = Snapchat()
    if not s.login(username, password).get('logged'):
        print('Invalid username or password')
        sys.exit(1)

    for snap in s.get_snaps():
        filename = '{0}_{1}.{2}'.format(snap['sender'], snap['id'],
                                        get_file_extension(snap['media_type']))
        abspath = os.path.abspath(os.path.join(path, filename))
        if os.path.isfile(abspath):
            continue
        data = s.get_blob(snap['id'])
        if data is None:
            continue
        with open(abspath, 'wb') as f:
            f.write(data)
            if not quiet:
                print('Saved: {0}'.format(abspath))
Beispiel #2
0
def main():
    arguments = docopt(__doc__)
    quiet = arguments['--quiet']
    username = arguments['--username']
    if arguments['--password'] is None:
        password = getpass('Password:'******'--password']
    path = arguments['<path>']

    if not os.path.isdir(path):
        print('No such directory: {0}'.format(arguments['<path>']))
        sys.exit(1)

    s = Snapchat()
    if not s.login(username, password).get('logged'):
        print('Invalid username or password')
        sys.exit(1)

    for snap in s.get_snaps():
        filename = '{0}_{1}.{2}'.format(snap['sender'], snap['id'],
                                        get_file_extension(snap['media_type']))
        abspath = os.path.abspath(os.path.join(path, filename))
        if os.path.isfile(abspath):
            continue
        data = s.get_blob(snap['id'])
        if data is None:
            continue
        with open(abspath, 'wb') as f:
            f.write(data)
            if not quiet:
                print('Saved: {0}'.format(abspath))
Beispiel #3
0
def main():
    arguments = docopt(__doc__)
    quiet = arguments['--quiet']
    username = arguments['--username']
    if arguments['--password'] is None:
        password = getpass('Password:'******'--password']
    #path = arguments['<path>']
    path = "snaps"

    if not os.path.isdir(path):
        print('No such directory: {0}'.format(arguments['<path>']))
        sys.exit(1)

    s = Snapchat()
    if not s.login(username, password).get('logged'):
        print('Invalid username or password')
        sys.exit(1)


    for snap in s.get_snaps():
        filename = '{0}_{1}.{2}'.format(snap['sender'], snap['id'],
                                        get_file_extension(snap['media_type']))
        abspath = os.path.abspath(os.path.join(path, filename))
        if os.path.isfile(abspath):
            continue
        data = s.get_blob(snap['id'])
        if data is None:
            continue
        with open(abspath, 'wb') as f:
            f.write(data)

            # If we successfully mark this as viewed, go ahead and email it.
            if s.mark_viewed(snap['id']):
                # Setup email message
                msg = MIMEMultipart()
                msg['From'] = "Snapchat"
                msg['To'] = email_toaddrs
                msg['Subject'] = "Snapchat from %s" % snap['sender']
                body = "You have received a new snapchat from %s" % snap['sender']
                msg.attach(MIMEText(body, "plain"))
                msg.attach(MIMEImage(data))

                # The actual mail send
                if not quiet:
                    print("Sending mail!")
                server = smtplib.SMTP()
                server.connect('mailhub.iastate.edu', 25)
                server.ehlo()
                server.starttls()
                #server.login('username', 'password')
                server.sendmail(email_fromaddr, email_toaddrs, msg.as_string())
                server.quit()

            if not quiet:
                print('Saved: {0}'.format(abspath))
Beispiel #4
0
def receive(username, password):
    path = "pictures"
    quiet = True
    if not os.path.isdir(path):
        print('No such directory: {0}'.format(path))
        sys.exit(1)
    s = Snapchat()
    if not s.login(username, password).get('logged'):
        print('Invalid username or password')
        sys.exit(1)

    for snap in s.get_snaps():
        process_snap(s, snap, path, quiet)
Beispiel #5
0
def main():
    arguments = docopt(__doc__)
    quiet = arguments['--quiet']
    username = arguments['--username']
    if arguments['--password'] is None:
        password = getpass('Password:'******'--password']
    path = arguments['<path>']

    if not os.path.isdir(path):
        print('No such directory: {0}'.format(arguments['<path>']))
        sys.exit(1)

    s = Snapchat()
    if not s.login(username, password).get('logged'):
        print('Invalid username or password')
        sys.exit(1)

    while True:
        try:
            for snap in s.get_snaps():
                filename = '{0}_{1}.{2}'.format(snap['sender'], snap['id'],
                                                get_file_extension(snap['media_type']))
                abspath = os.path.abspath(os.path.join(path, filename))
                if os.path.isfile(abspath):
                    continue
                data = s.get_blob(snap['id'])
                if data is None:
                    continue
                with open(abspath, 'wb') as f:
                    f.write(data)
                    if not quiet:
                        print('Saved: {0}'.format(abspath))
            time.sleep(5*60)
        except HTTPError: # v pripade ze se prihlasim na snapchatu na mobilu tak me to odhlasi tady
            print('logged of, waiting for another five minutes')
            time.sleep(5*60)
            del s
            s = Snapchat()
            if not s.login(username, password).get('logged'):
                print('Invalid username or password')
                sys.exit(1)            
Beispiel #6
0
def initialize_and_monitor():
	snapObject = Snapchat()
	snapObject.login(userAuth.USERNAME, userAuth.PASSWORD) #imported from a file called userAuth.py, which has two variables, USERNAME = "******" and PASSWORD = "******"
	added_snaps = []
	if (os.path.isfile("./pickled_files/added_snaps.pkl")):
		added_snaps = pickle.load(open("./pickled_files/added_snaps.pkl", 'rb'))
	try:
		while True:
			snaps = []
			for snap in snapObject.get_snaps():
				if snap['sender'] != 'teamsnapchat' and snap['id'] not in added_snaps:
					snaps.append(snapObject.get_blob(snap['id']))
					added_snaps.append(snap['id'])

			count = 0
			paths = []
			for snap in snaps:
				currpath = 'snap'+ str(count) + ".jpeg"
				if snap:
					with open(currpath, 'wb') as f:
						f.write(snap)
					paths.append(currpath)
					count += 1

			media_ids = [snapObject.upload(path) for path in paths]
			
			for media_id in media_ids:
				is_sent = snapObject.send_to_story(media_id)
				print(is_sent)
			
			for path in paths:
				os.remove(path)
			
			print('Finished one iteration, sleeping for a minute now')
			time.sleep(60)
	except:
		traceback.print_exc(file=sys.stdout)
	finally:
		with open("./pickled_files/added_snaps.pkl", 'wb') as output:
			pickle.dump(added_snaps, output, -1)
		sys.exit()
Beispiel #7
0
def main():
    arguments = docopt(__doc__)
    quiet = arguments['--quiet']
    username = arguments['--username']
    if arguments['--password'] is None:
        password = getpass('Password:'******'--password']
    path = arguments['<path>']

    if not os.path.isdir(path):
        print('No such directory: {0}'.format(arguments['<path>']))
        sys.exit(1)

    s = Snapchat()
    if not s.login(username, password).get('logged'):
        print('Invalid username or password')
        sys.exit(1)

    for snap in s.get_snaps():
        process_snap(s, snap, path, quiet)
def main():
    arguments = docopt(__doc__)
    username = arguments['-u']
    if arguments['-p'] is None:
        password = getpass('Password:'******'-p']
    path = arguments['-d']
    save = arguments['-s']
    verbose = arguments['-v']
    whiteListFile = arguments['WHITELIST']

    if not os.path.isdir(path):
        print('No such directory: {0}'.format(path))
        sys.exit(1)

    s = Snapchat()
    if verbose:
        print('Attempting to log in as {0}.'.format(username))
    if not s.login(username, password).get('logged'):
        print('Invalid username or pasword')
        sys.exit(1)

    if verbose:
        print('Attempting to open whitelist file at {0}.'.format(whiteListFile))
    with open(whiteListFile, 'r') as f:
        whitelist = [line.rstrip() for line in f]
        if verbose:
            print('Succesfully read whitelist and extracted {0} lines. Attempting to handle friends'.format(len(whitelist)))
        #sys.exit(0)
        addFriends(s,whitelist,verbose)

    
    for snap in s.get_snaps():
        if verbose:
            print('Working with snap')
        sendSnapToStory(s,snap,path,save,verbose)

    sys.exit(0)
Beispiel #9
0
def main():
    arguments = docopt(__doc__)
    quiet = arguments['--quiet']
    username = arguments['--username']
    period = int(arguments['--waittime'])
    if arguments['--password'] is None:
        password = getpass('Password:'******'--password']
    
    s = Snapchat()
    if not s.login(username, password).get('logged'):
        print('Invalid username or password')
        sys.exit(1)

    print('Running Brunonia for ' + username + ' on directory ' + os.getcwd())
    while True:
        #fetching snaps
        print('Fetching snaps...')
        for snap in s.get_snaps():
            process_snap(s, snap, os.getcwd(), False)
        print('Waiting for ' + str(period) + ' seconds...')
        time.sleep(period)
    return 0
Beispiel #10
0
class SnapchatBot(object):
    def __init__(self, username, password, **kwargs):
        self.bot_id = uuid.uuid4().hex[0:4]

        self.username = username
        self.password = password

        self.client = Snapchat()
        self.client.login(username, password)

        self.current_friends = self.get_friends()
        self.added_me = self.get_added_me()

        if hasattr(self, "initialize"):
            self.initialize(**kwargs)

    def log(self, message, level=logging.DEBUG):
        logger.log(level, "[%s-%s] %s" % (self.__class__.__name__, self.bot_id, message))

    @staticmethod
    def process_snap(snap_obj, data):
        media_type = snap_obj["media_type"]
        sender = snap_obj["sender"]
        snap_id = snap_obj['id']
        duration = snap_obj['time']
        snap = Snap(data=data,
                    snap_id=snap_id,
                    media_type=media_type,
                    duration=duration,
                    sender=sender)
        return snap

    def mark_viewed(self, snap):
        self.client.mark_viewed(snap.snap_id)

    def listen(self, timeout=DEFAULT_TIMEOUT):
        while True:
            self.log("Querying for new snaps...")
            snaps = self.get_snaps()

            if hasattr(self, "on_snap"):
                for snap in snaps:
                    self.on_snap(snap.sender, snap)

            added_me = self.get_added_me()

            newly_added = set(added_me).difference(self.added_me)
            newly_deleted = set(self.added_me).difference(added_me)

            self.added_me = added_me

            if hasattr(self, "on_friend_add"):
                for friend in newly_added:
                    self.log("User %s added me" % friend)
                    self.on_friend_add(friend)

            if hasattr(self, "on_friend_delete"):
                for friend in newly_deleted:
                    self.log("User %s deleted me" % friend)
                    self.on_friend_delete(friend)

            time.sleep(timeout)

    def get_friends(self):
        return map(lambda fr: fr['name'], self.client.get_friends())

    def get_added_me(self):
        updates = self.client.get_updates()
        return map(lambda fr: fr['name'], updates["added_friends"])

    def send_snap(self, recipients, snap):
        self.log("Preparing to send snap %s" % snap.snap_id)

        if not snap.uploaded:
            self.log("Uploading snap %s" % snap.snap_id)
            snap.upload(self)

        if type(recipients) is not list:
            recipients = [recipients]

        recipients_str = ','.join(recipients)

        self.log("Sending snap %s to %s" % (snap.snap_id, recipients_str))

        self.client.send(snap.media_id, recipients_str)

    def post_story(self, snap):
        if not snap.uploaded:
            self.log("Uploading snap")
            snap.upload(self)

        self.log("Posting snap as story")
        self.client.send_to_story(snap.media_id, media_type=snap.media_type)

    def add_friend(self, username):
        self.client.add_friend(username)

    def delete_friend(self, username):
        self.client.delete_friend(username)

    def block(self, username):
        self.client.block(username)

    def get_snaps(self, mark_viewed=True):
        snaps = self.client.get_snaps()
        ret = []

        for snap_obj in snaps:
            if snap_obj['status'] == 2:
                continue

            data = self.client.get_blob(snap_obj["id"])

            if data is None:
                continue

            snap = self.process_snap(snap_obj, data)

            if mark_viewed:
                self.mark_viewed(snap)

            ret.append(snap)

        return ret
Beispiel #11
0
class SnapchatBot(object):
    def __init__(self, username, password, authtoken = None, **kwargs):
        self.bot_id = uuid.uuid4().hex[0:4]

        self.auth_token = STATIC_TOKEN

        if authtoken is not None:
            self.auth_token = authtoken
        else:

            self.username = username
            self.password = password
            r = self._make_request("/loq/login", {
                'username': self.username,
                'password': self.password
            })

            result = r.json()
            print result
            self.auth_token = result['updates_response']['auth_token']

        self.client = Snapchat()
        self.client.username = username
        self.client.auth_token = self.auth_token

        self.current_friends = self.get_friends()
        self.added_me = self.get_added_me()

        if hasattr(self, "initialize"):
            self.initialize(**kwargs)

    def log(self, message, level=logging.DEBUG):
        logger.log(level, "[%s-%s] %s" % (self.__class__.__name__, self.bot_id, message))

    @staticmethod
    def process_snap(snap_obj, data, is_story = False):
        media_type = snap_obj["media_type"]
        sender = snap_obj["sender"]
        snap_id = snap_obj['id']
        duration = snap_obj['time']
        snap = Snap(data=data,
                    snap_id=snap_id,
                    media_type=media_type,
                    duration=duration,
                    sender=sender,
                    is_story=is_story)
        return snap

    def mark_viewed(self, snap):
        self.client.mark_viewed(snap.snap_id)

    def listen(self, timeout=DEFAULT_TIMEOUT):
        while True:
            self.log("Querying for new snaps...")
            snaps = self.get_snaps()

            if hasattr(self, "on_snap"):
                for snap in snaps:
                    self.on_snap(snap.sender, snap)

            added_me = self.get_added_me()

            newly_added = set(added_me).difference(self.added_me)
            newly_deleted = set(self.added_me).difference(added_me)

            self.added_me = added_me

            if hasattr(self, "on_friend_add"):
                for friend in newly_added:
                    self.log("User %s added me" % friend)
                    self.on_friend_add(friend)

            if hasattr(self, "on_friend_delete"):
                for friend in newly_deleted:
                    self.log("User %s deleted me" % friend)
                    self.on_friend_delete(friend)

            time.sleep(timeout)

    def get_friends(self):
        return map(lambda fr: fr['name'], self.client.get_friends())

    def get_added_me(self):
        updates = self.client.get_updates()
        return map(lambda fr: fr['name'], updates["added_friends"])

    def send_snap(self, recipients, snap):
        media_id = self._upload_snap(snap)

        if type(recipients) is not list:
            recipients = [recipients]

        recipients_str = ','.join(recipients)

        self.log("Sending snap %s to %s" % (snap.snap_id, recipients_str))

        self.client.send(media_id, recipients_str, snap.duration)

    def post_story(self, snap):
        media_id = self._upload_snap(snap)
        response = self.client.send_to_story(media_id, snap.duration, snap.media_type)

        try:
            snap.story_id = response['json']['story']['id']
        except:
            pass

    def delete_story(self, snap):
        print snap.story_id
        if snap.story_id is None:
            return

        self.client._request('delete_story', {
            'username': self.username,
            'story_id': snap.story_id
        })

    def add_friend(self, username):
        self.client.add_friend(username)

    def delete_friend(self, username):
        self.client.delete_friend(username)

    def block(self, username):
        self.client.block(username)

    def process_snaps(self, snaps, mark_viewed = True):
        ret = []

        for snap_obj in snaps:
            if snap_obj['status'] == 2:
                continue

            data = self.client.get_blob(snap_obj["id"])

            if data is None:
                continue

            snap = self.process_snap(snap_obj, data)

            if mark_viewed:
                self.mark_viewed(snap)

            ret.append(snap)

        return ret

    def process_stories(self, stories):
        ret = []
        for snap_obj in stories:
            media_key = base64.b64decode(snap_obj['media_key'])
            media_iv = base64.b64decode(snap_obj['media_iv'])
            data = self.client.get_story_blob(snap_obj['media_id'],
                                              media_key,
                                              media_iv)
            if data is None:
                continue
            snap_obj['sender'] = self.username
            snap = self.process_snap(snap_obj, data, is_story = True)
            ret.append(snap)
        return ret

    def get_snaps(self, mark_viewed=True):
        snaps = self.client.get_snaps()
        return self.process_snaps(snaps)

    def get_my_stories(self):
        response = self.client._request('stories', {
            'username': self.username
        })
        stories = map(lambda s: s['story'], response.json()['my_stories'])
        return self.process_stories(stories)

    def get_friend_stories(self):
        response = self.client._request('stories', {
            'username': self.username
        })
        ret = []
        stories_per_friend = map(lambda s: s['stories'], response.json()['friend_stories'])
        for stories_obj in stories_per_friend:
            stories = map(lambda so: so['story'], stories_obj)
            ret.extend(self.process_stories(stories))
        return ret

    def clear_stories(self):
        for story in self.get_my_stories():
            self.delete_story(story)

    def _upload_snap(self, snap):
        if not snap.uploaded:
            snap.media_id = self.client.upload(snap.file.name)
            snap.uploaded = True

        return snap.media_id

    def _make_request(self, path, data = None, method = 'POST', files = None):
        if data is None:
            data = {}

        headers = {
            'User-Agent': 'Snapchat/8.1.1 (iPhone5,1; iOS 8.1.3; gzip)',
            'Accept-Language': 'en-US;q=1, en;q=0.9',
            'Accept-Locale': 'en'
        }

        now = timestamp()

        if method == 'POST':
            data['timestamp'] = now
            data['req_token'] = make_request_token(self.auth_token, str(now))
            resp = requests.post(BASE_URL + path, data = data, files = files, headers = headers)
        else:
            resp = requests.get(BASE_URL + path, params = data, headers = headers)

        return resp
Beispiel #12
0
class SnapchatBot(object):
    def __init__(self, username, password, **kwargs):
        self.bot_id = uuid.uuid4().hex[0:4]

        self.username = username
        self.password = password

        self.client = Snapchat()
        self.client.login(username, password)

        self.current_friends = self.get_friends()
        self.added_me = self.get_added_me()

        self.events = []
        self.ticks = 0

        if hasattr(self, "initialize"):
            self.initialize(**kwargs)

    def log(self, message, level = logging.DEBUG):
        logger.log(level, "[%s-%s] %s" % (self.__class__.__name__, self.bot_id, message))

    def process_snap(self, snap_obj, data):
        media_type = snap_obj["media_type"]
        sender = snap_obj["sender"]
        snap_id = snap_obj['id']
        duration = snap_obj['time']
        snap = Snap(data = data,
                    snap_id = snap_id,
                    media_type = media_type,
                    duration = duration,
                    sender = sender)
        return snap

    def mark_viewed(self, snap):
        self.client.mark_viewed(snap.snap_id)

    def listen(self, timeout = DEFAULT_TIMEOUT):
        while True:
            self.log("Querying for new snaps...")
            snaps = self.get_snaps()

            if hasattr(self, "on_snap"):
                for snap in snaps:
                    self.on_snap(snap.sender, snap)

            added_me = self.get_added_me()

            newly_added = set(added_me).difference(self.added_me)
            newly_deleted = set(self.added_me).difference(added_me)

            self.added_me = added_me

            if hasattr(self, "on_friend_add"):
                for friend in newly_added:
                    self.log("User %s added me" % friend)
                    self.on_friend_add(friend)

            if hasattr(self, "on_friend_delete"):
                for friend in newly_deleted:
                    self.log("User %s deleted me" % friend)
                    self.on_friend_delete(friend)
            
            self.ticks += 1
            freq = 0
            while self.ticks % 2**freq == 0:
                if freq < len(self.events):
                    for func in self.events[freq]:
                        func()
                freq += 1

            time.sleep(timeout)

    def register_event(self, freq, func):
        if len(self.events) <= freq:
            self.events.extend([[] for i in xrange(1 + freq - len(self.events))])
        self.events[freq].append(func)

    def get_friends(self):
        return map(lambda fr: fr['name'], self.client.get_friends())

    def get_added_me(self):
        updates = self.client.get_updates()
        return map(lambda fr: fr['name'], updates["added_friends"])

    def send_snap(self, recipients, snap):
        self.log("Preparing to send snap %s" % snap.snap_id)

        if not snap.uploaded:
            self.log("Uploading snap %s" % snap.snap_id)
            snap.upload(self)

        if type(recipients) is not list:
            recipients = [recipients]

        recipients_str = ','.join(recipients)

        self.log("Sending snap %s to %s" % (snap.snap_id, recipients_str))

        self.client.send(snap.media_id, recipients_str)

    def post_story(self, snap):
        if not snap.uploaded:
            self.log("Uploading snap")
            snap.upload(self)

        self.log("Posting snap as story")
        self.client.send_to_story(snap.media_id, media_type = snap.media_type)

    def add_friend(self, username):
        self.client.add_friend(username)

    def delete_friend(self, username):
        self.client.delete_friend(username)

    def block(self, username):
        self.client.block(username)

    def get_snaps(self, mark_viewed = True):
        snaps = self.client.get_snaps()
        ret = []

        for snap_obj in snaps:
            if snap_obj['status'] == 2:
                continue

            data = self.client.get_blob(snap_obj["id"])

            if data is None:
                continue

            snap = self.process_snap(snap_obj, data)

            if mark_viewed:
                self.mark_viewed(snap)

            ret.append(snap)

        return ret
Beispiel #13
0
class SnapchatBot(object):
    def __init__(self, username, password, **kwargs):
        self.bot_id = uuid.uuid4().hex[0:4]

        self.auth_token = STATIC_TOKEN

        self.username = username
        self.password = password

        r = self._make_request("/loq/login", {
            'username': self.username,
            'password': self.password
        })

        result = r.json()
        self.auth_token = result['updates_response']['auth_token']

        self.client = Snapchat()
        self.client.username = username
        self.client.auth_token = self.auth_token

        self.current_friends = self.get_friends()
        self.added_me = self.get_added_me()

        if hasattr(self, "initialize"):
            self.initialize(**kwargs)

    def log(self, message, level=logging.DEBUG):
        logger.log(
            level,
            "[%s-%s] %s" % (self.__class__.__name__, self.bot_id, message))

    @staticmethod
    def process_snap(snap_obj, data, is_story=False):
        media_type = snap_obj["media_type"]
        sender = snap_obj["sender"]
        snap_id = snap_obj['id']
        duration = snap_obj['time']
        snap = Snap(data=data,
                    snap_id=snap_id,
                    media_type=media_type,
                    duration=duration,
                    sender=sender,
                    is_story=is_story)
        return snap

    def mark_viewed(self, snap):
        self.client.mark_viewed(snap.snap_id)

    def listen(self, timeout=DEFAULT_TIMEOUT):
        while True:
            self.log("Querying for new snaps...")
            snaps = self.get_snaps()

            if hasattr(self, "on_snap"):
                for snap in snaps:
                    self.on_snap(snap.sender, snap)

            added_me = self.get_added_me()

            newly_added = set(added_me).difference(self.added_me)
            newly_deleted = set(self.added_me).difference(added_me)

            self.added_me = added_me

            if hasattr(self, "on_friend_add"):
                for friend in newly_added:
                    self.log("User %s added me" % friend)
                    self.on_friend_add(friend)

            if hasattr(self, "on_friend_delete"):
                for friend in newly_deleted:
                    self.log("User %s deleted me" % friend)
                    self.on_friend_delete(friend)

            time.sleep(timeout)

    def get_friends(self):
        return map(lambda fr: fr['name'], self.client.get_friends())

    def get_added_me(self):
        updates = self.client.get_updates()
        return map(lambda fr: fr['name'], updates["added_friends"])

    def send_snap(self, recipients, snap):
        media_id = self._upload_snap(snap)

        if type(recipients) is not list:
            recipients = [recipients]

        recipients_str = ','.join(recipients)

        self.log("Sending snap %s to %s" % (snap.snap_id, recipients_str))

        self.client.send(media_id, recipients_str, snap.duration)

    def post_story(self, snap):
        media_id = self._upload_snap(snap)
        response = self.client.send_to_story(media_id, snap.duration,
                                             snap.media_type)

        try:
            snap.story_id = response['json']['story']['id']
        except:
            pass

    def delete_story(self, snap):
        print snap.story_id
        if snap.story_id is None:
            return

        self.client._request('delete_story', {
            'username': self.username,
            'story_id': snap.story_id
        })

    def add_friend(self, username):
        self.client.add_friend(username)

    def delete_friend(self, username):
        self.client.delete_friend(username)

    def block(self, username):
        self.client.block(username)

    def process_snaps(self, snaps, mark_viewed=True):
        ret = []

        for snap_obj in snaps:
            if snap_obj['status'] == 2:
                continue

            data = self.client.get_blob(snap_obj["id"])

            if data is None:
                continue

            snap = self.process_snap(snap_obj, data)

            if mark_viewed:
                self.mark_viewed(snap)

            ret.append(snap)

        return ret

    def process_stories(self, stories):
        ret = []
        for snap_obj in stories:
            media_key = base64.b64decode(snap_obj['media_key'])
            media_iv = base64.b64decode(snap_obj['media_iv'])
            data = self.client.get_story_blob(snap_obj['media_id'], media_key,
                                              media_iv)
            if data is None:
                continue
            snap_obj['sender'] = self.username
            snap = self.process_snap(snap_obj, data, is_story=True)
            ret.append(snap)
        return ret

    def get_snaps(self, mark_viewed=True):
        snaps = self.client.get_snaps()
        return self.process_snaps(snaps)

    def get_my_stories(self):
        response = self.client._request('stories', {'username': self.username})
        stories = map(lambda s: s['story'], response.json()['my_stories'])
        return self.process_stories(stories)

    def get_friend_stories(self):
        response = self.client._request('stories', {'username': self.username})
        ret = []
        stories_per_friend = map(lambda s: s['stories'],
                                 response.json()['friend_stories'])
        for stories_obj in stories_per_friend:
            stories = map(lambda so: so['story'], stories_obj)
            ret.extend(self.process_stories(stories))
        return ret

    def clear_stories(self):
        for story in self.get_my_stories():
            self.delete_story(story)

    def _upload_snap(self, snap):
        if not snap.uploaded:
            snap.media_id = self.client.upload(snap.file.name)
            snap.uploaded = True

        return snap.media_id

    def _make_request(self, path, data=None, method='POST', files=None):
        if data is None:
            data = {}

        headers = {
            'User-Agent': 'Snapchat/8.1.1 (iPhone5,1; iOS 8.1.3; gzip)',
            'Accept-Language': 'en-US;q=1, en;q=0.9',
            'Accept-Locale': 'en'
        }

        now = timestamp()

        if method == 'POST':
            data['timestamp'] = now
            data['req_token'] = make_request_token(self.auth_token, str(now))
            resp = requests.post(BASE_URL + path,
                                 data=data,
                                 files=files,
                                 headers=headers)
        else:
            resp = requests.get(BASE_URL + path, params=data, headers=headers)

        return resp
Beispiel #14
0
#!/usr/bin/env python

from pysnap import Snapchat
import secrets
import os

path = os.path.dirname(os.path.realpath(__file__)) + '/tmp.jpg'

s = Snapchat()
s.login(secrets.USERNAME, secrets.PASSWORD)

for friend in [friend['name'] for friend in s.get_updates()['added_friends'] if friend['type'] == 1]:
    s.add_friend(friend)

snaps = [snap for snap in s.get_snaps() if snap['status'] == 1 and snap['media_type'] == 0]
for snap in snaps:
    with open(path, 'wb') as f:
        f.write(s.get_blob(snap['id']))
    media_id = s.upload(path)
    print s.post_story(media_id, 5)
    s.mark_viewed(snap['id'])