Commit 810cb1a3 authored by MBoretto's avatar MBoretto

fix

parent d29ab2b3
<?php
/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Longman\TelegramBot\Commands\UserCommands;
use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Conversation;
use Longman\TelegramBot\Entities\ReplyKeyboardHide;
use Longman\TelegramBot\Request;
/**
* User "/cancel" command
*
* This command cancels the currently active conversation and
* returns a message to let the user know which conversation it was.
* If no conversation is active, the returned message says so.
*/
class CancelCommand extends UserCommand
{
/**#@+
* {@inheritdoc}
*/
protected $name = 'cancel';
protected $description = 'Cancel the currently active conversation';
protected $usage = '/cancel';
protected $version = '0.1.1';
protected $need_mysql = true;
/**#@-*/
/**
* {@inheritdoc}
*/
public function execute()
{
$text = 'No active conversation!';
//Cancel current conversation if any
$conversation = new Conversation(
$this->getMessage()->getFrom()->getId(),
$this->getMessage()->getChat()->getId()
);
if ($conversation_command = $conversation->getCommand()) {
$conversation->cancel();
$text = 'Conversation "' . $conversation_command . '" cancelled!';
}
return $this->hideKeyboard($text);
}
/**
* {@inheritdoc}
*/
public function executeNoDb()
{
return $this->hideKeyboard();
}
/**
* Hide the keyboard and output a text
*
* @param string $text
*
* @return Entities\ServerResponse
*/
private function hideKeyboard($text = '')
{
return Request::sendMessage([
'reply_markup' => new ReplyKeyboardHide(['selective' => true]),
'chat_id' => $this->getMessage()->getChat()->getId(),
'text' => $text,
]);
}
}
<?php
/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Longman\TelegramBot\Commands\UserCommands;
use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Exception\TelegramException;
use Longman\TelegramBot\Request;
/**
* User "/date" command
*/
class DateCommand extends UserCommand
{
/**#@+
* {@inheritdoc}
*/
protected $name = 'date';
protected $description = 'Show date/time by location';
protected $usage = '/date <location>';
protected $version = '1.2.1';
protected $public = true;
/**#@-*/
/**
* Base URL for Google Maps API
*
* @var string
*/
private $base_url = 'https://maps.googleapis.com/maps/api';
/**
* Date format
*
* @var string
*/
private $date_format = 'd-m-Y H:i:s';
/**
* Get coordinates
*
* @param string $location
*
* @return array|boolean
*/
private function getCoordinates($location)
{
$url = $this->base_url . '/geocode/json?';
$params = 'address=' . urlencode($location);
$google_api_key = $this->getConfig('google_api_key');
if (!empty($google_api_key)) {
$params .= '&key=' . $google_api_key;
}
$data = $this->request($url . $params);
if (empty($data)) {
return false;
}
$data = json_decode($data, true);
if (empty($data)) {
return false;
}
if ($data['status'] !== 'OK') {
return false;
}
$lat = $data['results'][0]['geometry']['location']['lat'];
$lng = $data['results'][0]['geometry']['location']['lng'];
$acc = $data['results'][0]['geometry']['location_type'];
$types = $data['results'][0]['types'];
return [$lat, $lng, $acc, $types];
}
/**
* Get date
*
* @param string $lat
* @param string $lng
*
* @return array|boolean
*/
private function getDate($lat, $lng)
{
$url = $this->base_url . '/timezone/json?';
$date_utc = new \DateTime(null, new \DateTimeZone("UTC"));
$timestamp = $date_utc->format('U');
$params = 'location=' . urlencode($lat) . ',' . urlencode($lng) . '&timestamp=' . urlencode($timestamp);
$google_api_key = $this->getConfig('google_api_key');
if (!empty($google_api_key)) {
$params .= '&key=' . $google_api_key;
}
$data = $this->request($url . $params);
if (empty($data)) {
return false;
}
$data = json_decode($data, true);
if (empty($data)) {
return false;
}
if ($data['status'] !== 'OK') {
return false;
}
$local_time = $timestamp + $data['rawOffset'] + $data['dstOffset'];
return [$local_time, $data['timeZoneId']];
}
/**
* Get formatted date
*
* @param string $location
*
* @return string
*/
private function getFormattedDate($location)
{
if (empty($location)) {
return 'The time in nowhere is never';
}
list($lat, $lng, $acc, $types) = $this->getCoordinates($location);
if (empty($lat) || empty($lng)) {
return 'It seems that in "' . $location . '" they do not have a concept of time.';
}
list($local_time, $timezone_id) = $this->getDate($lat, $lng);
$date_utc = new \DateTime(gmdate('Y-m-d H:i:s', $local_time), new \DateTimeZone($timezone_id));
return 'The local time in ' . $timezone_id . ' is: ' . $date_utc->format($this->date_format);
}
/**
* Perform a simple cURL request
*
* @param string $url
*
* @return object
*/
private function request($url)
{
$ch = curl_init();
$curlConfig = [CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true];
curl_setopt_array($ch, $curlConfig);
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($http_code !== 200) {
throw new TelegramException('Error receiving data from url');
}
curl_close($ch);
return $response;
}
/**
* {@inheritdoc}
*/
public function execute()
{
$message = $this->getMessage();
$chat_id = $message->getChat()->getId();
$message_id = $message->getMessageId();
$text = $message->getText(true);
if (empty($text)) {
$text = 'You must specify location in format: /date <city>';
} else {
$date = $this->getformattedDate($text);
if (empty($date)) {
$text = 'Can not find date for location: ' . $text;
} else {
$text = $date;
}
}
$data = [
'chat_id' => $chat_id,
'reply_to_message_id' => $message_id,
'text' => $text,
];
return Request::sendMessage($data);
}
}
<?php
/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Longman\TelegramBot\Commands\UserCommands;
use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Request;
/**
* User "/slap" command
*/
class SlapCommand extends UserCommand
{
/**#@+
* {@inheritdoc}
*/
protected $name = 'slap';
protected $description = 'Slap someone with their username';
protected $usage = '/slap <@user>';
protected $version = '1.0.1';
/**#@-*/
/**
* {@inheritdoc}
*/
public function execute()
{
$message = $this->getMessage();
$chat_id = $message->getChat()->getId();
$message_id = $message->getMessageId();
$text = $message->getText(true);
$sender = '@' . $message->getFrom()->getUsername();
//username validation
$test = preg_match('/@[\w_]{5,}/', $text);
if ($test === 0) {
$text = $sender . ' sorry no one to slap around..';
} else {
$text = $sender . ' slaps ' . $text . ' around a bit with a large trout';
}
$data = [
'chat_id' => $chat_id,
'text' => $text,
];
return Request::sendMessage($data);
}
}
<?php
/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Longman\TelegramBot\Commands\UserCommands;
use Longman\TelegramBot\Request;
use Longman\TelegramBot\Conversation;
use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Entities\ForceReply;
use Longman\TelegramBot\Entities\ReplyKeyboardHide;
use Longman\TelegramBot\Entities\ReplyKeyboardMarkup;
/**
* User "/survery" command
*/
class SurveyCommand extends UserCommand
{
/**#@+
* {@inheritdoc}
*/
protected $name = 'survey';
protected $description = 'Survery for bot users';
protected $usage = '/survey';
protected $version = '0.1.1';
protected $need_mysql = true;
/**#@-*/
/**
* Conversation Object
*
* @var Longman\TelegramBot\Conversation
*/
protected $conversation;
/**
* {@inheritdoc}
*/
public function execute()
{
$message = $this->getMessage();
$chat = $message->getChat();
$user = $message->getFrom();
$text = $message->getText(true);
$chat_id = $chat->getId();
$user_id = $user->getId();
//Preparing Respose
$data = [];
if ($chat->isGroupChat() || $chat->isSuperGroup()) {
//reply to message id is applied by default
$data['reply_to_message_id'] = $message_id;
//Force reply is applied by default to so can work with privacy on
$data['reply_markup'] = new ForceReply([ 'selective' => true]);
}
$data['chat_id'] = $chat_id;
//Conversation start
$this->conversation = new Conversation($user_id, $chat_id, $this->getName());
//cache data from the tracking session if any
if (!isset($this->conversation->notes['state'])) {
$state = '0';
} else {
$state = $this->conversation->notes['state'];
}
//state machine
//entrypoint of the machine state if given by the track
//Every time the step is achived the track is updated
switch ($state) {
case 0:
if (empty($text)) {
$this->conversation->notes['state'] = 0;
$this->conversation->update();
$data['text'] = 'Type your name:';
$data['reply_markup'] = new ReplyKeyBoardHide(['selective' => true]);
$result = Request::sendMessage($data);
break;
}
$this->conversation->notes['name'] = $text;
$text = '';
// no break
case 1:
if (empty($text)) {
$this->conversation->notes['state'] = 1;
$this->conversation->update();
$data['text'] = 'Type your surname:';
$result = Request::sendMessage($data);
break;
}
$this->conversation->notes['surname'] = $text;
++$state;
$text = '';
// no break
case 2:
if (empty($text) || !is_numeric($text)) {
$this->conversation->notes['state'] = 2;
$this->conversation->update();
$data['text'] = 'Type your age:';
if (!empty($text) && !is_numeric($text)) {
$data['text'] = 'Type your age, must be a number';
}
$result = Request::sendMessage($data);
break;
}
$this->conversation->notes['age'] = $text;
$text = '';
// no break
case 3:
if (empty($text) || !($text == 'M' || $text == 'F')) {
$this->conversation->notes['state'] = 3;
$this->conversation->update();
$keyboard = [['M','F']];
$reply_keyboard_markup = new ReplyKeyboardMarkup(
[
'keyboard' => $keyboard ,
'resize_keyboard' => true,
'one_time_keyboard' => true,
'selective' => true
]
);
$data['reply_markup'] = $reply_keyboard_markup;
$data['text'] = 'Select your gender:';
if (!empty($text) && !($text == 'M' || $text == 'F')) {
$data['text'] = 'Select your gender, choose a keyboard option:';
}
$result = Request::sendMessage($data);
break;
}
$this->conversation->notes['gender'] = $text;
$text = '';
// no break
case 4:
if (is_null($message->getLocation())) {
$this->conversation->notes['state'] = 4;
$this->conversation->update();
$data['text'] = 'Insert your home location (need location object):';
$data['reply_markup'] = new ReplyKeyBoardHide(['selective' => true]);
$result = Request::sendMessage($data);
break;
}
$this->conversation->notes['longitude'] = $message->getLocation()->getLongitude();
$this->conversation->notes['latitude'] = $message->getLocation()->getLatitude();
// no break
case 5:
if (is_null($message->getPhoto())) {
$this->conversation->notes['state'] = 5;
$this->conversation->update();
$data['text'] = 'Insert your picture:';
$result = Request::sendMessage($data);
break;
}
$this->conversation->notes['photo_id'] = $message->getPhoto()[0]->getFileId();
// no break
case 6:
$out_text = '/Survey result:' . "\n";
unset($this->conversation->notes['state']);
foreach ($this->conversation->notes as $k => $v) {
$out_text .= "\n" . ucfirst($k).': ' . $v;
}
$data['photo'] = $this->conversation->notes['photo_id'];
$data['reply_markup'] = new ReplyKeyBoardHide(['selective' => true]);
$data['caption'] = $out_text;
$this->conversation->stop();
$result = Request::sendPhoto($data);
break;
}
return $result;
}
}
<?php
/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Longman\TelegramBot\Commands\UserCommands;
use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Request;
/**
* User "/weather" command
*/
class WeatherCommand extends UserCommand
{
/**#@+
* {@inheritdoc}
*/
protected $name = 'weather';
protected $description = 'Show weather by location';
protected $usage = '/weather <location>';
protected $version = '1.0.1';
protected $public = true;
/**#@-*/
/**
* Get weather using cURL request
*
* @param string $location
*
* @return object
*/
private function getWeather($location)
{
$url = 'http://api.openweathermap.org/data/2.5/weather?q=' . $location . '&units=metric';
$ch = curl_init();
$curlConfig = [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
];
curl_setopt_array($ch, $curlConfig);
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($http_code !== 200) {
throw new \Exception('Error receiving data from url');
}
curl_close($ch);
return $response;
}
/**
* Get weather string
*
* @param string $location
*
* @return bool|string
*/
private function getWeatherString($location)
{
if (empty($location)) {
return false;
}
try {
$data = $this->getWeather($location);
$decode = json_decode($data, true);
if (empty($decode) || $decode['cod'] != 200) {
return false;
}
$city = $decode['name'];
$country = $decode['sys']['country'];
$temp = 'The temperature in ' . $city . ' (' . $country . ') is ' . $decode['main']['temp'] . '°C';
$conditions = 'Current conditions are: ' . $decode['weather'][0]['description'];
switch (strtolower($decode['weather'][0]['main'])) {
case 'clear':
$conditions .= ' ☀';
break;
case 'clouds':
$conditions .= ' ☁☁';
break;
case 'rain':
$conditions .= ' ☔';
break;
case 'thunderstorm':
$conditions .= ' ☔☔☔☔';
break;
}
$result = $temp . "\n" . $conditions;
} catch (\Exception $e) {
$result = '';
}
return $result;
}
/**
* {@inheritdoc}
*/
public function execute()
{
$message = $this->getMessage();
$chat_id = $message->getChat()->getId();
$message_id = $message->getMessageId();
$text = $message->getText(true);
if (empty($text)) {
$text = 'You must specify location in format: /weather <city>';
} else {
$weather = $this->getWeatherString($text);
if (empty($weather)) {
$text = 'Can not find weather for location: ' . $text;
} else {
$text = $weather;
}
}
$data = [
'chat_id' => $chat_id,
'reply_to_message_id' => $message_id,
'text' => $text,
];
return Request::sendMessage($data);
}
}
<?php
/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* Written by Marco Boretto <marco.bore@gmail.com>
*/
namespace Longman\TelegramBot\Commands\UserCommands;
use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Entities\File;
use Longman\TelegramBot\Request;
/**
* User "/whoami" command
*/
class WhoamiCommand extends UserCommand
{
/**#@+
* {@inheritdoc}
*/
protected $name = 'whoami';
protected $description = 'Show your id, name and username';
protected $usage = '/whoami';
protected $version = '1.0.1';
protected $public = true;
/**#@-*/
/**
* {@inheritdoc}
*/
public function execute()
{
$message = $this->getMessage();
$user_id = $message->getFrom()->getId();
$chat_id = $message->getChat()->getId();
$message_id = $message->getMessageId();
$text = $message->getText(true);
//Send chat action
Request::sendChatAction(['chat_id' => $chat_id, 'action' => 'typing']);
$caption = 'Your Id: ' . $user_id . "\n";
$caption .= 'Name: ' . $message->getFrom()->getFirstName()
. ' ' . $message->getFrom()->getLastName() . "\n";
$caption .= 'Username: ' . $message->getFrom()->getUsername();
//Fetch user profile photo
$limit = 10;
$offset = null;
$ServerResponse = Request::getUserProfilePhotos([
'user_id' => $user_id ,
'limit' => $limit,
'offset' => $offset,
]);
//Check if the request isOK
if ($ServerResponse->isOk()) {
$UserProfilePhoto = $ServerResponse->getResult();
$totalcount = $UserProfilePhoto->getTotalCount();
} else {
$totalcount = 0;
}
$data = [
'chat_id' => $chat_id,
'reply_to_message_id' => $message_id,
];
if ($totalcount > 0) {
$photos = $UserProfilePhoto->getPhotos();
//I pick the latest photo with the hight definition
$photo = $photos[0][2];
$file_id = $photo->getFileId();
$data['photo'] = $file_id;
$data['caption'] = $caption;
$result = Request::sendPhoto($data);
//Download the image pictures
//Download after send message response to speedup response
$file_id = $photo->getFileId();
$ServerResponse = Request::getFile(['file_id' => $file_id]);
if ($ServerResponse->isOk()) {
Request::downloadFile($ServerResponse->getResult());
}
} else {
//No Photo just send text
$data['text'] = $caption;
$result = Request::sendMessage($data);
}
return $result;
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment