#Facebook Poker     Jacob Hobbs 2016

#Facebook changes its page layout every 5 seconds, and this code is probably broken by now
#I will comment where the changes occour in the code, but if you would like me to update it for you
#email: jacobhobbs@vodafone.co.nz

import mechanize
from bs4 import BeautifulSoup
import re
import time


print("Setting up browser...")

baseUrl = "http://m.facebook.com"
pokeUrl = "http://m.facebook.com/pokes"

email = "EMAIL"                                     #Put your facebook email and password into these variables
password = "PASS"                                   #It feels wrong to even write that, read the code if you're uncomfortable.

pokeLimit = 4                                                   #Maximum amount of pokes per refresh (incase fb updates and you try and poke your whole friends list)
frequency = 80                                                  #Time between checking for new pokes in seconds


browser = mechanize.Browser()
browser.set_handle_robots(False)                                #This block sets up the mechanize browser with cookies so that it remains logged in
cookies = mechanize.CookieJar()
browser.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US)     AppleWebKit/534.7 (KHTML, like Gecko) Chrome/7.0.517.41 Safari/534.7')]


### http://stackoverflow.com/questions/9835506/urllib-urlopen-works-on-sslv3-urls-with-python-2-6-6-on-1-machine-but-not-wit/24158047#24158047
import ssl                          
from functools import wraps
def sslwrap(func):                                              #The mechanize browser would throw exceptions seemingly at random
    @wraps(func)                                                #It was using bad ssl versions, this code I copied from ^^^ fixes it
    def bar(*args, **kw):
        kw['ssl_version'] = ssl.PROTOCOL_TLSv1  
        return func(*args, **kw)
    return bar

ssl.wrap_socket = sslwrap(ssl.wrap_socket)
###


browser.open(baseUrl)
browser.select_form(nr=0)                                       #Load m.facebook.com, select the login form, fill with data and submit.

browser.form["email"] = email
browser.form["pass"] = password                                 #Haven't implemented a way of checking if login was succesful so if it isn't working check
                                                                #your login info first.
browser.submit()

print("Running... Checking every " + str(frequency) + "s")

while (0==0):
    try:
        toPoke = []

        pokePage = browser.open(pokeUrl).read()                         #Load the pokes page and put it into beautifulsoup
        soup = BeautifulSoup(pokePage, "html.parser")
        ### This section of code is likely to break on fb update###
        for link in soup.find_all(id = re.compile("^poke_live_item_")): #Find the divs for each new poke                            IF BROKEN, CHECK "poke_live_item_"
            print "Poking: " + link.find("img").get("alt")              #Print the name of the person we're poking
            for a in link.find_all("a"):
                if("hide=0" in a.get("href")):
                   toPoke.append(a.get("href"))                         #Get the url for the 'Poke Back' button and save to list
        ###########################################################

        if (len(toPoke) > pokeLimit):
            print "Poking too many people, something must be wrong"     #If there are too many people to poke, don't do it and say so
            print len(toPoke)

        else:
            for person in toPoke:
                browser.open(baseUrl + person)                          #Else tell the browser to load the poke url (and poke the person)

        time.sleep(frequency)
    except:
        print("Something bad happened, internet connection lost?")      #Sometimes wifi drops, or something weird happens, instead of killing the poker
        time.sleep(frequency)                                           #just say something went wrong and ignore it (it should fix itself if it's wifi)
