13.0.4 • Published 5 months ago

lnw-bot-fb v13.0.4

Weekly downloads
-
License
ISC
Repository
-
Last release
5 months ago

repo นี้แยกจาก repo หลัก และโดยปกติจะรวมฟีเจอร์ใหม่ไว้เร็วกว่า repo หลัก (และอาจรวมข้อบกพร่องบางอย่างด้วย)

ขณะนี้ Facebook มี API อย่างเป็นทางการสำหรับแชทบอทแล้ว here.

API นี้เป็นวิธีเดียวที่จะทำให้ฟังก์ชันการแชทในบัญชีผู้ใช้เป็นแบบอัตโนมัติ เราทำสิ่งนี้โดยการจำลองเบราว์เซอร์ นี่หมายถึงการดำเนินการตามคำขอ GET/POST เดียวกันทุกประการ และหลอกให้ Facebook คิดว่าเรากำลังเข้าถึงเว็บไซต์ตามปกติ เนื่องจากเรากำลังทำเช่นนี้ API นี้จึงไม่ทำงานกับโทเค็นการตรวจสอบสิทธิ์ แต่ต้องใช้ข้อมูลประจำตัวของบัญชี Facebook

ข้อจำกัดความรับผิดชอบ: เราจะไม่รับผิดชอบหากบัญชีของคุณถูกแบนจากกิจกรรมสแปม เช่น การส่งข้อความจำนวนมากถึงคนที่คุณไม่รู้จัก การส่งข้อความอย่างรวดเร็ว การส่ง URL ที่ดูเป็นสแปม การเข้าสู่ระบบและออกอย่างรวดเร็ว... จงรับผิดชอบ Facebook ตัวเอง

See below กูขี้เกียจแปลเอาเป็นว่าไปดูคู่มือเอาอัพเดตมาใหม่คือ แก้ไขข้อความได้ตามเวอร์ชั่นล่าสุด

Install

หากคุณต้องการใช้ lnw-bot-fb คุณควรใช้คำสั่งนี้:

npm install lnw-bot-fb 

มันจะดาวน์โหลด lnw-bot-fb จากที่เก็บ NPM

Bleeding edge

หากคุณต้องการใช้ Bleeding Edge (โดยตรงจาก GitHub) เพื่อทดสอบฟีเจอร์ใหม่หรือส่งรายงานข้อผิดพลาด นี่คือคำสั่งสำหรับคุณ:

npm install lnw-bot-fb 

Testing your bots

หากคุณต้องการทดสอบบอทโดยไม่ต้องสร้างบัญชีอื่นบน Facebook คุณสามารถใช้ได้ Facebook Whitehat Accounts.

Example Usage

const login = require("lnw-bot-fb");

// Create simple echo bot
login({email: "FB_EMAIL", password: "FB_PASSWORD"}, (err, api) => {
    if(err) return console.error(err);

    api.listen((err, message) => {
        api.sendMessage(message.body, message.threadID);
    });
});

Result:

Documentation

ดูคู่มือ here.

Main Functionality

Sending a message

api.sendMessage(message, threadID, callback)

Various types of message can be sent:

  • Regular: set field body to the desired message as a string.
  • Sticker: set a field sticker to the desired sticker ID.
  • File or image: Set field attachment to a readable stream or an array of readable streams.
  • URL: set a field url to the desired URL.
  • Emoji: set field emoji to the desired emoji as a string and set field emojiSize with size of the emoji (small, medium, large)

Note that a message can only be a regular message (which can be empty) and optionally one of the following: a sticker, an attachment or a url.

Tip: to find your own ID, you can look inside the cookies. The userID is under the name c_user.

Example (Basic Message)

const login = require("lnw-bot-fb");

login({email: "FB_EMAIL", password: "FB_PASSWORD"}, (err, api) => {
    if(err) return console.error(err);

    var yourID = "000000000000000";
    var msg = "Hey!";
    api.sendMessage(msg, yourID);
});

Example (File upload)

const login = require("lnw-bot-fb");

login({email: "FB_EMAIL", password: "FB_PASSWORD"}, (err, api) => {
    if(err) return console.error(err);

    // Note this example uploads an image called image.jpg
    var yourID = "000000000000000";
    var msg = {
        body: "Hey!",
        attachment: fs.createReadStream(__dirname + '/image.jpg')
    }
    api.sendMessage(msg, yourID);
});

