def hear_meet(client, author_id, message_object, thread_id, thread_type): """Creates poll to decide on time for given date""" global meeting_polls global time_options today = date.today() gc_thread = Client.fetchThreadInfo(client, thread_id)[thread_id] try: msg_date = parse(message_object.text.split(' ', 1)[1]) assert (not isinstance(msg_date, type(None))) if msg_date.date() < today: raise ValueError except (IndexError, AssertionError) as e: action_queue.put( Action(client, 'message', thread_id, thread_type, text='I can\'t read that date.')) return except ValueError: action_queue.put( Action(client, 'message', thread_id, thread_type, text='I\'m not stupid that date has passed.')) return meeting = Poll( title=f"Meeting on {datetime.strftime(msg_date, '%A, %x')}. Who's in?", options=[PollOption(text=time) for time in time_options]) action_queue.put( Action(client, 'makepoll', thread_id, thread_type, poll=meeting)) tag_all(client, author_id, None, thread_id, thread_type)
def person_removed_handler(client, removed_id, author_id, thread_id): gc_thread = Client.fetchThreadInfo(client, thread_id)[thread_id] if removed_id == client.uid and gc_thread.type == ThreadType.GROUP: try: groups_ref.child(thread_id).delete() except FirebaseError: print("Not deleted properly")
def message(): speak("Checking for messages....") userID = "your email" psd = 'your password' useragent = "you user agent" cli = Client(userID, psd, user_agent=useragent, max_tries=1) if cli.isLoggedIn(): threads = cli.fetchUnread() if len(threads) == 1: speak(f"Sir, You have {len(threads)} message.") info = cli.fetchThreadInfo(threads[0])[threads[0]] speak("You have message from {}".format(info.name)) msg = cli.fetchThreadMessages(threads[0], 1) for message in msg: speak("Sir, the message is {}".format(message.text)) elif len(threads) >= 2: speak(f"Sir, You have {len(threads)} messages.") for thread in threads: initial_number = 0 info = cli.fetchUserInfo(thread[initial_number])[thread[initial_number]] initial_number += 1 speak("Sir, you have message from {}".format(info.name)) msg = cli.fetchThreadMessages(thread[initial_number], 1) msg.reverse() for message in msg: speak(f"The message is {message.text}.") else: speak("Sir, You have no messages.") else: print("Not logged in")
def hear_meet(client, author_id, message_object, thread_id, thread_type): gc_thread = Client.fetchThreadInfo(client, thread_id)[thread_id] date = datetime.strptime(message_object.text.split(' ')[1], '%m/%d/%y') message_text = 'Meeting at' + date.strftime( '%A, %m/%d/%y') + '. Who\'s in?' client.send(Message(text=message_text), thread_id=thread_id, thread_type=thread_type)
def GetMembers(): client = Client(SECRETARY_EMAIL, SECRETARY_PASSWORD) user_id_list = list( client.fetchThreadInfo(ROCKETRY_THREAD)[ROCKETRY_THREAD].participants) user_list = [] for user_id in user_id_list: user_list.append(client.fetchUserInfo(user_id)[user_id]) client.logout() return user_list
def print_all_threads(client: Client): threads = client.fetchThreadList() for thread in threads: messages = client.fetchThreadMessages(thread.uid, limit=30) if thread.type == ThreadType.USER: thread_info = client.fetchThreadInfo(thread.uid) interlocutor = thread_info[thread.uid] _print_thread_messages(client, messages, interlocutor) else: _print_thread_messages(client, messages, None)
def hear_meet(self, author_id, message_object, thread_id, thread_type, **kwargs): gc_thread = Client.fetchThreadInfo(self, thread_id)[thread_id] date = datetime.strptime(message_object.text.split(' ')[1], '%m/%d/%y') message_text = 'Meeting at' + strfrtime( date, '%A, %m/%d/%y') + '. Who\'s in?' self.send(Message(text=message_text), thread_id=thread_id, thread_type=thread_type)
def tag_all(client, author_id, message_object, thread_id, thread_type): gc_thread = Client.fetchThreadInfo(client, thread_id)[thread_id] mention_list = [] message_text = '@all' for person in Client.fetchAllUsersFromThreads(self=client, threads=[gc_thread]): mention_list.append(Mention(thread_id=person.uid, offset=0, length=1)) client.send(Message(text=message_text, mentions=mention_list), thread_id=thread_id, thread_type=thread_type)
def kick_random(client, author_id, message_object, thread_id, thread_type): """Kicks a random person from the chat""" gc_thread = Client.fetchThreadInfo(client, thread_id)[thread_id] persons_list = Client.fetchAllUsersFromThreads(self=client, threads=[gc_thread]) num = random.randint(0, len(persons_list) - 1) #random number within range person = persons_list[num] log.info("{} removed {} from {}".format(author_id, "random", thread_id)) action_queue.put( Action(client, 'removeuser', thread_id, thread_type, pid=person.uid)) return log.info("Unable to remove: person not found.")
def make_friend(client, author_id, message_object, thread_id, thread_type): gc_thread = Client.fetchThreadInfo(client, thread_id)[thread_id] person_to_friend = message_object.text.split(' ', 1)[1] for person in Client.fetchAllUsersFromThreads(self=client, threads=[gc_thread]): if person_to_friend.lower() in person.name.lower(): action_queue.put( Action(client, 'makefriend', thread_id, thread_type, pid=person.uid))
def kick(client, author_id, message_object, thread_id, thread_type): gc_thread = Client.fetchThreadInfo(client, thread_id)[thread_id] person_to_kick = message_object.text.split(' ')[1:] for person in Client.fetchAllUsersFromThreads(self=client, threads=[gc_thread]): names = [person.first_name, person.last_name, person.nickname] if any([name in person_to_kick for name in names]): log.info("{} removed {} from {}").format(author_id, person_to_kick, thread_id) Client.removeUserFromGroup(user_id=person.uid, thread_id=thread_id) return log.info("Unable to remove: person not found.")
def brief(client, author_id, message_object, thread_id, thread_type): if Client.fetchThreadInfo(client, thread_id)[thread_id].type == ThreadType.USER: action_queue.put( Action(client, 'message', thread_id, thread_type, text="Brief only works in Group chats!")) return string_get = groups_ref.child(thread_id).child("string").get() pin_get = groups_ref.child(thread_id).child("pin_id").get() if string_get is None and pin_get is None: action_queue.put( Action(client, 'message', thread_id, thread_type, text="You never pinned anything")) elif pin_get is None: action_queue.put( Action(client, 'message', thread_id, thread_type, text=string_get)) else: try: message_object = Client.fetchMessageInfo(client, mid=pin_get, thread_id=thread_id) print(message_object.attachments) if not message_object.attachments: action_queue.put( Action(client, 'message', thread_id, thread_type, text=message_object.text)) else: for x in message_object.attachments: action_queue.put( Action(client, 'forward', thread_id, thread_type, attachmentID=x.uid)) except FBchatException: action_queue.put( Action(client, 'message', thread_id, thread_type, text="Your Pinned Message might not exist anymore"))
class FbBot(): def __init__(self): config = configparser.ConfigParser() config.read('config.ini') config = config['FACEBOOK'] self.client = Client(config['email'], config['password']) self.thread_id = config['thread_id'] self.group = self.client.fetchThreadInfo( self.thread_id)[self.thread_id] self.names = self.getListOfNames() def getListOfNames(self): # Returns a list of all names in chat. self.users = [ self.client.fetchUserInfo(uid) for uid in tqdm(self.group.participants) ] return [self._formatName(str(user)) for user in self.users] def _formatName(self, user): name, uid = tuple(user.split('USER ')[1].split(')')[0].split('(')) return (name[:-1], uid) def getLunches(self): cnt = self.group.message_count + 1 flach_id = '100002684466673' frokost_besked = 'Hvem spiser med i dag?' messages = self.client.fetchThreadMessages(self.thread_id, cnt) messages = messages[::-1] ppl = [] for message in messages: if (message.author == flach_id and (message.text is not None and frokost_besked in message.text)): date = int(message.timestamp) // 1000 # F*****g miliseconds ppl.append({ 'date': dt.fromtimestamp(date), 'msgid': message.uid, 'reactions': [ self._idToName(user) for user, react in message.reactions.items() if react == MessageReaction.YES ] }) return ppl def _idToName(self, target_id): for name, uid in self.names: if uid == target_id: return name
def pm_person(client, author_id, message_object, thread_id, thread_type): gc_thread = Client.fetchThreadInfo(client, thread_id)[thread_id] person_to_pm = message_object.text.split(' ')[1:] for person in Client.fetchAllUsersFromThreads(self=client, threads=[gc_thread]): names = [person.first_name, person.last_name, person.nickname] if any([name in person_to_pm for name in names]): thread_id = person.uid action_queue.put( Action(client, 'message', thread_id, ThreadType.USER, text="hello friend"))
def tag_all(client, author_id, message_object, thread_id, thread_type): """Tags everyone in the chat""" gc_thread = Client.fetchThreadInfo(client, thread_id)[thread_id] mention_list = [] message_text = '@all' for person in Client.fetchAllUsersFromThreads(self=client, threads=[gc_thread]): mention_list.append(Mention(thread_id=person.uid, offset=0, length=1)) action_queue.put( Action(client, 'message', thread_id, thread_type, text=message_text, mentions=mention_list))
def admin(client, author_id, message_object, thread_id, thread_type): gc_thread = Client.fetchThreadInfo(client, thread_id)[thread_id] person_to_admin = message_object.text.split(' ', 1)[1] for person in Client.fetchAllUsersFromThreads(self=client, threads=[gc_thread]): if person_to_admin.lower() in person.name.lower(): log.info("{} added as admin {} from {}".format( author_id, person_to_admin, thread_id)) action_queue.put( Action(client, 'makeadmin', thread_id, thread_type, pid=person.uid)) return log.info("Unable to add admin: person not found.")
def handle_meeting_vote(client, author_id, poll, thread_id, thread_type): global meeting_polls global CONSENSUS_THRESHOLD gc_thread = Client.fetchThreadInfo(client, thread_id)[thread_id] # update meeting_polls by checking today's date, and prune any that've passed today = date.today() for poll_uid in list(meeting_polls.keys()): if meeting_polls[poll_uid]['date'].date() < today: meeting_polls.pop(poll_uid) # check poll for consensus, i.e majority of users. If so, send update and deactivate poll n_users = float( len(Client.fetchAllUsersFromThreads(self=client, threads=[gc_thread]))) check_consensus = lambda votes: (votes / n_users) >= CONSENSUS_THRESHOLD consensus = [ check_consensus(float(option.votes_count)) for option in client.fetchPollOptions(poll.uid) ] if any(consensus[:-1]): # meeting is happening meeting_time = client.fetchPollOptions( poll.uid)[consensus.index(True)].text meeting_date = datetime.strftime(meeting_polls[poll.uid]['date'], '%A, %x') action_queue.put( Action( client, 'message', thread_id, thread_type, text= f'Consensus reached! Meeting at {meeting_time} on {meeting_date}' )) return elif consensus[-1]: # meeting is not happening action_queue.put( Action( client, 'message', thread_id, thread_type, text= f'Consensus reached! Meeting at {meeting_time} isn\'t happening.' )) return else: log.info(f"No consensus on poll {poll.uid} yet.")
def kick(client, author_id, message_object, thread_id, thread_type): """Kicks the specified user from the chat""" gc_thread = Client.fetchThreadInfo(client, thread_id)[thread_id] person_to_kick = message_object.text.split(' ', 1)[1] for person in Client.fetchAllUsersFromThreads(self=client, threads=[gc_thread]): if person_to_kick.lower() in person.name.lower(): log.info("{} removed {} from {}".format(author_id, person_to_kick, thread_id)) action_queue.put( Action(client, 'removeuser', thread_id, thread_type, pid=person.uid)) return log.info("Unable to remove: person not found.")
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 random_mention(client, author_id, message_object, thread_id, thread_type): """Tags a random person""" random.seed(time.time()) gc_thread = Client.fetchThreadInfo(client, thread_id)[thread_id] person_list = [] for person in Client.fetchAllUsersFromThreads(self=client, threads=[gc_thread]): person_list.append(person) chosen_number = random.randrange(0, len(person_list), 1) chosen_person = person_list[chosen_number] person_name = chosen_person.first_name rand_mention = Mention(thread_id=chosen_person.uid, offset=0, length=len(person_name) + 1) action_queue.put( Action(client, 'message', thread_id, thread_type, text="@" + person_name + " you have been chosen", mentions=[rand_mention]))
def pin(client, author_id, message_object, thread_id, thread_type): if Client.fetchThreadInfo(client, thread_id)[thread_id].type == ThreadType.USER: action_queue.put( Action(client, 'message', thread_id, thread_type, text="Pin only works in Group chats!")) return string_get = groups_ref.child(thread_id).child("string").get() pin_get = groups_ref.child(thread_id).child("pin_id").get() if message_object.replied_to == None: to_pin = message_object.text.split(' ')[1:] if not to_pin: action_queue.put( Action(client, 'message', thread_id, thread_type, text="Make sure you have something to pin!")) return if string_get is None: groups_ref.child(thread_id).set({"string": to_pin}) else: groups_ref.child(thread_id).update({"string": to_pin}) if pin_get != None: groups_ref.child(thread_id).child("pin_id").delete() else: if pin_get is None: groups_ref.child(thread_id).set( {"pin_id": message_object.replied_to.uid}) else: groups_ref.child(thread_id).update( {"pin_id": message_object.replied_to.uid}) if string_get != None: groups_ref.child(thread_id).child("string").delete()
threads = client.fetchThreadList() # Fetches the next 10 threads threads += client.fetchThreadList(offset=20, limit=10) print("Threads: {}".format(threads)) # Gets the last 10 messages sent to the thread messages = client.fetchThreadMessages(thread_id='<thread id>', limit=10) # Since the message come in reversed order, reverse them messages.reverse() # Prints the content of all the messages for message in messages: print(message.text) # If we have a thread id, we can use `fetchThreadInfo` to fetch a `Thread` object thread = client.fetchThreadInfo('<thread id>')['<thread id>'] print("thread's name: {}".format(thread.name)) print("thread's type: {}".format(thread.type)) # `searchForThreads` searches works like `searchForUsers`, but gives us a list of threads instead thread = client.searchForThreads('<name of thread>')[0] print("thread's name: {}".format(thread.name)) print("thread's type: {}".format(thread.type)) # Here should be an example of `getUnread`
from fbchat.models import Message # log in # facebook user credentials username = "******" password = "******" # login client = Client(username, password) # get 20 users you most recently talked to users = client.fetchThreadList() #print(users) # # get the detailed informations about these users detailed_users = [ list(client.fetchThreadInfo(user.uid).values())[1] for user in users ] # # sort by number of messages sorted_detailed_users = sorted(detailed_users, key=lambda u: u.message_count, reverse=True) # # print the best friend! friend = sorted_detailed_users[1] print("Friend:", friend.name, "with a message count of", friend.message_count) # # message the friend! client.send(Message( text= f"Congratulations {friend.name}, I just tested out my bot with you {friend.message_count} fear not!"
users = client.fetchAllUsers() print("users' IDs: {}".format([user.uid for user in users])) print("users' names: {}".format([user.name for user in users])) # Fetches a list of the 20 top threads you're currently chatting with threads = client.fetchThreadList() # Fetches the next 10 threads threads += client.fetchThreadList(limit=10) print("Threads: {}".format(threads)) # Gets the last 10 messages sent to the thread messages = client.fetchThreadMessages(thread_id="100004155888313", limit=10) # Since the message come in reversed order, reverse them messages.reverse() # Prints the content of all the messages for message in messages: print(message.text) # If we have a thread id, we can use `fetchThreadInfo` to fetch a `Thread` object thread = client.fetchThreadInfo("100004155888313")["100004155888313"] print("thread's name: {}".format(thread.name)) print("thread's type: {}".format(thread.type)) # `searchForThreads` searches works like `searchForUsers`, but gives us a list of threads instead thread = client.searchForThreads("<name of thread>")[0] print("thread's name: {}".format(thread.name)) print("thread's type: {}".format(thread.type))
def print_single_thread(client: Client, thread_id): messages = client.fetchThreadMessages(thread_id, limit=30) thread_info = client.fetchThreadInfo(thread_id) interlocutor = thread_info[thread_id] _print_thread_messages(client, messages, interlocutor)
print("user's photo: {}".format(user.photo)) print("Is user client's friend: {}".format(user.is_friend)) # Fetches a list of the 20 top threads you're currently chatting with threads = client.fetchThreadList() # Fetches the next 10 threads threads += client.fetchThreadList(offset=20, limit=10) print("Threads: {}".format(threads)) # Gets the last 10 messages sent to the thread messages = client.fetchThreadMessages(thread_id="<thread id>", limit=10) # Since the message come in reversed order, reverse them messages.reverse() # Prints the content of all the messages for message in messages: print(message.text) # If we have a thread id, we can use `fetchThreadInfo` to fetch a `Thread` object thread = client.fetchThreadInfo("<thread id>")["<thread id>"] print("thread's name: {}".format(thread.name)) print("thread's type: {}".format(thread.type)) # `searchForThreads` searches works like `searchForUsers`, but gives us a list of threads instead thread = client.searchForThreads("<name of thread>")[0] print("thread's name: {}".format(thread.name)) print("thread's type: {}".format(thread.type)) # Here should be an example of `getUnread`
try: print('Logging in...') client = Client(email, pswd, logging_level=50) except FBchatUserError as e: print(e) sys.exit() thread_limit = 15 if client is not None and client.isLoggedIn(): print('Logged in as ' + email) threads = client.fetchThreadList(limit=thread_limit) for i in range(thread_limit): thread_info = client.fetchThreadInfo(threads[i].uid)[threads[i].uid] print('[{}] {}'.format(i, thread_info.name)) selected_thread = int(input('Select thread: ')) if not selected_thread > thread_limit - 1: thread_uid = client.fetchThreadInfo( threads[selected_thread].uid)[threads[selected_thread].uid].uid print('Selected thread uid: {}'.format(thread_uid)) thread_dir = os.path.join(os.path.dirname(__file__), thread_uid) if not os.path.isdir(thread_dir): os.mkdir(thread_dir) attachments = client.fetchThreadImages(thread_uid)
sentence = 'Been working so hard I'm punching my card Eight hours, for what? Oh, tell me what I got I gotten this feeling That time's just holding me down I'll hit the ceiling Or else I'll tear up this town Tonight I gotta cut loose, footloose Kick off your Sunday shoes Please, Louise Pull me up off my knees Jack, get back C'mon, before we crack Lose your blues Everybody cut footloose You're playing so cool Obeying every rule Dig way down in your heart You're burning, yearning for some Somebody to tell you That life ain't passing you by I'm trying to tell you It will if you don't even try You can fly if you'd only cut loose, footloose Kick off your Sunday shoes Ooh-wee, Marie Shake it, shake it for me Whoa, Milo C'mon, c'mon let's go Lose your blues Everybody cut footloose' sentence = sentence.split(' ') username = "******" password = "******" # login client = Client(username, password) personToSpam = 'friendsName' #just making sure if not client.isLoggedIn(): client.login(username, password) print('fetching most recent users u talked too...') users = client.fetchThreadList() detailed_users = [ list(client.fetchThreadInfo(user.uid).values())[0] for user in users ] #sorting them by message count sorted_detailed_users = sorted(detailed_users, key=lambda u: u.message_count, reverse=True) print('looking for',personToSpam) for friend in sorted_detailed_users: if personToSpam in friend.name : personToSpam = friend break print('sending aannoying spam to:',personToSpam.name) for word in sentence: client.send(Message(text=word),thread_id=personToSpam.uid)
def odds(client, author_id, message_object, thread_id, thread_type): # if message contains bracket - is a reply hash_search = target = re.match(r"[^[]*\[([^]]*)\]", message_object.text).groups() gc_thread = Client.fetchThreadInfo(client, thread_id)[thread_id] if len(hash_search) == 0: # message contains people - is start of new game # make sure game is started in group chat if thread_type != ThreadType.GROUP: action_queue.put( Action(client, 'message', thread_id, thread_type, text='Please only do this is a group chat.')) return new_hash = shake_256( str(int(author_id) + random.randint(-1e4, 1e4)).encode('utf-8')).hexdigest(6) instigator = client.fetchUserInfo(author_id)[author_id] # find user person_to_friend = message_object.text.split(' ', 1)[1] target = None for person in Client.fetchAllUsersFromThreads(self=client, threads=[gc_thread]): if person_to_friend.lower in person.name.lower(): target = person.uid if target == None: # tell the user they're dumb return action_queue.put( Action( client, 'message', target.uid, ThreadType.USER, text= f"You've been challenged to an odds game by {instigator.first_name}. Pick a number between 1 and 10. To reply, copy and send the message below." )) action_queue.put( Action(client, 'message', target.uid, ThreadType.USER, text=f"!odds [{new_hash}] <your number here>")) action_queue.put( Action( client, 'message', instigator.uid, ThreadType.USER, text= f"You started an odds game with {target.first_name}. Pick a number between 1 and 10. To reply, copy and send the message below." )) action_queue.put( Action(client, 'message', instigator.uid, ThreadType.USER, text=f"!odds [{new_hash}] <your number here>")) else: # if message contains bracket - is a reply # check hashcode against database # check if both slots in the hashcode are filled if '''both slots are filled''': action_queue.put( Action( client, 'message', gc_thread, ThreadType.GROUP, text= f'{winner.first_name} has won the odds. Do what you will.') )
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) client.logout() exit(5) #-----get searched user's thread uid----- #-----fetch and set number of attachments and messages----- thread_info = client.fetchThreadInfo(uid_c)[uid_c] thread_info = client.fetchThreadInfo(uid_c)[ uid_c] #twice because of documentation but idk messages_count = thread_info.message_count print("Number of messages in the thread: %d" % messages_count) messages_number = messages_count if args.last != None: messages_number = args.last print("Fetching %d messages" % messages_number) #-----fetch and set number of attachments and messages----- last_timestamp = None messages_count = 0 active = True messages_list = []