Php curl telegram send message

Hey there! Today I’m going to let you know how to build the simplest webhook telegram bot on PHP.

Php curl telegram send message

⚠️ Requirements:

You need php 7.2+, cUrl extension anddomain with SSL certificate.You can use free SSL certificate from Let’s Encrypt certificate authority https://letsencrypt.org/getting-started

Step 0 — Problem Formulation

In this article we will create simple bot, that saves user data from chat with user and returns this data back to user. It’s going to happen after:

  • /start action: bot says “Hello” and describe his functions
  • /save action: saves name and surname of user
  • /me action: returns saved data about user, but only if user data was saved. In other case, it returns message that he’s don’t remember this user

We want interact with bot by input field, this type of bot perk called “Inline mode” and mean that interaction be via inline queries from the text input field in any chat. Telegram supports different bot perks, as: inline mode, payments platform, gaming platform, keyboards, commands, etc. If you want to know more about perks, see https://core.telegram.org/bots#5-bot-perks

My implementation of bot based on simple-telegram-bot library. Because there is no magic in there, you can see it yourself, just basic connection service and simple helpers.

Step 1 — A Bit of Theory

Bot is a special account without the required phone number. Users can interact with bots in two ways:

a) send messages and commands to the bot by using chat with it;

b) use @botname to add bot to groups and use it from there;

We use simple HTTPS-interface to communicate with Telegram API servers. Interface supports GET and POST HTTP methods. The response contains a JSON object, which always has a Boolean field ‘ok’ and may have an optional String field ‘description’ with a human-readable description of the result. You can read more information about making request here: https://core.telegram.org/bots/api#making-requests

To create any bot one should start with…talking. Talking to BotFather.After a few simple steps it sends your authorization token of your bot. More information you can find in https://core.telegram.org/bots#3-how-do-i-create-a-bot

Now time for getting updates from telegram, because our bot will react on them. Any bots can get updates in two ways:

  • using /getUpdate, which will return updates, only at the moment when it was called
  • using webhook, every action with bot will send the request to our application

The simple getUpdate is useful when you need to send notification to the user or group in telegram from our application after some action in it.

You need webhook when you want to use your bot not only for notification. It helps to create an automatic bot, that will communicate with users, immediately after user writes to bot. Full information about getting updates you can find here: https://core.telegram.org/bots/api#getting-updates

Php curl telegram send message

by Max Vegerchuk

[1–2] User sends the command to our bot

[2–3] Telegram application sends request to API

[3–4] Two ways of communication between application and Telegram API

  • [Case A]: using getUpdate — we can`t answer to user right after he sent command, so in this case just we can get updates only after some action on our application side
  • [Case B]: using webhook — we can communicate with the user on real time. Any updates of our bot will make requests to our application

Step 2 — Building…

Yey! We are ready to build it!

1. Go to the BotFather and get your Bot token and shhh… it`s a secret token.

2. As I said, we can work with Telegram API only by HTTS interface, so that`s why we need cUrl in our application. You can test it, by making this simple request from browser, just paste into url input: https://api.telegram.org/bot<SecretBotToken>/getMe

3. Now we need to create some connection service from here, we always will use cUrl connection, example:

define('BASIC_API_URL', 'https://api.telegram.org/bot<BOT_TOKEN>/');public function make(string $action): array 
{
$curlInit = curl_init();
curl_setopt($curlInit, CURLOPT_URL, BASIC_API_URL . $action);
$curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($curlInit);
return json_decode($output, true);
}

I used this CurlConnectionService which implements a ConnectionService interface.

4. For every action you will need a secret token, it will be used in url, like /getMe example. So imagine, that we have already created some method with сURL, which take a url for request. Then simple action will be like this:

$aboutMe = (new ConnectionService())->make('getMe');

And yes, result in $aboutMe will be in json format:

{
"ok": true,
"result": {
"id": <bot_id>,
"is_bot": true,
"first_name": "bot_name",
"username": "bot_username"
}
}

Okay, but what’s next? Now we need set a webhook, you need hosting with HTTPS URL. On that URL, you need the unique route or filename (.php) — this route or file will work as CORE handler for our bot.

1. Dialogflow V2 REST API Communication

2. A Conversation With My 35-year-old Chatbot (Part 1)

3. A ChatBot for ServiceNow using Amazon Connect, Lex and Lambda

4. Chatbot Conference 2020

This path to webhook must be secret (in security reasons), you can name it as your bot token, no one knows it, so it`s safe. Information about webhook setting: https://core.telegram.org/bots/api#setwebhook

You can simply setup webhook from the browser search input.

https://api.telegram.org/bot<SecretBotToken>/setWebhook?url=<webhookPageUrl>

In my case, I prepared helper for this thing: WebhookConfigurationHelper

5. From now, we can catch updates from bot, without reloading pages. Let’s prepare handler for this task:

// getting all data from incoming POST requestfile_get_contents("php://input");/*
* handle update as Associative array
* (or you can use object for this task)
*/
$update = json_decode($update, true);

All params, which ‘Update’ request contains, you can see in official docs: https://core.telegram.org/bots/api#update

We want to react on user commands. So we need to catch message data with sub params ‘chat’ and ‘text’, and exactly ‘text’ sub param we need.

switch ($update['text']) {
case '/start':
//some action
exit;
}

okay, now we react on user commad ‘/start’, let`s send him a message:

/*
* if user send /start command
* we answer hi!
*/
$connectionService->make(
'sendMessage?chat_id=' . $update['chat']['id'] . '&text=hi!'
);

After that you can test it on your bot. Just send him a message ‘/start’.

6. Now, we can catch commands as we want. Next — we need to create data saving service, feel free to do it on your own.

More information, what information you can get from available types read here: https://core.telegram.org/bots/api#available-types

How to send Telegram message using PHP?

To send a message to the Telegram channel use the following PHP script example: <? php $apiToken = "5082654068:AAF7quCLZ4xuTq2FBdo3POssdJsM_FRHwTs"; $data = [ 'chat_id' => '515382482', 'text' => 'Hello from PHP! ' ]; $response = file_get_contents("https://api.telegram.org/bot$apiToken/sendMessage?" .

Can Telegram BOT send message to channel?

Create a Telegram bot NOTE: Bots can't message people first, but can message channels.

Is there an API for Telegram?

We offer two kinds of APIs for developers. The Bot API allows you to easily create programs that use Telegram messages for an interface. The Telegram API and TDLib allow you to build your own customized Telegram clients.

Can Telegram BOT send message to phone number?

It is NOT possible for a bot to send messages to a phone number.