Example of posting to FB chat (Messenger) USER or GROUP from OH2 rule

First go here an/or here and/or here.

When it works from within python or running python from the login shell, we need to tweak things a bit in order to run it from a rule.

sendFBchatMsg.py:

#!/usr/bin/python

import sys
sys.path.append('/home/omr/.local/lib/python2.7/site-packages')

import fbchat
from fbchat import Client
from fbchat.models import *

thread_id = sys.argv[1]
if (len(sys.argv) > 3):
    thread_type = ThreadType.GROUP
else:
    thread_type = ThreadType.USER

chatMsg = sys.argv[2] # de-qoute string from OH2
if chatMsg.startswith('"') and chatMsg.endswith('"'):
    chatMsg = chatMsg[1:-1]

#print "Params"
#print "argv1:", sys.argv[1]
#print "argv2:", sys.argv[2]
#print "chatMsg:", chatMsg

client = Client('<yourFBid>','<yourFBpassw>')
client.send(Message(text=chatMsg), thread_id=thread_id, thread_type=thread_type)
client.logout()

My ssh login on Ubuntu is /home/omr you must tune into yours.
Also, the path to /home/omr/.local/lib/python2.7/site-packages (where pip installs fbchat) needs to be
chown to openhab:youruser and chmod to +r & +x (all path items). This is because executeCommandLine from OH2 starts without much of an environment.

In OH2:
We want the uid to be globally available:
.items

String USERfbChatUid
String GROUPfbGroupChatUid

.rules

var String msg = "'System started. Stand by'"  // note: double quoting!
var String msgGroup = "'System just restarted!'" // note: double quoting!
var String test = "" 

rule "System start"
when
        System started
then 
    logInfo("System", "System started (or a rule changed)");    
    USERfbChatUid.postUpdate("1234567...")  // you must obtain your own uid
    GROUPfbGroupChatUid.postUpdate("89101112...")  // you must obtain your own uid 

    test = executeCommandLine("/usr/bin/python /home/omr/sendFBchatMsg.py " + USERfbChatUid.state.toString + " " + msg, 10000)
    logInfo("fbchat", "sendFBchatMsg returned:" + test);  

    test = executeCommandLine("/usr/bin/python /home/omr/sendFBchatMsg.py " + GROUPfbGroupChatUid.state.toString + " " + msgGroup + " " + "GROUP", 10000)
    logInfo("fbchat", "sendFBchatMsg returned:" + test);  
end

This will trigger as soon as you save the rules file:
image

It is also possible to answer back from messenger back into OH2, but I leave that to the ones who need it.

Nice, thanks for posting!

For those who are already using MQTT, MQTTWarn supports FB Chat if you don’t want to go through executeCommandLine.

I really like the idea of being able to receive commands from the chat. I hope someone completes the tutorial with that. :slight_smile: