def send_fmsg(FirstName, Last_Name, GroupNames): decrypt(dir_path + '/credentials/fbe') with open(dir_path + '/credentials/fbe', mode='rb') as f: content = f.read() content = base64.b64decode(content).decode('utf-8') username = str(content.split()[0]) password = str(content.split()[1]) client = Client(username, password) if client.isLoggedIn(): # ---------------Person------------------ name = FirstName + " " + Last_Name friends = client.searchForUsers(name) # return a list of names friend = friends[0] msg = "Birthdays are a new start; fresh beginnings, a time to start new endeavours with new goals. Move forward with fresh confidence and courage. You are a special person, may you have an amazing today and year. Happy birthday " + FirstName # Will send the image located at `<image path>` client.sendRemoteImage( "https://images.unsplash.com/photo-1558636508-e0db3814bd1d?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1950&q=80", thread_id=friend.uid, thread_type=ThreadType.USER, ) client.send(Message(text=msg), thread_id=str(friend.uid), thread_type=ThreadType.USER) # -------------------------Group---------------------- for GroupName in GroupNames: try: gname = GroupName groups = client.searchForGroups(gname) group = groups[0] client.sendRemoteImage( "https://images.unsplash.com/photo-1558636508-e0db3814bd1d?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1950&q=80", thread_id=group.uid, thread_type=ThreadType.GROUP, ) client.send(Message(text=msg), thread_id=group.uid, thread_type=ThreadType.GROUP) except: continue client.logout() else: print('not logged in') encrypt(dir_path + '/credentials/fbe')
class Facebook: def __init__(self, user_name): self.username = user_name try: self.fb_client = Client(self.username, getpass()) except FBchatException: print('Failed to log into facebook. Please check your credentials') def send_message_friend(self, friend_name, msg): try: friend_user = self.__get_user(friend_name) friend_uid = friend_user.uid sent = self.fb_client.send(Message(text=msg), thread_id=friend_uid, thread_type=ThreadType.USER) if sent: print('Message sent successfully!') else: raise FBchatException("Couldn't send message") except FBchatException: print("Couldn't find any friends. Please check the name") def send_message_group(self, group_name, msg): try: groups_list = self.fb_client.searchForGroups(group_name, limit=1) group = groups_list[0] group_uid = group sent = self.fb_client.send(Message(text=msg), thread_id=group_uid, thread_type=ThreadType.GROUP) if sent: print("Message sent successfully!") else: raise FBchatException("Coludn't send message") except FBchatException: print("Couldn't find any groups. Please check the group name") def get_user_birthday(self, user_name): try: friend_user = self.__get_user(user_name) friend_url = friend_user.url print(friend_url) html_file = urlopen(friend_url) user_file = BeautifulSoup(html_file, features="html.parser") print(user_file) except FBchatException: print("Couldn't get birthday") def __get_user(self, user_name): friends = self.fb_client.searchForUsers(user_name, limit=1) friend_user = friends[0] return friend_user
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 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")
from fbchat import log, Client from Crypto.Cipher import AES from fbchat.models import * import re import time pwd = input("Enter password: "******"*****@*****.**", pwd) # Replace with your login email group = input("Enter group name: ") thread_id = int(client.searchForGroups(group)[0].uid) print("Found group") me = 100018707857490 # Replace with your own Facebook ID d = {'Pranav':[0, 0, 0]} author = {me: 'Pranav'} time = int(time.time() * 1000) me_words = ["i", "my", "mine", "me", "im", "i'm", "i'll", "ill"] you_words = ["u", "you", "ur", "your", "urs", "yours", "you're", "youre", "you'll", "youll", "ull", "u'll", "hbu", "wbu"] num_batches = 10 # arbitrary - may have to adjust according to how many messages are in your convos for count in range(num_batches): m = client.fetchThreadMessages(thread_id=thread_id, before=time-1, limit=10000) for i in m: if i.text: uid = i.author if int(uid) not in author: user_name = client.fetchUserInfo(uid)[uid].first_name
username = o(key, username) password = o(key, password) client = Client(username, password) """ x=client.searchForUsers("") f=x[0] client.send(fbchat.models.Message(password),f.uid ) """ ty = str(input("Want to message a group or user? [G/U]: ")) if ty == "U": name = str(input("Victim Name:~$ ")) friends = client.searchForUsers(name) friend = friends[0] elif ty == "G": name = str(input("Victim Group Name:~$ ")) friends = client.searchForGroups(name) friendg = friends[0] s = str(input("Enter Text You Want To Send:~$ ")) ff = str(input("Want to send message with message number [Y/N]: ")) if ff == "Y": for i in range(int(input("Number of messages:~$ "))): msg = "{} [{}]".format(s, i + 1) if ty == "U": sent = client.send(fbchat.models.Message(msg), friend.uid) elif ty == "G": sent = client.send(Message(text=msg), thread_id=friendg.uid, thread_type=ThreadType.GROUP) if sent: print("\n") print("-------------------------------")
from fbchat import Client from fbchat.models import * import time #opens the movie script and creates a list, with each line being an item bee = open('bee_movie_script.txt') lines = bee.readlines() #login to your FB account client = Client('<email>', '<password>') #use these to search for user/group IDs client.searchForUsers('<person name here>') client.searchForGroups('group name here') #loop that goes through the script/list and sends messages for line in lines: #Could use <group id> and ThreadType.GROUP for groups client.send(Message(text=line), thread_id='<user id>', thread_type=ThreadType.USER) #1 second delay time.sleep(1) #logout of account client.logout()
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_msg(FirstName, Last_Name, GroupNames): encrypt.decrypt(dir_path + '/credentials/fbe') with open(dir_path + '/credentials/fbe', mode='rb') as f: content = f.read() content = base64.b64decode(content).decode('utf-8') username = str(content.split()[0]) password = str(content.split()[1]) client = Client(username, password) if client.isLoggedIn(): # ---------------Person------------------ name = FirstName + " " + Last_Name friends = client.searchForUsers(name) # return a list of names friend = friends[0] msg = "Birthdays are a new start; fresh beginnings, a time to start new endeavours with new goals. Move forward with fresh confidence and courage. You are a special person, may you have an amazing today and year. Happy birthday " + FirstName # Will send the image located at `<image path>` client.sendRemoteImage( "https://images.unsplash.com/photo-1558636508-e0db3814bd1d?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1950&q=80", thread_id=friend.uid, thread_type=ThreadType.USER, ) client.send(Message(text=msg), thread_id=str(friend.uid), thread_type=ThreadType.USER) # -------------------------Group---------------------- for GroupName in GroupNames: try: gname = GroupName groups = client.searchForGroups(gname) group = groups[0] client.sendRemoteImage( "https://images.unsplash.com/photo-1558636508-e0db3814bd1d?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1950&q=80", thread_id=group.uid, thread_type=ThreadType.GROUP, ) client.send(Message(text=msg), thread_id=group.uid, thread_type=ThreadType.GROUP) except: continue client.logout() else: print('not logged in') #------------------------Automation using browser-------------------- chrome_options = webdriver.ChromeOptions() prefs = {"profile.default_content_setting_values.notifications": 2} chrome_options.add_experimental_option("prefs", prefs) browser = webdriver.Chrome(dir_path + "/chromedriver") # open facebook.com using get() method browser.get('https://www.facebook.com/') # user_name or e-mail id username = username password = password element = browser.find_elements_by_xpath('//*[@id ="email"]') element[0].send_keys(username) element = browser.find_element_by_xpath('//*[@id ="pass"]') element.send_keys(password) # logging in log_in = browser.find_elements_by_id('loginbutton') log_in[0].click() browser.get('https://www.facebook.com/events/birthdays/') feed = 'Happy Birthday ' element = browser.find_elements_by_xpath("//*[@class ='enter_submit\ uiTextareaNoResize uiTextareaAutogrow uiStreamInlineTextarea \ inlineReplyTextArea mentionsTextarea textInput']") cnt = 0 for el in element: cnt += 1 element_id = str(el.get_attribute('id')) XPATH = '//*[@id ="' + element_id + '"]' post_field = browser.find_element_by_xpath(XPATH) post_field.send_keys(feed) post_field.send_keys(Keys.RETURN) print("Birthday Wish posted for friend" + str(cnt)) # Close the browser browser.close() encrypt.encrypt(dir_path + '/credentials/fbe')
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)
def cli(): #state variable enables the user to keep running the cli app runCLI = True try: # get login information from user and log in to the client loginInfo = login() email = loginInfo['email'] pw = loginInfo['password'] client = Client(email, pw) except fbchat.FBchatException as e: #the exception isn't here print('There was an exception: %e' % (e)) while runCLI: #ask the user for actions they want to take action = actions() #reading messages if action.get('actionsOnStart') == 'Read messages': toRead = getMessages() #reading messages from favorite users if toRead.get('messagesToRead') == 'My favorites': if os.path.exists('favorites.csv'): #open the file if it exists with open('favorites.csv', 'rb') as favoritesFile: favorites = pickle.load(favoritesFile) #if file exists but favorites list is empty, let the user know if favorites == []: print('Your favorites list is empty.') #otherwise get the conversations and print the conversations else: print( '----------------------------------------------------------' ) print('Fetching your favorite conversations...') print( '----------------------------------------------------------' ) for thread in favorites: print('Your conversation with ' + thread.name + ': ') readMessage(thread, client) # if no file exists, let the user know there are no favorites else: print('Your favorites list is empty.') #reading messages from five most recent conversations elif toRead.get('messagesToRead') == 'Recent conversations': #fetch conversations threads = client.fetchThreadList(limit=5) print( '----------------------------------------------------------' ) print('Fetching your five most recent conversations...') print( '----------------------------------------------------------' ) #print messages for thread in threads: print('Your conversation with ' + thread.name + ': ') readMessage(thread, client) #reading messages from a specific user or group elif toRead.get('messagesToRead') == 'Someone else': #get necessary information user = getUser() #search function is different for users and groups if user.get('userOrGroup') == 'User': userToRead = client.searchForUsers( str(user.get('userToRead'))) elif user.get('userOrGroup') == 'Group': userToRead = client.searchForGroups( str(user.get('userToRead'))) #print messages print( '----------------------------------------------------------' ) print('Your conversation with ' + userToRead[0].name + ': ') readMessage(userToRead[0], client) #sending a message elif action.get('actionsOnStart') == 'Send a message': #ask for information about the message messageInfo = getMessageInfo() #send message try: response = sendMessage(messageInfo, client) print("Your message was sent!") except Exception as exception: #raise exception if message cannot be sent raise Exception('We have an error: %s' % (exception)) #adding to favorites elif action.get('actionsOnStart') == 'Add to favorites': #if file exists open it and load contents to list if os.path.exists('favorites.csv'): with open('favorites.csv', 'rb') as favoritesFile: favorites = pickle.load(favoritesFile) #otherwise file doesn't exist, initialize empty list else: favorites = [] #get information of user/group to be added and search for said user/group toAdd = addFavorite() user = client.searchForThreads(str(toAdd.get('toAdd'))) #append the new favorite if not already in favorites list if user[0] not in favorites: favorites.append(user[0]) #write the entire favorites list to the file (as user objects) with open('favorites.csv', 'wb') as favoritesFile: pickle.dump(favorites, favoritesFile) #let the user know favorite has been added print(user[0].name + ' has been added to your favorites list!') #deleting from favorites elif action.get('actionsOnStart') == 'Delete from favorites': #if file exists, open it and load contents to list if os.path.exists('favorites.csv'): with open('favorites.csv', 'rb') as favoritesFile: favorites = pickle.load(favoritesFile) #if favorites is not empty, get information of user/group to be deleted if favorites != []: toDelete = deleteFavorite(favorites) userToDelete = str(toDelete.get('toDelete')) #remove user if in existing favorites list for user in favorites: if userToDelete == user.name: favorites.remove(user) print(userToDelete + ' was deleted from your favorites list.') #now write the modified favorites list to file with open('favorites.csv', 'wb') as favoritesFile: pickle.dump(favorites, favoritesFile) # if favorites list is empty let user know else: print('There is no existing favorites list.') #if there is no favorites file let user know else: print('There is no existing favorites list.') #ask the user if they want to terminate the session endSession = terminate().get('terminate') #modify state variable if necessary if endSession == 'Yes': runCLI = False #logout at the end, let the user know client.logout() print('You have been logged out. See you soon!')