-
-
Notifications
You must be signed in to change notification settings - Fork 187
/
ImageCommand.php
110 lines (93 loc) · 2.76 KB
/
ImageCommand.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
<?php
/**
* This file is part of the PHP Telegram Bot example-bot package.
* https://github.com/php-telegram-bot/example-bot/
*
* (c) PHP Telegram Bot Team
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* User "/image" command
*
* Randomly fetch any uploaded image from the Uploads path and send it to the user.
*/
namespace Longman\TelegramBot\Commands\UserCommands;
use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Entities\ServerResponse;
use Longman\TelegramBot\Exception\TelegramException;
use Longman\TelegramBot\Request;
class ImageCommand extends UserCommand
{
/**
* @var string
*/
protected $name = 'image';
/**
* @var string
*/
protected $description = 'Randomly fetch any uploaded image';
/**
* @var string
*/
protected $usage = '/image';
/**
* @var string
*/
protected $version = '1.2.0';
/**
* Main command execution
*
* @return ServerResponse
* @throws TelegramException
*/
public function execute(): ServerResponse
{
$message = $this->getMessage();
// Use any extra parameters as the caption text.
$caption = trim($message->getText(true));
// Make sure the Upload path has been defined and exists.
$upload_path = $this->telegram->getUploadPath();
if (!is_dir($upload_path)) {
return $this->replyToChat('Upload path has not been defined or does not exist.');
}
// Get a random picture from the Upload path.
$random_image = $this->getRandomImagePath($upload_path);
if ('' === $random_image) {
return $this->replyToChat('No image found!');
}
// If no caption is set, use the filename.
if ('' === $caption) {
$caption = basename($random_image);
}
return Request::sendPhoto([
'chat_id' => $message->getFrom()->getId(),
'caption' => $caption,
'photo' => $random_image,
]);
}
/**
* Return the path to a random image in the passed directory.
*
* @param string $dir
*
* @return string
*/
private function getRandomImagePath($dir): string
{
if (!is_dir($dir)) {
return '';
}
// Filter the file list to only return images.
$image_list = array_filter(scandir($dir), function ($file) {
$extension = pathinfo($file, PATHINFO_EXTENSION);
return in_array($extension, ['png', 'jpg', 'jpeg', 'gif']);
});
if (!empty($image_list)) {
shuffle($image_list);
return $dir . '/' . $image_list[0];
}
return '';
}
}