Sending images and tracking user count in PHP Telegram bot

I’m building a Telegram bot using PHP and need help with two specific features. Here’s my current code:

<?php
$input = json_decode(file_get_contents('php://input'));

function handleMessage($message) {
    if($message == 'Hello')
        $response = 'Hello there';
    if($message == 'What is your name?')
        $response = 'I am ChatBot';
    if($message == 'How are you?')
        $response = 'I am doing well, thank you';
}

$bot_token = '';
$api_url = 'https://api.telegram.org/bot'.$bot_token.'/sendMessage?chat_id='.$chat_id;
$api_url .= '&text=' .$response;
$result = file_get_contents($api_url);
?>

I need to add two more features:

  1. Image responses: How do I send a photo from a URL when users ask for it? I want to use PHP for this.

  2. User tracking: How can I store user IDs in a database and count total users? For example, when someone sends /stats command, the bot should reply with the member count. Each time a new user sends /start, it should add 1 to the total count.

quick tip - use sendPhoto instead of sendMessage for images. just switch your endpoint to /sendPhoto and add the photo parameter with your img url. for user counting, create a simple table with a user_id column. use INSERT IGNORE so u don’t get duplicates when people hit /start. then just SELECT COUNT(*) for ur /stats command. make sure u grab the chat_id from $input->message->chat->id first though.

Your code has a basic issue; you’re not extracting the chat_id and user_id from the $input object. Right now, $chat_id isn’t even defined. Use $chat_id = $input->message->chat->id and $user_id = $input->message->from->id. For sending images, instead of file_get_contents, use cURL, as it provides better error handling. Construct your sendPhoto URL by including the photo parameter that points to your image URL, then utilize curl_exec to send it. Regarding user tracking, consider adding a timestamp column alongside user_id in your users table to track when users first interacted with your bot, which can be beneficial for analytics. Additionally, ensure you verify whether the message exists before accessing its properties to prevent crashes when processing edited messages or other update types.

Your code’s missing a few things for those features. For sending images, ditch sendMessage and use sendPhoto instead. Your URL becomes: https://api.telegram.org/bot{$bot_token}/sendPhoto - just pass chat_id and photo (with your image URL). Use file_get_contents or cURL to make the request.

For tracking users, grab the user ID from $input->message->from->id. Set up a MySQL table with user_id as primary key so you don’t get duplicates, then use INSERT IGNORE when adding new users. When someone hits the stats command, just count the rows in that table. Don’t forget to pull chat_id from the incoming message - you’ll need it for both features to work.