Skip to content

Commit

Permalink
Ran through pyflake, mostly spacing issues
Browse files Browse the repository at this point in the history
  • Loading branch information
ChanChar committed Feb 18, 2015
1 parent 913d80e commit 2d9437e
Show file tree
Hide file tree
Showing 9 changed files with 73 additions and 38 deletions.
7 changes: 4 additions & 3 deletions examples/autowelcomebot.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from argparse import ArgumentParser
from snapchat_bots import SnapchatBot, Snap


class AutoWelcomerBot(SnapchatBot):
def on_friend_add(self, friend):
self.send_snap(friend, Snap.from_file("resources/auto_welcome.png"))
Expand All @@ -10,10 +11,10 @@ def on_friend_delete(self, friend):

if __name__ == '__main__':
parser = ArgumentParser("Auto-Welcomer Bot")
parser.add_argument('-u', '--username', required = True, type=str, help = "Username of the account to run the bot on")
parser.add_argument('-p', '--password', required = True, type=str, help = "Password of the account to run the bot on")
parser.add_argument('-u', '--username', required=True, type=str, help="Username of the account to run the bot on")

This comment has been minimized.

Copy link
@uyuyuy2
parser.add_argument('-p', '--password', required=True, type=str, help="Password of the account to run the bot on")

args = parser.parse_args()

bot = AutoWelcomerBot(args.username, args.password)
bot.listen()
bot.listen()
7 changes: 4 additions & 3 deletions examples/connectorbot.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from argparse import ArgumentParser
from snapchat_bots import SnapchatBot, Snap


class ConnectorBot(SnapchatBot):
def initialize(self):
self.connections = []
Expand Down Expand Up @@ -44,10 +45,10 @@ def on_snap(self, sender, snap):

if __name__ == '__main__':
parser = ArgumentParser("ConnectorBot Bot")
parser.add_argument('-u', '--username', required = True, type=str, help = "Username of the account to run the bot on")
parser.add_argument('-p', '--password', required = True, type=str, help = "Password of the account to run the bot on")
parser.add_argument('-u', '--username', required=True, type=str, help="Username of the account to run the bot on")
parser.add_argument('-p', '--password', required=True, type=str, help="Password of the account to run the bot on")

args = parser.parse_args()

bot = ConnectorBot(args.username, args.password)
bot.listen(timeout = 5)
bot.listen(timeout=5)
6 changes: 5 additions & 1 deletion examples/gifbot.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from snapchat_bots import SnapchatBot, Snap
from lxml.html import parse


def grab_trending_gif_urls():
doc = parse("http://giphy.com").getroot()
els = doc.cssselect(".gif-link img")[:10]
Expand All @@ -11,15 +12,18 @@ def grab_trending_gif_urls():
ret.append("http:" +re.sub(r"\/([^./])*\.gif", "/giphy.gif", el.attrib['src']))
return ret


def gif_to_video(url):
f = tempfile.NamedTemporaryFile(suffix=".mp4", delete = False)
code = subprocess.Popen(["/bin/sh", "scripts/gif_to_mp4.sh", url, f.name]).wait()
print code
print(code)
return f.name


def is_valid_video(filename):
return subprocess.Popen(["ffprobe", filename]).wait() == 0


class GIFBot(SnapchatBot):
def on_friend_add(self, friend):
self.add_friend(friend)
Expand Down
21 changes: 14 additions & 7 deletions examples/googlerbot.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,48 +6,55 @@
from snapchat_bots import SnapchatBot, Snap

def public_url_for(key):
return ('http://%s.s3.amazonaws.com/' % key.bucket.name) + key.key
return ('http://%s.s3.amazonaws.com/' % key.bucket.name) + key.key


def get_bucket(conn, name, public = False):
b = conn.get_bucket(name)
if public:
b.make_public()
return b


def upload_file(bucket, filename):
k = Key(bucket)
k.key = uuid.uuid4().hex + get_file_extension(filename)
k.set_contents_from_filename(filename)
k.make_public()
return public_url_for(k)


def get_file_extension(filename):
return os.path.splitext(filename)[1]


def get_url_extension(url):
path = urlparse.urlparse(url).path
return os.path.splitext(path)[1]


