Example #1
0
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")
Example #2
0
def login(name=None):
    global client
    global user_name
    global username
    global password

    if request.method == "POST":
        # Get the Username and Password from the form
        username = request.form['emailadress']
        password = request.form['password']

        # # Load previous cookies this is for debug only!!!
        # session_cookies = json.load(open("session.json"))
        
        # Open the Client Object
        client = Client(username, password)#,session_cookies=session_cookies)
        
        # Get User Name
        newuser = client.fetchUserInfo(client.uid)[client.uid]

        # Make User Name
        user_name = "%s %s" % (newuser.first_name,newuser.last_name)
        
        # Get the Session Cookies and Save them for Later
        session_cookies = client.getSession()

        # Write the Cookies to a file
        with open("session.json","wt") as out:
            res = json.dump(session_cookies,out,sort_keys=True,indent=4,separators=(',',':'))
        
    return render_template("main.html", name=user_name)
Example #3
0
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
Example #4
0
def _print_thread_messages(client: Client, messages, interlocutor):
    name = client.fetchUserInfo(client.uid)[client.uid].name
    user = client.searchForUsers(name)[0]
    print("\n--------------------------------------------------\n")
    messages.reverse()
    for message in messages:
        if user.uid == message.author:
            print(user.name, ": ", message.text)
        elif interlocutor is not None and interlocutor.uid == message.author:
            print(interlocutor.name, ":", message.text)
        else:
            print("Group Member :", message.text)
    print("\n--------------------------------------------------\n")
Example #5
0
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
Example #6
0
def _get_messages(client: Client, sent: bool):
    threads = client.fetchThreadList()
    sent_messages = []
    received_messages = []
    for thread in threads:
        messages = client.fetchThreadMessages(thread.uid, limit=30)
        name = client.fetchUserInfo(client.uid)[client.uid].name
        user = client.searchForUsers(name)[0]
        messages.reverse()
        for message in messages:
            if user.uid == message.author:
                sent_messages.append(message)
            elif user.uid != message.author:
                received_messages.append(message)
    if sent:
        return sent_messages
    else:
        return received_messages
Example #7
0
class TrackerClient:
    def __init__(self, options, logger, config):
        self.options = options
        self.logger = logger
        self.trackerLogger = TrackerLogger.TrackerLogger(config['db'])
        self.config = config

        # let's try to login into that account
        self.client = Client(self.options['username'],
                             self.options['password'], None, 5, None,
                             logging.CRITICAL)

    # I'm not sure why, but Facebook API sometimes does return a "historical" data (2-3 hours old)

    def onChatTimestamp(self, **kwargs):
        updatedUsers = kwargs['buddylist'].items()
        self.trackerLogger.log(updatedUsers)

        for user, timestamp in updatedUsers:
            userInfo = self.client.fetchUserInfo(user)[user]
            self.trackerLogger.userdata(userInfo)

            if (
                    self.config['env'] == 'dev'
            ):  #and time.time() - int(timestamp) < 60): # to save some unneeded requests
                self.logger.info('{}: {} updated: {}'.format(
                    self.options['username'], userInfo.name,
                    datetime.datetime.fromtimestamp(
                        int(timestamp)).strftime('%Y-%m-%d %H:%M:%S')))

    def listen(self):
        if (not self.client):
            self.logger.error('%s: FBChat client not detected!',
                              self.options['username'])
            return False

        if (not self.client.isLoggedIn()):
            self.client.login(self.options['username'],
                              self.options['password'])

        # monkey patching. not sure if this is a good idea
        self.client.onChatTimestamp = self.onChatTimestamp

        self.client.listen()
Example #8
0
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()
Example #9
0
def send_alert(msg):
    client = Client('*****@*****.**', 'Temp123!')

    for i in range(person.__len__()):
        # If we have a user id, we can use `fetchUserInfo` to fetch a `User` object
        user_id = person[i]
        user = client.fetchUserInfo(user_id)[user_id]
        print("user's name: {}".format(user.name))

        msg_id = client.send(Message(text=msg), thread_id=user_id, thread_type=ThreadType.USER)

        client.onMessageDelivered(msg_ids=msg_id,
                                  delivered_for=user.name,
                                  thread_id=user_id,
                                  thread_type=ThreadType.USER,
                                  ts=1)

    client.logout()
    print('Complete.')

