X
    Categories: API Tutorials and Use Cases

Send Notifications to Trello Using CloudwaysBot API

Now A days Bots are handy way to automate any communications with targeted audience. Bots are able to send alerts, notifications in real time. Luckily Cloudways is offering an intelligent CloudwaysBot which is a very smart assistant for yur server and apps hosted on Cloudways. The CloudwaysBot sends you the notifications and integerate with many applications.

In this article, I will demonstrate how to collect all notifications (new and old) from the CloudwaysBot and send them to a Trello project as an individual task.

Send CloudwaysBot Alerts

To send CloudwaysBot alerts as task in Trello, I will setup a webhook in CloudwaysBot. But before that, I will add the code to get the response of the webhook.

$json = file_get_contents('php://input'); //get the webhook response

$actions = json_decode($json); //decode the task object

$text = $actions->text; //save the task in $text

This is a simple code snippet that will get the CloudwaysBot response and save it in $text.

Start Building With Trello

The first step is to get the Application Key that identify the API and authenticate API calls.

Here is how you get the key

Setup the Webhook in CloudwaysBot

CloudwaysBot supports custom APIs and I will now create a webhook for the index.php file. I will use the the staging URL that is located in the Application Access Details tab.

Go to CloudwaysBot from the top navigation menu, click on the channels tab and then click the Add Channel button.

Select the API option from the drop down list.

Enter the complete URL of the index.php, set the Name of the channel and the status to Active.

Include Client Library and jQuery

The next step is the inclusion of jQuery and client.js in the application. Before the body tag, add the following code and replace the AppKey. When you add this code to the page, a global Trello object (with several important methods) becomes available. In addition, by specifying the Application Key in the URL for client.js, I can automatically use it when making requests.

<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="https://api.trello.com/1/client.js?key=[AppKey]"></script>

Now, that these two dependencies have been included , I can access a global Trello object.

Receive User Token

There are two ways to authorize a client and receive a User Token. The first is through the authorize route while the second is the basic OAuth. The default parameter is redirect. This decides whether authorization should be done in a new window, or by leaving the current page.

name

The name of the application, which is displayed during the authorization process.

persist

true or false. The default parameter is true, in which case, the token is saved to the local storage.

interactive

true or false. The default parameter is true. In the case of false, the stored token is used instead of redirection or other methods.  

scope

Object like { read: allowRead, write: allowWrite, account: allowAccount }

The default value is read-only, i.e. { read: true, write: false, account: false }

Each permission is a boolean variable.

expiration

1hour, 1day, 30days ,never

The default duration of token expiration is 30days.

success

Optional function to be called in the event of success.

error

Optional function to be called in the event of error.

If using type: “redirect”, the token will be returned to the current location.href. When it is returned, call authorize with interactive: false to get the token.

Authenticate User

It’s important to understand that the Authentication Token gives the application the ability to make calls on behalf of the user, from their context. This token grants access to the authenticated user’s Boards, Lists, Cards, and other settings, depending on the permissions requested in the authenticate method.

Define Success and Failure

First, let’s define what happens when authentication has finished, using success and failure callbacks.

var authenticationSuccess = function() { console.log(Successful authentication); };
var authenticationFailure = function() { console.log(Failed authentication); };

Use php client for consuming the Trello API

Install

Via Composer

$ require stevenmaguire/trello-php

By using this, you could:

  • Configure client
  • Authenticate user and retrieve access token
  • Access API

Configuration Creating Client

$client = new Stevenmaguire\Services\Trello\Client(array(
    'callbackUrl' => 'http://your.domain/oauth-callback-url',
    'domain' => 'https://trello.com',
    'expiration' => '3days',
    'key' => 'application-key',
    'name' => $text,
    'scope' => 'read,write',
    'secret' => 'application-secret',
    'token'  => 'abcdefghijklmnopqrstuvwxyz',
));

Multiple Configuration After Creating Client

$client = new Stevenmaguire\Services\Trello\Client(array(
    'key' => 'application-key',
    'name' => $text,
));

$config = array(
    'callbackUrl' => 'http://your.domain/oauth-callback-url',
       'scope' => 'read,write',
);

$client->addConfig($config);

Single configuration after creating client

$client = new Stevenmaguire\Services\Trello\Client(array(
    'key' => 'my-application-key',
    'name' => $text,
));
$client->addConfig('token', 'abcdefghijklmnopqrstuvwxyz');

Authenticate User Access Token

The Trello client allows you to assist walking the users through the OAuth authorization process and provide application access token credentials. This package utilizes The League’s OAuth1 Trello Client to provide this assistance.

OAuth 1 Client is an OAuth library for authentication at OAuth 1 servers.

