UBports Robot Logo UBports Forum
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    • Register
    • Login

    Facebook Messenger PUSH notifications

    Scheduled Pinned Locked Moved Off topic
    4 Posts 3 Posters 1.3k Views 1 Watching
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
      Reply
      • Reply as topic
      Log in to reply
      This topic has been deleted. Only users with topic management privileges can see it.
      • F Offline
        FeZ
        last edited by FeZ

        PREREQUISITES:

        • a FaceBook account;
        • a Messenger client installed on your device from appstore (Pesbuk recommended);
        • a "home" server capable running python3 code. You can run on your own UPBorts device instead, but I have not tested;
        • "pushclient" mini app installed on your device from AppStore;
        • basic programming skills;
        • understanding, and taking your own responsibility of security considerations.

        GETTING YOUR APP TOKEN

        1. Start your pushclient on the UB device.
        2. Write/copy your token (take care, it's yours, don't share with others!)

        INSTALL fbchat

        1. Login as administrator (aka. root) to your home server
        2. install fbchat:
        # pip install fbchat 
        

        INSTALL AND SETUP fbnotifications.py

        1. Login as a safe normal user to your home server.
        2. Open your favourite code editor, and create a file 'fbnotifications.py'. Copy this code into that file:
        #!/usr/bin/env python
        
        import signal
        import sys
        import requests
        import json
        from datetime import datetime, timedelta
        
        from fbchat import Client
        from fbchat.models import *
        
        DEBUG = True
        LOG_FILENAME = "debug.log"
        
        USER = "<your facebook login email>"
        PASSWORD = "<your facebook login password>"
        
        PUSH_URL = "https://push.ubports.com/notify"
        HEADERS = {"Content-Type" : "application/json"}
        
        card = {
            "icon" : "message",
            "body" : "",
            "summary" : "Messenger",
            "popup" : True,
            "persist" : True
        }
        
        notification = {
            "card" : card,
            "vibrate" : True,
            "sound"   : True
            }
        
        data = {
            "notification" : notification,
            }
        
        params = {
            "appid" : "pushclient.christianpauly_pushclient",
            "token" : "<your ubuntu one app token>",
            "expire_on" : "",
            "data" : data
        }
        
        
        client = None
        logfile = None
        
        def log(log_msg):
            if DEBUG:
                logfile.write(f'{str(log_msg)}\n')
                logfile.flush()
        def signal_handler(sig, frame):
            log('Exiting with signal {sig}')
            if client and client.isLoggedIn():
                client.logout()
            if logfile:
                logfile.close()
            sys.exit(0)
        
        
        class CustomClient(Client):
            def onMessage(self, mid, author_id, message_object, thread_id, thread_type, ts, metadata, msg, **kwargs):
                if not DEBUG and author_id == self.uid:
                    return
                
                user = self.fetchUserInfo(author_id)[author_id]
                log(f'Message from:\n{str(user)}\n')
                name = 'noname'
                if user.nickname:
                    name = user.nickname
                elif user.name:
                    name = user.name
                
                dt = datetime.now() + timedelta(days=1)
                dt_str = dt.strftime("%Y-%m-%dT%H:%M:00.000Z")
                if message_object:
                    if message_object.text:
                        body = f'{name}: {message_object.text[:23]}'
                    else:
                        body = f'{name} sent media content.'
                    params["expire_on"] = dt_str
                    params["data"]["notification"]["card"]["body"] = body
                    json_data = json.dumps(params)
                    log(f'Data sent:\n {json_data}\n')
                    r = requests.post(url=PUSH_URL, headers=HEADERS, data=json_data)
                    log(r.json())
        
        ##################### MAIN #####################
        if __name__ == "__main__":
        
            if DEBUG:
                print(f'Loggin in: {LOG_FILENAME}')
                logfile = open(LOG_FILENAME, "a")
        
            client = CustomClient(USER, PASSWORD)
        
            log(f'User logged in: {client.isLoggedIn()}')
            log(client.getSession())
        
            signal.signal(signal.SIGINT, signal_handler)
        
            client.listen()
        
        1. Change <your facebook login email>, <your facebook login password>, and <your ubuntu one app token> strings to your own data respectively.
        2. Set DEBUG global variable according to your needs to False or True.
        3. Save the file.
        4. Set permissions so that only you (and administrator) can read your personal data:
        $ chmod 600 fbnotifications.py
        
        
        1. Run the program:
        $ python fbnotifications.py
        

        TESTING
        If you want to run a self-test, then:

        • set DEBUG = True, and see the generated logfile in another terminal;
        • open FB Messenger web client in a desktop browser;
        • search for yourself in the search box above the contact list;
        • send a message to yourself;

        Now you have to wait until the push notification arrives.
        If you have issues, write me on telegram UBPorts Supergroup.

        POSSIBLE OPTIONS

        1. Run the program on home server as a system service (recommended).
        • on most modern Linux use systemd
        • on BSD use rc scripts
        1. Run the program in a screen process

        This is a very simple solution to run it quick and "service" like.
        Note, this will not start automatically after a system restart.

        DEFICIENCIES

        • Tapping the notification does not open the Messenger app automatically. You have to open it explicitly.
        1 Reply Last reply Reply Quote 5
        • K Offline
          kugiigi
          last edited by

          Wow this sounds interesting. Sadly I don't have my own server.

          Another alternative though is using the Pesbuk app. It's just a webapp but if you set it to run in the background (via UTTT) it'll get push notifications whenever you get new ones. There's a know issue though when you have a different webapp header than the one tested with it.

          I'm not intentionally promoting my app. Just trying to help 😛

          1 Reply Last reply Reply Quote 1
          • F Offline
            FeZ
            last edited by

            Thank you, I'll try that also.

            1 Reply Last reply Reply Quote 0
            • L Offline
              L-00334 Banned
              last edited by L-00334

              This post is deleted!
              1 Reply Last reply Reply Quote 0
              • First post
                Last post