コード例 #1
0
ファイル: login.py プロジェクト: Hasnep/fbmcli
def login(_config=config):
    try:
        with open(_config["cookies_path"],
                  "rb") as handle:  # read the cookies file
            session_cookies = pickle.load(handle)
    except FileNotFoundError:
        print("No cookies file found, logging in with username and password.")
        try:
            client = fb.Client(_config["username"],
                               _config["password"])  # log in using cookies
        except ConnectionError:
            print("Could not log in using username/password.")
            return None
    else:
        try:
            client = fb.Client(
                _config["username"],
                _config["password"],
                session_cookies=session_cookies)  # log in using cookies
        except (ConnectionError, fb.models.FBchatUserError):
            print("Could not log in using cookies or username and password.")
            return None

    session_cookies = client.getSession()  # put cookies in a variable
    with open(_config["cookies_path"],
              "wb") as handle:  # save the cookies to a file
        pickle.dump(session_cookies, handle)
    return client
コード例 #2
0
def login():
    cookies = None
    if os.path.isfile(user_file) and os.path.isfile(cookies_file):
        with open(user_file, 'r') as user_f:
            name = user_f.read().rstrip('\n').rstrip('\r')
            print('Found login info for {}. Is this you? (y/n): '.format(name), end='')
            try:
                option = sys.stdin.readline()[0]
                if (option == 'y'):
                    with open(cookies_file, 'r') as cookie_f:
                        cookies = json.load(cookie_f)
                        client = fbchat.Client(None, None, max_tries=3, session_cookies=cookies)
            except KeyboardInterrupt:
                exit()
            except:
                print('Unexpected exception: {}'.format(sys.exc_info()))

    # Prompt user for login information if didn't load cookies
    if cookies == None:
        while(True):
            print('Enter your email: ', end='')
            email = sys.stdin.readline().rstrip('\n')
            print('Enter your password: '******'')
            password = sys.stdin.readline().rstrip('\n')

            try:
                client = fbchat.Client(email, password, max_tries=3)
                # Save user information
                writeMetadata(client)
                break
            except FBchatUserError:
                print('Login error: {}'.format(sys.exc_info()))

    return client
コード例 #3
0
    def _get_client(self, auth):
        """
        Returns fb client oject for the user associated with this token.

        auth must be a string of the format fb_username:fb_password
        """

        # Check if cached copy exists
        cached = self._client_store.get(auth)
        if cached is not None:
            return cached

        # Get creds from auth token 
        split = auth.partition(':')
        if split[1] != ':':
            # auth didn't contain a ':', format was unexpected
            raise ValueError("Invalid Facebook auth token: {}".format(auth))
        username = split[0]
        password = split[2]

        try:
            client = fbchat.Client(username, password)
        except FBChatUserError as e:
            raise AuthenticationError(e)

        self._clients.set(auth, client)
        return client
コード例 #4
0
ファイル: Shenanigans.py プロジェクト: Joe1best/StupidProject
def login_fb():
    global client
    #User gives their name
    username = str(input("Username: "))
    
    #Script asks for password
    client = fbchat.Client(username,getpass())
コード例 #5
0
 async def load_session(self,
                        _override: bool = False,
                        _raise_errors: bool = False) -> bool:
     if self._is_logged_in and not _override:
         return True
     elif not self._session_data:
         return False
     try:
         session = await fbchat.Session.from_cookies(
             self._session_data,
             user_agent=self.user_agent,
             domain=self.fb_domain)
         logged_in = await session.is_logged_in()
     except ProxyError:
         self.log.exception("ProxyError while trying to restore session, "
                            "retrying in 10 seconds")
         await asyncio.sleep(10)
         return await self.load_session(_override, _raise_errors)
     except Exception:
         self.log.exception("Failed to restore session")
         if _raise_errors:
             raise
         return False
     if logged_in:
         self.log.info("Loaded session successfully")
         self.session = session
         self.client = fbchat.Client(session=self.session)
         METRIC_LOGGED_IN.labels(fbid=self.fbid).state("true")
         self._is_logged_in = True
         self.is_connected = None
         self.stop_listening()
         self.start_listen()
         asyncio.ensure_future(self.post_login(), loop=self.loop)
         return True
     return False
