Commit e12ffd6c authored by MBoretto's avatar MBoretto

Merge branch 'master' into feature/externalconnection

parents 546d62ac 999ee2e7
sudo: false
language: php
php:
......@@ -6,7 +8,17 @@ php:
- 7.0
- hhvm
sudo: false
matrix:
allow_failures:
- php: hhvm
fast_finish: true
notifications:
on_success: never
on_failure: always
git:
depth: 1
before_install:
- composer self-update
......@@ -14,17 +26,9 @@ before_install:
install:
- travis_retry composer install --no-interaction
before_script:
- mysql -e 'create database telegrambot; use telegrambot; source structure.sql;'
script:
- vendor/bin/phpunit
- sh -c "if [ '$TRAVIS_PHP_VERSION' != '7.0' ]; then vendor/bin/phpcs --report=full --extensions=php -np --standard=build/phpcs .; fi"
matrix:
allow_failures:
- php: hhvm
- php: 7.0
fast_finish: true
notifications:
on_success: never
on_failure: always
- vendor/bin/phpcs --report=full --extensions=php -np --standard=build/phpcs .
......@@ -28,7 +28,8 @@ The Bot can:
- handle commands in chat with other bots.
- manage Channel from the bot admin interface.
- full support for **inline bots**. (**new!**)
- Messages, InlineQuery and ChosenInlineQuery are stored in the Database. (**new!**)
- Messages, InlineQuery and ChosenInlineQuery are stored in the Database.
- Conversation feature (**new!**)
-----
This code is available on
......@@ -354,7 +355,7 @@ $telegram->enableExternalMySQL($external_pdo_connection)
### Channels Support
All methods implemented can be used to manage channels.
With [admin commands](#admin-commands) you can manage your channel directly with your bot private chat.
With [admin commands](#admin-commands) you can manage your channels directly with your bot private chat.
### Commands
......@@ -403,7 +404,7 @@ $telegram->setCommandConfig('date', ['google_api_key' => 'your_google_api_key_he
Enabling this feature, the admin bot can perform some super user commands like:
- Send message to all chats */sendtoall*
- List all the chats started with the bot */chats*
- Send a message to a channel */sendtochannel* (NEW! see below how to configure it)
- Post any content to your channels */sendtochannel* (NEW! see below how to configure it)
You can specify one or more admins with this option:
```php
......@@ -420,7 +421,11 @@ To enable this feature follow these steps:
- Enable admin interface for your user as explained in the admin section above.
- Enter your channel name as a parameter for the */sendtochannel* command:
```php
$telegram->setCommandConfig('sendtochannel', ['your_channel' => '@type_here_your_channel']);
$telegram->setCommandConfig('sendtochannel', ['your_channel' => ['@type_here_your_channel']]);
```
- If you want to manage more channels:
```php
$telegram->setCommandConfig('sendtochannel', ['your_channel'=>['@type_here_your_channel', '@type_here_another_channel', '@and_so_on']]);
```
- Enjoy!
......
<?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.bore@gmail.com>
*/
namespace Longman\TelegramBot\Commands;
*/
use Longman\TelegramBot\Request;
use Longman\TelegramBot\Command;
use Longman\TelegramBot\Entities\Update;
namespace Longman\TelegramBot\Commands\UserCommands;
use Longman\TelegramBot\Entities\ReplyKeyboardMarkup;
use Longman\TelegramBot\Entities\ReplyKeyboardHide;
use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Request;
use Longman\TelegramBot\Entities\ForceReply;
class ForceReplyCommand extends Command
/**
* User "/forcereply" command
*/
class ForceReplyCommand extends UserCommand
{
/**#@+
* {@inheritdoc}
*/
protected $name = 'forcereply';
protected $description = 'Force reply with reply markup';
protected $usage = '/forcereply';
protected $version = '0.0.5';
protected $enabled = true;
/**#@-*/
/**
* {@inheritdoc}
*/
public function execute()
{
$update = $this->getUpdate();
$message = $this->getMessage();
$message_id = $message->getMessageId();
$chat_id = $message->getChat()->getId();
$text = $message->getText(true);
$data = array();
$data = [];
$data['chat_id'] = $chat_id;
$data['text'] = 'Write something:';
#$data['reply_to_message_id'] = $message_id;
$force_reply = new ForceReply(['selective' => false]);
#echo $json;
$data['reply_markup'] = $force_reply;
$data['reply_markup'] = new ForceReply(['selective' => false]);
$result = Request::sendMessage($data);
return $result;
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;
*/
use Longman\TelegramBot\Request;
use Longman\TelegramBot\Command;
use Longman\TelegramBot\Entities\Update;
namespace Longman\TelegramBot\Commands\UserCommands;
use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Request;
use Longman\TelegramBot\Entities\ReplyKeyboardMarkup;
use Longman\TelegramBot\Entities\ReplyKeyboardHide;
use Longman\TelegramBot\Entities\ForceReply;
class HidekeyboardCommand extends Command
/**
* User "/hidekeyboard" command
*/
class HidekeyboardCommand extends UserCommand
{
/**#@+
* {@inheritdoc}
*/
protected $name = 'hidekeyboard';
protected $description = 'Hide the custom keyboard';
protected $usage = '/hidekeyboard';
protected $version = '0.0.5';
protected $enabled = true;
/**#@-*/
/**
* {@inheritdoc}
*/
public function execute()
{
$update = $this->getUpdate();
$message = $this->getMessage();
$message_id = $message->getMessageId();
$chat_id = $message->getChat()->getId();
$text = $message->getText(true);
$data = array();
$data = [];
$data['chat_id'] = $chat_id;
$data['text'] = 'Keyboard Hided';
#$data['reply_to_message_id'] = $message_id;
$reply_keyboard_hide = new ReplyKeyboardHide([ 'selective' => false]);
$data['reply_markup'] = $reply_keyboard_hide;
$data['reply_markup'] = new ReplyKeyboardHide([ 'selective' => false]);
$result = Request::sendMessage($data);
return $result;
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;
*/
namespace Longman\TelegramBot\Commands\UserCommands;
use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Request;
use Longman\TelegramBot\Command;
use Longman\TelegramBot\Entities\Update;
use Longman\TelegramBot\Entities\ReplyKeyboardMarkup;
class ImageCommand extends Command
/**
* User "/image" command
*/
class ImageCommand extends UserCommand
{
/**#@+
* {@inheritdoc}
*/
protected $name = 'image';
protected $description = 'Send Image';
protected $usage = '/image';
protected $version = '1.0.0';
protected $enabled = true;
protected $public = true;
/**#@-*/
/**
* {@inheritdoc}
*/
public function execute()
{
$update = $this->getUpdate();
$message = $this->getMessage();
$chat_id = $message->getChat()->getId();
$text = $message->getText(true);
$data = array();
$data = [];
$data['chat_id'] = $chat_id;
$data['caption'] = $text;
//$result = Request::sendDocument($data,'structure.sql');
//$result = Request::sendSticker($data, $this->telegram->getUploadPath().'/'.'image.jpg');
$result = Request::sendPhoto($data, $this->telegram->getUploadPath().'/'.'image.jpg');
return $result;
return Request::sendPhoto($data, $this->telegram->getUploadPath().'/'.'image.jpg');
}
}
<?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;
*/
use Longman\TelegramBot\Request;
use Longman\TelegramBot\Command;
use Longman\TelegramBot\Entities\Update;
namespace Longman\TelegramBot\Commands\UserCommands;
use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Request;
use Longman\TelegramBot\Entities\ReplyKeyboardMarkup;
use Longman\TelegramBot\Entities\ReplyKeyboardHide;
use Longman\TelegramBot\Entities\ForceReply;
class KeyboardCommand extends Command
/**
* User "/keyboard" command
*/
class KeyboardCommand extends UserCommand
{
/**#@+
* {@inheritdoc}
*/
protected $name = 'keyboard';
protected $description = 'Show a custom keybord with reply markup';
protected $usage = '/keyboard';
protected $version = '0.0.5';
protected $enabled = true;
/**#@-*/
/**
* {@inheritdoc}
*/
public function execute()
{
$update = $this->getUpdate();
$message = $this->getMessage();
$message_id = $message->getMessageId();
$chat_id = $message->getChat()->getId();
$text = $message->getText(true);
$data = array();
$data = [];
$data['chat_id'] = $chat_id;
$data['text'] = 'Press a Button:';
#$data['reply_to_message_id'] = $message_id;
#Keyboard examples
$keyboards = array();
//Keyboard examples
$keyboards = [];
//0
$keyboard[] = ['7','8','9'];
......@@ -64,7 +62,6 @@ class KeyboardCommand extends Command
$keyboards[] = $keyboard;
unset($keyboard);
//2
$keyboard[] = ['A'];
$keyboard[] = ['B'];
......@@ -73,8 +70,6 @@ class KeyboardCommand extends Command
$keyboards[] = $keyboard;
unset($keyboard);
//3
$keyboard[] = ['A'];
$keyboard[] = ['B'];
......@@ -83,8 +78,7 @@ class KeyboardCommand extends Command
$keyboards[] = $keyboard;
unset($keyboard);
$reply_keyboard_markup = new ReplyKeyboardMarkup(
$data['reply_markup'] = new ReplyKeyboardMarkup(
[
'keyboard' => $keyboards[1] ,
'resize_keyboard' => true,
......@@ -92,10 +86,7 @@ class KeyboardCommand extends Command
'selective' => false
]
);
#echo $json;
$data['reply_markup'] = $reply_keyboard_markup;
$result = Request::sendMessage($data);
return $result;
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;
use Longman\TelegramBot\Command;
use Longman\TelegramBot\Request;
/**
* Admin "/sendtochannel" command
*/
class SendtochannelCommand extends Command
{
/**#@+
* {@inheritdoc}
*/
protected $name = 'sendtochannel';
protected $description = 'Send message to a channel';
protected $usage = '/sendchannel <message to send>';
protected $version = '0.1.1';
protected $public = true;
protected $need_mysql = false;
/**#@-*/
/**
* Execute command
*
* @todo Don't use empty, as a string of '0' is regarded to be empty
*
* @return boolean
*/
public function execute()
{
$message = $this->getMessage();
$chat_id = $message->getChat()->getId();
$text = $message->getText(true);
if (empty($text)) {
$text_back = 'Write the message to send: /sendtochannel <message>';
} else {
$your_channel = $this->getConfig('your_channel');
//Send message to channel
$data = [
'chat_id' => $your_channel,
'text' => $text,
];
$result = Request::sendMessage($data);
if ($result->isOk()) {
$text_back = 'Message sent succesfully to: ' . $your_channel;
} else {
$text_back = 'Sorry message not sent to: ' . $your_channel;
}
}
$data = [
'chat_id' => $chat_id,
'text' => $text_back,
];
return Request::sendMessage($data)->isOk();
}
}
<?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;
/**
* Abstract Admin Command Class
*/
abstract class AdminCommand extends Command
{
}
......@@ -8,9 +8,9 @@
* file that was distributed with this source code.
*/
namespace Longman\TelegramBot\Commands;
namespace Longman\TelegramBot\Commands\AdminCommands;
use Longman\TelegramBot\Command;
use Longman\TelegramBot\Commands\AdminCommand;
use Longman\TelegramBot\DB;
use Longman\TelegramBot\Entities\Chat;
use Longman\TelegramBot\Request;
......@@ -18,7 +18,7 @@ use Longman\TelegramBot\Request;
/**
* Admin "/chats" command
*/
class ChatsCommand extends Command
class ChatsCommand extends AdminCommand
{
/**#@+
* {@inheritdoc}
......@@ -27,33 +27,11 @@ class ChatsCommand extends Command
protected $description = 'List all chats stored by the bot';
protected $usage = '/chats';
protected $version = '1.0.1';
protected $public = true;
protected $need_mysql = false;
/**#@-*/
/**
* Execution if MySQL is required but not available
*
* @return boolean
*/
public function executeNoDB()
{
//Preparing message
$message = $this->getMessage();
$chat_id = $message->getChat()->getId();
$data = [
'chat_id' => $chat_id,
'text' => 'Sorry no database connection, unable to execute "' . $this->name . '" command.',
];
return Request::sendMessage($data)->isOk();
}
/**
* Execute command
*
* @return boolean
* {@inheritdoc}
*/
public function execute()
{
......@@ -105,6 +83,6 @@ class ChatsCommand extends Command
'text' => $text,
];
return Request::sendMessage($data)->isOk();
return Request::sendMessage($data);
}
}
......@@ -8,46 +8,26 @@
* file that was distributed with this source code.
*/
namespace Longman\TelegramBot\Commands;
namespace Longman\TelegramBot\Commands\AdminCommands;
use Longman\TelegramBot\Command;
use Longman\TelegramBot\Commands\AdminCommand;
use Longman\TelegramBot\Request;
/**
* Admin "/sendtoall" command
*/
class SendtoallCommand extends Command
class SendtoallCommand extends AdminCommand
{
/**#@+
* {@inheritdoc}
*/
protected $name = 'sendtoall';
protected $description = 'Send the message to all the user\'s bot';
protected $usage = '/sendall <message to send>';
protected $usage = '/sendtoall <message to send>';
protected $version = '1.2.1';
protected $public = true;
protected $need_mysql = true;
/**#@-*/
/**
* Execution if MySQL is required but not available
*
* @return boolean
*/
public function executeNoDB()
{
//Preparing message
$message = $this->getMessage();
$chat_id = $message->getChat()->getId();
$data = [
'chat_id' => $chat_id,
'text' => 'Sorry no database connection, unable to execute "' . $this->name . '" command.',
];
return Request::sendMessage($data)->isOk();
}
/**
* Execute command
*
......@@ -60,9 +40,10 @@ class SendtoallCommand extends Command
$message = $this->getMessage();
$chat_id = $message->getChat()->getId();
$text = $message->getText(true);
if (empty($text)) {
$text = 'Write the message to send: /sendall <message>';
$text = 'Write the message to send: /sendtoall <message>';
} else {
$results = Request::sendToActiveChats(
'sendMessage', //callback function to execute (see Request.php methods)
......@@ -103,9 +84,10 @@ class SendtoallCommand extends Command
$text .= $tot . ') ' . $status . ' ' . $type . ' ' . $name . "\n";
}
$text .= 'Delivered: ' . ($tot - $fail) . '/' . $tot . "\n";
}
if ($tot === 0) {
$text = 'No users or chats found..';
if ($tot === 0) {
$text = 'No users or chats found..';
}
}
$data = [
......@@ -113,6 +95,6 @@ class SendtoallCommand extends Command
'text' => $text,
];
return Request::sendMessage($data)->isOk();
return Request::sendMessage($data);
}
}
This diff is collapsed.
......@@ -8,14 +8,17 @@
* file that was distributed with this source code.
*/
namespace Longman\TelegramBot;
namespace Longman\TelegramBot\Commands;
use Longman\TelegramBot\DB;
use Longman\TelegramBot\Request;
use Longman\TelegramBot\Telegram;
use Longman\TelegramBot\Entities\Chat;
use Longman\TelegramBot\Entities\Update;
use Longman\TelegramBot\Entities\User;
/**
* Class Command
* Abstract Command Class
*/
abstract class Command
{
......@@ -40,13 +43,6 @@ abstract class Command
*/
protected $message;
/**
* Command
*
* @var string
*/
protected $command;
/**
* Name
*
......@@ -59,7 +55,7 @@ abstract class Command
*
* @var string
*/
protected $description = 'Command help';
protected $description = 'Command description';
/**
* Usage
......@@ -82,13 +78,6 @@ abstract class Command
*/
protected $enabled = true;
/**
* If this command is public
*
* @var boolean
*/
protected $public = false;
/**
* If this command needs mysql
*
......@@ -101,16 +90,18 @@ abstract class Command
*
* @var array
*/
protected $config;
protected $config = [];
/**
* Constructor
*
* @param Telegram $telegram
* @param Telegram $telegram
* @param Entities\Update $update
*/
public function __construct(Telegram $telegram)
public function __construct(Telegram $telegram, Update $update = null)
{
$this->telegram = $telegram;
$this->setUpdate($update);
$this->config = $telegram->getCommandConfig($this->name);
}
......@@ -120,40 +111,52 @@ abstract class Command
* @param Entities\Update $update
* @return Command
*/
public function setUpdate(Update $update)
public function setUpdate(Update $update = null)
{
$this->update = $update;
$this->message = $this->update->getMessage();
if (!empty($update)) {
$this->update = $update;
$this->message = $this->update->getMessage();
}
return $this;
}
/**
* Pre-execute command
*
* @return mixed
* @return Entities\ServerResponse
*/
public function preExecute()
{
if (!$this->need_mysql |
$this->need_mysql & $this->telegram->isDbEnabled() & DB::isDbConnected()
) {
return $this->execute();
if ($this->need_mysql && !($this->telegram->isDbEnabled() && DB::isDbConnected())) {
return $this->executeNoDB();
}
return $this->executeNoDB();
return $this->execute();
}
/**
* Execute command
*
* @return Entities\ServerResponse
*/
abstract public function execute();
/**
* This methods is executed if $need_mysql is true
* but DB connection for some reason is not avaiable
* Execution if MySQL is required but not available
*
* @return Entities\ServerResponse
*/
public function executeNoDB()
{
//Preparing message
$message = $this->getMessage();
$chat_id = $message->getChat()->getId();
$data = [
'chat_id' => $chat_id,
'text' => 'Sorry no database connection, unable to execute "' . $this->name . '" command.',
];
return Request::sendMessage($data);
}
/**
......@@ -179,21 +182,22 @@ abstract class Command
/**
* Get command config
*
* Look for parameter $name if found return it, if not return null.
* If $name is not set return the all set params
* Look for config $name if found return it, if not return null.
* If $name is not set return all set config.
*
* @param string|null $name
*
* @return mixed
*/
public function getConfig($name = null)
{
if ($name === null) {
return $this->config;
}
if (isset($this->config[$name])) {
return $this->config[$name];
} else {
return null;
}
return $this->config;
return null;
}
/**
......@@ -206,18 +210,6 @@ abstract class Command
return $this->telegram;
}
/**
* Set command
*
* @param string $command
* @return Command
*/
public function setCommand($command)
{
$this->command = $command;
return $this;
}
/**
* Get usage
*
......@@ -269,12 +261,32 @@ abstract class Command
}
/**
* Check if command is public
* If this is a SystemCommand
*
* @return boolean
* @return bool
*/
public function isSystemCommand()
{
return ($this instanceof SystemCommand);
}
/**
* If this is an AdminCommand
*
* @return bool
*/
public function isAdminCommand()
{
return ($this instanceof AdminCommand);
}
/**
* If this is a UserCommand
*
* @return bool
*/
public function isPublic()
public function isUserCommand()
{
return $this->public;
return ($this instanceof UserCommand);
}
}
......@@ -10,29 +10,24 @@
namespace Longman\TelegramBot\Commands;
use Longman\TelegramBot\Command;
use Longman\TelegramBot\Request;
/**
* Generic message command
* Abstract System Command Class
*/
class GenericmessageCommand extends Command
abstract class SystemCommand extends Command
{
/**#@+
* {@inheritdoc}
*/
protected $name = 'Genericmessage';
protected $description = 'Handle generic message';
protected $version = '1.0.1';
/**#@-*/
/**
* Execute command
* A system command just executes
*
* Although system commands should just work and return a successful ServerResponse,
* each system command can override this method to add custom functionality.
*
* @return boolean
* @return Entities\ServerResponse
*/
public function execute()
{
//System command, do nothing
return true;
//System command, return empty ServerResponse
return Request::emptyResponse();
}
}
......@@ -8,34 +8,29 @@
* file that was distributed with this source code.
*/
namespace Longman\TelegramBot\Commands;
namespace Longman\TelegramBot\Commands\SystemCommands;
use Longman\TelegramBot\Command;
use Longman\TelegramBot\Commands\SystemCommand;
/**
* Channel chat created command
*/
class ChannelchatcreatedCommand extends Command
class ChannelchatcreatedCommand extends SystemCommand
{
/**#@+
* {@inheritdoc}
*/
protected $name = 'Channelchatcreated';
protected $name = 'Channelchatcreated';
protected $description = 'Channel chat created';
protected $version = '1.0.1';
protected $version = '1.0.1';
/**#@-*/
/**
* Execute command
*
* @return boolean
* {@inheritdoc}
*/
public function execute()
/*public function execute()
{
//$message = $this->getMessage();
//$channel_chat_created = $message->getChannelChatCreated();
//System command, do nothing
return true;
}
}*/
}
......@@ -8,36 +8,31 @@
* file that was distributed with this source code.
*/
namespace Longman\TelegramBot\Commands;
namespace Longman\TelegramBot\Commands\SystemCommands;
use Longman\TelegramBot\Command;
use Longman\TelegramBot\Commands\SystemCommand;
/**
* Chosen inline result command
*/
class ChoseninlineresultCommand extends Command
class ChoseninlineresultCommand extends SystemCommand
{
/**#@+
* {@inheritdoc}
*/
protected $name = 'choseninlineresult';
protected $name = 'choseninlineresult';
protected $description = 'Chosen result query';
protected $version = '1.0.1';
protected $version = '1.0.1';
/**#@-*/
/**
* Execute command
*
* @return boolean
* {@inheritdoc}
*/
public function execute()
/*public function execute()
{
//Information about chosen result is returned
//$update = $this->getUpdate();
//$inline_query = $update->getChosenInlineResult();
//$query = $inline_query->getQuery();
//System command, do nothing
return true;
}
}*/
}
......@@ -8,14 +8,14 @@
* file that was distributed with this source code.
*/
namespace Longman\TelegramBot\Commands;
namespace Longman\TelegramBot\Commands\SystemCommands;
use Longman\TelegramBot\Command;
use Longman\TelegramBot\Commands\SystemCommand;
/**
* Delete chat photo command
*/
class DeletechatphotoCommand extends Command
class DeletechatphotoCommand extends SystemCommand
{
/**#@+
* {@inheritdoc}
......@@ -26,16 +26,11 @@ class DeletechatphotoCommand extends Command
/**#@-*/
/**
* Execute command
*
* @return boolean
* {@inheritdoc}
*/
public function execute()
/*public function execute()
{
//$message = $this->getMessage();
//$delete_chat_photo = $message->getDeleteChatPhoto();
//System command, do nothing
return true;
}
}*/
}
......@@ -8,15 +8,15 @@
* file that was distributed with this source code.
*/
namespace Longman\TelegramBot\Commands;
namespace Longman\TelegramBot\Commands\SystemCommands;
use Longman\TelegramBot\Command;
use Longman\TelegramBot\Commands\SystemCommand;
use Longman\TelegramBot\Request;
/**
* Generic command
*/
class GenericCommand extends Command
class GenericCommand extends SystemCommand
{
/**#@+
* {@inheritdoc}
......@@ -27,11 +27,7 @@ class GenericCommand extends Command
/**#@-*/
/**
* Execute command
*
* @todo This can't be right, as it always returns "Command: xyz not found.. :("
*
* @return boolean
* {@inheritdoc}
*/
public function execute()
{
......@@ -43,9 +39,9 @@ class GenericCommand extends Command
$data = [
'chat_id' => $chat_id,
'text' => 'Command: ' . $command . ' not found.. :(',
'text' => 'Command /' . $command . ' not found.. :(',
];
return Request::sendMessage($data)->isOk();
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\SystemCommands;
use Longman\TelegramBot\Conversation;
use Longman\TelegramBot\Request;
use Longman\TelegramBot\Commands\SystemCommand;
/**
* Generic message command
*/
class GenericmessageCommand extends SystemCommand
{
/**#@+
* {@inheritdoc}
*/
protected $name = 'Genericmessage';
protected $description = 'Handle generic message';
protected $version = '1.0.2';
protected $need_mysql = true;
/**#@-*/
/**
* Execution if MySQL is required but not available
*
* @return boolean
*/
public function executeNoDB()
{
//Do nothing
return Request::emptyResponse();
}
/**
* Execute command
*
* @return boolean
*/
public function execute()
{
//If a conversation is busy, execute the conversation command after handling the message
$conversation = new Conversation(
$this->getMessage()->getChat()->getId(),
$this->getMessage()->getFrom()->getId()
);
//Fetch conversation command if it exists and execute it
if ($conversation->exists() && ($command = $conversation->getCommand())) {
return $this->telegram->executeCommand($command, $this->update);
}
return Request::emptyResponse();
}
}
......@@ -8,14 +8,14 @@
* file that was distributed with this source code.
*/
namespace Longman\TelegramBot\Commands;
namespace Longman\TelegramBot\Commands\SystemCommands;
use Longman\TelegramBot\Command;
use Longman\TelegramBot\Commands\SystemCommand;
/**
* Group chat created command
*/
class GroupchatcreatedCommand extends Command
class GroupchatcreatedCommand extends SystemCommand
{
/**#@+
* {@inheritdoc}
......@@ -26,16 +26,11 @@ class GroupchatcreatedCommand extends Command
/**#@-*/
/**
* Execute command
*
* @return boolean
* {@inheritdoc}
*/
public function execute()
/*public function execute()
{
//$message = $this->getMessage();
//$group_chat_created = $message->getGroupChatCreated();
//System command, do nothing
return true;
}
}*/
}
......@@ -8,16 +8,16 @@
* file that was distributed with this source code.
*/
namespace Longman\TelegramBot\Commands;
namespace Longman\TelegramBot\Commands\SystemCommands;
use Longman\TelegramBot\Command;
use Longman\TelegramBot\Commands\SystemCommand;
use Longman\TelegramBot\Entities\InlineQueryResultArticle;
use Longman\TelegramBot\Request;
/**
* Inline query command
*/
class InlinequeryCommand extends Command
class InlinequeryCommand extends SystemCommand
{
/**#@+
* {@inheritdoc}
......@@ -28,9 +28,7 @@ class InlinequeryCommand extends Command
/**#@-*/
/**
* Execute command
*
* @return boolean
* {@inheritdoc}
*/
public function execute()
{
......@@ -52,6 +50,6 @@ class InlinequeryCommand extends Command
}
$data['results'] = '[' . implode(',', $array_article) . ']';
return Request::answerInlineQuery($data)->isOk();
return Request::answerInlineQuery($data);
}
}
......@@ -8,14 +8,14 @@
* file that was distributed with this source code.
*/
namespace Longman\TelegramBot\Commands;
namespace Longman\TelegramBot\Commands\SystemCommands;
use Longman\TelegramBot\Command;
use Longman\TelegramBot\Commands\SystemCommand;
/**
* Left chat participant command
*/
class LeftchatparticipantCommand extends Command
class LeftchatparticipantCommand extends SystemCommand
{
/**#@+
* {@inheritdoc}
......@@ -26,16 +26,11 @@ class LeftchatparticipantCommand extends Command
/**#@-*/
/**
* Execute command
*
* @return boolean
* {@inheritdoc}
*/
public function execute()
/*public function execute()
{
//$message = $this->getMessage();
//$participant = $message->getLeftChatParticipant();
//System command, do nothing
return true;
}
}*/
}
......@@ -8,15 +8,15 @@
* file that was distributed with this source code.
*/
namespace Longman\TelegramBot\Commands;
namespace Longman\TelegramBot\Commands\SystemCommands;
use Longman\TelegramBot\Command;
use Longman\TelegramBot\Commands\SystemCommand;
use Longman\TelegramBot\Request;
/**
* New chat participant command
*/
class NewchatparticipantCommand extends Command
class NewchatparticipantCommand extends SystemCommand
{
/**#@+
* {@inheritdoc}
......@@ -27,9 +27,7 @@ class NewchatparticipantCommand extends Command
/**#@-*/
/**
* Execute command
*
* @return boolean
* {@inheritdoc}
*/
public function execute()
{
......@@ -49,6 +47,6 @@ class NewchatparticipantCommand extends Command
'text' => $text,
];
return Request::sendMessage($data)->isOk();
return Request::sendMessage($data);
}
}
......@@ -8,14 +8,14 @@
* file that was distributed with this source code.
*/
namespace Longman\TelegramBot\Commands;
namespace Longman\TelegramBot\Commands\SystemCommands;
use Longman\TelegramBot\Command;
use Longman\TelegramBot\Commands\SystemCommand;
/**
* New chat title command
*/
class NewchattitleCommand extends Command
class NewchattitleCommand extends SystemCommand
{
/**#@+
* {@inheritdoc}
......@@ -26,16 +26,11 @@ class NewchattitleCommand extends Command
/**#@-*/
/**
* Execute command
*
* @return boolean
* {@inheritdoc}
*/
public function execute()
/*public function execute()
{
//$message = $this->getMessage();
//$new_chat_title = $message->getNewChatTitle();
//System command, do nothing
return true;
}
}*/
}
......@@ -8,29 +8,27 @@
* file that was distributed with this source code.
*/
namespace Longman\TelegramBot\Commands;
namespace Longman\TelegramBot\Commands\SystemCommands;
use Longman\TelegramBot\Command;
use Longman\TelegramBot\Commands\SystemCommand;
use Longman\TelegramBot\Request;
/**
* Start command
*/
class StartCommand extends Command
class StartCommand extends SystemCommand
{
/**#@+
* {@inheritdoc}
*/
protected $name = 'start';
protected $description = 'Start command';
protected $usage = '/';
protected $usage = '/start';
protected $version = '1.0.1';
/**#@-*/
/**
* Execute command
*
* @return boolean
* {@inheritdoc}
*/
public function execute()
{
......@@ -44,6 +42,6 @@ class StartCommand extends Command
'text' => $text,
];
return Request::sendMessage($data)->isOk();
return Request::sendMessage($data);
}
}
......@@ -8,15 +8,15 @@
* file that was distributed with this source code.
*/
namespace Longman\TelegramBot\Commands;
namespace Longman\TelegramBot\Commands\SystemCommands;
use Longman\TelegramBot\Command;
use Longman\TelegramBot\Commands\SystemCommand;
use Longman\TelegramBot\Request;
/**
* Super group chat created command
*/
class SupergroupchatcreatedCommand extends Command
class SupergroupchatcreatedCommand extends SystemCommand
{
/**#@+
* {@inheritdoc}
......@@ -27,9 +27,7 @@ class SupergroupchatcreatedCommand extends Command
/**#@-*/
/**
* Execute command
*
* @return boolean
* {@inheritdoc}
*/
public function execute()
{
......@@ -48,6 +46,6 @@ class SupergroupchatcreatedCommand extends Command
'text' => $text,
];
return Request::sendMessage($data)->isOk();
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;
/**
* Abstract User Command Class
*/
abstract class UserCommand extends Command
{
}
<?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,
]);
}
}
......@@ -8,16 +8,16 @@
* file that was distributed with this source code.
*/
namespace Longman\TelegramBot\Commands;
namespace Longman\TelegramBot\Commands\UserCommands;
use Longman\TelegramBot\Command;
use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Exception\TelegramException;
use Longman\TelegramBot\Request;
/**
* User "/date" command
*/
class DateCommand extends Command
class DateCommand extends UserCommand
{
/**#@+
* {@inheritdoc}
......@@ -175,9 +175,7 @@ class DateCommand extends Command
}
/**
* Execute command
*
* @return boolean
* {@inheritdoc}
*/
public function execute()
{
......@@ -204,6 +202,6 @@ class DateCommand extends Command
'text' => $text,
];
return Request::sendMessage($data)->isOk();
return Request::sendMessage($data);
}
}
......@@ -8,15 +8,15 @@
* file that was distributed with this source code.
*/
namespace Longman\TelegramBot\Commands;
namespace Longman\TelegramBot\Commands\UserCommands;
use Longman\TelegramBot\Command;
use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Request;
/**
* User "/echo" command
*/
class EchoCommand extends Command
class EchoCommand extends UserCommand
{
/**#@+
* {@inheritdoc}
......@@ -25,25 +25,26 @@ class EchoCommand extends Command
protected $description = 'Show text';
protected $usage = '/echo <text>';
protected $version = '1.0.1';
protected $public = true;
/**#@-*/
/**
* Execute command
*
* @return boolean
* {@inheritdoc}
*/
public function execute()
{
$message = $this->getMessage();
$chat_id = $message->getChat()->getId();
$text = $message->getText(true);
$text = trim($message->getText(true));
if ($text === '') {
$text = 'Command usage: ' . $this->getUsage();
}
$data = [
'chat_id' => $chat_id,
'text' => $text,
];
return Request::sendMessage($data)->isOk();
return Request::sendMessage($data);
}
}
......@@ -8,15 +8,15 @@
* file that was distributed with this source code.
*/
namespace Longman\TelegramBot\Commands;
namespace Longman\TelegramBot\Commands\UserCommands;
use Longman\TelegramBot\Command;
use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Request;
/**
* User "/help" command
*/
class HelpCommand extends Command
class HelpCommand extends UserCommand
{
/**#@+
* {@inheritdoc}
......@@ -25,63 +25,51 @@ class HelpCommand extends Command
protected $description = 'Show bot commands help';
protected $usage = '/help or /help <command>';
protected $version = '1.0.1';
protected $public = true;
/**#@-*/
/**
* Execute command
*
* @return boolean
* {@inheritdoc}
*/
public function execute()
{
$message = $this->getMessage();
$chat_id = $message->getChat()->getId();
$message_id = $message->getMessageId();
$text = $message->getText(true);
$command = trim($message->getText(true));
$commands = $this->telegram->getCommandsList();
//Only get enabled Admin and User commands
$commands = array_filter($this->telegram->getCommandsList(), function ($command) {
return (!$command->isSystemCommand() && $command->isEnabled());
});
if (empty($text)) {
$msg = $this->telegram->getBotName() . ' v. ' . $this->telegram->getVersion() . "\n\n";
$msg .= 'Commands List:' . "\n";
//If no command parameter is passed, show the list
if ($command === '') {
$text = $this->telegram->getBotName() . ' v. ' . $this->telegram->getVersion() . "\n\n";
$text .= 'Commands List:' . "\n";
foreach ($commands as $command) {
if (is_object($command)) {
if (!$command->isEnabled()) {
continue;
}
if (!$command->isPublic()) {
continue;
}
$msg .= '/' . $command->getName() . ' - ' . $command->getDescription() . "\n";
}
$text .= '/' . $command->getName() . ' - ' . $command->getDescription() . "\n";
}
$msg .= "\n" . 'For exact command help type: /help <command>';
$text .= "\n" . 'For exact command help type: /help <command>';
} else {
$text = str_replace('/', '', $text);
if (isset($commands[$text])) {
$command = $commands[$text];
if (!$command->isEnabled() || !$command->isPublic()) {
$msg = 'Command ' . $text . ' not found';
} else {
$msg = 'Command: ' . $command->getName() . ' v' . $command->getVersion() . "\n";
$msg .= 'Description: ' . $command->getDescription() . "\n";
$msg .= 'Usage: ' . $command->getUsage();
}
$command = str_replace('/', '', $command);
if (isset($commands[$command])) {
$command = $commands[$command];
$text = 'Command: ' . $command->getName() . ' v' . $command->getVersion() . "\n";
$text .= 'Description: ' . $command->getDescription() . "\n";
$text .= 'Usage: ' . $command->getUsage();
} else {
$msg = 'Command ' . $text . ' not found';
$text = 'No help available: Command /' . $command . ' not found';
}
}
$data = [
'chat_id' => $chat_id,
'reply_to_message_id' => $message_id,
'text' => $msg,
'text' => $text,
];
return Request::sendMessage($data)->isOk();
return Request::sendMessage($data);
}
}
......@@ -8,15 +8,15 @@
* file that was distributed with this source code.
*/
namespace Longman\TelegramBot\Commands;
namespace Longman\TelegramBot\Commands\UserCommands;
use Longman\TelegramBot\Command;
use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Request;
/**
* User "/slap" command
*/
class SlapCommand extends Command
class SlapCommand extends UserCommand
{
/**#@+
* {@inheritdoc}
......@@ -28,9 +28,7 @@ class SlapCommand extends Command
/**#@-*/
/**
* Execute command
*
* @return boolean
* {@inheritdoc}
*/
public function execute()
{
......@@ -55,6 +53,6 @@ class SlapCommand extends Command
'text' => $text,
];
return Request::sendMessage($data)->isOk();
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;
}
}
......@@ -8,15 +8,15 @@
* file that was distributed with this source code.
*/
namespace Longman\TelegramBot\Commands;
namespace Longman\TelegramBot\Commands\UserCommands;
use Longman\TelegramBot\Command;
use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Request;
/**
* User "/weather" command
*/
class WeatherCommand extends Command
class WeatherCommand extends UserCommand
{
/**#@+
* {@inheritdoc}
......@@ -110,9 +110,7 @@ class WeatherCommand extends Command
}
/**
* Execute command
*
* @return boolean
* {@inheritdoc}
*/
public function execute()
{
......@@ -139,6 +137,6 @@ class WeatherCommand extends Command
'text' => $text,
];
return Request::sendMessage($data)->isOk();
return Request::sendMessage($data);
}
}
......@@ -10,16 +10,16 @@
* Written by Marco Boretto <marco.bore@gmail.com>
*/
namespace Longman\TelegramBot\Commands;
namespace Longman\TelegramBot\Commands\UserCommands;
use Longman\TelegramBot\Command;
use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Entities\File;
use Longman\TelegramBot\Request;
/**
* User "/whoami" command
*/
class WhoamiCommand extends Command
class WhoamiCommand extends UserCommand
{
/**#@+
* {@inheritdoc}
......@@ -32,9 +32,7 @@ class WhoamiCommand extends Command
/**#@-*/
/**
* Execute command
*
* @return boolean
* {@inheritdoc}
*/
public function execute()
{
......@@ -100,6 +98,6 @@ class WhoamiCommand extends Command
$result = Request::sendMessage($data);
}
return $result->isOk();
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;
/**
* Class Conversation
*
* Only one conversation can be active at any one time.
* A conversation is directly linked to a user, chat and the command that is managing the conversation.
*/
class Conversation
{
/**
* All information fetched from the database
*
* @var array
*/
protected $conversation = null;
/**
* Notes stored inside the conversation
*
* @var array
*/
protected $protected_notes = null;
/**
* Notes to be stored
*
* @var array
*/
public $notes = null;
/**
* Telegram user id
*
* @var int
*/
protected $user_id;
/**
* Telegram chat id
*
* @var int
*/
protected $chat_id;
/**
* Command to be executed if the conversation is active
*
* @var string
*/
protected $command;
/**
* Conversation contructor to initialize a new conversation
*
* @param int $user_id
* @param int $chat_id
* @param string $command
*/
public function __construct($user_id, $chat_id, $command = null)
{
$this->user_id = $user_id;
$this->chat_id = $chat_id;
$this->command = $command;
//Try to load an existing conversation if possible
if (!$this->load() && $command !== null) {
//A new conversation start
$this->start();
}
}
/**
* Clear all conversation variables.
*
* @return bool Always return true, to allow this method in an if statement.
*/
protected function clear()
{
$this->conversation = null;
$this->protected_notes = null;
$this->notes = null;
return true;
}
/**
* Load the conversation from the database
*
* @return bool
*/
protected function load()
{
//Select an active conversation
$conversation = ConversationDB::selectConversation($this->user_id, $this->chat_id, 1);
if (isset($conversation[0])) {
//Pick only the first element
$this->conversation = $conversation[0];
//Load the command from the conversation if it hasn't been passed
$this->command = $this->command ?: $this->conversation['command'];
if ($this->command !== $this->conversation['command']) {
$this->cancel();
return false;
}
//Load the conversation notes
$this->protected_notes = json_decode($this->conversation['notes'], true);
$this->notes = $this->protected_notes;
}
return $this->exists();
}
/**
* Check if the conversation already exists
*
* @return bool
*/
public function exists()
{
return ($this->conversation !== null);
}
/**
* Start a new conversation if the current command doesn't have one yet
*
* @return bool
*/
protected function start()
{
if (!$this->exists() && $this->command) {
if (ConversationDB::insertConversation(
$this->user_id,
$this->chat_id,
$this->command
)) {
return $this->load();
}
}
return false;
}
/**
* Delete the current conversation
*
* Currently the Conversation is not deleted but just set to 'stopped'
*
* @return bool
*/
public function stop()
{
return ($this->updateStatus('stopped') && $this->clear());
}
/**
* Cancel the current conversation
*
* @return bool
*/
public function cancel()
{
return ($this->updateStatus('cancelled') && $this->clear());
}
/**
* Update the status of the current conversation
*
* @param string $status
*
* @return bool
*/
protected function updateStatus($status)
{
if ($this->exists()) {
$fields = ['status' => $status];
$where = [
'id' => $this->conversation['id'],
'status' => 'active',
'user_id' => $this->user_id,
'chat_id' => $this->chat_id,
];
if (ConversationDB::updateConversation($fields, $where)) {
return true;
}
}
return false;
}
/**
* Store the array/variable in the database with json_encode() function
*
* @return bool
*/
public function update()
{
if ($this->exists()) {
$fields = ['notes' => json_encode($this->notes)];
//I can update a conversation whatever the state is
$where = ['id' => $this->conversation['id']];
if (ConversationDB::updateConversation($fields, $where)) {
return true;
}
}
return false;
}
/**
* Retrieve the command to execute from the conversation
*
* @return string|null
*/
public function getCommand()
{
return $this->command;
}
}
<?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;
use Longman\TelegramBot\DB;
use Longman\TelegramBot\Exception\TelegramException;
/**
* Class ConversationDB
*/
class ConversationDB extends DB
{
/**
* Initilize conversation table
*/
public static function initializeConversation()
{
if (!defined('TB_CONVERSATION')) {
define('TB_CONVERSATION', self::$table_prefix . 'conversation');
}
}
/**
* Select a conversation from the DB
*
* @param int $user_id
* @param int $chat_id
* @param bool $limit
*
* @return array|bool
*/
public static function selectConversation($user_id, $chat_id, $limit = null)
{
if (!self::isDbConnected()) {
return false;
}
try {
$query = 'SELECT * FROM `' . TB_CONVERSATION . '` ';
$query .= 'WHERE `status` = :status ';
$query .= 'AND `chat_id` = :chat_id ';
$query .= 'AND `user_id` = :user_id ';
$tokens = [':chat_id' => $chat_id, ':user_id' => $user_id];
if (!is_null($limit)) {
$query .= ' LIMIT :limit';
}
$sth = self::$pdo->prepare($query);
$active = 'active';
$sth->bindParam(':status', $active, \PDO::PARAM_STR);
$sth->bindParam(':user_id', $user_id, \PDO::PARAM_INT);
$sth->bindParam(':chat_id', $chat_id, \PDO::PARAM_INT);
$sth->bindParam(':limit', $limit, \PDO::PARAM_INT);
$sth->execute();
$results = $sth->fetchAll(\PDO::FETCH_ASSOC);
} catch (\Exception $e) {
throw new TelegramException($e->getMessage());
}
return $results;
}
/**
* Insert the conversation in the database
*
* @param int $user_id
* @param int $chat_id
* @param string $command
*
* @return bool
*/
public static function insertConversation($user_id, $chat_id, $command)
{
if (!self::isDbConnected()) {
return false;
}
try {
$sth = self::$pdo->prepare('INSERT INTO `' . TB_CONVERSATION . '`
(
`status`, `user_id`, `chat_id`, `command`, `notes`, `created_at`, `updated_at`
)
VALUES (
:status, :user_id, :chat_id, :command, :notes, :date, :date
)
');
$active = 'active';
//$notes = json_encode('');
$notes = '""';
$created_at = self::getTimestamp();
$sth->bindParam(':status', $active);
$sth->bindParam(':command', $command);
$sth->bindParam(':user_id', $user_id);
$sth->bindParam(':chat_id', $chat_id);
$sth->bindParam(':notes', $notes);
$sth->bindParam(':date', $created_at);
$status = $sth->execute();
} catch (\Exception $e) {
throw new TelegramException($e->getMessage());
}
return $status;
}
/**
* Update a specific conversation
*
* @param array $fields_values
* @param array $where_fields_values
*
* @return bool
*/
public static function updateConversation(array $fields_values, array $where_fields_values)
{
return self::update(TB_CONVERSATION, $fields_values, $where_fields_values);
}
/**
* Update the conversation in the database
*
* @param string $table
* @param array $fields_values
* @param array $where_fields_values
*
* @todo This function is generic should be moved in DB.php
*
* @return bool
*/
public static function update($table, array $fields_values, array $where_fields_values)
{
if (!self::isDbConnected()) {
return false;
}
//Auto update the field update_at
$fields_values['updated_at'] = self::getTimestamp();
//Values
$update = '';
$tokens = [];
$tokens_counter = 0;
$a = 0;
foreach ($fields_values as $field => $value) {
if ($a) {
$update .= ', ';
}
++$a;
++$tokens_counter;
$update .= '`' . $field . '` = :' . $tokens_counter;
$tokens[':' . $tokens_counter] = $value;
}
//Where
$a = 0;
$where = '';
foreach ($where_fields_values as $field => $value) {
if ($a) {
$where .= ' AND ';
} else {
++$a;
$where .= 'WHERE ';
}
++$tokens_counter;
$where .= '`' . $field .'`= :' . $tokens_counter ;
$tokens[':' . $tokens_counter] = $value;
}
$query = 'UPDATE `' . $table . '` SET ' . $update . ' ' . $where;
try {
$sth = self::$pdo->prepare($query);
$status = $sth->execute($tokens);
} catch (\Exception $e) {
throw new TelegramException($e->getMessage());
}
return $status;
}
}
......@@ -543,22 +543,17 @@ class DB
self::insertUser($forward_from, $forward_date);
$forward_from = $forward_from->getId();
}
//Insert the new chat user
$new_chat_participant = '';
if (is_object($new_chat_participant)) {
if ($new_chat_participant) {
//Insert the new chat user
self::insertUser($new_chat_participant, $date, $chat);
$new_chat_participant = $new_chat_participant->getId();
}
//Insert the left chat user
$left_chat_participant = '';
if (is_object($left_chat_participant)) {
} elseif ($left_chat_participant) {
//Insert the left chat user
self::insertUser($left_chat_participant, $date, $chat);
$left_chat_participant = $left_chat_participant->getId();
}
try {
//message Table
$sth = self::$pdo->prepare('INSERT IGNORE INTO `' . TB_MESSAGE . '`
......@@ -638,8 +633,8 @@ class DB
$sth->bindParam(':caption', $caption, \PDO::PARAM_STR);
$sth->bindParam(':contact', $contact, \PDO::PARAM_STR);
$sth->bindParam(':location', $location, \PDO::PARAM_STR);
$sth->bindParam(':new_chat_participant', $new_chat_paticipant, \PDO::PARAM_INT);
$sth->bindParam(':left_chat_participant', $left_chat_paticipant, \PDO::PARAM_INT);
$sth->bindParam(':new_chat_participant', $new_chat_participant, \PDO::PARAM_INT);
$sth->bindParam(':left_chat_participant', $left_chat_participant, \PDO::PARAM_INT);
$sth->bindParam(':new_chat_title', $new_chat_title, \PDO::PARAM_STR);
//Array of Photosize
......
......@@ -88,14 +88,14 @@ class Request
}
/**
* Set input from update or stdin and return it
* Set input from custom input or stdin and return it
*
* @return string
*/
public static function getInput()
{
if ($update = self::$telegram->getCustomUpdate()) {
self::setInputRaw($update);
if ($input = self::$telegram->getCustomInput()) {
self::setInputRaw($input);
} else {
self::setInputRaw(file_get_contents('php://input'));
}
......@@ -109,6 +109,7 @@ class Request
* @todo Take log verbosity into account
*
* @param string $string
*
* @return mixed
*/
private static function log($string)
......@@ -129,6 +130,7 @@ class Request
* Generate general fake server response
*
* @param array $data Data to add to fake response
*
* @return array Fake response data
*/
public static function generateGeneralFakeServerResponse(array $data = null)
......@@ -167,6 +169,7 @@ class Request
*
* @param string $action Action to execute
* @param array|null $data Data to attach to the execution
*
* @return mixed Result of the cURL call
*/
public static function executeCurl($action, array $data = null)
......@@ -227,6 +230,7 @@ class Request
* Download file
*
* @param Entities\File $file
*
* @return boolean
*/
public static function downloadFile(File $file)
......@@ -281,6 +285,7 @@ class Request
* Encode file
*
* @param string $file
*
* @return CURLFile
*/
protected static function encodeFile($file)
......@@ -296,6 +301,7 @@ class Request
*
* @param string $action
* @param array|null $data
*
* @return Entities\ServerResponse
*/
public static function send($action, array $data = null)
......@@ -331,6 +337,7 @@ class Request
* @todo Could do with some cleaner recursion
*
* @param array $data
*
* @return mixed
*/
public static function sendMessage(array $data)
......@@ -353,6 +360,7 @@ class Request
* Forward message
*
* @param array $data
*
* @return mixed
*/
public static function forwardMessage(array $data)
......@@ -369,6 +377,7 @@ class Request
*
* @param array $data
* @param string $file
*
* @return mixed
*/
public static function sendPhoto(array $data, $file = null)
......@@ -389,6 +398,7 @@ class Request
*
* @param array $data
* @param string $file
*
* @return mixed
*/
public static function sendAudio(array $data, $file = null)
......@@ -409,6 +419,7 @@ class Request
*
* @param array $data
* @param string $file
*
* @return mixed
*/
public static function sendDocument(array $data, $file = null)
......@@ -429,6 +440,7 @@ class Request
*
* @param array $data
* @param string $file
*
* @return mixed
*/
public static function sendSticker(array $data, $file = null)
......@@ -449,6 +461,7 @@ class Request
*
* @param array $data
* @param string $file
*
* @return mixed
*/
public static function sendVideo(array $data, $file = null)
......@@ -469,6 +482,7 @@ class Request
*
* @param array $data
* @param string $file
*
* @return mixed
*/
public static function sendVoice(array $data, $file = null)
......@@ -488,6 +502,7 @@ class Request
* Send location
*
* @param array $data
*
* @return mixed
*/
public static function sendLocation(array $data)
......@@ -503,6 +518,7 @@ class Request
* Send chat action
*
* @param array $data
*
* @return mixed
*/
public static function sendChatAction(array $data)
......@@ -518,6 +534,7 @@ class Request
* Get user profile photos
*
* @param array $data
*
* @return mixed
*/
public static function getUserProfilePhotos(array $data)
......@@ -537,6 +554,7 @@ class Request
* Get updates
*
* @param array $data
*
* @return mixed
*/
public static function getUpdates(array $data)
......@@ -549,6 +567,7 @@ class Request
*
* @param string $url
* @param string $file
*
* @return mixed
*/
public static function setWebhook($url = '', $file = null)
......@@ -566,6 +585,7 @@ class Request
* Get file
*
* @param array $data
*
* @return mixed
*/
public static function getFile(array $data)
......@@ -581,6 +601,7 @@ class Request
* Answer inline query
*
* @param array $data
*
* @return mixed
*/
public static function answerInlineQuery(array $data)
......@@ -592,6 +613,19 @@ class Request
return self::send('answerInlineQuery', $data);
}
/**
* Return an empty Server Response
*
* No request to telegram are sent, this function is used in commands that
* don't need to fire a message after execution
*
* @return Entities\ServerResponse
*/
public static function emptyResponse()
{
return new ServerResponse(['ok' => true, 'result' => true], null);
}
/**
* Send message to all active chats
*
......@@ -602,6 +636,7 @@ class Request
* @param boolean $send_users
* @param string $date_from
* @param string $date_to
*
* @return array
*/
public static function sendToActiveChats(
......
This diff is collapsed.
CREATE TABLE IF NOT EXISTS `user` (
`id` bigint NULL DEFAULT NULL COMMENT 'Unique user identifier',
`id` bigint COMMENT 'Unique user identifier',
`first_name` CHAR(255) NOT NULL DEFAULT '' COMMENT 'User first name',
`last_name` CHAR(255) DEFAULT NULL COMMENT 'User last name',
`username` CHAR(255) DEFAULT NULL COMMENT 'User username',
......@@ -10,7 +10,7 @@ CREATE TABLE IF NOT EXISTS `user` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;
CREATE TABLE IF NOT EXISTS `chat` (
`id` bigint NULL DEFAULT NULL COMMENT 'Unique user or chat identifier',
`id` bigint COMMENT 'Unique user or chat identifier',
`type` ENUM('private', 'group', 'supergroup', 'channel') NOT NULL COMMENT 'chat type private, group, supergroup or channel',
`title` CHAR(255) DEFAULT '' COMMENT 'chat title null if case of single chat with the bot',
`created_at` timestamp NULL DEFAULT NULL COMMENT 'Entry date creation',
......@@ -20,8 +20,8 @@ CREATE TABLE IF NOT EXISTS `chat` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;
CREATE TABLE IF NOT EXISTS `user_chat` (
`user_id` bigint NULL DEFAULT NULL COMMENT 'Unique user identifier',
`chat_id` bigint NULL DEFAULT NULL COMMENT 'Unique user or chat identifier',
`user_id` bigint COMMENT 'Unique user identifier',
`chat_id` bigint COMMENT 'Unique user or chat identifier',
PRIMARY KEY (`user_id`, `chat_id`),
FOREIGN KEY (`user_id`) REFERENCES `user` (`id`)
ON DELETE CASCADE ON UPDATE CASCADE,
......@@ -31,7 +31,7 @@ CREATE TABLE IF NOT EXISTS `user_chat` (
CREATE TABLE IF NOT EXISTS `inline_query` (
`id` bigint UNSIGNED NULL COMMENT 'Unique identifier for this query.',
`id` bigint UNSIGNED COMMENT 'Unique identifier for this query.',
`user_id` bigint NULL COMMENT 'Sender',
`query` CHAR(255) NOT NULL DEFAULT '' COMMENT 'Text of the query',
`offset` CHAR(255) NOT NULL DEFAULT '' COMMENT 'Offset of the result',
......@@ -41,11 +41,11 @@ CREATE TABLE IF NOT EXISTS `inline_query` (
FOREIGN KEY (`user_id`)
REFERENCES `user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;
CREATE TABLE IF NOT EXISTS `chosen_inline_query` (
`id` bigint UNSIGNED NULL AUTO_INCREMENT COMMENT 'Unique identifier for chosen query.',
`id` bigint UNSIGNED AUTO_INCREMENT COMMENT 'Unique identifier for chosen query.',
`result_id` CHAR(255) NOT NULL DEFAULT '' COMMENT 'Id of the chosen result',
`user_id` bigint NULL COMMENT 'Sender',
`query` CHAR(255) NOT NULL DEFAULT '' COMMENT 'Text of the query',
......@@ -55,11 +55,11 @@ CREATE TABLE IF NOT EXISTS `chosen_inline_query` (
FOREIGN KEY (`user_id`)
REFERENCES `user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;
CREATE TABLE IF NOT EXISTS `message` (
`id` bigint UNSIGNED NULL COMMENT 'Unique message identifier',
`id` bigint UNSIGNED COMMENT 'Unique message identifier',
`user_id` bigint NULL COMMENT 'User identifier',
`chat_id` bigint NULL DEFAULT NULL COMMENT 'Chat identifier.',
`date` timestamp NULL DEFAULT NULL COMMENT 'Date the message was sent in timestamp format',
......@@ -115,7 +115,7 @@ CREATE TABLE IF NOT EXISTS `message` (
CREATE TABLE IF NOT EXISTS `telegram_update` (
`id` bigint UNSIGNED NULL COMMENT 'The update\'s unique identifier.',
`id` bigint UNSIGNED COMMENT 'The update\'s unique identifier.',
`message_id` bigint UNSIGNED DEFAULT NULL COMMENT 'Unique message identifier',
`inline_query_id` bigint UNSIGNED DEFAULT NULL COMMENT 'The query unique identifier.',
`chosen_inline_query_id` bigint UNSIGNED DEFAULT NULL COMMENT 'The chosen query unique identifier.',
......@@ -135,4 +135,23 @@ CREATE TABLE IF NOT EXISTS `telegram_update` (
REFERENCES `chosen_inline_query` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;
CREATE TABLE IF NOT EXISTS `conversation` (
`id` bigint(20) unsigned AUTO_INCREMENT COMMENT 'Row unique id',
`user_id` bigint NULL DEFAULT NULL COMMENT 'User id',
`chat_id` bigint NULL DEFAULT NULL COMMENT 'Telegram chat_id can be a the user id or the chat id ',
`status` ENUM('active', 'cancelled', 'stopped') NOT NULL DEFAULT 'active' COMMENT 'active conversation is active, cancelled conversation has been truncated before end, stopped conversation has end',
`command` varchar(160) DEFAULT '' COMMENT 'Default Command to execute',
`notes` varchar(1000) DEFAULT 'NULL' COMMENT 'Data stored from command',
`created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`),
KEY `chat_id` (`chat_id`),
KEY `status` (`status`),
FOREIGN KEY (`user_id`)
REFERENCES `user` (`id`),
FOREIGN KEY (`chat_id`)
REFERENCES `chat` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;
<?php
/*
/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
......@@ -7,7 +7,9 @@
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tests;
/*
* Set error reporting to the max level.
*/
......@@ -18,24 +20,22 @@ error_reporting(-1);
*/
date_default_timezone_set('UTC');
$autoloader = __DIR__ . '/../vendor/autoload.php';
$root = realpath(dirname(dirname(__FILE__)));
/**
/*
* Check that --dev composer installation was done
*/
if (!file_exists($root . '/vendor/autoload.php')) {
if (!file_exists($autoloader)) {
throw new \Exception(
'Please run "php composer.phar install --dev" in root directory '
. 'to setup unit test dependencies before running the tests'
);
}
// Include the Composer autoloader
$loader = require __DIR__ . '/../vendor/autoload.php';
//Include the Composer autoloader
require_once $autoloader;
/*
* Unset global variables that are no longer needed.
*/
unset($root, $loader);
unset($autoloader);
<?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 Tests;
use Longman\TelegramBot\DB;
use Longman\TelegramBot\Entities\Chat;
use Longman\TelegramBot\Entities\Message;
use Longman\TelegramBot\Entities\Update;
use Longman\TelegramBot\Entities\User;
/**
* @package TelegramTest
* @author Avtandil Kikabidze <akalongman@gmail.com>
* @copyright Avtandil Kikabidze <akalongman@gmail.com>
* @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)
* @link http://www.github.com/akalongman/php-telegram-bot
*/
class TestHelpers
{
/**
* Data template of a user.
*
* @var array
*/
protected static $user_template = [
'id' => 1,
'first_name' => 'first',
'last_name' => 'last',
'username' => 'user',
];
/**
* Data template of a chat.
*
* @var array
*/
protected static $chat_template = [
'id' => 1,
'first_name' => 'first',
'last_name' => 'last',
'username' => 'name',
'type' => 'private',
];
/**
* Set the value of a private/protected property of an object
*
* @param object $object Object that contains the private property
* @param string $property Name of the property who's value we want to set
* @param mixed $value The value to set to the property
*/
public static function setObjectProperty($object, $property, $value)
{
$ref_object = new \ReflectionObject($object);
$ref_property = $ref_object->getProperty($property);
$ref_property->setAccessible(true);
$ref_property->setValue($object, $value);
}
/**
* Return a simple fake Update object
*
* @param array $data Pass custom data array if needed
*
* @return Entities\Update
*/
public static function getFakeUpdateObject($data = null)
{
$data = $data ?: [
'update_id' => 1,
'message' => [
'message_id' => 1,
'chat' => [
'id' => 1,
],
'date' => 1,
]
];
return new Update($data, 'botname');
}
/**
* Return a fake command object for the passed command text
*
* @param string $command_text
*
* @return Entities\Update
*/
public static function getFakeUpdateCommandObject($command_text)
{
$data = [
'update_id' => 1,
'message' => [
'message_id' => 1,
'from' => self::$user_template,
'chat' => self::$chat_template,
'date' => 1,
'text' => $command_text,
],
];
return self::getFakeUpdateObject($data);
}
/**
* Return a fake user object.
*
* @return Entities\User
*/
public static function getFakeUserObject()
{
return new User(self::$user_template);
}
/**
* Return a fake chat object.
*
* @return Entities\Chat
*/
public static function getFakeChatObject()
{
return new Chat(self::$chat_template);
}
/**
* Return a fake message object using the passed ids.
*
* @param integer $message_id
* @param integer $user_id
* @param integer $chat_id
*
* @return Entities\Message
*/
public static function getFakeMessageObject($message_id = 1, $user_id = 1, $chat_id = 1)
{
return new Message([
'message_id' => $message_id,
'from' => ['id' => $user_id] + self::$user_template,
'chat' => ['id' => $chat_id] + self::$chat_template,
'date' => 1,
], 'botname');
}
/**
* Start a fake conversation for the passed command and return the randomly generated ids.
*
* @param string $command
* @return array
*/
public static function startFakeConversation($command)
{
if (!DB::isDbConnected()) {
return false;
}
//Just get some random values.
$message_id = rand();
$user_id = rand();
$chat_id = rand();
//Make sure we have a valid user and chat available.
$message = self::getFakeMessageObject($message_id, $user_id, $chat_id);
DB::insertMessageRequest($message);
DB::insertUser($message->getFrom(), null, $message->getChat());
return compact('message_id', 'user_id', 'chat_id');
}
/**
* Empty all tables for the passed database
*
* @param array $credentials
*/
public static function emptyDB(array $credentials)
{
$dsn = 'mysql:host=' . $credentials['host'] . ';dbname=' . $credentials['database'];
$options = [\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'];
try {
$pdo = new \PDO($dsn, $credentials['user'], $credentials['password'], $options);
$pdo->prepare('
DELETE FROM `conversation`;
DELETE FROM `telegram_update`;
DELETE FROM `chosen_inline_query`;
DELETE FROM `inline_query`;
DELETE FROM `message`;
DELETE FROM `user_chat`;
DELETE FROM `chat`;
DELETE FROM `user`;
')->execute();
} catch (\Exception $e) {
throw new TelegramException($e->getMessage());
}
}
}
<?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 Tests\Unit\Commands;
use Tests\Unit\TestCase;
use Tests\TestHelpers;
use Longman\TelegramBot\Telegram;
/**
* @package TelegramTest
* @author Avtandil Kikabidze <akalongman@gmail.com>
* @copyright Avtandil Kikabidze <akalongman@gmail.com>
* @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)
* @link http://www.github.com/akalongman/php-telegram-bot
*/
class CommandTest extends TestCase
{
private $command_namespace = 'Longman\TelegramBot\Commands\Command';
private $telegram;
private $command_stub;
private $telegram_with_config;
private $command_stub_with_config;
public function setUp()
{
//Default command object
$this->telegram = new Telegram('apikey', 'botname');
$this->command_stub = $this->getMockForAbstractClass($this->command_namespace, [$this->telegram]);
//Create separate command object that contain a command config
$this->telegram_with_config = new Telegram('apikey', 'botname');
$this->telegram_with_config->setCommandConfig('command_name', ['config_key' => 'config_value']);
$this->command_stub_with_config = $this->getMockBuilder($this->command_namespace)
->disableOriginalConstructor()
->getMockForAbstractClass();
//Set a name for the object property so that the constructor can set the config correctly
TestHelpers::setObjectProperty($this->command_stub_with_config, 'name', 'command_name');
$this->command_stub_with_config->__construct($this->telegram_with_config);
}
/**
* @test
*/
public function testCommandConstructorNeedsTelegramObject()
{
$error_message = 'must be an instance of Longman\TelegramBot\Telegram';
$params_to_test = [
[],
[null],
['something'],
[new \stdClass],
];
foreach ($params_to_test as $param) {
try {
$this->getMockForAbstractClass($this->command_namespace, $param);
} catch (\Exception $e) {
$this->assertContains($error_message, $e->getMessage());
} catch (\Throwable $e) { //For PHP7
$this->assertContains($error_message, $e->getMessage());
}
}
}
/**
* @test
*/
public function testCommandHasCorrectTelegramObject()
{
$this->assertAttributeEquals($this->telegram, 'telegram', $this->command_stub);
$this->assertSame($this->telegram, $this->command_stub->getTelegram());
}
/**
* @test
*/
public function testDefaultCommandName()
{
$this->assertAttributeEquals('', 'name', $this->command_stub);
$this->assertEmpty($this->command_stub->getName());
}
/**
* @test
*/
public function testDefaultCommandDescription()
{
$this->assertAttributeEquals('Command description', 'description', $this->command_stub);
$this->assertEquals('Command description', $this->command_stub->getDescription());
}
/**
* @test
*/
public function testDefaultCommandUsage()
{
$this->assertAttributeEquals('Command usage', 'usage', $this->command_stub);
$this->assertEquals('Command usage', $this->command_stub->getUsage());
}
/**
* @test
*/
public function testDefaultCommandVersion()
{
$this->assertAttributeEquals('1.0.0', 'version', $this->command_stub);
$this->assertEquals('1.0.0', $this->command_stub->getVersion());
}
/**
* @test
*/
public function testDefaultCommandIsEnabled()
{
$this->assertAttributeEquals(true, 'enabled', $this->command_stub);
$this->assertTrue($this->command_stub->isEnabled());
}
/**
* @test
*/
public function testDefaultCommandNeedsMysql()
{
$this->assertAttributeEquals(false, 'need_mysql', $this->command_stub);
}
/**
* @test
*/
public function testDefaultCommandEmptyConfig()
{
$this->assertAttributeEquals([], 'config', $this->command_stub);
}
/**
* @test
*/
public function testDefaultCommandUpdateNull()
{
$this->assertAttributeEquals(null, 'update', $this->command_stub);
}
/**
* @test
*/
public function testCommandSetUpdateAndMessage()
{
$stub = $this->command_stub;
$this->assertSame($stub, $stub->setUpdate());
$this->assertEquals(null, $stub->getUpdate());
$this->assertEquals(null, $stub->getMessage());
$this->assertSame($stub, $stub->setUpdate(null));
$this->assertEquals(null, $stub->getUpdate());
$this->assertEquals(null, $stub->getMessage());
$update = TestHelpers::getFakeUpdateObject();
$message = $update->getMessage();
$stub->setUpdate($update);
$this->assertAttributeEquals($update, 'update', $stub);
$this->assertEquals($update, $stub->getUpdate());
$this->assertAttributeEquals($message, 'message', $stub);
$this->assertEquals($message, $stub->getMessage());
}
/**
* @test
*/
public function testCommandWithConfigNotEmptyConfig()
{
$this->assertAttributeNotEmpty('config', $this->command_stub_with_config);
}
/**
* @test
*/
public function testCommandWithConfigCorrectConfig()
{
$this->assertAttributeEquals(['config_key' => 'config_value'], 'config', $this->command_stub_with_config);
$this->assertEquals(['config_key' => 'config_value'], $this->command_stub_with_config->getConfig(null));
$this->assertEquals(['config_key' => 'config_value'], $this->command_stub_with_config->getConfig());
$this->assertEquals('config_value', $this->command_stub_with_config->getConfig('config_key'));
$this->assertEquals(null, $this->command_stub_with_config->getConfig('not_config_key'));
}
}
<?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 Tests\Unit\Commands;
use Tests\Unit\TestCase;
use Longman\TelegramBot\Telegram;
/**
* @package TelegramTest
* @author Avtandil Kikabidze <akalongman@gmail.com>
* @copyright Avtandil Kikabidze <akalongman@gmail.com>
* @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)
* @link http://www.github.com/akalongman/php-telegram-bot
*/
class CommandTestCase extends TestCase
{
protected $telegram;
protected $command;
public function setUp()
{
$this->telegram = new Telegram('apikey', 'botname');
$this->telegram->addCommandsPath(BASE_COMMANDS_PATH . '/UserCommands');
$this->telegram->getCommandsList();
}
/**
* Make sure the version number is in the format x.x.x, x.x or x
*
* @test
*/
public function testVersionNumberFormat()
{
$this->assertRegExp('/^(\d+\\.)?(\d+\\.)?(\d+)$/', $this->command->getVersion());
}
}
<?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 Tests\Unit\Commands\UserCommands;
use Tests\Unit\Commands\CommandTestCase;
use Tests\TestHelpers;
use Longman\TelegramBot\Telegram;
use Longman\TelegramBot\Commands\UserCommands\EchoCommand;
/**
* @package TelegramTest
* @author Avtandil Kikabidze <akalongman@gmail.com>
* @copyright Avtandil Kikabidze <akalongman@gmail.com>
* @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)
* @link http://www.github.com/akalongman/php-telegram-bot
*/
class EchoCommandTest extends CommandTestCase
{
public function setUp()
{
parent::setUp();
$this->command = new EchoCommand($this->telegram);
}
/**
* @test
*/
public function testEchoCommandProperties()
{
$this->assertAttributeEquals('echo', 'name', $this->command);
$this->assertAttributeEquals('Show text', 'description', $this->command);
$this->assertAttributeEquals('/echo <text>', 'usage', $this->command);
}
/**
* @test
*/
public function testEchoCommandExecuteWithoutParameter()
{
$text = $this->command
->setUpdate(TestHelpers::getFakeUpdateCommandObject('/echo'))
->execute()
->getResult()
->getText();
$this->assertEquals('Command usage: /echo <text>', $text);
$text = $this->command
->setUpdate(TestHelpers::getFakeUpdateCommandObject('/echo '))
->execute()
->getResult()
->getText();
$this->assertEquals('Command usage: /echo <text>', $text);
}
/**
* @test
*/
public function testEchoCommandExecuteWithParameter()
{
$text = $this->command
->setUpdate(TestHelpers::getFakeUpdateCommandObject('/echo Message!'))
->execute()
->getResult()
->getText();
$this->assertEquals('Message!', $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 Tests\Unit\Commands\UserCommands;
use Tests\Unit\Commands\CommandTestCase;
use Tests\TestHelpers;
use Longman\TelegramBot\Commands\UserCommands\HelpCommand;
/**
* @package TelegramTest
* @author Avtandil Kikabidze <akalongman@gmail.com>
* @copyright Avtandil Kikabidze <akalongman@gmail.com>
* @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)
* @link http://www.github.com/akalongman/php-telegram-bot
*/
class HelpCommandTest extends CommandTestCase
{
public function setUp()
{
parent::setUp();
$this->command = new HelpCommand($this->telegram);
}
/**
* @test
*/
public function testHelpCommandProperties()
{
$this->assertAttributeEquals('help', 'name', $this->command);
$this->assertAttributeEquals('Show bot commands help', 'description', $this->command);
$this->assertAttributeEquals('/help or /help <command>', 'usage', $this->command);
}
/**
* @test
*/
public function testHelpCommandExecuteWithoutParameter()
{
$text = $this->command
->setUpdate(TestHelpers::getFakeUpdateCommandObject('/help'))
->execute()
->getResult()
->getText();
$this->assertContains(
"botname v. " . $this->telegram->getVersion() . "\n\nCommands List:",
$text
);
}
/**
* @test
*/
public function testHelpCommandExecuteWithParameterInvalidCommand()
{
$text = $this->command
->setUpdate(TestHelpers::getFakeUpdateCommandObject('/help invalidcommand'))
->execute()
->getResult()
->getText();
$this->assertEquals('No help available: Command /invalidcommand not found', $text);
}
/**
* @test
*/
public function testHelpCommandExecuteWithParameterValidCommand()
{
$text = $this->command
->setUpdate(TestHelpers::getFakeUpdateCommandObject('/help echo'))
->execute()
->getResult()
->getText();
$this->assertContains("Description: Show text\nUsage: /echo <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 Tests\Unit;
use Tests\TestHelpers;
use Longman\TelegramBot\Conversation;
use Longman\TelegramBot\Telegram;
/**
* @package TelegramTest
* @author Avtandil Kikabidze <akalongman@gmail.com>
* @copyright Avtandil Kikabidze <akalongman@gmail.com>
* @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)
* @link http://www.github.com/akalongman/php-telegram-bot
*/
class ConversationTest extends TestCase
{
/**
* @var \Longman\TelegramBot\Telegram
*/
private $telegram;
/**
* setUp
*/
protected function setUp()
{
$credentials = [
'host' => '127.0.0.1',
'user' => 'travis',
'password' => '',
'database' => 'telegrambot',
];
$this->telegram = new Telegram('testapikey', 'testbotname');
$this->telegram->enableMySQL($credentials);
//Make sure we start with an empty DB for each test.
TestHelpers::emptyDB($credentials);
}
/**
* @test
*/
public function conversationThatDoesntExistPropertiesSetCorrectly()
{
$conversation = new Conversation(123, 456);
$this->assertAttributeEquals(123, 'user_id', $conversation);
$this->assertAttributeEquals(456, 'chat_id', $conversation);
$this->assertAttributeEquals(null, 'command', $conversation);
}
/**
* @test
*/
public function conversationThatExistsPropertiesSetCorrectly()
{
$info = TestHelpers::startFakeConversation('command');
$conversation = new Conversation($info['user_id'], $info['chat_id'], 'command');
$this->assertAttributeEquals($info['user_id'], 'user_id', $conversation);
$this->assertAttributeEquals($info['chat_id'], 'chat_id', $conversation);
$this->assertAttributeEquals('command', 'command', $conversation);
}
/**
* @test
*/
public function conversationThatDoesntExistWithoutCommand()
{
$conversation = new Conversation(1, 1);
$this->assertFalse($conversation->exists());
$this->assertNull($conversation->getCommand());
}
/**
* @test
* @expectedException \Longman\TelegramBot\Exception\TelegramException
*/
public function conversationThatDoesntExistWithCommand()
{
new Conversation(1, 1, 'command');
}
/**
* @test
*/
public function newConversationThatWontExistWithoutCommand()
{
TestHelpers::startFakeConversation(null);
$conversation = new Conversation(0, 0);
$this->assertFalse($conversation->exists());
$this->assertNull($conversation->getCommand());
}
/**
* @test
*/
public function newConversationThatWillExistWithCommand()
{
$info = TestHelpers::startFakeConversation('command');
$conversation = new Conversation($info['user_id'], $info['chat_id'], 'command');
$this->assertTrue($conversation->exists());
$this->assertEquals('command', $conversation->getCommand());
}
/**
* @test
*/
public function stopConversation()
{
$info = TestHelpers::startFakeConversation('command');
$conversation = new Conversation($info['user_id'], $info['chat_id'], 'command');
$this->assertTrue($conversation->exists());
$conversation->stop();
$conversation2 = new Conversation($info['user_id'], $info['chat_id']);
$this->assertFalse($conversation2->exists());
}
/**
* @test
*/
public function cancelConversation()
{
$info = TestHelpers::startFakeConversation('command');
$conversation = new Conversation($info['user_id'], $info['chat_id'], 'command');
$this->assertTrue($conversation->exists());
$conversation->cancel();
$conversation2 = new Conversation($info['user_id'], $info['chat_id']);
$this->assertFalse($conversation2->exists());
}
/**
* @test
*/
public function updateConversationNotes()
{
$info = TestHelpers::startFakeConversation('command');
$conversation = new Conversation($info['user_id'], $info['chat_id'], 'command');
$conversation->notes = 'newnote';
$conversation->update();
$conversation2 = new Conversation($info['user_id'], $info['chat_id'], 'command');
$this->assertSame('newnote', $conversation2->notes);
$conversation3 = new Conversation($info['user_id'], $info['chat_id']);
$this->assertSame('newnote', $conversation3->notes);
}
}
<?php
/*
/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
......@@ -7,78 +7,83 @@
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tests\Unit;
use \Longman\TelegramBot\Telegram;
use Longman\TelegramBot\Telegram;
/**
* @package TelegramTest
* @author Avtandil Kikabidze <akalongman@gmail.com>
* @copyright Avtandil Kikabidze <akalongman@gmail.com>
* @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)
* @link http://www.github.com/akalongman/php-telegram-bot
* @package TelegramTest
* @author Avtandil Kikabidze <akalongman@gmail.com>
* @copyright Avtandil Kikabidze <akalongman@gmail.com>
* @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)
* @link http://www.github.com/akalongman/php-telegram-bot
*/
class TelegramTest extends TestCase
{
/**
* @var \Longman\TelegramBot\Telegram
*/
private $telegram;
/**
* setUp
*/
protected function setUp()
{
$this->telegram = new Telegram('testapikey', 'testbotname');
}
/**
* @var \Longman\TelegramBot\Telegram
*/
private $telegram;
/**
* setUp
*/
protected function setUp()
{
$this->telegram = new Telegram('testapikey', 'testbotname');
}
/**
* @test
* @expectedException \Longman\TelegramBot\Exception\TelegramException
*/
public function newInstanceWithoutParams() {
$telegram = new Telegram('testapikey', null);
$telegram = new Telegram(null, 'test');
public function newInstanceWithoutApiKeyParam()
{
new Telegram(null, 'testbotname');
}
/**
* @test
* @expectedException \Longman\TelegramBot\Exception\TelegramException
*/
public function getCommandsList() {
$commands = $this->telegram->getCommandsList();
$this->assertInternalType('array', $commands);
$this->assertNotCount(0, $commands);
public function newInstanceWithoutBotNameParam()
{
new Telegram('testapikey', null);
}
/**
* @test
*/
public function getCommandsClass() {
$command = $this->telegram->getCommandClass('help');
$this->assertInstanceOf('Longman\TelegramBot\Commands\HelpCommand', $command);
public function getApiKey()
{
$this->assertEquals('testapikey', $this->telegram->getApiKey());
}
/**
* @test
*/
public function getApiKey() {
$this->assertEquals('testapikey', $this->telegram->getApiKey());
public function getBotName()
{
$this->assertEquals('testbotname', $this->telegram->getBotName());
}
/**
* @test
*/
public function getBotName() {
$this->assertEquals('testbotname', $this->telegram->getBotName());
public function getCommandsList()
{
$commands = $this->telegram->getCommandsList();
$this->assertInternalType('array', $commands);
$this->assertNotCount(0, $commands);
}
/**
* @test
*/
public function getHelpCommandObject()
{
$command = $this->telegram->getCommandObject('help');
$this->assertInstanceOf('Longman\TelegramBot\Commands\UserCommands\HelpCommand', $command);
}
}
......@@ -12,5 +12,4 @@ class TestCase extends \PHPUnit_Framework_TestCase
);
}
}
}
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