# send_alert('Hello there')
Example #10
0
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]))
Example #11
0
day_sufix = [' !',
               ' :)',
               ' <3',
               ' c;',
               ' ;>',
               ' Przyjacielu!',
               ' Kolego']
client=Client("YOUR_EMAIL ","YOUR_PASSWORD")
client.send(Message('STARTED'), thread_id=client.uid, thread_type=ThreadType.USER)
var = True
while var == True:
    if(time.gmtime().tm_sec == 00
    and time.gmtime().tm_min == 00
    and time.gmtime().tm_hour == 22):
        for x in ids:
            user = client.fetchUserInfo(x)[x]
            interfix = user.first_name
            client.send(Message(text=night_prefix[random.randrange(len(night_prefix))]+interfix+night_sufix[random.randrange(len(night_sufix))]), thread_id=x, thread_type=ThreadType.USER)
            time.sleep(1)
        var = False
var = True
while var == True:
    if(time.gmtime().tm_sec == 00
    and time.gmtime().tm_min == 00
    and time.gmtime().tm_hour == 8):
        for x in ids:
            user = client.fetchUserInfo(x)[x]
            interfix = user.first_name
            client.send(Message(text=day_prefix[random.randrange(len(day_prefix))]+interfix+day_sufix[random.randrange(len(day_sufix))]), thread_id=x, thread_type=ThreadType.USER)
            time.sleep(1)
        var = False
Example #12
0
# -*- coding: UTF-8 -*-

from fbchat import Client
from fbchat.models import *

client = Client("<email>", "<password>")

# Fetches a list of all users you're currently chatting with, as `User` objects
users = client.fetchAllUsers()

print("users' IDs: {}".format([user.uid for user in users]))
print("users' names: {}".format([user.name for user in users]))

# If we have a user id, we can use `fetchUserInfo` to fetch a `User` object
user = client.fetchUserInfo("<user id>")["<user id>"]
# We can also query both mutiple users together, which returns list of `User` objects
users = client.fetchUserInfo("<1st user id>", "<2nd user id>", "<3rd user id>")

print("user's name: {}".format(user.name))
print("users' names: {}".format([users[k].name for k in users]))

# `searchForUsers` searches for the user and gives us a list of the results,
# and then we just take the first one, aka. the most likely one:
user = client.searchForUsers("<name of user>")[0]

