Re: Das Facebook Bot

Benutzeravatar
davidvajda.de
Site Admin
Beiträge: 1507
Registriert: Di Jul 18, 2023 8:36 pm
Wohnort: D-72072, Tübingen
Kontaktdaten:

Re: Das Facebook Bot

Beitrag von davidvajda.de »

Einen wohl geistreichen Beitrag zum Facebook Messanger Bot mit Python finde ich hier:

https://www.mediabynature.de/blog/faceb ... -tutorial/

Worum es jetzt geht - ist - man wird weiter geleitet - zu Facebook wegen Webhooks

https://developers.facebook.com/docs/me ... m/webhooks

Dieses legt node.JS nahe.

Wie man das benutzt findet man hier:

https://gridscale.io/community/tutorial ... ner-guide/

Ich selber habe viel Erfahrung mit Apache2-Webservern und ganz wenig mit nginx. Ich programmiere ich JavaScript. Wer früher auf meiner Homepage war fand dort einen Parser. - node.JS bietet jetzt an - das zu tun - was JavaScript bisher nicht konnte - man brauchte PHP - node.JS wird ausgeführt wie ein Server.

Gut, das habe ich gleich mal gemacht.

Code: Alles auswählen

apt-get install node.JS 
funktioniert.

Jetzt node.JS aufrufen

Code: Alles auswählen

node
Hat funktioniert. Jetzt JavaScript Code eingeben:

Code: Alles auswählen

david@git:~$ node
Welcome to Node.js v12.22.12.
Type ".help" for more information.
> console.log("Hello World");
Hello World
undefined
>
Ich probiere jetzt meinen Parser auf zu rufen.

Das ist mein Parser in JavaScript

Code: Alles auswählen

var p = "sin(5.1*(5.718*(3.43*(2.45+4.66*(sin(9.4)+3.01))))*2.22+1.12)*ln(2.2)";
var j = 0;

function parser_error() {
    alert("Parser Error");
}

function expression() {
     var x, y;
     x = term();
     if(p.charAt(j) == '+') {
        j++;
        y = expression();
        return x+y;
     }
     else if(p.charAt(j) == '-') {
        j++;
        y = expression();
        return x-y;
     }
     return x;
}

function factor() {
     var z;
     var x;
     var y;
     if(p.charAt(j) == '(') {
        j++;
        x = expression();
        if(p.charAt(j) == ')')
           j++;
        else
           parser_error();
        return x;
     }
     else if((p.charAt(j) == 't') && (p.charAt(j+1) == 'a') && (p.charAt(j+2) == 'n') && (p.charAt(j+3) == '(')) {
            j+=4;
            x = expression();
            y = Math.tan(x);
            if(p.charAt(j) == ')')
                j++;
            else
                parser_error();
            return y;
    }
    else if((p.charAt(j) == 'c') && (p.charAt(j+1) == 'o') && (p.charAt(j+2) == 's') && (p.charAt(j+3) == '(')) {
            j+=4;
            x = expression();
            y = Math.cos(x);
            if(p.charAt(j) == ')')
                j++;
            else
                parser_error();
            return y;
    }
    else if((p.charAt(j) == 's') && (p.charAt(j+1) == 'i') && (p.charAt(j+2) == 'n') && (p.charAt(j+3) == '(')) {
            j+=4;
            x = expression();
            y = Math.sin(x);
            if(p.charAt(j) == ')')
                j++;
            else
                parser_error();
            return y;
    }
    else if((p.charAt(j) == 'l') && (p.charAt(j+1) == 'n') && (p.charAt(j+2) == '(')) {
            j+=3;
            x = expression();
            y = Math.log(x);
            if(p.charAt(j) == ')')
                j++;
            else
                parser_error();
            return y;
    }
    else if((p.charAt(j) == 'e') && (p.charAt(j+1) == 'x') && (p.charAt(j+2) == 'p') && (p.charAt(j+3) == '(')) {
            j+=4;
            x = expression();
            y = Math.exp(x);
            if(p.charAt(j) == ')')
                j++;
            else
                parser_error();
            return y;
    }
    else if((x = parseFloat(p.substring(j))) != NaN) {
            var i = 0;
            while (parseFloat(p.substring(j)) != parseFloat(p.substring(j, i+j)))
                i++;
            while (p.charAt (i+j) == '0')
                j++;
            j += i;
            return x;
    }
    else
        parser_error();
}

function term() {
     var x, y;
     x = factor();
     if(p.charAt(j) == '*') {
         j++;
         y = term();
         return x * y;
     }
     else if(p.charAt(j) == '/') {
         j++;
         y = term();
         return x / y;
     }
     return x;
}