Saving session.

To avoid logging in every time you should save AppState (cookies etc.) to a file, then you can use it without having password in your scripts.

Example

const fs = require("fs");
const login = require("lnw-bot-fb");

var credentials = {email: "FB_EMAIL", password: "FB_PASSWORD"};

login(credentials, (err, api) => {
    if(err) return console.error(err);

    fs.writeFileSync('appstate.json', JSON.stringify(api.getAppState()));
});

Alternative: Use c3c-fbstate to get fbstate.json (appstate.json)


Listening to a chat

api.listen(callback)

Listen watches for messages sent in a chat. By default this won't receive events (joining/leaving a chat, title change etc…) but it can be activated with api.setOptions({listenEvents: true}). This will by default ignore messages sent by the current account, you can enable listening to your own messages with api.setOptions({selfListen: true}).

Example

const fs = require("fs");
const login = require("lnw-bot-fb");

// Simple echo bot. It will repeat everything that you say.
// Will stop when you say '/stop'
login({appState: JSON.parse(fs.readFileSync('appstate.json', 'utf8'))}, (err, api) => {
    if(err) return console.error(err);

    api.setOptions({listenEvents: true});

    var stopListening = api.listenMqtt((err, event) => {
        if(err) return console.error(err);

        api.markAsRead(event.threadID, (err) => {
            if(err) console.error(err);
        });

        switch(event.type) {
            case "message":
                if(event.body === '/stop') {
                    api.sendMessage("Goodbye…", event.threadID);
                    return stopListening();
                }
                api.sendMessage("TEST BOT: " + event.body, event.threadID);
                break;
            case "event":
                console.log(event);
                break;
        }
    });
});

