def download_pictures(user, password, thread_id, output_folder, msg_limit=100):
    if not isdir(output_folder):
        mkdir(output_folder)

    client = Client(user, password)

    if thread_id is None:
        thread = client.fetchThreadList()[0]
        msg_list = client.fetchThreadMessages(thread.uid, msg_limit)
    else:
        msg_list = client.fetchThreadMessages(thread_id=thread_id,
                                              limit=msg_limit)
    for msg in msg_list:
        for att in msg.attachments:
            att_valid = att.__class__.__name__ in "ImageAttachment, VideoAttachment".split(
                ", ")
            if not att_valid:
                continue
            url = client.fetchImageUrl(att.uid)
            data = http.request("GET", url=url, preload_content=False)
            data = data.read()
            try:
                ext = att.original_extension
            except AttributeError:
                ext = re.match(".+\.([a-z0-9]{3,4})\?.+", url)
                if ext is None:
                    ext = "unkown"
                else:
                    ext = ext.groups()[0]
            output_filename = join(output_folder, att.uid + "." + ext)
            print("Downloading %s" % output_filename)
            with open(output_filename, "wb") as f:
                f.write(data)
Exemplo n.º 2
0
 def get_all_threads(client: Client) -> dict:
     """ Returns a dictionary that maps the names of all threads associated with
     the imput client with their thread ids """
     threads = client.fetchThreadList()
     thread_dict = {}
     for thread in threads:
         thread_dict[thread.name] = str(thread.uid)
     return thread_dict
Exemplo n.º 3
0
 def name(self, uid):
     threads = Client.fetchThreadList()
     mes_thread = Client.fetchThreadMessages(uid, limit=1)
     for user in threads:
         if uid == user.uid:
             readable = time.ctime(int(user.last_message_timestamp[:10]))
             print(user.name, 'messaged at {}'.format(readable))
             for mes in mes_thread:
                 print(user.name, 'said {}'.format(mes.text))
Exemplo n.º 4
0
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)
Exemplo n.º 5
0
def messenger():
    client = Client('*****@*****.**', 'Fjohnkim0414')
    threads = client.fetchThreadList(limit=5)
    print("Threads: {}".format(threads))

    thread_id = choose_messenger_receiver(threads)
    thread_type = ThreadType.GROUP

    for file_name in os.listdir('./imgs'):
        client.sendLocalImage('./imgs/' + file_name,
                              thread_id=thread_id,
                              thread_type=thread_type)
        time.sleep(3)
Exemplo n.º 6
0
class Facebook:
	def __init__(self, email, password):
		self.user = Client(email, password)
		self.name = self.user.name
		self.id = self.user.uid

	def sendMessage(self, recipient, message, threadType = ThreadType.GROUP):
		self.user.send(Message(text=message, thread_id=self.getThreadID(recipient), thread_type=threadType))

	def getChats(self, n = 20):
		threads = self.user.fetchThreadList()
		threads += client.fetchThreadList(offset=n, limit=10)
		print("Threads: {}".format(threads))

	
	def logout(self):
		self.user.logout()
Exemplo n.º 7
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
Exemplo n.º 8
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]))
Exemplo n.º 9
0
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
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)

# Here should be an example of `getUnread`
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)
Exemplo n.º 11
0
        raise Exception(
            "The path specified in download_path does not exist ({path}). Please specify a valid path in "
            "config.ini".format(path=download_path))

    # Initialize FB Client
    fb_email = config.get('Credentials', 'email')
    fb_pw = config.get('Credentials', 'password')
    fb_client = Client(fb_email, fb_pw)

    # Search for latest threads
    thread_search_limit = int(config.get('Threads', 'search_limit'))
    thread_search_before = convert_date_to_epoch(
        config.get('Threads', 'before_date'))

    if thread_search_before is not None:
        threads = fb_client.fetchThreadList(limit=thread_search_limit,
                                            before=thread_search_before)
    else:
        threads = fb_client.fetchThreadList(limit=thread_search_limit)

    # Find correct thread for given user URL
    my_thread = None
    friend_url = config.get('Friend', 'url')
    for thread in threads:
        if thread.url == friend_url:
            my_thread = thread
            break

    # Get Messages for my_thread
    if my_thread is not None:
        thread_message_count = my_thread.message_count
        thread_message_name = my_thread.name
