Send a Facebook Message with XMPP using Access Tok

2019-06-14 03:59发布

问题:

This is a very specific question, but I cannot find any documentation on how I can do it. The Facebook Documentation is pretty vague with some horrible and useless PHP examples (really, it's code like the Facebook PHP Sample Code that make people think PHP sucks) but I cannot find anything around for Python.

I can't even work out how to apply the same principles from the PHP sample code into a Python world. The xmpppy and SleekXMPP docs are a bit bare (or broken) and Google only shows examples of people using passwords.

I have the access tokens coming from the database, I have no interest in spawning a browser to find stuff, or doing anything else to find a token. I have them, consider it a hardcoded string. I want to pass that string to XMPP and send a message, that is the whole scope of things.

Any suggestions?

回答1:

I answered this with a link to a blog I wrote because it described the solution perfectly, but apparently that annoyed some moderators.

While that's clearly ridiculous, here is the answer reposted.

import sleekxmpp
import logging

logging.basicConfig(level=logging.DEBUG)

class SendMsgBot(sleekxmpp.ClientXMPP):
    def init(self, jid, recipient, message):
        sleekxmpp.ClientXMPP.__init__(self, jid, 'ignore')
        # The message we wish to send, and the JID that
        # will receive it.
        self.recipient = recipient
        self.msg = message
        # The session_start event will be triggered when
        # the bot establishes its connection with the server
        # and the XML streams are ready for use. We want to
        # listen for this event so that we we can initialize
        # our roster.
        self.add_event_handler("session_start", self.start, threaded=True)
    def start(self, event):
        self.send_presence()
        self.get_roster()
        self.send_message(mto=self.recipient, mbody=self.msg, mtype='chat')
        # Using wait=True ensures that the send queue will be
        #emptied before ending the session.
        self.disconnect(wait=True)

I shoved that in a file called fbxmpp.py, then in another file (your worker, your command line app, your Flask controller, whatever) you'll need something like the following:

from fbxmpp import SendMsgBot

# The "From" Facebook ID
jid = '511501255@chat.facebook.com'

# The "Recipient" Facebook ID, with a hyphen for some reason
to = '-1000023894758@chat.facebook.com'

# Whatever you're sending
msg = 'Hey Other Phil, how is it going?'

xmpp = SendMsgBot(jid, to, unicode(msg))

xmpp.credentials['api_key'] = '123456'
xmpp.credentials['access_token'] = 'your-access-token'

if xmpp.connect(('chat.facebook.com', 5222)):
    xmpp.process(block=True)
    print("Done")
else:
    print("Unable to connect.")


回答2:

The below code worked, but only after some modifications mentioned in this thread