def __get_client__(self): configurations = self.db.get_fb_configurations() session = configurations.get('session') client = Client(configurations.get('email'), configurations.get('password'), session_cookies=session) configurations["session"] = client.getSession() self.db.set_fb_configurations(configurations) return client
def login(name=None): global client global user_name global username global password if request.method == "POST": # Get the Username and Password from the form username = request.form['emailadress'] password = request.form['password'] # # Load previous cookies this is for debug only!!! # session_cookies = json.load(open("session.json")) # Open the Client Object client = Client(username, password)#,session_cookies=session_cookies) # Get User Name newuser = client.fetchUserInfo(client.uid)[client.uid] # Make User Name user_name = "%s %s" % (newuser.first_name,newuser.last_name) # Get the Session Cookies and Save them for Later session_cookies = client.getSession() # Write the Cookies to a file with open("session.json","wt") as out: res = json.dump(session_cookies,out,sort_keys=True,indent=4,separators=(',',':')) return render_template("main.html", name=user_name)
def send_chat_message(message): client = Client(bot_email, bot_pwd, session_cookies=get_session_token()) set_session_token(client.getSession()) client.send(Message(text=message), thread_id='500949883413912', thread_type=ThreadType.GROUP) logservice.info("MESSAGE SENT")
def load_client(n, cache): client = Client( load_variable("client{}_email".format(n), cache), load_variable("client{}_password".format(n), cache), session_cookies=cache.get("client{}_session".format(n), None), ) yield client cache.set("client{}_session".format(n), client.getSession())
def write_cookies(cookies_location): mail = input("mail: ") password = getpass("password: "******"w") as cookies_file: cookies_file.write(json.dumps(session_cookies)) client.logout()
def load_client(n, cache): client = Client( load_variable("client{}_email".format(n), cache), load_variable("client{}_password".format(n), cache), user_agent='Mozilla/5.0 (Windows NT 6.3; WOW64; ; NCT50_AAP285C84A1328) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36', session_cookies=cache.get("client{}_session".format(n), None), ) yield client cache.set("client{}_session".format(n), client.getSession())
class FBManager(): #### Memmber Variables receiver_ids = [] login_id = '' login_pwd = '' session_cookies = {} #### Member Functions def __init__( self, username, password ): """ asdfassdfasdf only run this once, otherwies..... fb will. """ self.login_id = username self.login_pwd = password # Try to load session cookie try: self.session_cookies = json.load( open("session_cookie.json", "rb") ) except: # Session Cookie doesn't exist pass def login( self ): self.client = Client( self.login_id, self.login_pwd, session_cookies = self.session_cookies ) # save login session as cookie if such cookie doesn't exists if len( self.session_cookies ) == 0: self.session_cookies = self.client.getSession() f = open("session_cookie.json", "wb") json.dump( self.session_cookies, f ) f.close() def set_receiver_ids(self, receivers): """ setup FB accounts that want the deals messages sent to them """ self.receiver_ids = receivers def send_message(self, message): """ Call API to send message """ for r in self.receiver_ids: self.client.sendMessage(message, thread_id=r, thread_type=ThreadType.USER)
def send(arguments): login_data = json.loads(arguments[1]) content = arguments[2] recipient = arguments[3] group = arguments[4] action = arguments[5] if len(arguments) > 5 else datetime.now() try: action_time = action.split("T")[1].split(":") hour = int(action_time[0]) minute = int(action_time[1]) action_date = action.split("T")[0].split("-") year = int(action_date[0]) month = int(action_date[1]) day = int(action_date[2]) execution_datetime = datetime(year=year, month=month, day=day, hour=hour, minute=minute) while execution_datetime > datetime.now(): time.sleep(1) except IndexError: pass cookies = {} try: with open(f'session_{login_data["email"]}.json', 'r') as f: cookies = json.load(f) except: pass if group == "True": thread_type = ThreadType.GROUP else: thread_type = ThreadType.USER # Attempt a login with the session, and if it fails, just use the email & password client = Client(login_data["email"], login_data["password"], session_cookies=cookies, logging_level=50) client.sendMessage(content, thread_id=int(recipient), thread_type=thread_type) # Save the session again with open(f'session_{login_data["email"]}.json', 'w') as f: json.dump(client.getSession(), f)
def run(instance, profile): coordinator.profile = profile channel_id = FBMessengerChannel.channel_id if instance: channel_id += f"#{instance}" path = utils.get_data_path(channel_id) print( _("EFB Facebook Messenger Slave Session Updater\n" "============================================")) print() print(_("You are running EFMS {0}.").format(__version__)) print() print( _("This will update and overwrite your EFMS token by\n" "log into your account again manually.")) print() print( _("You usually need to do this when you want to log into\n" "a new account, or when the previous session is expired.")) print() print(_("This session is written to\n" "{0}").format(path)) print() print(_("To continue, press Enter/Return.")) input() email = input(_("Email: ")) password = getpass.getpass(_("Password: "******"Log in failed. Please check the information above and try again." )) exit(1) session_path = path / "session.pickle" with session_path.open('wb') as f: pickle.dump(client.getSession(), f) print( _("Your session has been successfully updated. It's stored at\n" "{0}").format(session_path)) print( _("Your session cookies is as valuable as your account credential.\n" "Please keep them with equal care."))
class Facebookface(object): """ Connects to Facebook using the credentials specified. Creates a dictionary of the users the authenticating user messaged and returns the userID of a desired contact you wish to message. Will then receive data from the Reddit libary and message the desired contact with the url and post title. """ def __init__(self): self.client = Client(FACEBOOK_SETTINGS.get('email'), FACEBOOK_SETTINGS.get('password')) self.session_cookies = self.client.getSession() self.client.setSession(self.session_cookies) self.username = FACEBOOK_SETTINGS.get('desired_username') self.redditing = Reddinterface() self.prompts = [ "Neato!", "Check out this thing I think is cool", "How neat is that?", "That's pretty neat!", "Check it", "Is this spam good enough?", "Can you feel it now, Mr. Krabs?", "If you don't like this, the communists win" ] def get_fb_users(self): user_list = [self.client.fetchAllUsers()] user_dict = {} for user in user_list[ 0]: # List only predictable when using the zeroth index user_dict.update({user.name: user.uid}) return user_dict[self.username] def send_message(self): if self.redditing.check_upvotes() is False: print("Will not send duplicate message") else: self.client.send(Message(text='{} \n\n{}\n{}'.format( random.choice(self.prompts), self.redditing.get_title(), self.redditing.get_url())), thread_id=self.get_fb_users(), thread_type=ThreadType.USER) self.client.logout() print("Message sent to {}".format(self.username))
def login(email=' ', password='******', cookies='./cookies', save_cookies=''): if email != ' ' and password != ' ': print("Connecting using email/password") client = Client(email, password) if save_cookies: print("Saving cookies...") session_cookies_str = json.dumps(client.getSession()) write_in_file('./cookies', session_cookies_str, "w") print("Done!") return client if cookies: print("Connecting using cookies") try: os.path.isfile(cookies) except: print("File not found") f = open(cookies, "r") session_cookies_dict = ast.literal_eval(f.read()) f.close() client = Client(' ', ' ', session_cookies = session_cookies_dict) return client else: return "Error while connecting"
import os import json from dotenv import load_dotenv from fbchat import Client load_dotenv() username = os.getenv("MESSENGER_USERNAME") password = os.getenv("MESSENGER_PASSWORD") client = Client( username, password, user_agent= "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.5 Safari/605.1.15", ) print(json.dumps(client.getSession()))
from fbchat import Client import json client = Client('email', 'pass') file_handle = open('session.txt', 'w+') file_handle.write(json.dumps(client.getSession())) file_handle.close()
file.close() if currentTime > long(float(lines[0].replace("\n", ""))) + 3600: # 3 600 000 consider that after more than 1 hour, people don't care about receiving notifications writeDefault() else: if sha224.hexdigest() != lines[1]: #print("changed !") cookies = {} try: with open('session.json', 'r') as f: cookies = json.load(f) except: pass client = Client("email", "password", session_cookies=cookies) #group = client.searchForGroups("Group name")[0] #print(group.uid) #print(group.name) client.send(Message(text='The website has been updated.'), thread_id=FOUND_YOUR_THREAD_ID, thread_type=ThreadType.GROUP) with open('session.json', 'w') as f: json.dump(client.getSession(), f) writeLog() writeDefault() else: writeDefault() else: writeDefault()
def message(): if request.method == "POST": data = request.get_json() if "email" not in data or "password" not in data: return jsonify("Missing credentials") email = data["email"] password = data["password"] try: cookies = {} try: with open(f'session_{email}.json', 'r') as f: cookies = json.load(f) except: pass client = Client(email, password, session_cookies=cookies, logging_level=50) with open(f'session_{email}.json', 'w') as f: json.dump(client.getSession(), f) except FBchatUserError: return jsonify("Wrong credentials") if "content" not in data or "recipient" not in data: return jsonify("Missing content") content = data["content"] recipient = data["recipient"] result_user = "" try: group = data["group"] if group == True: group = "True" else: group = "False" except KeyError: group = "False" if group == "True": users = client.searchForGroups(recipient) for user in users: if client.uid in user.participants: result_user = user.uid break else: users = client.searchForUsers(recipient) for user in users: if user.is_friend: result_user = user.uid break if not result_user: return jsonify("Recipient not found") login_data = json.dumps({"email": email, "password": password}) try: action_time = data["action_time"] except KeyError: action_time = None if client: subprocess.Popen([ "python", "send_message.py", login_data, content, result_user, group, action_time ]) return jsonify("Success") if request.method == "GET": return render_template("message.html")
import json from fbchat import Client from fbchat.models import * client = Client('username', 'password') session_cookies = client.getSession() json = json.dumps(session_cookies) f = open("session.json","w") f.write(json) f.close()
#Get creds user = input('Username: '******'Language (en-US*, zh-CN etc.): ') if (langCode == ''): langCode = 'en-US' cookies = load_cookies(os.path.join(sys.path[0], 'session.json')) #Initiate client writerClient = Client(user, password, session_cookies=cookies) #Save session cookies to file when the program exits atexit.register(lambda: save_cookies(os.path.join(sys.path[0], 'session.json'), writerClient.getSession())) run = True def callback(recognizer, audio): # received audio data, now we'll recognize it using Google Speech Recognition try: # for testing purpose, we're just using the default API key. Also I'm poor. verbal_diarrhea = recognizer.recognize_google(audio, pfilter=0, language=langCode) if re.search('abracadabra', verbal_diarrhea): verbal_diarrhea = recognizer.recognize_google( audio, pfilter=0 ) #Do an en-US search instead cuz all my friends have English names.
from itertools import islice from fbchat import Client from fbchat.models import * import time import pickle from getpass import getpass try: print('Checking for cookies...') session_cookies = pickle.load(open('cookies.p','rb')) client = Client("cookie", "cookie", session_cookies = session_cookies) print('Cookies found!') except: print('Cookies not found. Please enter credentials.') client = Client(input('Email: '), getpass('Password: '******'cookies.p','wb')) print('Cookies saved to cookies.p file.') user = '******' user_id = '' #Add User ID here i = 0 while i < 1: localtime = time.asctime(time.localtime(time.time())) user = client.fetchUserInfo(user_id)[user_id] not_avail = "Time: " + localtime + " | " + "User" + " is not available.\n" avail = "Time: " + localtime + " | " + "User {}".format(user.name) + " is available.\n"