Python fbchat庫

像 Python 這樣的編程語言之所以強大,是因為它為用戶提供了廣泛的模塊和庫。這次我們將探索其中的一個。可能會有這樣或那樣的時候,我們每個人都希望收到我們的臉書朋友發來的信息(或垃圾郵件)。能夠在臉書信使中自動化活動並製作支持機器人似乎很有趣。在下面的教程中,我們將了解如何使用 Python 編程語言在臉書信使中進行連接,並執行各種令人驚嘆的事情。

這一聲明暗示我們將執行相同的獲取/發布請求,並欺騙臉書認為它正在正常訪問網站。我們將需要一個名為 fbchat 的 Python 庫,它允許程序員為這個操作模擬瀏覽器。所以這個 API(API)不是官方的,不需要任何 API 密鑰。但是,它需要臉書帳戶的憑據。

那麼,讓我們開始吧。

Python fbchat庫簡介

Python 編程語言中的 fbchat 庫利用電子郵件標識和密碼與臉書服務器通信。這種說法意味着,如果有人在編寫代碼時偷偷進入密碼,我們應該始終將密碼存儲在單獨的文件中。我們還應該確保文件的訪問控制受到適當的限制。

為了安裝 fbchat 庫,我們將使用 pip 安裝程序執行如下所示的命令:

語法:


$ pip3 install fbchat

為了驗證庫安裝是否正確,我們可以創建一個新文件,並添加 import 語句,看看它是否返回任何錯誤。

文件:驗證. py


import fbchat

現在,保存 Python 文件,並使用命令提示符運行執行命令:

語法:


$ python verify.py

如果上面的 Python 文件沒有引起任何導入錯誤,我們就可以進入臉書信使機器人構建程序了。但是,如果它確實引發了異常,建議重新安裝庫並參考其官方文檔。

現在,讓我們了解一下 fbchat 庫的基礎知識。

登錄

