Skip to content

Instantly share code, notes, and snippets.

@misterx

misterx/bot.php Secret

Created March 1, 2015 10:03
Show Gist options
  • Save misterx/48fb01a574936aa19b63 to your computer and use it in GitHub Desktop.
Save misterx/48fb01a574936aa19b63 to your computer and use it in GitHub Desktop.
<?php
class Bot{
protected $key = null;
protected $session = null;
private $salt = 'some very-very long string without any non-latin characters due to different string representations inside of variable programming languages';
/**
* @param $key - Ключ из урла после создания инфа
*/
public function __construct($key){
$this->key = $key;
}
/**
* @param null $session - Идентификатор сессии существуюющей, если нет то создается новая
* @return string Идентификатор текущей сессии
*/
public function session($session=null){
if($session === null){
$response = file_get_contents('http://iii.ru/api/2.0/json/Chat.init/'.$this->key.'/');
$this->session = $this->decode($response)->result->cuid;
}else{
$this->session = $session;
}
return $this->session;
}
/**
* ОТправить сообщение боту
* @param string $message Сообщение
* @return string Ответ
*/
public function say($message){
$request = '["'.$this->session.'","'.$message.'"]';
$myCurl = curl_init();
curl_setopt_array($myCurl, array(
CURLOPT_URL => 'http://iii.ru/api/2.0/json/Chat.request',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $this->encode($request)
));
$response = curl_exec($myCurl);
curl_close($myCurl);
return $this->decode($response)->result->text->tts;
}
/**
* Кодирование сообщения
* @param $message
* @return string
*/
private function encode($message){
$message = base64_encode($message);
$ml = strlen($message);
$kl = strlen($this->salt);
$encoded = "";
for ($i = 0; $i < $ml; $i++) {
$encoded = $encoded . ($message[$i] ^ $this->salt[$i % $kl]);
}
return base64_encode($encoded);
}
/**
* Декодирование сообщения
* @param $message
* @return mixed|null
*/
private function decode($message){
$msg = base64_decode($message);
$ml = strlen($msg);
$kl = strlen($this->salt);
$decoded = "";
for ($i = 0; $i < $ml; $i++) {
$decoded.= ($msg[$i] ^ $this->salt[$i % $kl]);
}
return json_decode(base64_decode($decoded));
}
}
<?php
define('VK_TOKEN','Токен вконтакте');
define('BOT_TOKEN','Идентификатор бота с iii.ru');
include "vk.php";
include "bot.php";
$vk = new VK(VK_TOKEN);
$bot = new Bot(BOT_TOKEN);
$session = $bot->session();
write('Bot session:'.$session);
while(true){
foreach($vk->unread() as $message){
write("Request:".$message->message->body);
$vk->markAsRead($message->message->user_id);
sleep(4);
$vk->setActivity($message->message->user_id);
sleep(4);
$response = $bot->say($message->message->body);
$vk->sendMessage($message->message->user_id,$response);
write("Response:".$response);
$vk->ping();
}
sleep(5);
}
function write($text = ''){
echo $text."\n";
}
<?php
class VK{
/**
* Токен
* @var string
*/
private $token = '';
/**
* @param string $token Токен
*/
public function __construct($token){
$this->token = $token;
}
/**
* Уведомить об онлайне
*/
public function ping(){
$this->request('account.setOnline');
}
/**
* Получить список диалогов
* @return mixed|null
*/
public function dialogs(){
return $this->request('messages.getDialogs',['count'=>10]);
}
/**
* Получить список не прочитаных диалогов
* @return array
*/
public function unread(){
$response = $this->request('messages.getDialogs',['count'=>10,'unread'=>1]);
if(!property_exists($response,'response')){
return array();
}else{
return $response->response->items;
}
}
/**
* Отметить как прочитаное
* @param int $userID Идентификатор пользователя
* @return mixed|null
*/
public function markAsRead($userID){
return $this->request('messages.markAsRead',['peer_id'=>$userID]);
}
/**
* Показать активность
* @param int $userID Идентификатор пользователя
* @param string $type Тип уведомления
* @return mixed|null
*/
public function setActivity($userID,$type='typing'){
return $this->request('messages.setActivity',['user_id'=>$userID,'type'=>$type]);
}
/**
* Отправить сообщение пользователю
* @param int $userID Идентификатор пользователя
* @param string $message Сообщение
* @return mixed|null
*/
public function sendMessage($userID,$message){
return $this->request('messages.send',['message'=>$message,'user_id'=>$userID]);
}
/**
* Запрос к VK
* @param string $method Метод
* @param array $params Параметры
* @return mixed|null
*/
private function request($method,$params=array()){
$url = 'https://api.vk.com/method/'.$method;
$params['access_token']=$this->token;
$params['v']='5.28';
return json_decode(file_get_contents($url.'?'.http_build_query($params)));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment