0

I'm working with PHP to manage my Telegram Bot. Basically Telegram had added a feature which can lets users to get updates from their bots within this url:

https://api.telegram.org/bot[TOKEN_NUMBER]

Now I want to know, the bot that I'm going to search for, does exist or not.

So whenever you type the wrong Token Number of the bot, the API page returns this:

{"ok":false,"error_code":401,"description":"Unauthorized"}

And if exists the page returns this instead:

{"ok":true,"result":[]}

As you can see I have to get contents of a this page and determine some variables in order to know the existence of a bot. So, how can I do that with PHP ?

  • 1
    [curl](http://php.net/curl) or even easier using [file_get_contents](http://php.net/file_get_contents) ? – hassan Dec 05 '17 at 08:19

3 Answers3

4

you can use:

$content = file_get_contents($url);

or use cURL http://php.net/manual/en/curl.examples-basic.php

<?php

$ch = curl_init("http://www.example.com/");
$fp = fopen("example_homepage.txt", "w");

curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);

curl_exec($ch);
curl_close($ch);
fclose($fp);
?>
am05mhz
  • 2,727
  • 2
  • 23
  • 37
  • Great, but now I tested this `$ch = curl_init("https://api.telegram.org/bot".$token."/getUpdates");` and instead of writing `{"ok":false,"error_code":409,"description":"Conflict: can't use getUpdates method while webhook is active"}` (which is the current status of my bot update), it wrote: `{"ok":false,"error_code":404,"description":"Not Found"}` –  Dec 05 '17 at 08:36
  • try to echo/var_dump your url string, is it correctly formated? is there any missing `/`? – am05mhz Dec 05 '17 at 08:40
1

Try to use file_get_contents(), it will return whatever you see when opening the same URL in your browser. You could also have a look at the Composer packages that do so, such that you don't have to invent the wheel once more ;)

Nico Haase
  • 11,420
  • 35
  • 43
  • 69
0

Quick and easy two liner using get_headers

$headers=get_headers('https://api.telegram.org/bot/12345');
$active=$headers[0]=='HTTP/1.1 404 Not Found' ? false : true;

You can then use $active in a boolean logic test to either continue processing or abort.

if( $active ){/* do stuff */} else {/* go to the pub */}
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46