class NameImporter: """ This class helps to get names of our facebook friends in a few seconds. And this also generate a CSV file containing the names """ def __init__(self, email, password): """ :param email: Facebook `email`, `id` or `phone number` :param password: Facebook account password """ self.client = Client(email=email, password=password, user_agent=None, max_tries=10, session_cookies=None) self.XMLfile = open("C:\\Windows\\NameList.xml", "w") def Generate_XML(self): users = self.client.fetchAllUsers( ) # Fetches a list of all users you're currently chatting with, as `user` objects self.XMLfile.write("<FriendList UserName="******"Total=" + str(len(users)) + ">") for user in users: self.XMLfile.write( "<Name>" + user.name + "</Name>\n") # storing friends' name into CSV file self.XMLfile.write("</FriendList>") self.XMLfile.close() self.client.logout()
class SendMessenger(object): def __init__(self): self.__driver_() pass def __initialize_clinet_(self): self.client = Client("*****@*****.**", "2NInitu!1") pass def __deinitialize_client_(self): self.client.logout() pass def send(self, message, contactName): try: user = self.client.searchForUsers(contactName)[0] uid = user.uid self.client.sendMessage(message, thread_id=uid) self.__deinitialize_client_() return True except: return False pass def __driver_(self): self.__initialize_clinet_() users = self.client.fetchAllUsers() pass
class MessengerHandler(): def __init__(self): self.client = Client("*****@*****.**", "bl!dohuset") print("Own id: {}".format(self.client.uid)) def sendMessage(self, userID, message): self.client.send(Message(text=message), thread_id=userID, thread_type=ThreadType.USER) def logout(self): self.client.logout() def getUsers(self): self.users = self.client.fetchAllUsers() # print("users' IDs: {}".format([user.uid for user in self.users])) userIDs = [] for user in self.users: userIDs.append(user.uid) return userIDs def fetchMessage(self, sensorTemp, sensorHumid, timestamp, userIDs): for userID in userIDs: messages = self.client.fetchThreadMessages(thread_id=userID, limit=1) for message in messages: message.text = message.text.lower() if (message.text == 'info'): self.sendMessage( userID, f"Hej!\nTemperaturen i huset är {sensorTemp} och luftfuktigheten är {sensorHumid}\n Senast updaterad {timestamp}.\nMvh\nHuset" )
def main(json_input, context): fbClient = Client(FB_USER, FB_PASSWORD) fbUsers = fbClient.fetchAllUsers() fbUsersList = [user.uid for user in fbUsers if user.uid != "0"] # Getting weather information forecastPayload = { "apikey": ACCUWEATHER_KEY, "details": True, "metric": True } alertPayload = {"apikey": ACCUWEATHER_KEY} r = requests.get(ACCUWEATHER_FORECAST_URL, params=forecastPayload) weatherForecast = r.json() r = requests.get(ACCUWEATHER_ALARM_URL, params=alertPayload) weatherAlerts = r.json() dailyMinimum = weatherForecast["DailyForecasts"][0]["Temperature"][ "Minimum"]["Value"] dailyMaximum = weatherForecast["DailyForecasts"][0]["Temperature"][ "Maximum"]["Value"] feelsLikeMinimum = weatherForecast["DailyForecasts"][0][ "RealFeelTemperature"]["Minimum"]["Value"] feelsLikeMaximum = weatherForecast["DailyForecasts"][0][ "RealFeelTemperature"]["Maximum"]["Value"] weatherSummary = weatherForecast["DailyForecasts"][0]["Day"][ "LongPhrase"].lower() alerts = [] if len(weatherAlerts) > 0: for alert in weatherAlerts[0]["Alarms"]: alertType = alert["AlarmType"] alertText = getAlertText(alertType) alerts.append(alertText) forecastMessage = Message( text="Good morning!\nToday's weather calls for " + weatherSummary + ".\n\nHigh: " + str(dailyMaximum) + u"°\n(feels like " + str(feelsLikeMaximum) + u"°)" + "\nLow: " + str(dailyMinimum) + u"°\n(feels like " + str(feelsLikeMinimum) + u"°)") # Sending weather updates for id in fbUsersList: fbClient.send(forecastMessage, thread_id=id) for alertText in alerts: alertMessage = Message(text=alertText) fbClient.send(alertMessage, thread_id=id) time.sleep(5) # sleep for 5 seconds to avoid being too spammy fbClient.logout()
def get_all_users_in_chat_with(client: Client) -> dict: """ Returns a dictionary of user name and id pairs for all people the current user is in chats with """ users = client.fetchAllUsers() user_dict = {} for user in users: user_dict[user.name] = str(user.uid) return user_dict
class FB(): def __init__(self, config): self.config = config def send_messages(self, message): all_user_conversations = self.__get_all_conversations() logging.info("Got all conversations") users_uid_to_send = self.__get_uid_from_conversations( all_user_conversations) logging.info("Got selected UID to send messages to") self.__send_message_to_users(users_uid_to_send, message) def login_client(self): self.client = Client(self.config["fbUsername"], self.config["password"]) logging.info("Client successfully logged in!") def __get_all_conversations(self): return self.client.fetchAllUsers() def __get_uid_from_conversations(self, all_conversations): users_to_send = self.__get_users_to_send() out = [] for user in all_conversations: if (user.name in users_to_send): out.append(user.uid) return out def __get_users_to_send(self): return self.config["usersToSend"] def set_users_to_send(self, users): self.config["usersToSend"] = users def __send_message_to_users(self, users_uid_to_send, message): for uid in users_uid_to_send: self.client.send(Message(text=message), thread_id=uid, thread_type=ThreadType.USER) logging.info("All messages successfully sent") def logout(self): self.__delay() logging.info("Client logged out") if self.client.logout( ) else logging.debug("Something went wrong when logging client out!") ##Delay is used in order to simulate real user actions def __delay(self): random_time_span = random.randint(30, 145) logging.info("Delay started {}".format(random_time_span)) time.sleep(random_time_span)
def home(): if not session.get('logged_in'): return render_template('login.html') else: username = session['username'] password = session['password'] session_client = Client(username, password) friends = session_client.fetchAllUsers() friends = [{ 'name': friend.name, 'uid': friend.uid } for friend in friends] friends = sorted(friends, key=lambda k: k['name']) form = UserInput() form.friends.choices = [(friend['uid'], friend['name']) for friend in friends] session_client.logout() return render_template('user_input.html', form=form, friends=friends)
class Messenger(object): def __init__(self): username, login = get_login('login') self.client = Client(username, login) self.user_map = {} self._initialize_contacts() self._initialize_messages() def _initialize_contacts(self): self.user_map[self.client.uid] = self.client.fetchUserInfo(self.client.uid)[self.client.uid].name for user in self.client.fetchAllUsers(): self.user_map[user.uid] = user.name def _initialize_messages(self, limit=1000): try: print("Input the user you want to message:") to_search = input() if to_search == "exit": print("Exiting...") return users = self.client.searchForUsers(to_search) + self.client.searchForGroups(to_search) users = users for i in range(0, len(users)): print(i, ":", users[i].name) user = users[int(input("Please specify which chat you'd like to participate in: "))] self.messages = self.client.fetchThreadMessages(thread_id=user.uid, limit=limit)[::-1] thread = self.client.fetchThreadInfo(user.uid) self.chat = Chat(user.name, user.uid, self.messages, thread, self.client.uid, self.user_map[self.client.uid], self.user_map, find_answers=True) except IndexError : traceback.print_exc() except ValueError : traceback.print_exc() def run_loop(self, limit=150): print("Wrong literal, try again.") while True: self._initialize_messages(limit=limit) def get_messages(self): return self.chat.get_messages()
def do_admin_login(): try: username = request.form['username'] password = request.form['password'] session['username'] = username session['password'] = password client = Client(username, password, max_tries=1) friends = client.fetchAllUsers() friends = [{ 'name': friend.name, 'uid': friend.uid } for friend in friends] friends = sorted(friends, key=lambda k: k['name']) session['logged_in'] = True client.logout() except FBchatException as exception: print(exception) flash('wrong password') return home()
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))
class Hub: def __init__(self): self.Client = Client(USER, PASS) def logout(self): self.Client.logout() def list(self, size=20): users = self.Client.fetchThreadList(limit=size) convos = {} for u in users[:100]: if u.name != None: convos[u.name] = u.uid print("fetched conversations") return convos def fetchUsers(self): self.users = self.Client.fetchAllUsers() return self.users def fetchUserInfo(self, ui): return self.Client.fetchUserInfo(ui) def get_conversations(self): return self.conversations def fetch_messages(self, conv_id): messages = self.Client.fetchThreadMessages(thread_id=conv_id, limit=10) return messages def search_conversations(self): convos = self.list() print("Convos is " + str(convos)) selection = iterfzf(iter_conversations(convos.keys()), multi=False) # Fetch thread messages print(self.fetch_messages(convos[selection]))
def sjekk(): print("######### CHAT BOT ############ \n ") client = Client("FBMAIL@MAIL", "FB_PASSWORD") lars = 1288058845 #Example FB user ids that can be used to send a message to their profile cato = 525196495 print("Own id: {}".format(client.uid)) users = client.fetchAllUsers() #print(users) - Run this to see all IDs from the friendslist of the user you're logged into ###################################### print("\n \n ########### ELKJØP DEMOVARE SJEKK ############# \n") #Nettsiden for prishenting # quote_page er linken til produktet du vil overvåke #quote_page = "https://www.elkjop.no/product/data/ipad-og-nettbrett/15038/ipad-pro-11-2018-64-gb-wifi-cellular-solv#tab-refurbished-offers" quote_page = "https://www.elkjop.no/product/data/ipad-og-nettbrett/15068/ipad-pro-11-2018-64-gb-wifi-stellargra" page = requests.get(quote_page) print("\n Kobler til nettside...\n Status: " + str(page.status_code)) soup = BeautifulSoup(page.text, 'html.parser') # Finner tittel og pris title_box = soup.find('h1', attrs={'class': 'product-title'}) title = title_box.text.strip() price_box = soup.find('div', attrs={'class': 'product-price-container'}) price = price_box.text.strip() print(" Produkt: " + title + "\n Outlet Pris: " + price + " kr") ## FINNER UT OM DET ER TILBUD### offerclass = soup.find(class_="product-price align-left any-1-1 margin-1") seeMore = offerclass.find_all("a") if seeMore: global demovare demovare = True demo_price_box = soup.find( 'div', attrs={'class': 'product-price align-left any-1-1 margin-1'}) demo_price_text = demo_price_box.text.strip() demo_price_half = demo_price_text #re.sub('[^0-9]', '', demo_price_text) demo_price = "" for i in range(28, 28 + len(price)): demo_price += (demo_price_half[i]) print("\n Demovare: Ja \n Demo pris: " + demo_price + "kr \n \n Sender varlsing på Facebook.") client.send( Message(text="Nå er det Demovare på " + title + "!\n\nOrdinærpris: " + price + " kr \nDemo pris: " + demo_price + "kr \n \n Link: " + quote_page), thread_id=lars, thread_type=ThreadType.USER) client.logout() else: demovare = False print(" Demovare: Nei \n \n Prøver på nytt om 2 timer..\n") when_to_stop = 7200 """for i in tqdm(range(7200)): time.sleep(1)""" while when_to_stop > 0: m, s = divmod(when_to_stop, 60) h, m = divmod(m, 60) time_left = str(h).zfill(2) + ":" + str(m).zfill(2) + ":" + str( s).zfill(2) print(" " + time_left + "\r", end="") time.sleep(1) when_to_stop -= 1
def fetchFBInformation(app, userid, fbemailid, fbpassword): #### # 0. Set base variables ############ messagefile_complete_name = "all_messages_" messagefile_complete_filetype = ".txt" ############ # 1. Login into the FB account ############################### try: # define a FB connector client = Client(fbemailid, fbpassword) # Update FBemailid for the <userid> updateFBEmailid(app, int(userid), fbemailid) # Update the process status to '2' for successful login updateProcessStatus(app, int(userid), '2') except Exception as wrongLoginCredentials: print("Wrong User name or password") return (-1) ######### # 2. Fetch chat-interlocutors of <userid> ############################################## interlocutors = client.fetchAllUsers() print("Number of Users: " + str(len(users))) # Update the process status to '3' for having fetched FB chat data updateProcessStatus(app, int(userid), '3') ######### # 3. Fetch chatHistories for all interlocutors of <userid> that happen after <maxTimeStamp>; if <maxTimeStamp> is "1" : fetch all ################################################################################################################################## # initialize a list for all conversation threads of <userid> conversations = [] # initialize a list of interlocutor uids with whom <userid> has more than 1 message exchanged interlocutor_uids = [] # fetch the timestamp when the last FB fetch happened and cast it to <int>-type maxTimestampDB = fetchTimestamp(app, int(userid)) maxTimestampDB = int(maxTimestampDB) # Fetch messages <userid> chats with and append it to <conversations> for interlocutor in interlocutors: try: # try to fetch the last 1000 messages from the conversation between <userid> and <interlocutor> threadMessages = client.fetchThreadMessages( thread_id=interlocutor.uid, limit=10000) messageCount = len(threadMessages) # if more than one message has been exchanged ... if (len(threadMessages) > 1): # remember thread messages in the <conversations>-list conversations.append( client.fetchThreadMessages(thread_id=interlocutor.uid)) # remember the interlocutor_uid interlocutor_uids.append(interlocutor.uid) except fetchFBchatException: #print("## Error ## ","UID: ",user.uid, " Name: ", user.first_name, " ", user.last_name, "# of msgs: ") pass # Error conversations that contain no messages (i.e. conversations started automatically by messenger after becoming friends on FB print("Fetched ", "conversations: " + str(len(conversations)), " userlist length: " + str(len(userlist))) ########## # 4. Extract all non-empty conversations which have not been fetched before ########################################################################## write_log("Threads Fetched. Start language classfication.") # set paths ## path that will contain all messages as a single file in JSON format #messagefolder_json = "./Messages_json/" # ## path that will contain all messages as a single file in plain text format #messagefolder_plain = "./Messages_plain/" # path that will contain all messages the user has ever sent in one single file per language used messagefolder_complete = "./ServerFeatures/Userdata/Messages_complete/" + str( userid) + "/" # file-name to store a message temporarily for language classification message_tempfile_path = "./ServerFeatures/Userdata/Messages_complete/" + str( uderid) + "/tempfile.txt" # initialize a list for the languages used in <userid>'s conversations languages = [] # initialize (WRITE WHAT) language_count = [] # initialize a counting variable for the considered conversations interlocutor_number = 0 # return value of the function (all English messages in one string) # VERIFY - probably the timestamps for the conversations max_message_timestamps = [] # create message folders if not existing yet #if not os.path.exists(messagefolder_json): # os.makedirs(messagefolder_json) #if not os.path.exists(messagefolder_plain): # os.makedirs(messagefolder_plain) if not os.path.exists(messagefolder_complete): os.makedirs(messagefolder_complete) # clear all message files if existent # TODO: this will have to be removed # otherwise, running the script multiple times will cause messages to appear multiple times in the files # TODO: change later for updating #for root, dirs, files in os.walk(messagefolder_json): # for file_ in files: # if file_.endswith(".txt"): # os.remove(os.path.join(root, file_)) #for root, dirs, files in os.walk(messagefolder_plain): # for file_ in files: # if file_.endswith(".txt"): # os.remove(os.path.join(root, file_)) # collect all *.txt files in <messagefolder_complete> # (only relevant if the user has stored FB messages in the past for root, dirs, files in os.walk(messagefolder_complete): for file_ in files: if file_.endswith(".txt"): os.remove(os.path.join(root, file_)) # for all conversations (with more than one message) for conversation in conversations: # set sub directory paths for each chat partner in the #userdir_json = messagefolder_json + "/" + str(userlist[user_number]) #userdir_plain = messagefolder_plain + "/" + str(userlist[user_number]) # ## make directories if not yet existent #if not os.path.exists(userdir_json): # os.makedirs(userdir_json) #if not os.path.exists(userdir_plain): # os.makedirs(userdir_plain)## # remember all thread messages, their predicted language, and the number of considered messages of the conversation conversation_messages = [] conversation_message_languages = [] conversation_message_counter = 0 text_returned_en = "" conversation_empty = True # for all messages in the conversation for message in conversation: # get message text, author, timestamp message_text = message.text message_author = message.author message_timestamp = message.timestamp # encode <message_text> to utf-8 if type(message_text) == 'unicode': message_text = message_text.encode('utf-8') elif type(message_text) == str: message_text.decode('utf-8').encode('utf-8') # remember the timestamp of the message max_message_timestamps.append(message_timestamp) # (e.g. exclude automatically generated call messages) # if <message_text> is not empty # AND # the message has not been fetched in the past (maxTimestampDB indicates the most recent point in time <userid> fetched FB messages # AND # if the message was sent by <userid> and not by <interlocutor> message_not_empty = (message_text != None) message_sent_by_userid = (message_author == client.uid) message_not_fetched_before = (int(message_timestamp) > int(maxTimestampDB)) if (message_not_empty & message_sent_by_userid & message_not_fetched_before): conversation_empty = False # set message file paths for the json and text message files #messagedir_plain = userdir_plain + "/" + message_timestamp + ".txt" #messagedir_json = userdir_json + "/" + message_timestamp + ".txt" # remove newlines (\n) and carriage returns (\r) (for language classification - otherwise this would produce multiple outputs) message_text = message_text.replace('\n', ' ').replace('\r', '') ## write message json file #message_dictionary = {'timestamp': message_timestamp, 'author_id': message_author, 'text': message_text} #with open(messagedir_json, "w") as outfile: # json.dump(message_dictionary, outfile) # outfile.close() # write message text file #with open(messagedir_plain, "w") as outfile: # outfile.write(message_text) # outfile.close() # put <message_text> into a temporary file for languge prediction with open(message_tempfile_path, "w") as tempfile: tempfile.write(message_text) # try to predict the message's language with the original fasttext algorithm try: message_language = check_output([ './ServerFeatures/Wordembedding/fastText-original/fasttext', 'predict', './ServerFeatures/Preprocessing/Languageprediction/pretrainedmodel.bin', message_tempfile_path ]) # remove newlines (\n) from <message_language> message_language = str(message_language).replace('\n', '') except CalledProcessError as e: raise RuntimeError( "command '{}' returned with error (code {}): {}". format(e.cmd, e.returncode, e.output)) # keep track of every language prediction for the conversation and count the messages in the conversation # e.g. # conversation_messages = [msg1, msg2, msg3] # conversation_message_languages = ['__label__en', '__label__de', '__label__en'] conversation_messages.append(message_text) conversation_message_languages.append(message_language) conversation_message_counter += 1 #### # 5. Filter out empty conversations ########################################3 if conversation_empty: continue # with the next iteration of the loop """ # this code only focuses on English conversations # extract the languages used in the conversation and their respective counts conversation_message_languages_and_count = [ ( conversation_messages_languages.count(language), language) for language in set(conversation_message_languages) ] # pick the majority language, max finds the maximum in the 0-th elements of the duples majority_language = max(conversation_message_languages_and_count)[1] """ #### # 6. Build separate chat histories for <userid> for each conversation language ############################################################################ conversation_languages = [] conversation_language_count = [] # for all recorded conversation languages for message_language in conversation_message_languages: message_language_known = False conversation_language_index = 0 # for for conversation_language in conversation_languages: if conversation_language == message_language: conversation_language_count[ conversation_language_index] = conversation_language_count[ conversation_language_index] + 1 message_language_known = True break conversation_language_index = conversation_language_index + 1 if (message_language_known == False): conversation_languages.append(message_language) conversation_language_count.append(1) # retrieve final conversation language for the whole conversation max_language_count = 0 conversation_language = '' conversation_language_index = 0 for x in conversation_languages: if (conversation_language_count[conversation_language_index] > max_language_count): max_language_count = conversation_language_count[ conversation_language_index] conversation_language = conversation_languages[ conversation_language_index] conversation_language_index = conversation_language_index + 1 #print("Final conversation language: ", conversation_language) # add conversation language use to the global language use of the user language_index = 0 language_known = False for language in languages: if language == conversation_language: language_count[language_index] = language_count[ language_index] + len(conversation_messages) language_known = True break if (language_known == False): languages.append(conversation_language) language_count.append(len(conversation_messages)) # append all conversation messages to the respective complete history with regard to the conversation language # format e.g.: "./ServerFeatures/Userdata/Messages_complete/testid/all_messages___label__en.txt" complete_history_path = messagefolder_complete + messagefile_complete_name + str( userid) + conversation_language + messagefile_complete_filetype # the conversation messages are encoded in 'utf-8', see above with open(complete_history_path, "a+") as complete_file: for conversation_message in conversation_messages: append_message = (conversation_message.decode('utf-8') + " ").encode('utf-8') complete_file.write(append_message) # append message to the return string if it is english // TODO: potentially change later if (conversation_language == '__label__en'): text_returned_en = text_returned_en + conversation_message + " " interlocutor_number += 1 # print("Conversation languages: ",conversation_languages) # print("Conversation language count: ",conversation_language_count) print("Overall languages used: ", languages) print("Overall languages used count:", language_count) # delete tempfile if (os.path.isfile(message_tempfile_path)): os.remove(message_tempfile_path) # Update the process status to '4' updateProcessStatus(app, int(userid), '4') ###### # 7. Extract language usage statistics of <userid> ################################## # for testing only # get language statistics msg_count_en = 0 msg_count_total = 0 index = 0 for language in languages: if (language == '__label__en'): msg_count_en = msg_count_en + language_count[index] msg_count_total = msg_count_total + language_count[index] index = index + 1 write_log("Finished language classification") ###### # 8. Update <maxTimeStamp> in the userinfo TABLE if necessary #################################################### complete_EN_history_path = messagefolder_complete + messagefile_complete_name + str( userid) + '__label__en' + messagefile_complete_filetype # if an English chat history path exists EN_chatHistory_exists = os.path.isfile(complete_EN_history_path) if EN_chatHistory_exists: new_non_empty_conversations_fetched = len(max_message_timestamps) > 0 if new_non_empty_conversations_fetched: print("Update maxTimeStamp in the userinfo TABLE") word_count_en = len(text_returned_en.split()) write_log( "Fetched {} Facebook messages. Number of english classified messages: {}. Number of english words: {}" .format(msg_count_total, msg_count_en, word_count_en)) # Update maxTimeStamp in the userinfo TABLE status = updateMessageTimestamp(app, int(userid), max(max_message_timestamps)) # return the chat history path for English conversations return complete_EN_history_path # return "-1" if no changes were made return "-1"
# -*- coding: utf-8 -*- import sys from fbchat import Client from fbchat.models import * user = "******" pas = "******" client = Client(user, pas) users = client.fetchAllUsers() listuser = [user.uid for user in users if user.uid != "0"] # ดึง uid หรือ id ของทุกคนสำหรับใช้ส่งข้อความ on = input("input to send : ") # กดพิมพ์อะไรก็ได้เพื่อเริ่มส่ง if on == "exit": # กดพิมพ์ exit คือออก client.logout() # ออกจากระบบ sys.exit() #ออกจากโปรแกรม for id in listuser: # ลูป id เพื่อนทุกคนในเฟส client.send(Message(text='Demo Send Meassage with Python'), thread_id=id, thread_type=ThreadType.USER) print("hello world :D") client.logout() # ออกจากระบบ
def get_messages(): username, login = get_login('login') client = Client(username, login) users = client.fetchAllUsers() user = client.searchForGroups("Socialist")[0] return client.fetchThreadMessages(thread_id=user.uid, limit=1000)
class Engine: #initializing out constructor def __init__(self): print(" ") print(colored("[+] Written by Romeos CyberGypsy")) print(colored("Access and chat with Facebook friends at the comfort of your terminal","yellow")) print(colored("(C) Leusoft 2019","green")) print("In case of any query, contact me at:") print(colored("1. Email: [email protected] \n2. Telegram: https://t.me/Romeos_CyberGypsy \n3. Facebook: Romeos CyberGypsy","blue")) print(" ") print(colored("NOTE: To get a specific users ID, consider searching the target by username first to display the ID","red")) print(" ") self.parser = optparse.OptionParser() self.parser.add_option("--username", dest = "name", help = "Facebook Username") self.parser.add_option("--password", dest = "password", help = "Facebook password") self.parser.add_option("-s", "--search-for-user", dest = "user", help = "Search query. Search by name") self.parser.add_option("--search-for-group", dest = "group", help = "Search for a group by name") self.parser.add_option("-f", action = "store_true", dest = "", help = "Fetch info about all users you have chatted with") self.parser.add_option("-V","--view-messages", dest ="target_id", help = "View messages sent to the specified user. Enter the targets ID") self.parser.add_option("-l","--limit", dest = "limit", help = "Maximum number of messages to show. Defaults to 10") self.parser.add_option("-i", "--id", dest = "id", help = "User to inbox or view messages") self.parser.add_option("-m","--message", dest = "message", help = "Message to send to user") self.parser.add_option("-I","--image", dest = "image", help = "Path to image file to send") self.parser.add_option("-v", action = "store_true", help = "View my facebook ID") self.parser.add_option("--my-info", action = "store_true", help = "View my facebook info") #parse the values of the arguments provided (self.values, self.keys) = self.parser.parse_args() try: #logging in to your facebook account self.client = Client(self.values.name, self.values.password) except KeyboardInterrupt: #handle the keyboard KeyboardInterrupt error print(colored("[-] Exiting safely","red")) except Exception as e: #print out any other Exception that may arise print(e) sys.exit() if sys.argv[3] == "-i" or "--id" in sys.argv[3] or sys.argv[3] == "-m" or "--message" in sys.argv[3]: self.send_message(self.values.id, self.values.message) elif sys.argv[3] == "-s" or "--search-for-user" in sys.argv[3]: self.search_user(self.values.user) elif sys.argv[3] == "-V" or "--view-messages" in sys.argv[3]: self.view_messages(self.values.target_id, self.values.limit) elif sys.argv[3] == "-I" or "--image" in sys.argv[3]: self.send_image(self.values.image, self.values.id) elif sys.argv[3] == "-v": self.my_id() elif sys.argv[3] == "-f": self.fetch_users() elif "--search-for-group" in sys.argv[3]: self.search_for_group(self.values.group) elif sys.argv[3] == "--my-info": self.myinfo() else: sys.exit() def send_message(self, user, message): #Code to send messages self.client.send(Message(text = message), thread_id = user, thread_type = ThreadType.USER) print(colored("[+] Message sent...","green")) sys.exit() def search_user(self, username): #code to search for username on facebook #one name is enough for the search users = self.client.searchForUsers(username) x = 1 print(colored("SEARCH RESULTS:","red","on_green")) for user in users: print(colored("User {}" .format(str(x)),"blue")) x=x+1 name = colored(user.name,"green") id = colored(user.uid,"greenpyt") photo = colored(user.photo,"green") url = colored(user.url,"green") friendship = colored(user.is_friend,"green") print("Name: {}" .format(name)) print("User ID: {}" .format(id)) print("Photo url: {}" .format(photo)) print("Profile url: {}" .format(url)) print("Friend: {}" .format(friendship)) print("-"*10) def view_messages(self, user, limit): #code to view messages between you and the specified users if limit == None: limit = "10" print(colored("[+] Reading messages...","blue")) messages = self.client.fetchThreadMessages(thread_id = user, limit = int(limit)) #The messages arrive in a reversed order #so lets reverse them again messages.reverse() for message in messages: print(message.text) def send_image(self, path, userid): #sends an image stored in your local machine #a path can be e.g c:\\Images\\image.jpg self.client.sendLocalImage(path, message = Message(text = "Image"), thread_id = userid, thread_type = ThreadType.USER) print(colored("[+] Image sent successfully","green")) def my_id(self): #prints your facebook ID print(colored("Your Facebook ID is {}" .format(self.client.uid),"blue")) def fetch_users(self): #fetch info about users that you've chatted with recently users = self.client.fetchAllUsers() print(colored("[+] Fetching users information","green")) x = 1 print(users) for user in users: print("User {}" .format(str(x))) print("Username: {}" .format(user.name)) print("User ID: {}" .format(user.uid)) print("User profile url: {}" .format(user.url)) print("*"*10) x+=1 def myinfo(self): print(colored("[+] My info","blue")) name = colored(self.values.name, "green") id = colored(self.client.uid,"green") phone = colored(self.client.getPhoneNumbers(),"green") logged = colored(self.client.isLoggedIn(),"green") print("Name: {}" .format(name)) print("ID: {}" .format(id)) print("Phone numbers: {}" .format(phone)) print("Logged in: {}" .format(logged)) def search_for_group(self, name): groups = self.client.searchForGroups(name) x = 1 for group in groups: print(colored("Group {}" .format(str(x)),"blue")) print("Name: {}" .format(group.name)) print("ID: {}" .format(group.uid)) print("Group URL: {}" .format(group.url)) print("-"*10)
def send(): os.system('cls') user = input(Fore.YELLOW + "[Paso 1/4] " + Fore.CYAN + "Correo de la cuenta" + Fore.YELLOW + "\n-> ") password = getpass(Fore.YELLOW + "[Paso 2/4] " + Fore.CYAN + "Contraseña de la cuenta" + Fore.YELLOW + "\n-> ") msj = input(Fore.YELLOW + "[Paso 3/4] " + Fore.CYAN + "Mensaje a enviar" + Fore.YELLOW + "\n-> ") print(Fore.YELLOW + "[Paso 4/4] " + Fore.CYAN + "Elige el archivo con las cuentas " + Fore.YELLOW + "\n[Paso 4/4]" + Fore.CYAN + " (Si cancelas el proceso, el mensaje " + Fore.YELLOW + "\n[Paso 4/4]" + Fore.CYAN + " será enviado a todos los contactos)" + Fore.YELLOW + "\n-> ") print(Fore.WHITE) os.system('pause') root = Tk() # Iniciamos la ventana de la app file_path = filedialog.askopenfilename(initialdir="/", title="Select a File", filetypes=(("Text files", "*.txt*"), )) root.withdraw() # Cerramos la ventana destinatarios = [] client = Client(user, password, user_agent=None, max_tries=1, session_cookies=None) if file_path: print(Fore.YELLOW + '[INFO] ' + Fore.CYAN + 'Spam dirigido') with open(file_path, 'r') as f: for i in f.readlines(): contact = (i.replace('\n', '').replace('\t', '').replace( '\r', '').replace(' ', '')) destinatarios.append(contact) else: print(Fore.YELLOW + '[INFO] ' + Fore.CYAN + 'Spam no dirigido') for i in client.fetchAllUsers(): contact = i.uid destinatarios.append(contact) print(i.uid, i.first_name) # for i in client.fetchAllUsers(): # print(i.uid, i.first_name) # print(Fore.WHITE) # os.system('pause') # return for destinatario in destinatarios: try: client.send(_message.Message(text=msj), thread_id=destinatario, thread_type=_thread.ThreadType.USER) except Exception as e: print(Fore.CYAN + '[INFO] No se pudo enviar a: ' + Fore.YELLOW + str(e)) # client.logout() está presentando un error con la # función group() print(Fore.WHITE) os.system('pause')
return "Remember your umbrella, today's forecast calls for rain! 🌧 ☔" elif( alertType == "Snow" ): return "You'll be walking in a winter wonderland, because it is supposed to snow today! 🌨 ❄ " elif( alertType == "Wind" ): return "Be sure to bundle up, because it's going to be windy today! 🌪" elif( alertType == "WindGust" ): return "Hold on to your hat, wind gusts of over 60kph are in store for today! 🌬 💨" elif( alertType == "Thunderstorm" ): return "THUNDER!!! OOoooOOOOooooOOOOooOOh (thunderstorms are in store for today)! ⛈ ⚡" else : return "Unrecognized alert type." if __name__ == '__main__': fbClient = Client(FB_USER, FB_PASSWORD) fbUsers = fbClient.fetchAllUsers() fbUsersList = [user.uid for user in fbUsers if user.uid != "0"] # Getting weather information forecastPayload = { "apikey" : ACCUWEATHER_KEY, "details" : True, "metric" : True } alertPayload = { "apikey" : ACCUWEATHER_KEY } r = requests.get(ACCUWEATHER_FORECAST_URL, params=forecastPayload) weatherForecast = r.json()
class Facebook(): def __init__(self, settings, driver, logger, getConfirmation, speak, emitter): #Init self.log = logger self.settings = settings self.driver = driver self.api = None self.fbFriends = None self.getConfirmation = getConfirmation self.speak = speak self.emitter = emitter self.messengerClient = None self.URL = 'https://graph.facebook.com/v2.12/' #Init a new Auth instance, which will manage all the Authentication processes self.auth = Auth(settings, driver, logger) #Logs the user in facebook and init fb API self.initApi() def initApi(self): #Gets the fb app token from self.settings or, if none, init to default if "fbAppAccessToken" not in self.settings: self.appAccessToken = '185643198851873|6248814e48fd63d0353866ee3de9264f' elif not self.settings["fbAppAccessToken"]: self.appAccessToken = '185643198851873|6248814e48fd63d0353866ee3de9264f' else: self.appAccessToken = self.settings["fbAppAccessToken"] #If login was successful, init API if self.login(): self.api = facebook.GraphAPI(access_token=self.settings["fbUserAccessToken"]) self.setUserInfo() print self.userInfo self.speak("logged in facebook successfully") self.log.info("-- LOGGED IN FB --") else: self.speak("logging in facebook failed") self.log.error("-- LOG IN FB FAILED --") #Method to login to facebook, to fb api and to messengerClient def login(self): expired = False #init messengerClient if not self.messengerClient: self.messengerClient = Client(self.settings["FacebookEmail"], self.settings["FacebookPassword"]) #check if fb token has expired or not if "fbUserAccessTokenExpirationDate" in self.settings: if self.settings["fbUserAccessTokenExpirationDate"]: expToken = self.settings["fbUserAccessTokenExpirationDate"] expDate = datetime.datetime.fromtimestamp(float(expToken)).strftime('%Y-%m-%d %H:%M:%S') dateNow = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') if expDate < dateNow: expired = True else: expired = True #If no user access token or expired, then login to fb API if ((self.settings["fbUserAccessToken"] is None) or expired ): DATA = {'access_token': self.appAccessToken, 'scope':'public_profile, publish_actions, user_friends, publish_actions, user_posts'} #Gets the login info for fb devices authentication loginRequest = requests.post(url = self.URL + 'device/login', data = DATA) data = loginRequest.json() self.log.info("-- LOGGING IN FB --") self.speak("logging in facebook") code = data['code'] userCode = data['user_code'] verificationURI = data['verification_uri'] interval = data['interval'] DATA2 = {'access_token':self.appAccessToken, 'code':code} awaitingUserLoginRequest = requests.post(url = self.URL +'device/login_status', data = DATA2) #awaits for the user to enter the userCode fetched above awaitingUserLoginRes = awaitingUserLoginRequest.json() #Selenium : sign in to facebook and enter the userCode to activate the API self.auth.loginFb(verificationURI, userCode) #awaits for the user to enter the userCode fetched above while 'access_token' not in awaitingUserLoginRes.keys() : time.sleep(7) awaitingUserLoginRequest = requests.post(url = self.URL +'device/login_status', data = DATA2) awaitingUserLoginRes = awaitingUserLoginRequest.json() #Gets the user access token from the response and store it in self.settings if 'access_token' in awaitingUserLoginRes.keys(): self.settings["fbUserAccessToken"] = awaitingUserLoginRes['access_token'] expirationDate = datetime.datetime.now() + datetime.timedelta(0,awaitingUserLoginRes['expires_in']) self.settings["fbUserAccessTokenExpirationDate"] = expirationDate.strftime('%s') return self.login() else: return False #Checks if the user is signed in, sign him in if not return self.auth.signInFb("https://facebook.com/login") #Logout from fb API and messengerClient def logout(self): self.settings["fbUserAccessToken"] = None driverRestarted = restartDriver(self.driver) self.messengerClient.logout() self.messengerClient = None self.log.info("-- User logged out --") return True #Method to post on the user wall (Uses fb API) or on a user friend's wall (Uses Selenium). def post(self, message, to="me", tag="none"): if self.login(): if(to != "me"): userId = self.getFriendId(to) if userId: get_url(self.driver, "m.facebook.com/"+userId) self.driver.get_element(data=".// *[ @ id = 'u_0_0']", name="post_box", type="xpath") self.driver.click_element("post_box") self.driver.send_keys_to_element(text=message, name="post_box", special=False) time.sleep(5) self.driver.get_element(data="view_post", name="post_button", type="name") return self.driver.click_element("post_button") else: self.log.error("-- Could not post, no userId found --") return False else: post = self.api.put_object(parent_object=to, connection_name='feed', message=message) return True else: self.log.error("-- Could not post, user not logged in --") return False #message a friend on fb (Uses messengerClient) def message(self, message, friend): try: if self.login(): friendId = self.getFriendId(friend) if friendId: formattedMessage = make_unicode(message) self.messengerClient.send(Message(text=formattedMessage), thread_id=friendId, thread_type=ThreadType.USER) return True self.log.error("-- Could not send the message : friendId not found --") return False self.log.error("-- Could not send the message, user not logged in --") return False except Exception as e: self.log.error("-- An error occured : \n" + str(e) + " \n ------") return False #Likes a friend profile pic def likeProfilePic(self, friend): try: if self.login(): friendId = self.getFriendId(friend) if friendId: picId = self.getProfilePicId(friendId) return self.likePost(picId, False) self.log.error("-- Could not like the profile pic, friendId not found --") return False self.log.error("-- Could not like the profile pic, user not logged in --") return False except Exception as e: self.log.error("-- An error occured : \n" + str(e) + " \n ------") return False #comment a friend profile pic def commentProfilePic(self, comment, friend): try: if self.login(): friendId = self.getFriendId(friend) if friendId: picId = self.getProfilePicId(friendId) return self.commentPost(comment, picId, False) self.log.error("-- Could not comment the profile pic, friendId not found --") return False self.log.error("-- Could not comment the profile pic, user not logged in --") return False except Exception as e: self.log.error("-- An error occured : \n" + str(e) + " \n ------") return False #Likes a post (Uses selenium) def likePost(self, postId, checkLogin = True): loggedIn = True if checkLogin == True: loggedIn = self.login() if loggedIn: get_url(self.driver, "https://m.facebook.com/photo.php?fbid="+postId) self.driver.get_element(data="/html/body/div/div/div[2]/div/div[1]/div/div/div[2]/div/table/tbody/tr/td[1]/a", name="like_btn", type="xpath") liked = False if not liked: return self.driver.click_element("like_btn") return True return False #Comments a photo (Uses selenium) def commentPost(self, comment, postId, checkLogin = True): loggedIn = True if checkLogin == True: loggedIn = self.login() if loggedIn: get_url(self.driver, "https://m.facebook.com/photo.php?fbid="+postId) self.driver.get_element(data="//*[@id=\"composerInput\"]", name="comment_input", type="xpath") self.driver.send_keys_to_element(text=comment, name="comment_input", special=False) self.driver.get_element(data="/html/body/div/div/div[2]/div/div[1]/div/div/div[3]/div[2]/div/div/div[5]/form/table/tbody/tr/td[2]/div/input", name="comment_submit", type="xpath") return self.driver.click_element(name="comment_submit") return False #Method to get your facebook friends (Uses messengerClient) #Facebook API prevents the user to know his friends IDs so we use messengerClient #Thus, we don't get a full list of all the user friends but only those he's been talking with def getFriends(self, checkLogin = True): loggedIn = True if checkLogin == True: loggedIn = self.login() if loggedIn: if(self.fbFriends is None): try: friendsList = {} friends = self.messengerClient.fetchAllUsers() for friend in friends: friendsList[friend.name] = friend.uid self.fbFriends = friendsList except Exception as e: self.log.error("-- An error occured : \n" + str(e) + " \n ------") return False return self.fbFriends self.log.error("-- Could not get friends list, user not logged in --") return None #Method to know the number of friends the user has (Uses FB API) def getNumberOfFriends(self, checkLogin = True): loggedIn = True if checkLogin == True: loggedIn = self.login() if loggedIn: return self.api.get_connections(id='me', connection_name='friends')['summary']['total_count'] self.log.error("-- Could not get the number of friends, user not logged in --") return None #Method to get and set the user Info (Name, id ...) --> Uses FB API def setUserInfo(self, checkLogin = True): loggedIn = True if checkLogin == True: loggedIn = self.login() if loggedIn: PARAMS = {'access_token':self.settings["fbUserAccessToken"], 'fields':'name, id'} userInfoRequest = requests.get(url = self.URL+'me', params = PARAMS) self.userInfo = userInfoRequest.json() return True self.log.error("-- Could not comment set current user info, user not logged in --") return False #Method to get a friend profile pic Id (Uses selenium) def getProfilePicId(self, friendId): try: picSrc = None if friendId == "me": friendId = self.userInfo['id'] r = requests.get("https://graph.facebook.com/"+friendId+"/picture") picSrc = r.url findString = "\d_(.*)_\d" return re.search(findString, picSrc).group(1) except Exception as e: self.log.error("-- An error occured : \n" + str(e) + " \n ------") return None #Method to get a friend Id def getFriendId(self, friend, typeToSearchFor="people"): userId=None fbFriends = self.getFriends() #Gets the closest friend name to what the user said using fuzzy matching foundFriend = findMatchingString(friend, fbFriends.keys()) #Verify that the user is happy to proceed with the friend we found if self.getConfirmation("person.confirmation", dict( person=foundFriend )): userId = fbFriends[foundFriend] return userId
if password == None: password = getpass.getpass() else: print("Using password from command line: %s" % ('*' * len(password))) client = Client( email, password, user_agent= 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:71.0) Gecko/20100101 Firefox/71.0' ) #-----get searched user's thread uid----- uid_c = None threads = client.fetchAllUsers() #get all user's threads for thread in threads: #iterate over threads #print(thread.name) #print(thread.uid) if thread.name.startswith( thread_name ): #check if current thread starts with passed chat name uid_c = thread.uid print("Found thread with name >%s< and uid >%s<" % (thread.name, thread.uid)) break if uid_c == None: print("Unable to find thread with name >%s<, exiting" % thread_name)
import fbchat from fbchat import Client, User import os import re from dotenv import load_dotenv fbchat._util.USER_AGENTS = [ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36" ] fbchat._state.FB_DTSG_REGEX = re.compile(r'"name":"fb_dtsg","value":"(.*?)"') load_dotenv() client = Client(email=os.getenv('FB_EMAIL'), password=os.getenv('FB_PASSWORD'), max_tries=1) print(list(map(lambda user: (user.name, user.uid), client.fetchAllUsers())))