简体   繁体   English

使用php从电报机器人获取数据

[英]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... 它可以正常工作并从用户那里获取数据并显示名称,ID,但不显示用户电话号码,地址...

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语句添加到代码中:

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

Also you need to pass the "$contact" and "$name" variable to the "sendContact" function; 另外,您需要将“ $ contact”和“ $ name”变量传递给“ sendContact”函数; 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. 共享位置也一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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