我們可以簡單地創建一個 fbchat 庫的客戶端類的實例。如果我們啟用了雙因素身份驗證,我們需要在終端提示中鍵入代碼(如果我們想以另一種方式提供代碼,我們可以覆蓋客戶端。2FACode 功能。

現在讓我們在下面的語法中看到相同的內容:

示例:


# importing the required modules
from fbchat import Client
from fbchat.models import *

# input username and password of the Facebook account
username = "example@website.com"
password = "password2email"

# creating an object of the Client class
clientObj = Client(username, password)

說明:

在上面的代碼片段中,我們從 fbchat 庫中導入了客戶端類以及 fbchat.models 中的函數。我們已經定義了臉書賬戶的用戶名和密碼。最後,我們創建了一個客戶端類的對象,指定用戶名和密碼作為其參數,允許我們訪問臉書帳戶。

以上提供的用戶名和密碼僅演示了客戶端類的工作情況,並未達到真正的目的。但是,需要分別用實際的電子郵件標識和密碼替換變量字符串。

不正確的用戶名和密碼可能會導致連接到臉書帳戶時出現異常。

在整個代碼中,如果我們想檢查我們是否仍然登錄,我們可以使用客戶端類的 isLoggedIn() 功能。

我們可以使用客戶端類的登錄()功能登錄臉書賬戶。

讓我們考慮下面的例子,如果註銷,我們希望再次登錄。

示例:


# importing the required modules
from fbchat import Client
from fbchat.models import *

# input username and password of the Facebook account
username = "example@website.com"
password = "password2email"

# creating an object of the Client class
clientObj = Client(username, password)

# checking if we are logged in or not
if not clientObj.isLoggedIn():
    # logging in using the login() function
    clientObj.login(username, password)

說明:

在上面的代碼片段中,我們使用了 if 語句來檢查我們是否使用了 isLoggedIn() 功能登錄了臉書帳戶。我們還使用了登錄()功能,指定用戶名和密碼如果我們註銷了,可以再次登錄。

一旦我們使用完客戶端並想要安全註銷,我們將使用註銷()功能。

其語法如下所示:

示例:


# importing the required modules
from fbchat import Client
from fbchat.models import *

# input username and password of the Facebook account
username = "example@website.com"
password = "password2email"

# creating an object of the Client class
clientObj = Client(username, password)

# logging out
clientObj.logout()

說明:

在上面的代碼片段中,我們使用了客戶端類的註銷()功能以及客戶端的對象來註銷。

理解線程

一個線索可以被認為是兩件事:一個信使群聊或一個單一的臉書用戶。

線程類型是一個有兩個值的枚舉器。第一個值是用戶,另一個值是集團。這些將指定該線程是單用戶聊天還是群聊。這是 fbchat 庫的多種功能所必需的,因為臉書可以在內部區分這兩種功能。

我們可以使用客戶端類的 searchForGroups 方法搜索群聊並找到他們的 ID。我們也可以使用搜索用戶方法來搜索用戶。我們將在本教程的後面討論它。

我們可以在客戶端類的 uid 方法的幫助下檢索我們的用戶標識。

我們還可以檢索群聊 ID。然而,同樣的程序相當瑣碎。因為我們只需要導航到https://www.facebook.com/messages/,然後我們將不得不點擊我們想要找到的組的 ID,然後從地址欄讀取 ID。網址將顯示如下:https://www.facebook.com/messages/t/123456789,,其中 123456789 將是群聊的標識。

我們可以對幾個用戶帳戶應用相同的方法,儘管如果他們設置了自定義的網址,我們將只看到那個網址。

讓我們考慮下面的代碼片段,演示線程標識和線程類型的使用。

示例:


# importing the required modules
from fbchat import Client
from fbchat.models import *

# input username and password of the Facebook account
username = "example@website.com"
password = "password2email"

# creating an object of the Client class
clientObj = Client(username, password)

# sending some message to user and group
clientObj.send(Message(text = 'some message'), thread_id = '', thread_type = ThreadType.USER)
clientObj.send(Message(text = 'some message'), thread_id = '<group_id>', thread_type = ThreadType.GROUP)

# logging out
clientObj.logout()</group_id> 

說明:

在上面的代碼片段中,我們已經開始導入所需的庫並提供用戶名和密碼。然後我們創建了一個客戶端類的對象。之後,我們使用 send() 功能,將文本消息連同線程 ID 和線程類型指定為 USER 和 GROUP 。最後,我們已經使用註銷()功能註銷了。

我們可以觀察到,我們已經提供了線程標識和線程類型來啟動函數。然而,有些函數根本不需要線程類型。一個這樣的功能可以是更改螺紋顏色。在這種情況下,我們必須提供線程標識。

讓我們考慮下面的例子來證明這一點:

示例:


# importing the required modules
from fbchat import Client
from fbchat.models import *

# input username and password of the Facebook account
username = "example@website.com"
password = "password2email"

# creating an object of the Client class
clientObj = Client(username, password)

# changing the Thread Colors
clientObj.changeThreadColor(ThreadColor.BRIGHT_TURQUOISE, thread_id = '')
clientObj.changeThreadColor(ThreadColor.DARK_TANGERINE, thread_id = '<group_id>')

# logging out
clientObj.logout()</group_id> 

說明:

在上面的代碼片段中,我們已經導入了所需的模塊,並提供了用戶名和密碼。然後我們創建了一個客戶端類的對象。然後我們使用了客戶端類的 changeThreadColor 功能來更改線程的顏色。我們已經在函數中指定了線程顏色和線程標識。最後,我們已經使用註銷()功能註銷了。

了解消息標識

我們在臉書上發送的每條消息都由一個唯一的標識組成,我們在一個線程中執行的每項活動,例如更改昵稱或添加個人,都有一個唯一的標識。

fbchat 庫的一些功能需要這些 ID,比如reactomessage,其中一些功能提供這個 ID,比如 sendMessage 。

讓我們考慮下面演示這些函數使用的例子。

示例:


# importing the required modules
from fbchat import Client
from fbchat.models import *

# input username and password of the Facebook account
username = "example@website.com"
password = "password2email"

# creating an object of the Client class
clientObj = Client(username, password)

# getting the message ID
messageID = clientObj.send(Message(text = 'message'), thread_id = clientObj.uid, thread_type = '')

# using the message ID to react to message
clientObj.reactToMessage(messageID, MessageReaction.LOVE)

# logging out
clientObj.logout() 

說明:

在上面的代碼片段中,我們已經導入了所需的方法,並提供了用戶名和密碼。然後我們創建了一個客戶端類的對象。然後,我們使用發送()功能檢索消息標識。然後,我們使用了消息標識,以便在reactomessage()的幫助下對消息做出反應,其中我們將消息標識和消息反應一起指定為愛情表情符號。

與線程的交互

fbchat 庫提供了不同的功能,以便我們與線程進行交互。

大多數功能適用於所有線程,但有些功能,如在群聊中添加用戶和刪除用戶,邏輯上只適用於群聊。

下表描述了用於與線程交互的一些函數:

| 南號碼 | 功能 | 描述 |
| one | 發送 | 此功能用於向用戶或組發送消息。 |
| Two | sendLocalImage | 此功能用於發送位於本地的圖像。 |
| three | 發送遠程圖像 | 該功能用於從網址下載並發送圖像。 |
| four | addUsersToGroup | 此功能用於向組中添加一個或多個用戶。 |
| five | 刪除用戶來自組 | 此功能用於從組中刪除用戶。 |
| six | 更改昵稱 | 此功能用於更改用戶的昵稱。 |
| seven | 更改線程標題 | 這個函數有助於改變線程的標題。 |
| eight | 設置型式狀態 | 該功能有助於將打字狀態設置為打字或停止。 |
| nine | changeThreadColor | 此功能用於更改螺紋的顏色。 |
| Ten | 變線程動畫集 | 這個函數有助於改變線程中的表情符號。 |
| Eleven | 反作用消息 | 此功能有助於對消息做出反應。 |

讓我們考慮下面的例子,演示上述函數在與線程交互中的使用。

示例:


# importing the required modules
from fbchat import Client
from fbchat.models import *

# input username and password of facebook account
username = "example@website.com"
password = "password2email"

# creating an object of Client class
clientObj = Client(username, password)

# specifying the thread ID and type
threadID = "1234567890"
threadType = ThreadType.GROUP

# sending a message to the thread
clientObj.send(
    Message(text = "some text message"),
    thread_id = threadID,
    thread_type = threadType
    )

# sending the emoji `?`
clientObj.send(
    Message(text = "?", emoji_size = EmojiSize.LARGE),
    thread_id = threadID,
    thread_type = threadType
)

# sending the sticker with ID `767334476626295`
clientObj.send(
    Message(sticker = Sticker("767334476626295")),
    thread_id = threadID,
    thread_type = threadType
)

# sending a message with a mention
clientObj.send(
    Message(
        text = "An example of @mention",
        mentions = [Mention(
            threadID,
            offset = 10,
            length = 8
            )]),
    thread_id = threadID,
    thread_type = threadType
)

# sending the image located at `<path_to_image_file>`
clientObj.sendLocalImage(
    "<path_to_image_file>",
    message = Message(text = "This is a local image"),
    thread_id = threadID,
    thread_type = threadType
)

# downloading the image at the URL `<url_to_image_file>`, and then sending it
clientObj.sendRemoteImage(
    "<url_to_image_file>",
    message = Message(text = "This is a remote image"),
    thread_id = threadID,
    thread_type = threadType
)

# Only do these actions if the thread is a group
if threadType == ThreadType.GROUP:
    # removing the user with ID `<user_id>` from the thread
    clientObj.removeUserFromGroup("<user_id>", thread_id = threadID)

    # adding the user with ID `<user_id>` to the thread
    clientObj.addUsersToGroup("<user_id>", thread_id = threadID)

    # adding the users with IDs `<First_user_id>`, `<Second_user_id>` and `<Third_user_id>` to the thread
    clientObj.addUsersToGroup(
        ["<First_user_id>", "<Second_user_id>", "<Third_user_id>"], thread_id = threadID
    )

# changing the nickname of the user `<user_id>` to `<new_nickname>`
clientObj.changeNickname(
    "<new_nickname>", "<user_id>", thread_id = threadID, thread_type = threadType
)

# changing the title of the thread to `<title>`
clientObj.changeThreadTitle("<some_title>", thread_id = threadID, thread_type = threadType)

# setting the typing status of the thread to `TYPING`
clientObj.setTypingStatus(
    TypingStatus.TYPING,
    thread_id = threadID,
    thread_type = threadType
)

# changing the thread color to `RADICAL_RED`
clientObj.changeThreadColor(ThreadColor.RADICAL_RED, thread_id = threadID)

# changing the thread emoji to `?`
clientObj.changeThreadEmoji("?", thread_id = threadID)

# reacting to a message with a ? emoji
clientObj.reactToMessage("<messageID>", MessageReaction.LOVE)

```py

**說明:**

在上面的代碼片段中,我們已經導入了所需的模塊,並提供了**用戶名**和**密碼**。我們創建了一個**客戶端**類的實例,並指定了線程標識和類型。然後,我們使用了不同的功能來與線程進行交互,從發送文本消息和表情符號到更改線程顏色和表情符號。由於我們正在進行**群組**聊天,我們還使用了在群組中添加和刪除用戶的操作。我們還使用了在本地和特定的網址上發送圖像的功能。

現在,讓我們了解如何使用 **fbchat** 庫獲取信息。

### 獲取信息

我們可以利用 **fbchat** 庫來獲取關於用戶的基本信息,例如他們的用戶名、個人資料圖片、線程名稱和用戶標識。

我們可以使用**客戶端**類的**搜索用戶**功能來檢索用戶標識。讓我們考慮下面的例子,它演示了允許我們獲取用戶信息的函數的工作原理。

**示例:**

Python fbchat庫

from fbchat import Client
from fbchat.models import *

Python fbchat庫

username = “example@website.com”
password = “password2email”

Python fbchat庫

clientObj = Client(username, password)

Python fbchat庫

the_users = clientObj.searchForUsers(”)
the_user = the_users[0]

Python fbchat庫

print(“User ID: {}”.format(the_user.uid))
print(“Name of the User: {}”.format(the_user.name))
print(“Profile picture URL of the User: {}”.format(the_user.photo))
print(“Main URL of the URL: {}”.format(the_user.url))


**說明:**

在上面的代碼片段中,我們已經導入了所需的模塊,並創建了一個 **Client** 類的實例。然後我們使用**搜索用戶**功能來檢索用戶標識。然後,我們將第一個用戶的值存儲在一個變量中。最後,我們使用 **uid、姓名、照片、url** 功能打印了用戶信息。

由於這個例子利用了臉書的搜索功能,我們不需要指定完整的名稱;名字通常就足夠了。

現在讓我們了解會話。

### 理解會話

**fbchat** 庫提供了檢索和設置會話 cookies 的功能。這個函數將允許我們將會話 cookies 存儲在一個單獨的文件中,這樣我們就不必每次開始腳本時都登錄。

我們可以使用**客戶端**類的**獲取會話**功能來檢索 cookies。其語法如下所示:

**語法:**

sessionCookies = clientObj.getSession()


然後我們可以使用**客戶端**類的**設置會話**功能來設置會話。其語法如下所示:

**語法:**

clientObj.setSession(sessionCookies)


或者我們可以在首次登錄時設置 **session_cookies** 。(如果會話 cookies 無效,將使用電子郵件和密碼登錄):

**語法:**

clientObj = Client(”, ”, session_cookies = sessionCookies)


**警告:**會話 cookies 可以和密碼一樣有價值,所以存儲時要同樣小心。

### 傾聽和事件

**fbchat** 庫還提供了類似於**客戶端**類的**監聽**功能的監聽功能,我們需要定義當某些事件發生時應該執行什麼。默認情況下,(大多數)事件將只是一個 **logging.info** 語句,這意味着當事件發生時,它將簡單地向控制台打印細節。

#### 注意:我們可以通過前綴識別事件方法。例如,onMessage。

我們可以通過子類化**客戶端**然後覆蓋事件方法來改變事件動作,如下所示:

**語法:**

Python fbchat庫

class Custom_Client(Client):
def onMessage(self, mid, author_id, message_object, thread_id, thread_type, ts, metadata, msg, **kwargs):

Python fbchat庫

    pass

Python fbchat庫

clientObj = Custom_Client(”, ”)



**說明:**

在上面的語法中,我們已經將**客戶端**類的子類定義為**自定義 _ 客戶端**。在類中,我們定義了一個方法為 **onMessage** ,它接受多個參數,如 **self、mid、author_id、message_object、thread_id、thread_type、ts、元數據、msg** 和 ****kwargs** 。人們可以在這個方法中編寫一些功能。最後,我們通過**用戶名**和**密碼**作為參數實例化了 **Custom_Client** 類。

**onMessage** 方法即使在我們更改方法的參數時也可以工作;然而,我們必須把*** *誇格斯**包括在內。

#### 注意:因此,為了向後和向前兼容,API 要求我們包含**kwargs 作為最終參數。

更多信息見官方文件,網址為:

[https://fbchat . readthedocs . io/en/stable/intro . html](https://fbchat.readthedocs.io/en/stable/intro.html)

* * *

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/303249.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-12-31 11:49
下一篇 2024-12-31 11:49

相關推薦

  • Python周杰倫代碼用法介紹

    本文將從多個方面對Python周杰倫代碼進行詳細的闡述。 一、代碼介紹 from urllib.request import urlopen from bs4 import Bea…

    編程 2025-04-29
  • Python計算陽曆日期對應周幾

    本文介紹如何通過Python計算任意陽曆日期對應周幾。 一、獲取日期 獲取日期可以通過Python內置的模塊datetime實現,示例代碼如下: from datetime imp…

    編程 2025-04-29
  • 如何查看Anaconda中Python路徑

    對Anaconda中Python路徑即conda環境的查看進行詳細的闡述。 一、使用命令行查看 1、在Windows系統中,可以使用命令提示符(cmd)或者Anaconda Pro…

    編程 2025-04-29
  • Python中引入上一級目錄中函數

    Python中經常需要調用其他文件夾中的模塊或函數,其中一個常見的操作是引入上一級目錄中的函數。在此,我們將從多個角度詳細解釋如何在Python中引入上一級目錄的函數。 一、加入環…

    編程 2025-04-29
  • Python列表中負數的個數

    Python列表是一個有序的集合,可以存儲多個不同類型的元素。而負數是指小於0的整數。在Python列表中,我們想要找到負數的個數,可以通過以下幾個方面進行實現。 一、使用循環遍歷…

    編程 2025-04-29
  • Python清華鏡像下載

    Python清華鏡像是一個高質量的Python開發資源鏡像站,提供了Python及其相關的開發工具、框架和文檔的下載服務。本文將從以下幾個方面對Python清華鏡像下載進行詳細的闡…

    編程 2025-04-29
  • Python編程二級證書考試相關現已可以上網購買

    計算機二級Python考試是一項重要的國家級認證考試,也是Python編程的入門考試。與其他考試一樣,Python編程二級證書的考生需要進入正式考試,而為了備考,這篇文章將詳細介紹…

    編程 2025-04-29
  • Python字典去重複工具

    使用Python語言編寫字典去重複工具,可幫助用戶快速去重複。 一、字典去重複工具的需求 在使用Python編寫程序時,我們經常需要處理數據文件,其中包含了大量的重複數據。為了方便…

    編程 2025-04-29
  • 蝴蝶優化算法Python版

    蝴蝶優化算法是一種基於仿生學的優化算法,模仿自然界中的蝴蝶進行搜索。它可以應用於多個領域的優化問題,包括數學優化、工程問題、機器學習等。本文將從多個方面對蝴蝶優化算法Python版…

    編程 2025-04-29
  • Python程序需要編譯才能執行

    Python 被廣泛應用於數據分析、人工智能、科學計算等領域,它的靈活性和簡單易學的性質使得越來越多的人喜歡使用 Python 進行編程。然而,在 Python 中程序執行的方式不…

    編程 2025-04-29

發表回復

登錄後才能評論