p = window.prompt("Geben Sie einen arithmetischen Ausdruck ein, Zahlen duerfen nur eine Ziffer sein, nur + und * erlaubt", p);
alert(expression());
Das mit den Modulen habe ich verstanden

Code: Alles auswählen

var http = require (“http”)
Das sind Module, die ich einbinde, wie header Dateien in C - um Funktionalität zur Verfügung zu stellen.

OK, npm schaue ich nicht gross an - und, was da auf Facebook zu node.JS steht, sollte ich jetzt bereits tun können - aber ich mache etwas weiter. Es geht um File IO.

Ich schreibe mal den gesamten Code in eine Datei und probiere es so aus.

Ok, das hat funktioniert

Code: Alles auswählen

mynode.js:

Code: Alles auswählen

var http = require ("http");

var fs = require('fs');

fs.readFile('david.txt', 'utf8', function (err, content) {

if (err) throw err;

console.log('Es steht da:\n', content);

});

Code: Alles auswählen

david.txt

Code: Alles auswählen

Hallo Welt, sagt David Vajda 
Ausgabe:

Code: Alles auswählen

david@git:~$ node mynode.js 
david@git:~$ node mynode.js 
Es steht da:
 Hallo Welt, sagt David Vajda 

david@git:~$
Ich probiere jetzt den Server aus: - ich nehme nur einen anderen Port, weil der Rechner, an dem ich arbeite, auf dem läuft eigentlich git.

Sieht gut aus

Code: Alles auswählen

var http = require ("http");

var fs = require('fs');

fs.readFile('david.txt', 'utf8', function (err, content) {

if (err) throw err;

console.log('Es steht da:\n', content);

});

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello, World!\n');
}).listen(7777, '127.0.0.1');

console.log('Server running at http://127.0.0.1:7777');
Jetzt weiter mit Facebook, viel mehr muss man dafür auch nicht mehr tun. Bei Facebook steht dann da, wir sollen machen.

https://developers.facebook.com/docs/me ... m/webhooks

Auf der Facebookseite steht etwas, wie

Code: Alles auswählen

// Add support for GET requests to our webhook
app.get("/messaging-webhook", (req, res) => {
  
// Parse the query params
  let mode = req.query["hub.mode"];
  let token = req.query["hub.verify_token"];
  let challenge = req.query["hub.challenge"];

  // Check if a token and mode is in the query string of the request
  if (mode && token) {
    // Check the mode and token sent is correct
    if (mode === "subscribe" && token === config.verifyToken) {
      // Respond with the challenge token from the request
      console.log("WEBHOOK_VERIFIED");
      res.status(200).send(challenge);
    } else {
      // Respond with '403 Forbidden' if verify tokens do not match
      res.sendStatus(403);
    }
  }
});
zum Webhook. das geht nicht. Aber man kann den gesamten Code hier von github runter laden

https://github.com/fbsamples/original-c ... /tree/main

Gut. Und wenn man jetzt die app.js ausführt - gibt es eine Fehlermeldung can not find module express.

Und installiert mit npm das Module express

Code: Alles auswählen

npm install express
Gut dann installiert man npm

Code: Alles auswählen

apt-get install npm
Ok, das hat funktioniert - hier habe ich den gesamten Code heruner geladen

https://github.com/fbsamples/original-c ... ain/app.js

aber das ganze Verzeichnis, dann entzipt

Ich habe es ausgeführt, aber es kam, das Port 3000 bereits belegt ist.

Ich habe dann in der
./original-coast-clothing-main/services/

die datei config.js gefunden

hier steht

Code: Alles auswählen

  // Preferred port (default to 3000)
  port: process.env.PORT || 3000,
ich habe das ersetzt durch

Code: Alles auswählen

  // Preferred port (default to 3000)
  port: process.env.PORT || 2412,
und es geht.

Und es tut, wie in

https://developers.facebook.com/docs/me ... m/webhooks

beschrieben steht habe ich den Curl Befehl

Code: Alles auswählen

curl -H "Content-Type: application/json" -X POST "localhost:1337/webhook" -d '{"object": "page", "entry": [{"messaging": [{"message": "TEST_MESSAGE"}]}]}'

ausgeführt - und erhalten

Code: Alles auswählen

david@git:~$ curl -H "Content-Type: application/json" -X POST "localhost:2421/webhook" -d '{"object": "page", "entry": [{"messaging": [{"message": "TEST_MESSAGE"}]}]}'
curl: (7) Failed to connect to localhost port 2421: Verbindungsaufbau abgelehnt
david@git:~$ curl -H "Content-Type: application/json" -X POST "localhost:2412/webhook" -d '{"object": "page", "entry": [{"messaging": [{"message": "TEST_MESSAGE"}]}]}'
EVENT_RECEIVEDdavid@git:~$ 
Das ist richtig

Gut, ich kann jetzt weiter machen.
Antworten