コード例 #6
0
 async def load_session(self,
                        _override: bool = False,
                        _raise_errors: bool = False) -> bool:
     if self._is_logged_in and not _override:
         return True
     elif not self._session_data:
         return False
     try:
         session = await fbchat.Session.from_cookies(self._session_data)
         logged_in = await session.is_logged_in()
     except Exception:
         self.log.exception("Failed to restore session")
         if _raise_errors:
             raise
         return False
     if logged_in:
         self.log.info("Loaded session successfully")
         self.session = session
         self.client = fbchat.Client(session=self.session)
         self._is_logged_in = True
         self.is_connected = None
         if self.listen_task:
             self.listen_task.cancel()
         self.listen_task = self.loop.create_task(self.try_listen())
         asyncio.ensure_future(self.post_login(), loop=self.loop)
         return True
     return False
コード例 #7
0
def sendWithFacebookMessenger(email_address, password, receiver_id, message, image_path, debug=True):
  """Send message and or image via Facebook Messenger

    Keyword arguments:
      email_address -- (string) Facebook email address
      password -- (string) Facebook password
      receiver_id -- (string) ID of the user receiving the file
      message -- (string) Message to send
      image_path -- (string) Path of the file to send
      debug -- (bool, optional) Show debug information

  return: (bool) Image and or message sent
  """
  return_value = False

  # Initialize the dropbox connection
  client = fbchat.Client(email_address, password)

  if message != "" and image_path == "":
    try:
      client.sendMessage(message, thread_id=receiver_id, thread_type=ThreadType.USER)
      return_value = True
    # TODO: Be more precise in exceptions (but a lot of exceptions can occure with client.send)
    except Exception:
      pass
  elif image_path != "":
    try:
      client.sendLocalImage(image_path, message=message, thread_id=receiver_id, thread_type=ThreadType.USER)
      return_value = True
    # TODO: Be more precise in exceptions (but a lot of exceptions can occure with client.send)
    except Exception:
      pass

  return return_value
コード例 #8
0
ファイル: textsender.py プロジェクト: dmgoodman/TextSender
def send(message):
    client = fbchat.Client(SENDER_EMAIL, SENDER_PASSWORD)
    sent = client.sendMessage(message, thread_id=RECEIVER)
    if sent:
        print("Message sent successfully!")
    else:
        print("Oh my lord, something went wrong.")
コード例 #9
0
def main():
    # Need to export facebook ID and password as envinronment variables
    # Find facebook ID here: http://findmyfbid.com/
    client = fbchat.Client(os.environ['ID'], os.environ['PASSWORD'])

    friendsFile = open("friends.txt", "r")
    # average response times
    timesAtoB = {}
    timesBtoA = {}
    for line in friendsFile:
        split = line.split(" ")
        friendName = split[0] + " " + split[1]
        (userAtimes, userBtimes) = computeResponse(friendName, client)
        print("\n" + friendName)
        print(userAtimes)
        print(userBtimes)
        if len(userAtimes) > 50:  # make sure that there's enough data
            timesAtoB[friendName] = sum(userAtimes) / len(userAtimes)
            print(timesAtoB[friendName])
        if len(userBtimes) > 50:
            timesBtoA[friendName] = sum(userBtimes) / len(userBtimes)
            print(timesBtoA[friendName])

    sortedAtoB = sorted(timesAtoB.items(), key=operator.itemgetter(1))
    sortedBtoA = sorted(timesBtoA.items(), key=operator.itemgetter(1))

    numRank = 10  # number of friends to display
    print("Top " + str(numRank) + " fastest responding friends: ")
    for i in range(0, numRank):
        print(str(i + 1) + ") " + sortedBtoA[i][0])
    print("")
    print("Top 5 friends you respond to fastest: ")
    for i in range(0, numRank):
        print(str(i + 1) + ") " + sortedAtoB[i][0])