Exemplo n.º 12
0
email = str(input('Enter email: '))
pswd = getpass('Enter password: '******'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):
from fbchat import Client
from fbchat.models import *
from random import randint
import os
import time
import datetime

fb_login = os.environ("fb_login")
fb_passwd = os.environ("fb_passwd")

while True:
    client = Client(fb_login, fb_passwd)

    users = client.searchForUsers("mark zuckerberg")
    threads = client.fetchThreadList(limit=10)

    now = datetime.datetime.now()
    if (now.hour > 1) or (now.hour < 7):
        sleep_time = randint(40, 120) * 60
    else:
        sleep_time = randint(5, 10) * 60

    print("Sleeping " + str(sleep_time))
    time.sleep(sleep_time)
Exemplo n.º 14
0
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.options import Options

import time
from fbchat import Client, log
from fbchat.models import *
options = webdriver.ChromeOptions()
#options.add_argument('headless')
driver = webdriver.Chrome(ChromeDriverManager().install())
#driver = webdriver.Chrome(options=options)

client = Client("username", "password")
users = client.fetchAllUsers()
threads = client.fetchThreadList()

driver.get(
    "https://www.kv.ee/?act=search.simple&last_deal_type=1&orderby=cdwl&deal_type=1&search_type=old"
)
kirjeldus = ""
i = 0
while (i != 30):
    print(i)
    i += 1
    time.sleep(1)
    if (i == 29):
        driver.refresh()
        refreshedKirjeldus = driver.find_element_by_xpath(
            "/html/body/div[2]/div/div[2]/div[2]/table/tbody/tr[1]/td[2]/h2/a"
        ).text
        if (kirjeldus != refreshedKirjeldus):
Exemplo n.º 15
0
from fbchat import Client
from fbchat.models import *

client = Client('*****@*****.**', 'utBw735x4%@R')
threads = client.fetchThreadList()
while True:

    for thread in threads:
        print("Thread: {}".format(thread))
        client.send(Message(text="Merry Christmas!"),
                    thread_id=thread.uid,
                    thread_type=thread.type)
    lastTimeStamp = int(threads[-1].last_message_timestamp)
    threads = client.fetchThreadList(before=lastTimeStamp - 1)
Exemplo n.º 16
0
if username.lower() == 'y':
    names = str(
        raw_input(
            "Name of that friends separated by a comma like - satyendra pandey, Narendra pandey--: "
        ))
    names = names.split(',')
    for name in names:
        thread = client.searchForThreads(name)[0]
        do_rest(thread, client)
    if zipping.lower() == 'y':
        make_zip()

else:
    num = int(raw_input("Number of friends from top of your chatlist:"))
    if num < 20:
        threads = client.fetchThreadList(limit=num)

    else:
        threads = client.fetchThreadList(limit=20)
        num = (num - 20) / 20

        for i in range(num):
            offset = 20 * (i + 1)
            threads += client.fetchThreadList(offset=offset, limit=20)

    for thread in threads:
        do_rest(thread, client)
    if zipping.lower() == 'y':
        make_zip()
Exemplo n.º 17
0
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!')
Exemplo n.º 18
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')
Exemplo n.º 19
0
from fbchat import Client
from fbchat.models import *
import openpyxl
import json
wb = openpyxl.Workbook() 
wb.create_sheet('FB-Messages')
sheet=wb['FB-Messages']
client = Client("*****@*****.**", "^&Tytan76")
print("Own id: {}".format(client.uid))
# Fetches a list of the 20 top threads you're currently chatting with
threads = client.fetchThreadList() 
# Fetches the next 20 threads
threads += client.fetchThreadList(limit=20)
threads += client.fetchThreadList(limit=20)
threads += client.fetchThreadList(limit=20)
threads += client.fetchThreadList(limit=20)
#this is last 100 threads for each will retrieve last 20 messages
for t in range(0,len(threads)): 
    thread_name=threads[t].__dict__['name']
    thread_id=threads[t].__dict__['uid']
    wb.create_sheet(thread_id)
    sheet=wb[thread_id]
    messages = client.fetchThreadMessages(thread_id=thread_id, limit=20)
    sheet['A1']= "Index"
    sheet['B1']= "Text"
    sheet['C1']= "Mentions"
    sheet['D1']= "Emoji_size"
    sheet['E1']= "Uid.mid"
    sheet['D1']= "Author"
    sheet['E1']= "Timestamp"
    sheet['F1']= "Is Read"
# -*- coding: utf-8 -*-
from fbchat import Client
from fbchat.models import *
from getpass import getpass

usuario = input("Dame tu correo: ")
cliente = Client(usuario,getpass())

amigos = cliente.fetchThreadList()
nAmigo=0
for amigo in amigos:
	print(nAmigo+1,". "+amigo.name)
	nAmigo+=1

idAmigo=int(input("Ingresa el id del amigo o grupo: "))
mensaje=input("Ingresa tu mensaje:")
cliente.sendMessage(mensaje, thread_id=amigos[idAmigo].uid, thread_type=ThreadType.USER)


thread_type=ThreadType.GROUP
thread_id='1473908892667021'
# mandar un emoji '👍'
cliente.sendEmoji(emoji='👍', size=EmojiSize.LARGE, thread_id=thread_id, thread_type=thread_type)

# Will send the default 'like' emoji
cliente.sendEmoji(emoji=None, size=EmojiSize.LARGE, thread_id=thread_id, thread_type=thread_type)

# Will send the emoji '😏'
cliente.sendEmoji(emoji='😏 ', size=EmojiSize.LARGE, thread_id=thread_id, thread_type=thread_type)
cliente.sendEmoji(emoji='😏 ', size=EmojiSize.MEDIUM, thread_id=thread_id, thread_type=thread_type)
cliente.sendEmoji(emoji='😏 ', size=EmojiSize.SMALL, thread_id=thread_id, thread_type=thread_type)
Exemplo n.º 21
0
from fbchat import Client
from fbchat.models import *

username = input("Facebook user ID or e-mail:")
password = input("Enter in you Facebook Password:")
# login

client = Client(username, password)
users = list(client.fetchThreadList())

u = client.searchForUsers('lptcdojo')

print(u)

#for i in range(0,len(users)):
# if users[i].name =='Lorcan Mac Hugh':

# client.send(Message(text='This a test from my Facbook Bot'), thread_id=users[i].uid, thread_type=ThreadType.USER)

client.logout()
Exemplo n.º 22
0
class fbMessenger:
    def __init__(self, username, password):
        self.client = Client(username, password)  # facebook login

    def print(self, thread, index):
        print("{}.".format(index))
        print("thread name: {}".format(thread.name))
        print("type: {}".format("Group" if thread.is_group else "Single user"))
        print("msg count: {}".format(thread.msg_count))
        print("day count: {}".format(thread.day_count))
        print("file count: {}".format(thread.file_count))
        print("image count: {}".format(thread.image_count))
        print("first talk: {}".format(thread.first_talk))
        print("last talk: {}".format(thread.last_talk))
        print("last msg :'{}'\n".format(thread.last_msg))

    def get_messages(self):
        from_time = datetime.now() - timedelta(
            days=30)  # msg records in previous 30 days
        threads = self.client.fetchThreadList(
            limit=20)  # find 30 candidate contacts
        contact_list = []
        index = 1

        print("second try")
        for thread in threads:
            msgs = self.client.fetchThreadMessages(thread_id=str(thread.uid),
                                                   limit=500)
            if thread.type == ThreadType.USER:

                thread_info = ThreadInfo()
                thread_info.name = thread.name
                thread_info.is_group = False if thread.type == ThreadType.USER else True
                thread_info.last_talk = datetime.fromtimestamp(
                    int(msgs[0].timestamp) / 1000)
                thread_info.last_msg = msgs[0].text
                tem_day = None

                for msg in msgs:
                    msg_time = datetime.fromtimestamp(
                        int(msg.timestamp) / 1000)
                    if from_time < msg_time:
                        thread_info.msg_count += 1 if msg.text is not None else 0  # msg count
                        thread_info.first_talk = datetime.fromtimestamp(
                            int(msg.timestamp) / 1000)  # first talk
                        for atch in msg.attachments:  # file count & image count
                            if isinstance(atch, FileAttachment):
                                thread_info.file_count += 1
                            elif isinstance(atch, ImageAttachment):
                                thread_info.image_count += 1
                        if msg_time.day != tem_day:  # dat count
                            thread_info.day_count += 1
                            tem_day = msg_time.day

                if thread_info.msg_count == 0:
                    continue
                else:
                    contact_list.append(thread_info)
                    self.print(thread=thread_info, index=index)
                if index == 15:  #################### number of candidate contacts #####################
                    break
                else:
                    index += 1

        return contact_list
Exemplo n.º 23
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'))