FAQS

  1. How do I run tests?

    For tests, create a test-config.json file that resembles example-config.json and put it in the test directory. From the root >directory, run npm test.

  2. Why doesn't sendMessage always work when I'm logged in as a page?

    Pages can't start conversations with users directly; this is to prevent pages from spamming users.

  3. What do I do when login doesn't work?

    First check that you can login to Facebook using the website. If login approvals are enabled, you might be logging in incorrectly. For how to handle login approvals, read our docs on login.

  4. How can I avoid logging in every time? Can I log into a previous session?

    We support caching everything relevant for you to bypass login. api.getAppState() returns an object that you can save and pass into login as {appState: mySavedAppState} instead of the credentials object. If this fails, your session has expired.

  5. Do you support sending messages as a page?

    Yes, set the pageID option on login (this doesn't work if you set it using api.setOptions, it affects the login process).

    login(credentials, {pageID: "000000000000000"}, (err, api) => { … }
  6. I'm getting some crazy weird syntax error like SyntaxError: Unexpected token [!!!

    Please try to update your version of node.js before submitting an issue of this nature. We like to use new language features.

  7. I don't want all of these logging messages!

    You can use api.setOptions to silence the logging. You get the api object from login (see example above). Do

    api.setOptions({
        logLevel: "silent"
    });

Projects using this API:

  • c3c - A bot that can be customizable using plugins. Support Facebook & Discord.
acornacorn-jsxagent-baseajvansiansi-colorsansi-regexansi-stylesanymatchare-we-there-yetargparsearray-buffer-byte-lengtharray.prototype.reducearraybuffer.prototype.sliceasn1assert-plusastral-regexasync-limiterasynckitavailable-typed-arraysaws-sign2aws4axiosbalanced-matchbase64-jsbcrypt-pbkdfbinary-extensionsblbluebirdboolbasebrace-expansionbracesbrowser-stdoutbufferbuffer-fromcall-bindcall-bind-apply-helperscall-boundcallback-streamcallsitescamelcasecaselesschalkcheeriochokidarcliuicolor-convertcolor-namecombined-streamcommistconcat-mapconcat-streamcore-util-iscross-spawncss-selectcss-whatddashdashdata-view-bufferdata-view-byte-lengthdata-view-byte-offsetdebugdecamelizedeep-isdefine-data-propertydefine-propertiesdelayed-streamdelegatesdiffdoctrinedom-serializerdomelementtypedomhandlerdomutilsdunder-protoduplexifyecc-jsbnemoji-regexend-of-streamenquirerentitieses-abstractes-array-method-boxes-properlyes-define-propertyes-errorses-object-atomses-set-tostringtages-to-primitivees5-extes6-iteratores6-mapes6-setes6-symbolescape-string-regexpeslinteslint-scopeeslint-utilseslint-visitor-keysesniffespreeesprimaesqueryesrecurseestraverseesutilsevent-emitterextextendextsprintffast-deep-equalfast-json-stable-stringifyfast-levenshteinfast-urifile-entry-cachefill-rangefind-upflatflat-cachefigletflattedfollow-redirectsfor-eachforever-agentform-datafs.realpathfunction-bindfunction.prototype.namefunctional-red-black-treefunctions-have-namesgaugeget-caller-fileget-intrinsicget-symbol-descriptiongetpassglobglob-parentglob-streamglobalsglobalthisgopdgrowlhar-schemahar-validatorhas-bigintshas-flaghas-property-descriptorshas-protohas-symbolshas-tostringtaghas-unicodehasownhehelp-mehtmlparser2http-signaturehttps-proxy-agentieee754ignoreimport-freshimurmurhashinflightinheritsinternal-slotis-absoluteis-array-bufferis-async-functionis-bigintis-binary-pathis-boolean-objectis-bufferis-callableis-data-viewis-date-objectis-extglobis-finalizationregistryis-fullwidth-code-pointis-generator-functionis-globis-mapis-negated-globis-negative-zerois-numberis-number-objectis-regexis-relativeis-setis-shared-array-bufferis-stringis-symbolis-typed-arrayis-typedarrayis-unc-pathis-weakmapis-weakrefis-weaksetis-windowsisarrayisexeisstreamjs-tokensjs-yamljsbnjson-bufferjson-schemajson-schema-traversejson-stable-stringify-without-jsonifyjson-stringify-safejsprimkeyvlevenlevnlocate-pathlodashlodash.assigninlodash.bindlodash.defaultslodash.filterlodash.flattenlodash.foreachlodash.maplodash.mergelodash.padlodash.padendlodash.padstartlodash.picklodash.reducelodash.rejectlodash.somelodash.truncatelog-symbolsmath-intrinsicsmime-dbmime-typesminimatchminimistmkdirpmqttmqtt-packetmsnatural-comparenext-ticknode-environment-flagsnormalize-pathnpmlognth-checkoauth-signobject-inspectobject-keysobject.assignobject.getownpropertydescriptorsonceoptionatorordered-read-streamsp-limitp-locatep-tryparent-modulepath-dirnamepath-existspath-is-absolutepath-keyperformance-nowpicocolorspicomatchpossible-typed-array-namesprelude-lsprettierprocess-nextick-argsprogressproxy-from-envpslpumppumpifypunycodeqsrandom-seedrandom-useragentreadable-streamreaddirpreflect.getprototypeofregexp.prototype.flagsregexppreintervalremove-trailing-separatorrequestrequire-directoryrequire-from-stringrequire-main-filenameresolve-fromrimrafsafe-array-concatsafe-buffersafe-regex-testsafer-buffersemverset-blockingset-function-lengthset-function-nameshebang-commandshebang-regexside-channelside-channel-listside-channel-mapside-channel-weakmapslice-ansisplit2sprintf-jssshpkstream-shiftstring_decoderstring-widthstring.prototype.trimstring.prototype.trimendstring.prototype.trimstartstrip-ansistrip-json-commentssupports-colortabletext-tablethrough2through2-filterto-absolute-globto-regex-rangetough-cookietunnel-agenttweetnacltypetype-checktype-festtyped-array-buffertyped-array-byte-lengthtyped-array-byte-offsettyped-array-lengthtypedarrayultronunbox-primitiveunc-path-regexunique-streamuri-jsutil-deprecateuuidv8-compile-cacheverrorwebsocket-streamwhichwhich-boxed-primitivewhich-builtin-typewhich-collectionwhich-modulewhich-typed-arraywide-alignword-wrapwrap-ansiwrappywsxtendy18nyargsyargs-parseryargs-unparser
13.0.4

5 months ago

13.0.3

5 months ago

13.0.2

5 months ago

13.0.1

5 months ago

13.0.0

5 months ago