コード例 #10
0
def main():
	# Need to export facebook ID and password 
	# Find facebook ID here: http://findmyfbid.com/
	client = fbchat.Client(os.environ['ID'], os.environ['PASSWORD'])
	friendName = input("Friend's name: ")
	(userAtimes, userBtimes) = computeResponse(friendName, client)
	summarizeResults(userAtimes, userBtimes, friendName)
コード例 #11
0
def sendFriends(senderId):
    username = senderId
    username = username.replace("_", ".")
    userInfo = FirebaseFunctions.getFirebaseInfo(senderId)
    userEncryptedPassword = userInfo["encryptedPassword"]
    userTagPassword = userInfo["tag"]
    userNonce = userInfo["nonce"]

    userdatadict = {
        "Pass": userEncryptedPassword,
        "Key": systemKey,
        "Tag": userTagPassword,
        "Nonce": userNonce
    }
    #desenctipta contraseña
    userDectyptedPassword = UserPasswordDecrypt(userdatadict)
    client = fbchat.Client(username, userDectyptedPassword)
    friends = client.fetchAllUsers()

    jsonArray = []

    print(type(friends))
    print(friends)
    for user in friends:
        jsonUser = {}
        jsonUser[str(user.name)] = str(user.uid)
        jsonArray.append(jsonUser)
    return jsonArray
コード例 #12
0
ファイル: user.py プロジェクト: PastuDan/mautrix-facebook
 async def on_logged_in(self, session: fbchat.Session) -> None:
     self.session = session
     self.client = fbchat.Client(session=session)
     self.save()
     self.stop_listening()
     self.start_listen()
     asyncio.ensure_future(self.post_login(), loop=self.loop)
コード例 #13
0
def send_message(target_list, message):
    """
    @param target: list of friend_uids to send messages to
    """
    client = fbchat.Client(MY_UID, MY_PASSWORD)
    for target in target_list:
        client.send(target, message)
コード例 #14
0
def send_update(body):
    """
    Send message to self from FaceBook Bot
    :param body: text to be send
    :return: send notification to FB Messenger
    """
    # Logging into Bot
    cookies = {}
    try:
        client = fbchat.Client(email=os.getenv("FB_USERNAME"),
                               password=os.getenv("FB_PASSWORD"),
                               session_cookies=cookies)
        datetime = get_current_timestep()
        text = datetime['full'] + '\t\n\n'
        text += body

        # Personal FB UID (Sawyer Ruben)
        UID = int(os.getenv("FB_UID"))
        with open('session.json', 'w') as f:
            json.dump(client.getSession(), f)
        client.send(fbchat.Message(text=text),
                    thread_id=UID,
                    thread_type=fbchat.ThreadType.USER)
        client.logout()

    except:
        account_sid = os.getenv('TWILIO_ACC_SID')
        auth_token = os.getenv('TWILIO_AUTH_TOKEN')
        client = twilio.Client(account_sid, auth_token)

        message = client.messages.create(
            body="ERROR logging into Albert Facebook",
            from_='+12092314126',
            to=os.getenv('PHONE'))
コード例 #15
0
ファイル: core1.py プロジェクト: Skcheun2/Course-Snagger
def sendFBmessage(message):
    
    client = fbchat.Client(details['fbuser'],details['fbpass'])
    friends = client.getUsers(details['name'])
    sent = client.send(friend.uid, message)
    if sent:
        print("Message sent successfully!")
