首先需要有一个机器人拿到机器人token
token:68xxxx88:AAG5xxxxxxxx
想收到机器人的消息需要给bot设置一个回调地址
// 向telegram bot指定域名
public function setWebhook()
{
$url = 'https://api.telegram.org/bot' . $this->token . '/setWebhook';
$data = [
'url' => $this->callback. '?token=' . md5($this->token),
];
$result = $this->curl_post($url, $data);
}
这里token就是创建机器人时得到的token,callback为你自己的回调路径通过post发送给bot,$result返回信息会告诉你回调路径是否设置成功
// 接收bot回调信息
public function receive()
{
$input = file_get_contents('php://input');
$input = json_decode($input, true);
}
设置成功后每当bot接收到信息就会回调到receive方法,根据$input接收到的数据进行逻辑处理
// 删除回调
public function deleteWebhook()
{
$url = 'https://api.telegram.org/bot' . $this->token . '/deleteWebhook';
$data = [
'url' => $this->callback. '?token=' . md5($this->token),
];
$result = $this->curl_post($url, $data);
}
// 查看当前回调信息
public function getWebhookInfo()
{
$url = 'https://api.telegram.org/bot' . $this->token . '/getWebhookInfo';
$data = [
'url' => $this->callback. '?token=' . md5($this->token),
];
$result = $this->curl_post($url, $data);
}
// post
public function curl_post($url, $data)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
回复用户信息,可以在前面$input中拿到消息的chatid
// 回复用户信息
public function sendMessage($chatId, $text)
{
$url = 'https://api.telegram.org/bot' . $this->token . '/sendMessage';
$param = "?chat_id=".$chatId."&text=".$text;
$data = [
'chat_id' => $chatId,
'text' => $text,
];
$result = $this->curl_post($url, $data);
$result = json_decode($result, true);
if ($result['ok'] == true) {
return true;
} else {
$this->writeLog("error");
return false;
}
}
除此之外bot还有很多其他功能,详细可以了解telegram api