def download_file(url):
resp = requests.get(url)
local_file = tempfile.NamedTemporaryFile(suffix = get_url_extension(url), delete=False)
local_file.write(resp.content)
return local_file.name


def reverse_image_search(url):
headers = {}
headers['User-Bot'] = "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.27 Safari/537.17"
value = "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.27 Safari/537.17"
headers = {'User-Bot': value}
search_url = 'https://www.google.com/searchbyimage?image_url=%s' % url
resp = requests.get(search_url, headers=headers)
root = document_fromstring(resp.content)
href = root.cssselect(".bia")[0].attrib['href']
print search_url
print(search_url)
new_url = "https://www.google.com" + href
resp = requests.get(new_url, headers=headers)
return re.search("imgurl=([^&]*)", resp.content).group(1)


class GooglerBot(SnapchatBot):
def initialize(self, aws_key = None, aws_secret = None, bucket = None):
def initialize(self, aws_key=None, aws_secret=None, bucket=None):
self.conn = boto.connect_s3(aws_key, aws_secret)
self.bucket = get_bucket(self.conn, bucket)

Expand Down Expand Up @@ -81,5 +88,5 @@ def on_friend_delete(self, friend):

args = parser.parse_args()

bot = GooglerBot(args.username, args.password, aws_key = args.aws_key, aws_secret = args.aws_secret, bucket = args.bucket)
bot.listen(timeout = 3)
bot = GooglerBot(args.username, args.password, aws_key=args.aws_key, aws_secret=args.aws_secret, bucket=args.bucket)
bot.listen(timeout=3)
7 changes: 4 additions & 3 deletions examples/reflectorbot.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from argparse import ArgumentParser
from snapchat_bots import SnapchatBot


class ReflectorBot(SnapchatBot):
def on_snap(self, sender, snap):
self.send_snap([sender], snap)
Expand All @@ -13,10 +14,10 @@ def on_friend_delete(self, friend):

if __name__ == '__main__':
parser = ArgumentParser("Reflector Bot")
parser.add_argument('-u', '--username', required = True, type=str, help = "Username of the account to run the bot on")
parser.add_argument('-p', '--password', required = True, type=str, help = "Password of the account to run the bot on")
parser.add_argument('-u', '--username', required=True, type=str, help="Username of the account to run the bot on")
parser.add_argument('-p', '--password', required=True, type=str, help="Password of the account to run the bot on")

args = parser.parse_args()

bot = ReflectorBot(args.username, args.password)
bot.listen(timeout = 5)
bot.listen(timeout=5)
7 changes: 6 additions & 1 deletion examples/reporterbot.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,26 +6,30 @@

h = HTMLParser.HTMLParser()


def get_article_info(url):
content = urllib2.urlopen(url).read()
description = re.search("<meta name=\"Description\" content=\"([^\"]*)", content).group(1)
img_src = re.search("<meta property=\"og:image\" content=\"([^\"]*)", content).group(1)
img = download_image(img_src)
return (h.unescape(description), img)
return h.unescape(description), img


def download_image(src):
tmp = tempfile.NamedTemporaryFile(suffix = ".jpg")
tmp.write(urllib2.urlopen(src).read())
img = Image.open(tmp.name)
return img


def get_last_breaking_news_url():
content = urllib2.urlopen("https://twitter.com/BBCBreaking").read()
try:
return re.search('http://bbc.in[^<\"]*', content).group(0)
except:
pass


def create_breaking_news_image_from_info(info):
title, header_img = info
para = textwrap.wrap(title, width=30)
Expand All @@ -45,6 +49,7 @@ def create_breaking_news_image_from_info(info):

return im


class ReporterBot(SnapchatBot):
def initialize(self):
self.last_tweet_url = None
Expand Down
5 changes: 3 additions & 2 deletions examples/storifierbot.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
from argparse import ArgumentParser
from snapchat_bots import SnapchatBot


class StorifierBot(SnapchatBot):
def on_snap(self, sender, snap):
self.post_story(snap)

if __name__ == '__main__':
parser = ArgumentParser("Storifier Bot")
parser.add_argument('-u', '--username', required = True, type=str, help = "Username of the account to run the bot on")
parser.add_argument('-p', '--password', required = True, type=str, help = "Password of the account to run the bot on")
parser.add_argument('-u', '--username', required=True, type=str, help="Username of the account to run the bot on")
parser.add_argument('-p', '--password', required=True, type=str, help="Password of the account to run the bot on")

args = parser.parse_args()

Expand Down
38 changes: 23 additions & 15 deletions snapchat_bots/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@
DEFAULT_TIMEOUT = 15
DEFAULT_DURATION = 5


class UnknownMediaType(Exception):
pass


class Snap(object):
@staticmethod
def from_file(path, duration = None):
Expand All @@ -29,18 +34,19 @@ def from_file(path, duration = None):
tmp = create_temporary_file(".jpg")
output_path = tmp.name
resize_image(image, output_path)
if duration is None: duration = DEFAULT_DURATION
if not duration:
duration = DEFAULT_DURATION

else:
raise Exception, "Could not determine media type of the file"
raise UnknownMediaType("Could not determine media type of the file")

return Snap(path = output_path, media_type = media_type, duration = duration)
return Snap(path=output_path, media_type=media_type, duration=duration)

@staticmethod
def from_image(img, duration = DEFAULT_DURATION):
def from_image(img, duration=DEFAULT_DURATION):
f = create_temporary_file(".jpg")
resize_image(img, f.name)
return Snap(path = f.name, media_type = MEDIA_TYPE_IMAGE, duration = duration)
return Snap(path=f.name, media_type=MEDIA_TYPE_IMAGE, duration=duration)

def upload(self, bot):
self.media_id = bot.client.upload(self.file.name)
Expand Down Expand Up @@ -79,6 +85,7 @@ def __init__(self, **opts):
path = opts['path']
self.file = open(path)


class SnapchatBot(object):
def __init__(self, username, password, **kwargs):
self.bot_id = uuid.uuid4().hex[0:4]
Expand All @@ -95,25 +102,26 @@ def __init__(self, username, password, **kwargs):
if hasattr(self, "initialize"):
self.initialize(**kwargs)

def log(self, message, level = logging.DEBUG):
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):
@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)
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):
def listen(self, timeout=DEFAULT_TIMEOUT):
while True:
self.log("Querying for new snaps...")
snaps = self.get_snaps()
Expand Down Expand Up @@ -170,7 +178,7 @@ def post_story(self, snap):
snap.upload(self)

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

def add_friend(self, username):
self.client.add_friend(username)
Expand All @@ -181,7 +189,7 @@ def delete_friend(self, username):
def block(self, username):
self.client.block(username)

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

Expand Down
13 changes: 10 additions & 3 deletions snapchat_bots/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,31 +8,38 @@
MEDIA_TYPE_VIDEO = 2
MEDIA_TYPE_VIDEO_NOAUDIO = 3


def create_temporary_file(suffix):
return tempfile.NamedTemporaryFile(suffix = suffix, delete = False)
return tempfile.NamedTemporaryFile(suffix=suffix, delete=False)


def is_video_file(path):
return mimetypes.guess_type(path)[0].startswith("video")


def is_image_file(path):
return mimetypes.guess_type(path)[0].startswith("image")


def guess_type(path):
if is_video_file(path): return MEDIA_TYPE_VIDEO
if is_image_file(path): return MEDIA_TYPE_IMAGE
return MEDIA_TYPE_UNKNOWN


def resize_image(im, output_path):
im.thumbnail(SNAPCHAT_IMAGE_DIMENSIONS, Image.ANTIALIAS)
im.save(output_path)


def duration_string_to_timedelta(s):
[hours, minutes, seconds] = map(int, s.split(':'))
seconds = seconds + minutes * 60 + hours * 3600
return datetime.timedelta(seconds = seconds)
return datetime.timedelta(seconds=seconds)


def get_video_duration(path):
result = subprocess.Popen(["ffprobe", path], stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
result = subprocess.Popen(["ffprobe", path], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
matches = [x for x in result.stdout.readlines() if "Duration" in x]
duration_string = re.findall(r'Duration: ([0-9:]*)', matches[0])[0]
return math.ceil(duration_string_to_timedelta(duration_string).seconds)

0 comments on commit 2d9437e

Please sign in to comment.