print("user ID: {}".format(user.uid))
print("user's name: {}".format(user.name))
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
Example #13
0
class UnreadMessageFetcher():
    def __init__(self, username, password):
        self.__newUnreadMessageNb = 0  # Number of unread messages before the next graphic user interface actualusation.
        self.__unreadMessageDictionnaryList = []
        self.__threadList = []
        self.__unRodeThread = []

        self.__client = Client(username, password)
        self.__setThreadList()
        self.__setUnreadMessagesList()

    ##Public method to empty the list of notifications.
    #
    # arg: none
    #
    # return: none
    def EmptyLists(self):
        """
        To avoid to refill the list with already fetched notification, each conversation with at least one unread message is marked as read. To avoid to empty an already empty list,
        the size of the notification list must be superior to zero to empty the list.
        """
        if (len(self.__unreadMessageDictionnaryList) > 0):
            self.__unreadMessageDictionnaryList = []
            for i in range(len(self.__unRodeThread)):
                self.__client.markAsRead(self.__unRodeThread[i].uid)
            self.__threadList = []

    ##Private method to affect the list of the ten most recent messenger conversations of the user into the __threadlist attribute.
    #
    # arg: none
    #
    # return: none
    def __setThreadList(self):
        self.__threadList = self.__client.fetchThreadList(limit=10)

    ##Private method for setting the  __unreadMessageDictionnaryList attribute by storing the unread messages dictionnaries' into the list.
    #
    # arg: none
    #
    # return: none
    def __setUnreadMessagesList(self):
        i = 0
        isDictEmpty = False
        while ((i < 10) and (isDictEmpty == False)):
            dict = self.__getUnReadMessageDict(i)
            if ((dict != {})
                    and (not (dict in self.__unreadMessageDictionnaryList))):
                self.__unreadMessageDictionnaryList.append(dict)
                self.__newUnreadMessageNb += 1

                # ToDo check if the thread is already into the list before adding the thread into the list. For avoiding to mark as read a thread twice.
                self.__unRodeThread.append(self.__threadList[i])
                notifSoundThread = Thread(
                    target=PlayNotificationSound
                )  # For running the sound notification into a second thread who will run in a parallel of the main one.
                notifSoundThread.start()  # Starting the thread.
            else:
                isDictEmpty = True
            i += 1

    ##Private method to get the unread message dictionnary of the selected conversation.
    #
    # arg: threadIndex: the index of the conversation.
    #
    # return: unReadMessageDict: the unread message dictionnary of the selected conversation.
    def __getUnReadMessageDict(self, threadIndex):
        unreadMessageDict = {}

        fetchedMessage = self.__client.fetchThreadMessages(
            thread_id=self.__threadList[threadIndex].uid, limit=1)

        if (fetchedMessage[0].is_read == False):
            if (self.__threadList[threadIndex].type.name == "USER"):
                name = self.__threadList[threadIndex].name
            else:

                authorname = self.__getaUserName(
                    fetchedMessage[0].author
                )  # Get the name of the author of the last message in a group conversation with his user ID
                name = self.__threadList[
                    threadIndex].name + " (" + authorname + ")"  # Concatenate the author name in parenthesis with the name of the conversation
            message = fetchedMessage[0].text
            photo = self.__threadList[threadIndex].photo
            unreadMessageDict = {
                "name": name,
                "photo": photo,
                "message": message
            }

        return (unreadMessageDict)

    ##Public method to reset the unread message counter when emptying the notification list.
    #
    # arg: none
    #
    # return: none
    def resetNewUnreadMessageNb(self):
        self.__newUnreadMessageNb = 0

    ##Public method to update the __threadList and __unreadMessageLis attributes
    #
    # arg: none
    #
    # return: none
    def setLists(self):
        self.__setThreadList()
        self.__setUnreadMessagesList()

    ## Private method to get the name of the user who sent the message in a group conversation.
    # Messenger uses the real name of the other user in the name attribut of the dictionnary for
    # user to user conversation and group's name for group conversation. To specify who sent the
    # message, this method fetches the profile's informations of the user who sends the message
    # by using is facebook id (each message dictionnary returned by the client object by the
    # fbchat module contains the id of the user who sent the message) and extract his name to
    # return it to the __getUnReadMessageDict method.
    #
    # arg: userId: The Facebook user's id of the user who sent the message.
    #
    # return: name: The name of the user who sent the message.
    def __getaUserName(self, userId):

        userInfo = self.__client.fetchUserInfo(userId)

        name = userInfo.get(userId).name
        return (name)

    ##Public method to optain the size of the list
    # Usefull?
    # arg: none
    #
    # return: d: The size of the __unreadMessageDictionnaryList attribute.
    def getTotalUnreadMessageNumber(self):
        d = len(self.__unreadMessageDictionnaryList)
        return (d)

    ##Public method to get the number of new unread messages fetched during an iteration of
    # the __setUnReadMessageList method. #Usefull? Must see that at the last refactorings.
    #
    # arg: none
    #
    # return: __newUnReadMessageNb: The number of new unread messages fetched during an iteration of the
    # __setUnReadMessageList method.
    def getNewUnreadMessageNumber(self):
        return (self.__newUnreadMessageNb)

    ##Public method to return the message author's name into the interface.
    #
    # arg: dictIndex: the index of the selected message dict into the __unreadMessageDictionnaryList attribute.
    #
    # return: self.__unreadMessageDictionnaryList[dictIndex].get('name'): The message author's name.
    def getAuthorName(self, dictIndex):
        return (self.__unreadMessageDictionnaryList[dictIndex].get('name'))

    ##Public method to return the url of the message author's profile picture for loading it into the interface.
    #
    # arg: dictIndex: the index of the selected message dict into the __unreadMessageDictionnaryList attribute.
    #
    # return: self.__unreadMessageDictionnaryList[dictIndex].get('photo'): The url of the message author's profile picture.
    def getConversationPic(self, dictIndex):
        return (self.__unreadMessageDictionnaryList[dictIndex].get('photo'))

    ##Public method to return the message into the interface.
    #
    # arg: dictIndex: the index of the selected message dict into the __unreadMessageDictionnaryList attribute.
    #
    # return: self.__unreadMessageDictionnaryList[dictIndex].get('message'): The unread message.
    def getMessage(self, dictIndex):
        return (self.__unreadMessageDictionnaryList[dictIndex].get('message'))
