<?php
//Put Your telegrambot Toke in here
define('TOKEN','5198830189:AAEY2XLkRWgkmmZR_EcRtDidKGQDFGESwetrgd');
//setting menu
$line1 = array("MENU1","MENU2","MENU3");
$line2 = array("MENU4","MENU5","MENU6");
$line3 = array("MENU7","MENU8","MENU9");
$replyMarkup = array('keyboard' => array($line1,$line2,$line3),
"resize_keyboard" => true,"one_time_keyboard" => false);
$encodedMarkup = json_encode($replyMarkup);
//Function for send to api bot
function Send2Bot($command){
return 'https://api.telegram.org/bot'.TOKEN.'/'.$command;
}
function SendData2Bot($command,$data){
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data),
),
);
$context = stream_context_create($options);
$result = file_get_contents(Send2Bot($command), false, $context);
return $result;
}
function SendCurl($command,$data){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,Send2Bot($command));
curl_setopt($ch, CURLOPT_POST, count($data));
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec ($ch);
curl_close ($ch);
return $result;
}
/* Function to get update from api bot
use for long pooling method
*/
function GetUpdate($offset)
{
//send to Bot
$url = Send2Bot("getUpdates")."?offset=".$offset;
$result_send = file_get_contents($url);
//Get result and json decode
$result_json = json_decode($result_send, true);
if ($result_json["ok"]==1)
{
return $result_json["result"];
}
else
{
return array();
}
}
function RunningBot()
{
global $encodedMarkup;
$update_id = 0; //start with offset =0, offset set to file
//cek if there any file "belajarbot.last_update_id"
if (file_exists("belajarbot.last_update_id")) {
//if exist, read offsset
$update_id = (int)file_get_contents("belajarbot.last_update_id");
}
//get new update from ap bot
$updates = GetUpdate($update_id);
foreach ($updates as $message)
{
$receiveOK=false;
// var_dump($message);
$update_id = $message["update_id"];;
$message_data = $message["message"];
//jika terdapat text dari Pengirim
if (isset($message_data["text"])) {
$receiveOK=true;
$chatid = $message_data["chat"]["id"];
$message_id = $message_data["message_id"];
$text = $message_data["text"];
$data = array(
'chat_id' => $chatid,
'text' => 'You write message: ' . $text,
'parse_mode' => 'Markdown',
'reply_to_message_id' => $message_id
);
//ada menu
$data['reply_markup'] =$encodedMarkup;
//send message to api bot using curl
SendCurl('sendMessage',$data);
}
//update offset
if ($receiveOK){
file_put_contents("belajarbot.last_update_id", $update_id + 1);
}
}
}
//Main Program
while(true){
sleep(5); //delay 5 second
RunningBot();
}
No comments:
Post a Comment