コード例 #16
0
ファイル: fb.py プロジェクト: lucas999A/bee
def main():
    client = fbchat.Client(input('Username: '******'Do you want to spam a user or a groupchat? ').lower()

    while user_choice not in ['user', 'groupchat']:
        user_choice = input(
            'Please enter valid answer (user/groupchat)').lower()

    if user_choice == 'user':
        friends = client.searchForUsers(input('Who do you want to spam? '))
        thread_id = friends[0].uid
        thread_type = ThreadType.USER
    else:
        groups = client.searchForGroups(
            input('Which group do you want to spam? '))
        thread_id = groups[0].uid
        thread_type = ThreadType.GROUP

    delay = float(input('Delay between each message: '))
    script = open('no_line_script.txt')
    delay = float(input('Delay between each message: '))
    for i in range(count_lines()):
        line = script.readline().rstrip('\n').split(" ")
        for word in line:
            try:
                client.send(Message(text=word),
                            thread_id=thread_id,
                            thread_type=thread_type)
                print(f'Sending the word {word}')
                time.sleep(delay)
            except:
                print("Sorry, we've reached Facebook's spam limit.")
    script.close()
    client.logout()
コード例 #17
0
    def __init__(self, *args):
        super(QtGui.QWidget, self).__init__()
        self.setStyleSheet('font-size: 20pt')
        self.loadtensorflow()
        self.loadanswer()
        self.fps = 24
        self.counter = 15
        self.righttime_ans = np.zeros(10)
        self.detect_postion = np.zeros((3, 4))
        #self.pout = [0, 0, 0]
        self.seq = np.zeros(200000)
        self.nonnum = 0
        self.alp = [['a', 'b', 'c', 'd', 'e', 'f'], [0, 0, 0, 0, 0, 0]]
        #self.pri = []
        self.client = fbchat.Client("scure.le.1", sys.argv[1])
        self.fbstate = 1
        self.ofl, self.friendlist = self.buildfriendlist()
        self.chofid = 0
        self.chof = 'non'
        self.tbcounter = 21
        self.talkdelay = 0
        self.hmmmodel = self.loadhmmmodel()
        self.hmmpro = []
        self.cap = cv2.VideoCapture(0)
        self.cap.set(cv2.cv.CV_CAP_PROP_FRAME_WIDTH, 1000)
        self.cap.set(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT, 600)

        laysoc = QVBoxLayout()
        self.fblabel = QLabel()
        self.social = QLabel()
        fbimg = QPixmap('facebook-header.png')
        fbimg = fbimg.scaled(600, 100)
        self.fblabel.setPixmap(fbimg)
        laysoc.addWidget(self.fblabel)
        laysoc.addWidget(self.social)
        laysoc.setAlignment(QtCore.Qt.AlignTop)

        self.video_frame = QtGui.QLabel()
        #self.detect_frame = QtGui.QLabel()
        lay0 = QtGui.QHBoxLayout()
        lay0.setMargin(10)
        lay0.addWidget(self.video_frame)
        #lay0.addWidget(self.detect_frame)
        lay0.addLayout(laysoc)

        self.word = QLabel()
        self.word.setText("CNN Detect Sign Pose: ")
        self.bu = QLabel()
        #self.bu.setText("Ready to estimation...")

        buf = QtGui.QHBoxLayout()
        buf.addWidget(self.word)
        buf.addWidget(self.bu)

        lay = QVBoxLayout()
        lay.addLayout(lay0)
        lay.addLayout(buf)

        self.setLayout(lay)
コード例 #18
0
def send_fbchat(errors):
    user = get_config('FBUser')
    passwd = get_config('FBPassword')
    client = fbchat.Client(user, passwd)
    return client.send(
        fbchat.Message(text="EthosOS Alert: %d issues - Details: %s" %
                       (len(errors), json.dumps(errors))),
        thread_id=client.uid)
コード例 #19
0
def main(user, password, my_id, file_path, small_value, big_value):
    users_map = open_file(file_path)

    uag = fbchat._util.USER_AGENTS[0] # choose deterministic to prevent alerts from FB
    client = fbchat.Client(email=user, password=password, user_agent=uag)

    send_message(client, users_map, big_value, my_id)
    send_message(client, users_map, small_value, my_id)
コード例 #20
0
 async def on_logged_in(self, session: fbchat.Session) -> None:
     self.session = session
     self.client = fbchat.Client(session=session)
     self.save()
     if self.listen_task:
         self.listen_task.cancel()
     self.listen_task = self.loop.create_task(self.try_listen())
     asyncio.ensure_future(self.post_login(), loop=self.loop)
コード例 #21
0
 def restore_session(self, session):
     try:
         log("fbchat: restoreSession(...)")
         self.client = fbchat.Client(None,
                                     None,
                                     session_cookies=json.loads(session))
     except (FBchatException, json.JSONDecodeError):
         raise LoginRequiredError
コード例 #22
0
def connectToFacebook(username, password, name, msg):
    #code modified from https://www.geeksforgeeks.org/send-message-to-fb-friend-using-python/
    #with help of https://fbchat.readthedocs.io/en/master/examples.html
    client = fbchat.Client(username, password)
    friends = client.searchForUsers(name)  # return a list of names
    friend = friends[0]
    client.send(fbMessage(text=msg),
                thread_id=friend.uid,
                thread_type=ThreadType.USER)
コード例 #23
0
ファイル: fbbot.py プロジェクト: alui11/wolfratbot
 def login(self):
     fail_count = 0
     self.client = None
     while fail_count < MAX_ATTEMPTS and self.client == None:
         try:
             self.client = fbchat.Client(self.user, self.passw)
         except:
             self.client = None
             fail_count = fail_count + 1
コード例 #24
0
def get_user_info_and_login():
    try:
        username = input('Username: '******'Login sucessful ')
    except:
        print('Login unsucessful, please try again. ')
        get_user_info_and_login()
    return client
コード例 #25
0
ファイル: face.py プロジェクト: ficho2/Njuskalo-Notificator
def sendMail(msg,fdata):
    import fbchat
    try:
        client = fbchat.Client(fdata[0], fdata[1])

        friends = client.getUsers(fdata[2])  # return a list of names
        friend = friends[0]
        sent = client.send(friend.uid, msg)
    except:
        pass
コード例 #26
0
def wyslij_facebook(receiver_ids, message_content, credentials):
    client = fbchat.Client(credentials.fbuser, credentials.fbpass)
    #friends = client.searchForUsers(name)  # return a list of names
    #friend = friends[0]
    for id in receiver_ids:
        print(id.split(':')[0])
        sent = client.sendMessage(message_content, thread_id=id.split(':')[0])
        if sent:
            print("Message sent successfully!")
        time.sleep(2)
コード例 #27
0
ファイル: chat.py プロジェクト: bridger-herman/projects
def get_client():
    user, password = None, None
    try:
        with open("./.pass_cache") as fin:
            user = fin.readline()
            password = fin.readline()
    except FileNotFoundError:
        user = input("Username: ")
        password = getpass.getpass()
    return fbchat.Client(user, password)
コード例 #28
0
ファイル: chatbot.py プロジェクト: saviaga/chat-bots-manager
	def __init__(self, filename):
		config = ConfigParser.ConfigParser()
		config.read(filename)
		self.LOGIN_USER_VALUE = config.get('credentials', 'login_user_value')
		self.LOGIN_PASS_VALUE = config.get('credentials', 'login_pass_value')
		self.client = fbchat.Client(self.LOGIN_USER_VALUE, self.LOGIN_PASS_VALUE)
		self.driver = webdriver.Firefox()
		# self.driver = webdriver.PhantomJS()
		# self.driver = webdriver.Chrome('./chromedriver')
		self.driver.set_page_load_timeout(self.TIMEOUT)
コード例 #29
0
def create_client():
    try:
        client = fbchat.Client(email=email, password=password, max_tries=1)
        global SESSION_COOKIES
        SESSION_COOKIES = client.getSession()
        client.setSession(SESSION_COOKIES)
        return client
    except fbchat.FBchatException as e:
        print('Could not login...\n{}'.format(e))
    sys.exit(0)
コード例 #30
0
def login_facebook_sender(db_name, table_name):
    con = lite.connect(db_name)
    with con:
        cur = con.cursor()
        cur.execute("SELECT * FROM " + table_name)
        rows = cur.fetchone()
        client = fbchat.Client(rows[1], rows[2])
    con.close()

    return client