Install Via Composer

$ require league/oauth1-client

Use the Client Through the Following Code

$server =  new League\OAuth1\Client\Server\Trello(array(
    'identifier' => 'your-identifier',
    'secret' => 'your-secret',
    'callback_uri' => 'http://your-callback-uri/',
    'name' => 'your-application-name', // optional, defaults to null
    'expiration' => 'your-application-expiration', // optional ('never', '1day', '2days'), defaults to '1day'
    'scope' => 'your-application-scope' // optional ('read', 'read,write'), defaults to 'read'
));

This is often required when the user is redirected back. This involves retrieving token credentials, which could then be used to make calls to the server on behalf of the user. These calls were referred to as  access tokens in earlier versions of OAuth 1.

if (isset($_GET['oauth_token']) && isset($_GET['oauth_verifier'])) {
    // Retrieve the temporary credentials we saved before
    $temporaryCredentials = unserialize($_SESSION['temporary_credentials']);
    // We will now retrieve token credentials from the server
    $tokenCredentials = $server->getTokenCredentials($temporaryCredentials, $_GET['oauth_token'], $_GET['oauth_verifier']);
}

you  can check these by:

var_dump($tokenCredentials->getIdentifier());
var_dump($tokenCredentials->getSecret());

Access User Information

Now that token credentials are available, I could use them to make calls against the server, as an authenticated user.

$user = $server->getUserDetails($tokenCredentials);
$uid = $server->getUserUid($tokenCredentials);
$email = $server->getUserEmail($tokenCredentials);
$screenName = $server->getUserScreenName($tokenCredentials);

User Authentication and Store Access Token

$client = new Stevenmaguire\Services\Trello\Client(array(
    'key' => 'application-key',
    'secret' => 'application-secret',
));

Application’s Required OAuth Settings

$config = array(
    'name' => $text,
    'callbackUrl' => 'http://your.domain/oauth-callback-url',
    'scope' => 'read,write',
);

$client->addConfig($config);

Get Authorization URL, Then Redirect the User

$authorizationUrl = $client->getAuthorizationUrl();
header('Location: ' . $authorizationUrl);

Authorization Token for Access Token

After the user approves or denies access to the application, they are redirected to the provided callback URL. If the user approves access, the URL will include oauth_token and oauth_verifier in query string parameters.

$token = $_GET['oauth_token'];
$verifier = $_GET['oauth_verifier'];
$credentials = $client->getAccessToken($token, $verifier);
$accessToken = $credentials->getIdentifier();

Use Access Token to Make Requests

$client->addConfig('token', $accessToken);
$user = $client->getCurrentUser();

Access the API With Access Token

$client = new Stevenmaguire\Services\Trello\Client(array(
    'key' => 'application-key',
    'token' => 'access-token',
));

$boards = $client->getCurrentUserBoards();

$cards = $client->getCurrentUserCards();
$organizations = $client->getCurrentUserOrganizations();

Exceptions Handling

try {
    $board = $client->getBoard($boardId);
} catch (Stevenmaguire\Services\Trello\Exceptions\Exception $e) {
    $code = $e->getCode(); // Http status code from response
    $reason = $e->getMessage(); // Http status reason phrase
    $error = $e->getPrevious(); // GuzzleHttp\Exception\RequestException from http client
    $body = $e->getResponseBody(); // stdClass response body from http client
}

The above code sends CloudwaysBot notifications to Trello. Previously, I used $getalerts to fetch the alerts and var_dump to view the results. To send new alerts and avoid duplications, I will compare the current date of the server with the date of alerts, and then finally, create a task for the respective alert.

foreach($getalerts->alerts as $alerts)
	{
	$aid = $alerts->id;

	if ($cw_api->getid() != $aid && $tickeet == true)
		{
		/*As I have already defined the logic and the information to be entered above, instead of  *enter your information detail*, just insert all the information from the above commands to execute. */
        /* application key*/
        /* token*/
        /*Secret key*/
        /*Credential*/
		}
	  else
		{
		echo "else block";
		$tickeet = false;
		}

	if (empty($firstid))
		{
		$firstid = $aid;
		$cw_api->setid($aid);
		}
	}

This process could be automated through a cron job. Here is a handy tutorial on how to create and setup the cron job.

Conclusion

In this article, I discussed how you could add CloudwaysBot notifications in a Trello project through CloudwaysBot API. If you have a question about the process or would like to contribute to the discussion, leave a comment below.

Owais Alam: is the WordPress Community Manager at Cloudways - A Managed WooCommerce Hosting Platform and a seasoned PHP developer. He loves to develop all sorts of websites on WordPress and is in love with WooCommerce in particular. You can email him at owais.alam@cloudways.com