# Simple movies Telegram bot using PHP

I have been using telegram for almost 4+ years and have made more than 30 bots during this period. I made the first one in PHP and the rest were build in Python and JavaScript. So today I thought why not make a simple telegram bot in PHP. That's why we are going to make a movie's bot in PHP. Let's begin without wasting time.

# Gathering Requirements
Before we start making our bot, we need two things. It won't take much time, only few minutes. The things we need are:

- Telegram Bot Token

- TMDB API key

TMDB is the site from which we will pull the movie information from. It's free, you just need to register and fill some forms for an API key. So let's start gathering them.

## Get Telegram Bot token
It's actually pretty simple to get the token from telegram. But first you need is a telegram account. I assume that you have one. Search for a bot named BotFather or use this [link](https://tx.me/BotFather). It should have a verified emoji in its name.


![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1665903526384/b8KOpi0si.png align="left")

Click on the bot and press start, or if you don't see that option, then type `/start`. I should greet you with a help message. You can read through that if you want to, it lists all details about what the bot can do. Next is, type `/newbot ` and press send. It will ask for the name of the bot. After that it will ask for bot username which must be unique and should end in bot like mine here is `phpmoviesbot`.

![4HOD9NPmBo.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1665906428085/hpped5n9A.png align="left")

Now you will receive a message which has a http API token. This was the token we were looking for, save it somewhere because we will need it later.

## Get API key from TMDB
Head to [TMDB](https://www.themoviedb.org/) and find register or join now. Then create an account. Then find settings and on the left side you will see an option named API, press that or use this [link](https://www.themoviedb.org/settings/api). You will need to fill a form about what you will be using the API for etc, just fill it yourself. After that you will get an API Key (v3 auth), save it somewhere we need it later.
![ELYBOncHjY.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1665907514115/DQWWgGzYK.png align="left")

Now that we have what we wanted, let's start with the programming side.

# Setting up webhook

Setting up the webhook through which your Telegram bot will communicate is the next step in the creation process. In order to avoid having to query the API every few minutes (or seconds) to see whether, for example, a new message has been received, APIs use webhooks to notify you that something has occurred.

Telegram only makes use of one form of webhook, which delivers an `update` object each time something occurs. The webhook configuration is really simple.
There are only two things you must be aware of: your API token (which you should already have from step one), and the URL at which your bot will be hosted.
It will have a URL similar as `https://yourdomain.com/yourbot.php`.
To ensure that Telegram sends the webhook, insert `https` at the beginning of the URL.


Go to `https://api.telegram.org/<TELEGRAM_BOT_TOKEN>/setwebhook?url=https://yourdomain.com/yourbot.php` in a standard web browser now. Do replace `<TELEGRAM_BOT_TOKEN>` with your telegram bot token.

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1666591475038/-VkfPORHR.png align="left")


# Coding part
For this, I am assuming you know basic PHP syntax, formattings etc. Let's start then, we know that PHP script start with `<?php` and ends with `?>` and we write the code in between.
We are receiving webhook, therefore let's get input from the POST body: 
```php
$content = file_get_contents('php://input');
$update = json_decode ($content, true);
```
The received data is in JSON, to decode it to PHP based array, we have to use `json_decode` function. Now let's declare some variables which will store some, data from the update like username, chat ID etc.
```php
$chat_id = $update['message']['chat']['id'];
$message = $update['message']['text'];
$username = $update['message']['from']['username'];
```
We would have to send many messages, so let's define it directly as a function to make it easier to reuse.
```php
function send_message ($chat_id, $message) {
    $apiToken = <TELEGRAM_BOT_TOKEN>;
    $text = urlencode($message);
    file_get_contents("https://api.telegram.org/bot$apiToken/sendMessage?chat_id=$chat_id&text=$text");
}
```
Replace the `<TELEGRAM_BOT_TOKEN>` with the telegram bot token you made. Let's test the bot with a `/start` message, to do that we have to write some more code, just an if statement as below.

```php
if ($message == '/start') 
{
    send_message ($chat_id, "Hey @$username  \nsend me any query to search for the movie.");
}
```

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1666584937091/88jUlYr05.png align="left")

It seems to be working. Now let's complete it by adding the movie information fetching part. I want to make the bot search everything we text we send except `/start`. So we just add else to the pre-existing if statement. I am expecting you know how to parse JSON.

```php
else {
    $req = file_get_contents("https://api.themoviedb.org/3/search/movie?api_key=<TMDB_API_KEY>&language=en-US&page=1&query=$message" );
    $movie = json_decode ( $req, true )['results'];
    if ($movie) {
        $movie = $movie[0];
        $title = $movie['title'];
        $overview = $movie['overview'];
        $popularity = $movie['popularity'];
        $release_date = $movie['release_date'];
        $vote_count = $movie['vote_count'];
        send_message($chat_id, "
    	Title: $title
		Description: $overview
		Popularity : $popularity
		Release Date : $release_date
		Votes: $vote_count");
    } 
    else {
        send_message($chat_id, "Couldn't find any movie with that name!");
    }
```
Replace `<TMDB_API_KEY>` with the TMDB API KEY we gathered. Now let's try the bot, by sending a movie name.

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1666590852520/1b-UXeM8D.png align="left")
Works perfectly, You can add more functions to it, but for now I am stopping it here.

# Summed up
We learnt to create a small bot using webhooks. I will add an article about host the bot, for free, on vercel. The entire code for the bot is available below.

```php
<?php
$content = file_get_contents ('php://input');
$update = json_decode ($content, true);
$chat_id = $update['message']['chat']['id'];
$message = $update['message']['text'];
$username = $update['message']['from']['username'];

if ($message == '/start') {
    send_message ($chat_id, "Hey @$username  \nsend me any query to search for the movie.");
} else {
    $req = file_get_contents("https://api.themoviedb.org/3/search/movie?api_key=<TMDB_API_KEY>&language=en-US&page=1&query=$message" );
    $movie = json_decode ( $req, true )['results'];
    if ($movie) {
        $movie = $movie[0];
        $title = $movie['title'];
        $overview = $movie['overview'];
        $popularity = $movie['popularity'];
        $release_date = $movie['release_date'];
        $vote_count = $movie['vote_count'];
        send_message($chat_id, "
    	Title: $title
		Description: $overview
		Popularity : $popularity
		Release Date : $release_date
		Votes: $vote_count");
    } 
    else {
        send_message($chat_id, "Couldn't find any movie with that name!");
    }
}

function send_message ($chat_id, $message) {
    $apiToken = <TELEGRAM_BOT_TOKEN>;
    $text = urlencode($message);
    file_get_contents("https://api.telegram.org/bot$apiToken/sendMessage?chat_id=$chat_id&text=$text");
}
?>
```

Thanks for reading.
