简体   繁体   中英

get data from telegram bot with php

I have the following code to make telegram bot :

<?php
define('API_KEY','*****');
function makereq($method,$datas=[]){
    $url = "https://api.telegram.org/bot".API_KEY."/".$method;
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch,CURLOPT_POSTFIELDS,http_build_query($datas));
    $res = curl_exec($ch);
    if(curl_error($ch)){
        var_dump(curl_error($ch));
    }else{
        return json_decode($res);
    }
}
$result=json_decode($message,true);
//##############=--API_REQ
function apiRequest($method, $parameters) {
  if (!is_string($method)) {
    error_log("Method name must be a string\n");
    return false;
  }
  if (!$parameters) {
    $parameters = array();
  } else if (!is_array($parameters)) {
    error_log("Parameters must be an array\n");
    return false;
  }
  foreach ($parameters as $key => &$val) {
    // encoding to JSON array parameters, for example reply_markup
    if (!is_numeric($val) && !is_string($val)) {
      $val = json_encode($val);
    }
  }
  $url = "https://api.telegram.org/bot".API_KEY."/".$method.'?'.http_build_query($parameters);
  $handle = curl_init($url);
  curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 5);
  curl_setopt($handle, CURLOPT_TIMEOUT, 60);
  return exec_curl_request($handle);
}
//----######------
//---------
$update = json_decode(file_get_contents('php://input'));
var_dump($update);
$messages = $update->message;
//=========
$chat_id = $messages->chat->id;
$message_id = $update->callback_query->message->message_id;
$from_id = $messages->from->id;
$name = $messages->from->first_name;
$username = $messages->from->username;
$t = isset($messages->text)?$messages->text:'';
$reply = $messages->reply_to_message->forward_from->id;
$sticker = $messages->sticker;
$text = $messages->text;
$data = $update->callback_query->data;
$forward = $messages->forward_from;
$location = $messages->location->longitude;
$contact = $messages->contact->phone_number;
$admin = 88120404;

//-------
function SendMessage($chat_id, $TextMsg)
{
 makereq('sendMessage',[
'chat_id'=>$chat_id,
'text'=>$TextMsg,
'parse_mode'=>"MarkDown"
]);
}
function SendContact($chat_id, $contactMsg)
{
 makereq('sendContact',[
'chat_id'=>$chat_id,
'phone_number'=>$contact,
'first_name'=>$name
]);
}
function SendSticker($chat_id, $sticker_ID)
{
 makereq('sendSticker',[
'chat_id'=>$chat_id,
'sticker'=>$sticker_ID
]);
}
function bots($method,$datas=[]){
    $url = "https://api.telegram.org/bot".API_KEY."/".$method;
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch,CURLOPT_POSTFIELDS,$datas);
    $res = curl_exec($ch);
    if(curl_error($ch)){
        var_dump(curl_error($ch));
    }else{
        return json_decode($res);
    }
}
function typing($chat_id)
{
file_get_contents(API_TELEGRAM.'sendChatAction?chat_id='.$chat_id.'&action=typing');
}
function Forward($KojaShe,$AzKoja,$KodomMSG)
{
makereq('ForwardMessage',[
'chat_id'=>$KojaShe,
'from_chat_id'=>$AzKoja,
'message_id'=>$KodomMSG
]);
}
function save($filename,$TXTdata)
  {
  $myfile = fopen($filename, "w") or die("Unable to open file!");
  fwrite($myfile, "$TXTdata");
  fclose($myfile);
  }
//==========

if($t == "test1"){
var_dump(makereq('sendMessage',[
        'chat_id'=>$chat_id,
        'text'=>"Okay Share Your Number, Location And Your Zip Code",
        'parse_mode'=>'MarkDown',
        'reply_markup'=>json_encode([
            'keyboard'=>[
              [
               ['text'=>"Zip Code"],['text'=>"Address",'request_location'=>true], ['text'=>"Phone Number",'request_contact'=>true]
              ],
              [
                ['text'=>"Done!"]
              ],
            ],
            'resize_keyboard'=>true
        ])
    ]));  
}
if($t == "Done!"){
var_dump(makereq('sendMessage',[
'chat_id'=>$Admin,
'text'=>"Hey some one just submit in our bot:
name 👤 : $name
id 🗣 : @$username
phone number 📱 : $contact
address 📫 : $location 
zip code 📦 : 
",
])); 
 }
?>

It works fine and get data from users and shows name, ID, but it does not show the user Phone number, address...

I guess my code is fine ( base on this documantions ), I just don't know why it's not working and does not show phone number and address.

If anyone know where my problem is, help me to solve it, thanks. Sorry for bad english.

You are not handling the share contact update. when a user shares his/her contact, its just like another update that need to be handled. for example you need to add this if statement to your code:

if(isset($contact)){
    SendContact($chat_id, $contact, $name);
}

Also you need to pass the "$contact" and "$name" variable to the "sendContact" function; as these variable are global (you defined them outside of a fucntion) they can only be accessed outside a function.

function SendContact($chat_id, $contact, $name)
{
    makereq('sendContact', [
        'chat_id' => $chat_id,
        'phone_number' => $contact,
        'first_name' => $name
    ]);
}

the same for sharing location.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM