Hello everyone, In this we will do a simple echo bot for the purposes of testing if fbchat library is working and for wreaking instant karma...........
Echo Bot
An echo bot simply echoes back whatever is given to
You: Sun
Bot: Sun
You: Moon
Bot: Moon
You: Zen
Bot: Zen
In short whatever you give, it returns. Ok lets get our hands dirty
First things first: Importing libraries
from fbchat import log, Client
Client is the main class of fbchat, which contains all the methods you use to interact with Facebook. You can extend this class, and overwrite the on methods, to provide custom event handling (mainly useful while listening).
On the other hand logging is simply used for logging
Subclassing the client class
class EchoBot(Client):
I just died and on reincarnation I decide to be Client's son so I inherit all
the good genes(properties and methods) he has. How lucky i am.
Overriding the onMessage
onMessage method is executed every-time a message is sent whether from you or someone else. However we want it to execute in some special way different from the parent class so we override it.
def onMessage(self, author_id, message_object, thread_id, thread_type, **kwargs):
self.markAsDelivered(thread_id, message_object.uid)
self.markAsRead(thread_id)
log.info("{} from {} in {}".format(message_object, thread_id, thread_type.name))
# If you're not the author, echo
if author_id != self.uid:
self.send(message_object, thread_id=thread_id, thread_type=thread_type)
What Happening
- We get a message
- We tell the sender that his message was delivered and read
- We log some info which we received
- If the id that sent the message is not ours we simply echo back the message
Last but not least: Loging in and listening
client = EchoBot("nightfury@mars.example", "easypass123")
client.listen()
We create our Echobot object then get into listen mode. What we receive we return back given that we did not send that message. Breaking this condition will result in an endless echo loop that is if facebook doesn't ban you.
Bye bye
Top comments (1)
where's the github link... Show material