├── .gitignore ├── LICENSE ├── README.md ├── config.yaml.sample ├── package.json ├── src ├── app.d.ts ├── auth.ts ├── config.ts ├── facebook.ts ├── facebookThread.ts ├── fb-tool.ts ├── matrix-fbook.ts ├── matrix.ts ├── polyfill.js ├── roomMapping.ts └── userInfo.ts ├── tsconfig.json └── tslint.json /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | 6 | # Runtime data 7 | pids 8 | *.pid 9 | *.seed 10 | 11 | # Directory for instrumented libs generated by jscoverage/JSCover 12 | lib-cov 13 | 14 | # Coverage directory used by tools like istanbul 15 | coverage 16 | 17 | # nyc test coverage 18 | .nyc_output 19 | 20 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 21 | .grunt 22 | 23 | # node-waf configuration 24 | .lock-wscript 25 | 26 | # Compiled binary addons (http://nodejs.org/api/addons.html) 27 | build/Release 28 | 29 | # Dependency directories 30 | node_modules 31 | jspm_packages 32 | 33 | # Optional npm cache directory 34 | .npm 35 | 36 | # Optional REPL history 37 | .node_repl_history 38 | 39 | config.yaml 40 | build/ 41 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2016 Will Hunt 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # matrix-fb-chat 2 | 3 | A quick n dirty facebook bot bridge. 4 | 5 | ## ⚠️ Warning 6 | 7 | This API is undocumented, and likely against the Facebook TOS. I am not responsible if you 8 | go and get yourself banned from Facebook. This tool is here for anybody to use, but comes 9 | with no warrantys or guarantees. In addition, this software is *a hack*, not a completed or even partially completed work so support will be limited. 10 | 11 | ## What can it do? 12 | 13 | * Bridge one conversation to one room. 14 | * Send text messages from matrix. 15 | * Recieve messages and urls from facebook. 16 | 17 | ## Instructions 18 | 19 | 1. Run ``npm install`` 20 | 2. Run ``npm run-script build`` 21 | 3. We now have a tool to retrieve thread numbers, see below. 22 | 4. Clone ``config.yaml.sample`` and fill it in. 23 | - Your facebook id can be seen in your cookies or requests as "c_user". 24 | - You will need a threadID in addition to a room_id. 25 | - ~~Currently you need to do some digging on [getThreadList](https://github.com/Schmavery/facebook-chat-api/blob/master/DOCS.md#getThreadList) to find it, which requires a bit of manual work. A tool to pretty print your threads might arrive in the future.~~ 26 | 5. Run ``npm run-script start`` 27 | 6. Chat away! 28 | 29 | ## ``fb-tool`` 30 | 31 | This tool allows you to retrieve values used for configuring the bot. 32 | 33 | ### ``--list-threads``. 34 | 35 | You can get thread numbers by running the tool with ``npm run-script tool -- --list-threads``. Make sure you've filled in the config.yaml first with your facebook details. 36 | 37 | ## Contributing 38 | 39 | This was a quick half day hack for me so I won't be developing this into a full bridge just yet. PRs are welcome and a full review will be given. 40 | -------------------------------------------------------------------------------- /config.yaml.sample: -------------------------------------------------------------------------------- 1 | facebook: 2 | user_id: # See Readme 3 | email: # Your FB Email 4 | password: # Your FB Password 5 | 6 | matrix: 7 | user_id: # Bot user's userid 8 | token: # Bot user's token 9 | homeserver: # Homeserver url (with protocol and port) 10 | 11 | rooms: # Mapping of roomids to 'threads' 12 | - room: "!foodsdoobar3kcvdhi:half-shot.uk" 13 | thread: "12345678901234567890" 14 | - room: "!foodsdoobar3kcvdhi:half-shot.uk" 15 | thread: "12345678901234567890" 16 | - room: "!foodsdoobar3kcvdhi:half-shot.uk" 17 | thread: "12345678901234567890" 18 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "matrix-fb-chat", 3 | "version": "0.0.1", 4 | "description": "Chat on facebook via Matrix", 5 | "main": "matrix-fbook.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1", 8 | "lint": "tslint --project ./tsconfig.json", 9 | "tool": "node ./build/src/fb-tool.js", 10 | "build": "tsc", 11 | "start": "node ./build/src/matrix-fbook.js" 12 | }, 13 | "author": "Will Hunt ", 14 | "license": "MIT", 15 | "dependencies": { 16 | "@types/node": "^6.0.52", 17 | "bluebird": "^3.4.6", 18 | "command-line-args": "^3.0.4", 19 | "facebook-chat-api": "^1.2.0", 20 | "js-yaml": "^3.7.0", 21 | "matrix-js-sdk": "^0.7.1", 22 | "npmlog": "^4.0.1", 23 | "tslint": "^4.0.2", 24 | "typescript": "^2.1.4" 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/app.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | -------------------------------------------------------------------------------- /src/auth.ts: -------------------------------------------------------------------------------- 1 | export class Auth { 2 | public readonly email: string; 3 | public readonly password: string; 4 | constructor(email: string, password: string) { 5 | this.email = email; 6 | this.password = password; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/config.ts: -------------------------------------------------------------------------------- 1 | import * as Fs from "fs"; 2 | import * as Path from "path"; 3 | import * as Yaml from "js-yaml"; 4 | import { Auth } from "./auth"; 5 | import { RoomMapping } from "./roomMapping"; 6 | 7 | export class Config { 8 | private fbUserId: string; 9 | private fbEmail: string; 10 | private fbPassword: string; 11 | private mxUserId: string; 12 | private mxToken: string; 13 | private mxHomeserver: string; 14 | private roomMappings: RoomMapping[]; 15 | 16 | get FacebookId(): string { 17 | return this.fbUserId; 18 | } 19 | 20 | get UserId (): string { 21 | return this.mxUserId; 22 | } 23 | get Token (): string { 24 | return this.mxToken; 25 | } 26 | get Homeserver (): string { 27 | return this.mxHomeserver; 28 | } 29 | 30 | get Rooms (): RoomMapping[] { 31 | return this.roomMappings; 32 | } 33 | 34 | public GetRoomByRoom(roomId: string): RoomMapping { 35 | return this.Rooms.find((room: RoomMapping) : boolean => { 36 | return room.room === roomId; 37 | }); 38 | } 39 | 40 | public GetRoomByThread(thread: string): RoomMapping { 41 | return this.Rooms.find((room: RoomMapping) : boolean => { 42 | return room.thread === thread; 43 | }); 44 | } 45 | 46 | public readConfig(file: string) { 47 | file = Path.resolve(file); 48 | let regObj = Yaml.safeLoad(Fs.readFileSync(file, "utf8")); 49 | this.fbUserId = regObj.facebook.user_id; 50 | this.fbEmail = regObj.facebook.email; 51 | this.fbPassword = regObj.facebook.password; 52 | this.mxUserId = regObj.matrix.user_id; 53 | this.mxToken = regObj.matrix.token; 54 | this.mxHomeserver = regObj.matrix.homeserver; 55 | this.roomMappings = regObj.rooms; 56 | 57 | } 58 | 59 | public getFBAuth(): Auth { 60 | return new Auth(this.fbEmail, this.fbPassword); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/facebook.ts: -------------------------------------------------------------------------------- 1 | import * as fblogin from "facebook-chat-api"; 2 | import {Config} from "./config"; 3 | import {FacebookThread} from "./facebookThread"; 4 | import {FacebookUserProfile} from "./userInfo"; 5 | import * as Promise from "bluebird"; 6 | import * as log from "npmlog"; 7 | 8 | export class Facebook { 9 | public onThreadMessage: (body: string, thread: string, messageId: string, sender: string) => void; 10 | private appConfig: Config; 11 | private boundThreads: string[]; 12 | private userProfiles: any; 13 | private api; 14 | constructor(config: Config) { 15 | this.appConfig = config; 16 | this.boundThreads = []; 17 | } 18 | 19 | public Login(listen: boolean = true): Promise { 20 | let ids = []; 21 | return Promise.promisify(fblogin)(this.appConfig.getFBAuth(), { 22 | logLevel: "warn", 23 | selfListen: true, 24 | }).then((api) => { 25 | this.api = Promise.promisifyAll(api); 26 | return this.GetAllThreads(); 27 | }).each( (thread: FacebookThread) => { 28 | // If we are listening, just get the relevant users. Otherwise, get them all. 29 | if (this.boundThreads.includes(thread.threadID) || !listen) { 30 | ids = ids.concat(thread.participantIDs.filter((item) => { 31 | return !ids.includes(item); 32 | })); 33 | } 34 | }).then(() => { 35 | return this.api.getUserInfoAsync(ids); 36 | }).then((profiles) => { 37 | this.userProfiles = profiles; 38 | if (listen) { 39 | this.startListening(); 40 | } 41 | }).catch((err) => { 42 | log.error("Facebook", err); 43 | }); 44 | } 45 | 46 | public GetAllThreads(type: string = "inbox", end: number = 99, start: number = 0): Promise { 47 | return this.api.getThreadListAsync(start, end, type).catch((err) => { 48 | log.error("Facebook", "Couldn't get threads."); 49 | }); 50 | } 51 | 52 | public GetThreadParticipantNames(thread: FacebookThread): Map { 53 | let names: Map = new Map(); 54 | thread.participantIDs.forEach( (id) => { 55 | names.set(id, this.userProfiles[id] || null ); 56 | }); 57 | return names; 58 | } 59 | 60 | public GetThreadName(thread: FacebookThread): string { 61 | if (thread.name !== "" && thread.name) { 62 | return thread.name; 63 | } else if (thread.participantIDs.length === 2) { 64 | let names: Map = this.GetThreadParticipantNames(thread); 65 | for (let name of names) { 66 | if (name[0] !== this.appConfig.FacebookId) { 67 | return name[1] !== null ? name[1].name : "Unknown User";// TODO: Attempt to get info on this user? 68 | } 69 | } 70 | } else if (thread.participantIDs.length > 2) { 71 | return `Group chat with ${thread.participantIDs.length} people.`; 72 | } else { 73 | return "Unnamed chat."; 74 | } 75 | } 76 | 77 | public BindThread(thread: string) { 78 | this.boundThreads.push(thread); 79 | } 80 | 81 | public SendMessage (msg: string, thread: string) { 82 | return this.api.sendMessageAsync({body: msg}, thread).then((sentMsg: any) => { 83 | log.info("Facebook", "Message sent!"); 84 | return sentMsg.messageID; 85 | }).catch((err) => { 86 | log.error("Facebook", "Couldn't send message!\n" + err); 87 | }); 88 | } 89 | 90 | public SendEmote (msg: string, thread: string) { 91 | this.SendMessage("/me " + msg, thread); // TODO:improve this 92 | } 93 | 94 | private startListening(): void { 95 | this.api.listen((err, msg) => { 96 | if (err) { 97 | log.error("Facebook", "Couldn't listen for new messages." + err); 98 | return; 99 | } 100 | let sender = this.userProfiles[msg.senderID] ? this.userProfiles[msg.senderID].name : msg.senderID; 101 | let body = "Unknown type"; 102 | if (msg.type === "message") { 103 | body = msg.body ? msg.body : ""; 104 | for (let attachment of msg.attachments) { 105 | if (attachment.url) { 106 | body += " " + attachment.url; 107 | } 108 | } 109 | } 110 | this.onThreadMessage(msg.body, msg.threadID, msg.messageID, sender); 111 | }); 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /src/facebookThread.ts: -------------------------------------------------------------------------------- 1 | export class FacebookThread { 2 | public threadID: string; 3 | public participants: string[]; 4 | public participantIDs: string[]; 5 | public formerParticipants: string[]; 6 | public name: string; 7 | public snippet: string; 8 | public snippetHasAttachment: boolean; 9 | public snippetAttachments: any[]; 10 | public snippetSender: string; 11 | public unreadCount: number; 12 | public messageCount: number; 13 | public imageSrc: string; 14 | public timestamp: string; 15 | public serverTimestamp: string; 16 | public muteSettings: any; 17 | public isCanonicalUser: boolean; 18 | public isCanonical: boolean; 19 | public canonicalFbid: string; 20 | public isSubscribed: boolean; 21 | public rootMessageThreadingID: string; 22 | public folder: string; 23 | public isArchived: boolean; 24 | public recipientsLoadable: boolean; 25 | public hasEmailParticipant: boolean; 26 | public readOnly: boolean; 27 | public canReply: boolean; 28 | public composerEnabled: boolean; 29 | public blockedParticipants: boolean; 30 | public lastMessageID: string; 31 | } 32 | -------------------------------------------------------------------------------- /src/fb-tool.ts: -------------------------------------------------------------------------------- 1 | import { Facebook } from "./facebook"; 2 | import { Config } from "./config"; 3 | import { FacebookThread } from "./FacebookThread"; 4 | import * as Promise from "bluebird"; 5 | import * as CLIArgs from "command-line-args"; 6 | import * as log from "npmlog"; 7 | 8 | const args: any = CLIArgs([ 9 | { name: "list-threads", alias: "l", type: Boolean }, 10 | { name: "config", alias: "c", type: String }, 11 | ]); 12 | 13 | if ( Object.keys(args).length === 0 ) { 14 | log.error("CLI", "Please use a command as an argument. Examples:\n --list-threads"); 15 | process.exit(0); 16 | } 17 | 18 | let appCfg: Config = new Config(); 19 | try { 20 | appCfg.readConfig(args.config || "config.yaml"); 21 | } catch (err) { 22 | log.error("CLI", "Couldn't read config. Did you enter the path correctly and use correct syntax?"); 23 | log.error(err.message); 24 | } 25 | 26 | if (args["list-threads"]) { 27 | let fbook: Facebook = new Facebook(appCfg); 28 | fbook.Login(false).then(() => { 29 | log.info("Lisiting threads for user.."); 30 | return fbook.GetAllThreads(); 31 | }).map((thread: FacebookThread) => { 32 | let name: string = fbook.GetThreadName(thread); 33 | return `Name: ${name}\nThreadID ${thread.threadID}` 34 | }).then((threads) => { 35 | log.info("CLI", threads.join("\n====\n")); 36 | }); 37 | } 38 | -------------------------------------------------------------------------------- /src/matrix-fbook.ts: -------------------------------------------------------------------------------- 1 | import { Config } from "./config"; 2 | import { Facebook } from "./facebook"; 3 | import { Matrix } from "./matrix"; 4 | import { RoomMapping } from "./roomMapping"; 5 | import * as CLIArgs from "command-line-args"; 6 | import * as log from "npmlog"; 7 | 8 | import "polyfill.js"; 9 | 10 | function main (args) { 11 | const checkThreads = args["list-threads"] === true; 12 | 13 | let appCfg: Config = new Config(); 14 | appCfg.readConfig(args.config || "config.yaml"); 15 | 16 | let fbook: Facebook = new Facebook(appCfg); 17 | let matrix: Matrix = new Matrix(appCfg.Homeserver, appCfg.Token, appCfg.UserId); 18 | let ignoreList = []; 19 | for (let roomDef of appCfg.Rooms) { 20 | matrix.AddRoom(roomDef.room); 21 | fbook.BindThread(roomDef.thread); 22 | } 23 | matrix.onRoomMessage = (content: any, roomId: string) => { 24 | // TODO Catch the bots messages. 25 | let room: RoomMapping = appCfg.GetRoomByRoom(roomId); 26 | if (content.msgtype === "m.text") { 27 | fbook.SendMessage(content.body, room.thread).then((id) => { 28 | ignoreList.push(id); 29 | }); 30 | } else if (content.msgtype === "m.emote") { 31 | fbook.SendEmote(content.body, room.thread); 32 | } 33 | log.info("MatrixFB", `MSG from ${roomId} going to ${room.thread}`); 34 | }; 35 | 36 | fbook.onThreadMessage = (body: string, thread: string, messageId: string, sender: string) => { 37 | if (ignoreList.includes(messageId)) { 38 | log.info("MatrixFB", "Ignoring dupe message"); 39 | return; 40 | } 41 | let room: RoomMapping = appCfg.GetRoomByThread(thread); 42 | log.info("MatrixFB", `MSG from ${thread} going to ${room.room}`); 43 | matrix.SendMessage(body, sender, room.room); 44 | }; 45 | matrix.Start(); 46 | fbook.Login(); 47 | 48 | } 49 | 50 | const args: any = CLIArgs([ 51 | { name: "config", alias: "c", type: String }, 52 | ]); 53 | main(args); 54 | -------------------------------------------------------------------------------- /src/matrix.ts: -------------------------------------------------------------------------------- 1 | import * as MatrixSDK from "matrix-js-sdk"; 2 | import * as log from "npmlog"; 3 | 4 | export class Matrix { 5 | public onRoomMessage: (content: any, roomId: string) => void; 6 | private mxClient; 7 | private userId: string; 8 | private rooms: string[]; 9 | 10 | constructor(baseUrl: string, accessToken: string, userId: string) { 11 | this.mxClient = MatrixSDK.createClient({ 12 | baseUrl, 13 | accessToken, 14 | userId, 15 | }); 16 | this.rooms = []; 17 | this.userId = userId; 18 | this.mxClient.on("sync", (state, prevState, data) => { 19 | if (state === "PREPARED") { 20 | this.mxClient.on("event", this.onEvent.bind(this)); 21 | } 22 | }); 23 | } 24 | 25 | public AddRoom(roomId: string): Promise { 26 | this.rooms.push(roomId); 27 | return this.mxClient.joinRoom(roomId).catch((err) => { 28 | log.error("Facebook", "Failed to join ", roomId, "\n", err); 29 | }); 30 | } 31 | 32 | public SendMessage(body: string, user: string, roomId: string) { 33 | this.mxClient.sendTextMessage(roomId, `${user}: ${body}`); 34 | } 35 | 36 | public Start() { 37 | this.mxClient.startClient(); 38 | } 39 | 40 | private onEvent(event) { 41 | if (event.event.type === "m.room.message" 42 | && this.rooms.includes(event.event.room_id) 43 | && event.event.sender !== this.userId 44 | ) { 45 | this.onRoomMessage(event.event.content, event.event.room_id); 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/polyfill.js: -------------------------------------------------------------------------------- 1 | if (!Array.prototype.includes) { 2 | Array.prototype.includes = function(searchElement /*, fromIndex*/) { 3 | 'use strict'; 4 | if (this == null) { 5 | throw new TypeError('Array.prototype.includes called on null or undefined'); 6 | } 7 | 8 | var O = Object(this); 9 | var len = parseInt(O.length, 10) || 0; 10 | if (len === 0) { 11 | return false; 12 | } 13 | var n = parseInt(arguments[1], 10) || 0; 14 | var k; 15 | if (n >= 0) { 16 | k = n; 17 | } else { 18 | k = len + n; 19 | if (k < 0) {k = 0;} 20 | } 21 | var currentElement; 22 | while (k < len) { 23 | currentElement = O[k]; 24 | if (searchElement === currentElement || 25 | (searchElement !== searchElement && currentElement !== currentElement)) { // NaN !== NaN 26 | return true; 27 | } 28 | k++; 29 | } 30 | return false; 31 | }; 32 | } 33 | -------------------------------------------------------------------------------- /src/roomMapping.ts: -------------------------------------------------------------------------------- 1 | export class RoomMapping { 2 | public readonly room: string; 3 | public readonly thread: string; 4 | } 5 | -------------------------------------------------------------------------------- /src/userInfo.ts: -------------------------------------------------------------------------------- 1 | export class FacebookUserProfile { 2 | public name: string; 3 | public firstName: string; 4 | public vanity: string; 5 | public thumbSrc: string; 6 | public profileUrl: string; 7 | public gender: string; 8 | public type: string; 9 | public isFriend: boolean; 10 | public isBirthday: boolean; 11 | public searchTokens: string; 12 | public alternateName: string; 13 | } 14 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "moduleResolution": "Node", 5 | "target": "ES6", 6 | "noImplicitAny": false, 7 | "sourceMap": false, 8 | "outDir": "./build" 9 | }, 10 | "compileOnSave": true, 11 | "include": [ 12 | "src/**/*" 13 | ] 14 | } 15 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "tslint:recommended", 3 | "rules": { 4 | "ordered-imports": "off", 5 | "no-trailing-whitespace": "off" 6 | } 7 | } 8 | --------------------------------------------------------------------------------