Creating a Bot/PHP

PHP as JavaScript, is also loosely typed and very easy to learn.

Again, **this guide is for Windows users only.** Linux users, you're smart. Figure it out.

## Theory

This extract explaining what Facebok SDK is was taken from the Facebook for Web Developers guide

> The Facebook SDK for PHP is a library [...] to easily integrate Facebook login and make requests to the Graph API. It [...] makes it easy to upload photos and videos and send batch requests to the Graph API among other things.
>
>

In short, it is a compilation of PHP functions that allows us to interact with the Graph API in a practical way.

But what is this Graph API we keep talking about? the Graph API docs put it this way

> The Graph API is the primary way to get data into and out of the Facebook platform.
>
>

There is no other way around it! If you wanna make a Facebook Bot you **need** to use this API.

## Practice

#### Requirements

* PHP installed in your environment. (How to)
* Composer as dependency manager in your PHP project. (How to)
* An IDE to start coding, preferably PhpStorm.

> If you don't meet some of this requirements, check this guide.
>
>

#### Getting started

Ok since we decided we were going to use Facebook's official SDK, the best way to get it for PHP is using Composer, the dependency manger.

To install the SDK run this command in your project root directory

```
composer require facebook/graph-sdk

```

Or if you are using PhpStorm like me, you could just create a new *Composer Project* from scratch, selecting the facebook/graph-sdk package on the search bar.

   Now our project is ready for us to start coding!

I made a "MyBot" directory under the source ("src") folder, a HelloWorld.php class and our run.php script that will call our helloWorld function.

   HelloWorld.php

```
 <?php
  /\*\*
   \* Created by PhpStorm.
   \* User: Saramba
   \* Date: 2/24/2019
   \* Time: 1:01 AM
   \*/

  class HelloWorld
  {

      // Gotten from the App Dashboard
      private $APP\_ID = '<YOURS>';
      // Gotten from the App Dashboard
      private $APP\_SECRET = '<YOURS>';
      // Gotten from PaintBot tool
      private $ACCESS\_TOKEN\_DEBUG = '<YOURS>';

      /\*\*
   \* @author Saramba
   \* @desc Initializes the Facebook Object
   \*
   \* @return \Facebook\Facebook
   \*/
      public function init()
      {
          try {
              $fb = new \Facebook\Facebook([
                  'app\_id' => $this->APP\_ID,
                  'app\_secret' => $this->APP\_SECRET,
                  'default\_access\_token' => $this->ACCESS\_TOKEN\_DEBUG,
                  'default\_graph\_version' => 'v3.2'
              ]);
              return $fb;
          } catch (\Facebook\Exceptions\FacebookSDKException $e) {
              echo 'Facebook SDK returned an error: ' . $e->getMessage();
              exit;
          }
      }

      /\*\*
   \* @author Saramba
   \* @desc Posts to reference, if reference not given posts to page's feed.
   \*
   \* @param \Facebook\Facebook $fb
   \* @param string $id\_reference
   \* @param string $comment
   \* @param string $comment\_photo
   \*
   \* @return \Facebook\FacebookResponse
   \*/
  <nowiki>    public function postToReference($fb, $id\_reference, $comment, $comment\_photo = '')</nowiki>
      {
          try {
              // setting up the data we'll send
              $data = array ();
              if (!empty($comment)) {
                  $data['message'] = $comment;
              }
              if (!empty($comment\_photo)) {
                  // Supports images hosted locally or remotely
                  $data['source'] = $fb->fileToUpload($comment\_photo);
              }
              if (count($data) < 1) {
                  echo 'No data given to post.';
              }

              /\*\* @var $response \Facebook\FacebookResponse \*/
              /\* Since we provided a 'default\_access\_token', we don't need to pass it as second parameter here. \*/
              if (!empty($id\_reference)) {
                  // $id\_reference Could either be a post or a comment
                  $response = $fb->post($id\_reference.'/comments', $data);
              } else {
                  // post to page feed
                  if (empty($comment\_photo)) {
                      $response = $fb->post('me/feed', $data);
                  } else {
                      $response = $fb->post('me/photos', $data);
                  }
              }
              return $response;

          } catch (\Facebook\Exceptions\FacebookSDKException $e) {
              echo 'Facebook SDK returned an error: ' . $e->getMessage();
              exit;
          }
      }

      public function helloWorld(){

          $fb = $this->init();

          /\*\* Since $id\_reference is null, postToReference will post to the page's feed \*/
          $message = "Hello World!";
          $response = $this->postToReference($fb, null, $message);

          /\*\*
   \* Same thing as above but with an image attached (message is optional if $image is given)
   \* $image can either be a local path or a remote image on the internet
   \*/
          $image = \_\_DIR\_\_.'/sentient.png'; // local
          $image = 'https://pbs.twimg.com/profile\_images/715527793463853056/6MGmLjgz\_400x400.jpg'; // remote
          $response = $this->postToReference($fb, null, $message, $image);

          /\*\*
   \* $id\_reference can either be a post id or a comment id
   \*
   \* Getting the id for a post could be done from the post url
   \* ex: https://www.facebook.com/permalink.php?story\_fbid=2007895549329937&id=1960628010723358
   \* ID\_POST => 1960628010723358\_2007895549329937
   \* But the right way is using the Graph API me/feed endpoint
   \*/
          $id\_reference = '1960628010723358\_2007895549329937'; // reference is a post
          $response = $this->postToReference($fb, $id\_reference, $message, $image);

          /\*\*
   \* Getting the $id\_reference for a comments could be done from the comment url too
   \* ex: https://www.facebook.com/permalink.php?story\_fbid=2007895549329937&id=1960628010723358&comment\_id=2007921219327370
   \* ID\_COMMENT => 2007895549329937\_2007921219327370
   \* Again, the right way is using a Graph API endpoint, in this case <IDPOST>/comments
   \*/
          $id\_reference = '2007895549329937\_2007921219327370'; // reference is a comment
          $response = $this->postToReference($fb, $id\_reference, $message, $image);

          if (!$response->isError()) {
              echo 'Posted!';
              // Continue coding
          }
      }

  }

```

run.php

```
 <?php
  /\*\*
   \* Created by PhpStorm.
   \* User: Saramba
   \* Date: 2/24/2019
   \* Time: 1:33 AM
   \*/

  require \_\_DIR\_\_ .'/../../vendor/autoload.php';
  require\_once 'HelloWorld.php';

  $HW = new \HelloWorld();
  $HW->helloWorld();

```

Now, choose which flavor of postToReference you want to run, comment the other so those don't interfere and run run.php