Example #14
0
        Moves 1 month at a time to account for newly added users.
    '''
    current = int(time.time()) * 1000
    for i in range(9):
        updateActiveIds(current)
        current -= 2592000000 # go back a month

def idsToNames(idDict):
    '''
    Convert a dictionary of user information to a list of names
    '''
    nameList = []
    for id in idDict:
        user = idDict[id]
        nameList.append(user.name)
    nameList.sort()

    return nameList


if __name__ == '__main__':
    updateWithTimestamps()

    totalParticipants = set(client.fetchGroupInfo(gcID)[gcID].participants)
    inactiveIDs = client.fetchUserInfo(*totalParticipants.difference(activeIDs))

    nameList = idsToNames(inactiveIDs)
    print(len(nameList), "people have not checked the chat in the last 9 months")
    print(nameList)
    client.logout()
Example #15
0
# -*- coding: UTF-8 -*-

import os
import time
from dotenv import load_dotenv

load_dotenv()
from fbchat import Client
from fbchat.models import *

client = Client(os.getenv("FBEMAIL"), os.getenv("FBPASS"))
myuser = client.fetchUserInfo(client.uid)[client.uid]

# Fetches a list of all users you're currently chatting with, as `User` objects
users = client.fetchAllUsers()
users.append(myuser)
print(users)

print("users' IDs: {}".format([user.uid for user in users]))
print("users' names: {}".format([user.name for user in users]))

# If we have a user id, we can use `fetchUserInfo` to fetch a `User` object
#user = client.fetchUserInfo(users[0].uid)[users[0].uid]
# We can also query both mutiple users together, which returns list of `User` objects
#users = client.fetchUserInfo(users[0].uid, users[0].uid)

#print("user's name: {}".format(user.name))
#print("users' names: {}".format([users[k].name for k in users]))

# `searchForUsers` searches for the user and gives us a list of the results,
# and then we just take the first one, aka. the most likely one:
socket.setdefaulttimeout(60)
reload(sys)
sys.setdefaultencoding("utf-8")

ending = '</div></div>'

username = str(raw_input("Username: "******"Want to save your data as a .Zip file y/n?: "))

uid = client.uid
USER = client.fetchUserInfo(client.uid)[client.uid]
self = USER.name

ID = []
NAME = []

docs = ['docx', 'doc', 'pdf', 'pptx', 'txt', 'xlsx']
media = ['mp3', 'mp4', 'aac', 'webm', 'avi', '3gp']
gen = ['jpg', 'png']


def download_file(add, name):
    request = requests.get(add, timeout=60, stream=True)
    #Open the output file and make sure we write in binary mode
    flag = 0
    with open(name, 'wb') as fh:
Example #17
0
# client.reactToMessage(thread_id, MessageReaction.LOVE)

# ''' End Testing '''

message_id = client.send(Message(text='ligma'), thread_id='100012769301046', thread_type=ThreadType.USER)

# Fetches a list of all users you're currently chatting with, as `User` objects
users = client.fetchAllUsers()

print("users' IDs: {}".format([user.uid for user in users]))
print("users' names: {}".format([user.name for user in users]))


# If we have a user id, we can use `fetchUserInfo` to fetch a `User` object
user = client.fetchUserInfo('100006039725095')['100006039725095']
# We can also query both mutiple users together, which returns list of `User` objects
# users = client.fetchUserInfo('<1st user id>', '<2nd user id>', '<3rd user id>')

print("user's name: {}".format(user.name))
# print("users' names: {}".format([users[k].name for k in users]))


# `searchForUsers` searches for the user and gives us a list of the results,
# and then we just take the first one, aka. the most likely one:
user = client.searchForUsers('Sarah')[0]

print('user ID: {}'.format(user.uid))
print("user's name: {}".format(user.name))
print("user's photo: {}".format(user.photo))
print("Is user client's friend: {}".format(user.is_friend))
except:
	print('Cookies not found. Please enter credentials.')
	client = Client(input('Email: '), getpass('Password: '******'cookies.p','wb'))
	print('Cookies saved to cookies.p file.')


user = '******'
user_id = '' #Add User ID here


i = 0
while i < 1:
	localtime = time.asctime(time.localtime(time.time()))
	user = client.fetchUserInfo(user_id)[user_id]
	not_avail = "Time: " + localtime + " | " + "User" + " is not available.\n"
	avail = "Time: " + localtime + " | " + "User {}".format(user.name) + " is available.\n"

	if user.name == 'Facebook User':
		print(not_avail)
		f = open("report.txt", "a+")
		f.write(not_avail)
		f.close()
	else:
		print(avail)
		f = open("report.txt", "a+")
		f.write(avail)
		f.close()
		user = '******'
	time.sleep(50)
Example #19
0
from fbchat import Client
from Auth.credentials import user, password, person

client = Client(user, password)
if not client.isLoggedIn():
    client.login(user, password)
    print("Login successful...")

user = client.searchForUsers(person)[0]
userid = user.uid
thread_id = userid
messages = []

me = client.fetchThreadMessages(thread_id=thread_id, limit=500)
me.reverse()
print(len(me))
for m in me:
    u = client.fetchUserInfo(m.author)[m.author]
    print(u.name, m.text)

client.logout()
Example #20
0
from itertools import islice
from fbchat import Client
from fbchat.models import *
import time

client = Client("email", "password")
session_cookies = client.getSession()
client.getSession()

user = '******'

i = 0
while i < 1:
    localtime = time.asctime(time.localtime(time.time()))
    user = client.fetchUserInfo("user_id")["user_id"]
    not_avail = "Time: " + localtime + " | " + "User {}".format(
        user.name) + " is not available.\n"
    avail = "Time: " + localtime + " | " + "User {}".format(
        user.name) + " is available.\n"

    if user == '0':
        print(not_avail)
        f = open("report.txt", "a")
        f.write(not_avail)
        f.close()
    else:
        print(avail)
        f = open("report.txt", "a")
        f.write(avail)
        f.close()
        user = '******'
Example #21
0
# -*- coding: UTF-8 -*-

from fbchat import Client
from fbchat.models import *

client = Client('<email>', '<password>')

# Fetches a list of all users you're currently chatting with, as `User` objects
users = client.fetchAllUsers()

print("users' IDs: {}".format(user.uid for user in users))
print("users' names: {}".format(user.name for user in users))

# If we have a user id, we can use `getUserInfo` to fetch a `User` object
user = client.fetchUserInfo('<user id>')['<user id>']
# We can also query both mutiple users together, which returns list of `User` objects
users = client.fetchUserInfo('<1st user id>', '<2nd user id>', '<3rd user id>')

print("user's name: {}".format(user.name))
print("users' names: {}".format(users[k].name for k in users))

# `searchForUsers` searches for the user and gives us a list of the results,
# and then we just take the first one, aka. the most likely one:
user = client.searchForUsers('<name of user>')[0]

print('user ID: {}'.format(user.uid))
print("user's name: {}".format(user.name))
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
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
                d[user_name] = [0, 0, 0]
                author[int(uid)] = user_name
                print("Found user {}".format(user_name))
            time = int(i.timestamp)
            message = str(re.sub(r'[^\x00-\x7f]', r' ', str(i.text))).lower().split()
            if message:
                # print(message)
                for t in me_words:
                    d[author[int(uid)]][0] += message.count(t)
                for t in you_words:
                    d[author[int(uid)]][1] += message.count(t)
                d[author[int(uid)]][2] += 1
    print("Done with batch {}".format(count+1))

Example #23
0
    except FBchatException:
        print("Could not find a group with this ID...")
    # except:
    #   print("There has been an error collecting the group info...")
    else:
        print("\nGroup \"{}\" found!".format(inputGroup.name))
        if selectMode:
            confirmation = input("Select from users in this group? [Y/n] > ")
        else:
            confirmation = input(
                "Send messages to all other users in this group? [Y/n] > ")
        if confirmation.lower()[0] == 'y':
            break

inputParticipantDict = client.fetchUserInfo(*list(inputGroup.participants))
inputParticipants = inputParticipantDict.values()
myUserList = []

# sort the list randomly and store the head of the list
# each participant is assigned the next member of the list, and the last participant is assigned the first.
print("Host excluded: {}".format(
    client.fetchUserInfo(client.uid).get(client.uid).name))
print("\nTotal people in group: {} ".format(len(inputParticipants)))
count = 0
for user in inputParticipants:
    myUserList.append(MyUser(user, user.uid != client.uid))

# Allow the user to toggle participants
while True:
    for i in range(len(myUserList)):
Example #24
0
class MessengerAnalysis:
    def __init__(self, email, password):
        self.client = Client(email, password)
        self.all_words = {}
        self.all_emojis = {}
        self.all_reactions = {}
        self.users = {}
        self.words_by_users = {}
        self.emojis_by_users = {}
        self.reactions_by_users = {}
        self.longest_time = -sys.maxsize - 1
        self.messages = []
        self.words_to_skip = json.loads(
            open("settings.json").read())["words_to_skip"]
        self.punctuation_table = str.maketrans(
            {key: None
             for key in string.punctuation})

    def is_emoji(self, word):
        count = 0
        for emoji in UNICODE_EMOJI:
            count += word.count(emoji)
            if count > 1:
                return False
        return bool(count)

    def clean_up_words(self, words):
        cleaned_words = []
        for word in words:

            word = word.lower()
            word = word.translate(self.punctuation_table)

            if word in self.words_to_skip:
                continue

            cleaned_words.append(word)

        return cleaned_words

    def get_thread_list(self, limit=5):
        self.all_words = {}
        self.all_emojis = {}
        self.all_reactions = {}
        self.users = {}
        self.words_by_users = {}
        self.emojis_by_users = {}
        self.reactions_by_users = {}
        self.longest_time = -sys.maxsize - 1
        self.messages = []
        return self.client.fetchThreadList(limit=limit)

    def get_user_name(self, user_id):
        return self.client.fetchUserInfo(user_id)[user_id].name

    def get_thread_messages(self, thread_id, limit):
        return self.client.fetchThreadMessages(thread_id=thread_id,
                                               limit=limit)

    def get_messages_and_analyze(self, thread_id, limit=500):
        if self.messages:
            return

        self.messages = self.get_thread_messages(thread_id, limit)
        self.messages.reverse()
        last_message_time = None

        for message in self.messages:

            current_message_time = int(message.timestamp)
            if last_message_time != None:
                time_difference = current_message_time - last_message_time
                if time_difference > self.longest_time:
                    self.longest_time = time_difference
            last_message_time = current_message_time

            reactions = message.reactions
            if reactions:
                for id in reactions:
                    reaction = reactions[id]
                    if reaction not in self.all_reactions:
                        self.all_reactions[reaction] = 0
                    self.all_reactions[reaction] += 1

                    if id not in self.reactions_by_users:
                        self.reactions_by_users[id] = {}

                    user_dict = self.reactions_by_users[id]

                    if reaction not in user_dict:
                        user_dict[reaction] = 0
                    user_dict[reaction] += 1

            if not message.text:
                continue

            user_id = message.author

            if user_id not in self.users:
                self.users[user_id] = self.get_user_name(user_id)

            if user_id not in self.words_by_users:
                self.words_by_users[user_id] = {}

            if user_id not in self.emojis_by_users:
                self.emojis_by_users[user_id] = {}

            user_name = self.users[user_id]

            words = message.text.split()
            cleaned_words = self.clean_up_words(words)

            for word in cleaned_words:

                if not word:
                    continue

                if self.is_emoji(word):
                    if word not in self.all_emojis:
                        self.all_emojis[word] = 0
                    self.all_emojis[word] += 1

                    user_emojis_dict = self.emojis_by_users[user_id]
                    if word not in user_emojis_dict:
                        user_emojis_dict[word] = 0
                    user_emojis_dict[word] += 1

                    continue

                if word not in self.all_words:
                    self.all_words[word] = 0
                self.all_words[word] += 1

                user_words_dict = self.words_by_users[user_id]
                if word not in user_words_dict:
                    user_words_dict[word] = 0
                user_words_dict[word] += 1

        print('Analysis Complete!')

    def convert_millis_to_time(self):
        millis = self.longest_time
        seconds = (millis / 1000) % 60
        seconds = int(seconds)
        minutes = (millis / (1000 * 60)) % 60
        minutes = int(minutes)
        hours = (millis / (1000 * 60 * 60))
        print("%d:%d:%d" % (hours, minutes, seconds))

    def get_sorted_by_frequency(self, dict, reverse=True):
        return sorted(dict, key=dict.get, reverse=reverse)

    def print_words(self, words, dict, limit):
        index = 0
        for word in words:
            if index == limit:
                break

            index += 1
            print(word, end=': ')
            print(dict[word])

    def get_top_reactions(self, reverse=True):
        sorted_by_frequency = self.get_sorted_by_frequency(self.all_reactions,
                                                           reverse=reverse)
        for reaction in sorted_by_frequency:
            print(reaction.value, end=": ")
            print(self.all_reactions[reaction])

    def get_top_reactions_by_user(self, reverse=True):
        for user_id in self.reactions_by_users:
            reaction_dict = self.reactions_by_users[user_id]
            user_name = self.users[user_id]
            sorted_by_frequency = self.get_sorted_by_frequency(reaction_dict,
                                                               reverse=reverse)
            print(user_name)
            for reaction in sorted_by_frequency:
                print(reaction.value, end=": ")
                print(reaction_dict[reaction])

    def get_top_words(self, limit=10, reverse=True):
        sorted_by_frequency = self.get_sorted_by_frequency(self.all_words,
                                                           reverse=reverse)
        self.print_words(sorted_by_frequency, self.all_words, limit)

    def get_top_emojis(self, limit=10, reverse=True):
        sorted_by_frequency = self.get_sorted_by_frequency(self.all_emojis,
                                                           reverse=reverse)
        self.print_words(sorted_by_frequency, self.all_emojis, limit=limit)

    def get_top_words_by_user(self, limit=10, reverse=True):
        for user_id in self.users:
            user_words_dict = self.words_by_users[user_id]
            sorted_by_frequency = self.get_sorted_by_frequency(user_words_dict,
                                                               reverse=reverse)
            print(self.users[user_id] + ':')
            self.print_words(sorted_by_frequency, user_words_dict, limit)
            print('\n')

    def get_top_emojis_by_user(self, limit=5, reverse=True):
        for user_id in self.users:
            user_emojis_dict = self.emojis_by_users[user_id]
            sorted_by_frequency = self.get_sorted_by_frequency(
                user_emojis_dict, reverse=reverse)
            print(self.users[user_id] + ':')
            self.print_words(sorted_by_frequency, user_emojis_dict, limit)
            print('\n')