Skip to content
Open
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 26 additions & 18 deletions examples/multi-threading.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
# -*- coding: UTF-8 -*-

from fbchat import Client
from fbchat import Client, logging
from fbchat.models import *
import threading
import sys

user = "<email>"
password = "<password>"


# Subclass fbchat.Client and override required methods
class PrintMessage(Client):
class MessagePrinter(Client):
def onMessage(self, author_id, message_object, thread_id, thread_type, **kwargs):
self.markAsDelivered(thread_id, message_object.uid)
self.markAsRead(thread_id)
Expand All @@ -17,26 +22,29 @@ def onLoggedIn(self, email=None):
print("Login of {} successful.".format(email))


# Logging in and setting logging level to WARNING to avoid some unessential output
client = PrintMessage("<email>", "<password>", logging_level=30)
# Login and set logging level to WARNING to avoid some unessential output
client1 = Client(user, password, logging_level=logging.WARNING)
client2 = MessagePrinter(user, password, logging_level=logging.WARNING)


# Creating and starting a separate thread for receiving messages
t1 = threading.Thread(target=client2.listen, daemon=True)
t1.start()


def send():
# Loop checking for, and sending messages
try:
while True:
payload = input("Message: ")
if payload:
client.send(
Message(text=payload), thread_id=client.uid, thread_type=ThreadType.USER
client1.send(
Message(text=payload),
thread_id=client1.uid,
thread_type=ThreadType.USER,
)


def receive():
while True:
client.doOneListen()


# Creating and starting separate threads for handling the receiving and sending of messages
t1 = threading.Thread(target=receive)
t2 = threading.Thread(target=send)
t1.start()
t2.start()
# Clean-up on exit
except KeyboardInterrupt:
client1.logout()
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd argue there's really not a big need to log out (it's not shown in the other examples, either)

client2.logout()
sys.exit(0)
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should clean the client2 up properly instead. That can be done by setting Client.listening to False, and then wait for the thread to clean up afterwards, using Thread.join

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And then there'd be no need to make t1 daemonic