Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 16 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ composer require devrabie/php-telegram-bot-plus

## 🚀 Using the Redis Helper

This library provides a simple helper to integrate a [Predis](https://github.com/predis/predis) client, allowing you to easily use Redis for your custom data persistence needs (e.g., storing user states, settings, caching). The library itself remains stateless.
This library provides a simple helper to integrate a Redis client, allowing you to easily use Redis for your custom data persistence needs (e.g., storing user states, settings, caching). The library itself remains stateless.

### 1. Enable Redis

Expand All @@ -47,12 +47,11 @@ $bot_username = 'YOUR_BOT_USERNAME';
$telegram = new Longman\TelegramBot\Telegram($bot_api_key, $bot_username);

// Initialize the Redis client and make it available to all commands
// Default connection: tcp://127.0.0.1:6379
// Default connection: 127.0.0.1:6379
$telegram->enableRedis();

// Or with custom connection parameters:
// $telegram->enableRedis([
// 'scheme' => 'tcp',
// 'host' => 'your-redis-host',
// 'port' => 6379,
// // 'password' => 'your-redis-password'
Expand All @@ -64,8 +63,7 @@ $telegram->handle();

### 2. Use Redis in Your Commands

You can access the shared Redis client instance from any command class using `getRedis()`:

You can access the shared Redis client instance from any command class using automatic dependency injection. Simply add a `redis` property to your command class and it will be automatically populated:
```php
<?php

Expand All @@ -81,21 +79,22 @@ class SettingsCommand extends UserCommand
protected $usage = '/settings';
protected $version = '1.0.0';

/**
* @var \Redis
*/
protected $redis;

public function execute()
{
$message = $this->getMessage();
$chat_id = $message->getChat()->getId();

// Get the shared Redis client instance.
/** @var \Predis\Client|null $redis */
$redis = $this->getTelegram()->getRedis();

if ($redis) {
if ($this->redis) {
$settings_key = 'bot:settings:' . $chat_id;

// Example: Use Redis to store custom settings for a chat
$redis->hset($settings_key, 'language', 'en');
$lang = $redis->hget($settings_key, 'language');
$this->redis->hset($settings_key, 'language', 'en');
$lang = $this->redis->hget($settings_key, 'language');

$text = 'Language set to: ' . $lang . ' (using Redis!)';
} else {
Expand All @@ -110,6 +109,11 @@ class SettingsCommand extends UserCommand
}
```

You can also access the Redis instance statically from anywhere in your project:
```php
$redis = \Longman\TelegramBot\Telegram::getRedis();
```

---

🙏 Acknowledgments
Expand Down
1 change: 0 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@
"ext-json": "*",
"ext-mbstring": "*",
"guzzlehttp/guzzle": "^6.0|^7.0",
"predis/predis": "^2.0",
"psr/log": "^1.1|^2.0|^3.0"
},
"require-dev": {
Expand Down
265 changes: 265 additions & 0 deletions src/Conversation.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,265 @@
<?php

/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <[email protected]>
*
* 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\Exception\TelegramException;

/**
* 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 man
aging the conversation.
*/
class Conversation
{
/**
* All information fetched from the database
*
* @var array|null
*/
protected $conversation;

/**
* Notes stored inside the conversation
*
* @var mixed
*/
protected $protected_notes;

/**
* Notes to be stored
*
* @var mixed
*/
public $notes;

/**
* 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 constructor to initialize a new conversation
*
* @param int $user_id
* @param int $chat_id
* @param string $command
*
* @throws TelegramException
*/
public function __construct(int $user_id, int $chat_id, string $command = '')
{
$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 !== '') {
//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(): bool
{
$this->conversation = null;
$this->protected_notes = null;
$this->notes = null;

return true;
}

/**
* Load the conversation from the database
*
* @return bool
* @throws TelegramException
*/
protected function load(): bool
{
//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(): bool
{
return $this->conversation !== null;
}

/**
* Start a new conversation if the current command doesn't have one yet
*
* @return bool
* @throws TelegramException
*/
protected function start(): bool
{
if (
$this->command
&& !$this->exists()
&& 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
* @throws TelegramException
*/
public function stop(): bool
{
return $this->updateStatus('stopped') && $this->clear();
}

/**
* Cancel the current conversation
*
* @return bool
* @throws TelegramException
*/
public function cancel(): bool
{
return $this->updateStatus('cancelled') && $this->clear();
}

/**
* Update the status of the current conversation
*
* @param string $status
*
* @return bool
* @throws TelegramException
*/
protected function updateStatus(string $status): bool
{
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
* @throws TelegramException
*/
public function update(): bool
{
if ($this->exists()) {
$fields = ['notes' => json_encode($this->notes, JSON_UNESCAPED_UNICODE)];
//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
*/
public function getCommand(): string
{
return $this->command;
}

/**
* Retrieve the user id
*
* @return int
*/
public function getUserId(): int
{
return $this->user_id;
}

/**
* Retrieve the chat id
*
* @return int
*/
public function getChatId(): int
{
return $this->chat_id;
}
}
Loading