Наша библиотека вновь обновлена, посему продолжим учиться создавать Телеграм-ботов. В сегодняшней статье поговорим о реализации системы мута пользователей.
Для понимания принципа работы нашей задумки - пройдёмся по изменениям в библиотеке и её новым возможностям. Изменения коснулись по сути только класса Bot. Итак, начинаем разбирать:
public function deleteMessage( int $chat_id, int $message_id ) : void
{
$this->request( 'deleteMessage', [ 'chat_id' => $chat_id, 'message_id' => $message_id ] );
}
public function memberStatus( int $chat_id, int $user_id ) : string|false|null
{
$member_info = $this->request( 'getChatMember', [ 'chat_id' => $chat_id, 'user_id' => $user_id ] );
return ( $member_info['result']
? ( $member_info['result']['status'] == 'creator' ) ? 'creator'
: ( $member_info['result']['status'] == 'left' ? 'left' : false ) : null );
}
public function mute( int $chat_id, int $user_id, string $unit = '', int $value = 0, string $reason = '' ) : void
{
[ $arr, $mutes_file ] = $this->blacklistCache( 'mutes' );
$arr[$chat_id . '_' . $user_id] = [
'duration' => $this->durationCount( $unit, $value ),
'reason' => $reason,
];
$this->record( $arr, $mutes_file );
}
public function unMute( int $chat_id, int $user_id ) : void
{
[ $arr ] = $this->blacklistCache( 'mutes' );
unset( $arr[$chat_id . '_' . $user_id] );
}
public function isMuted( int $chat_id, int $user_id ) : bool
{
[ $arr ] = $this->blacklistCache( 'mutes' );
if ( isset( $arr[$chat_id . '_' . $user_id] ) and $arr[$chat_id . '_' . $user_id]['duration'] >= time() )
return true;
return false;
}
private function blacklistCache( string $type ) : array
{
if ( !is_dir( self::$cache_dir ) )
mkdir( self::$cache_dir );
$bans_file = self::$cache_dir . '/' . $type . '.php';
$arr = file_exists( $bans_file ) ? require $bans_file : [];
return [ $arr, $bans_file ];
}
private function durationCount( string $unit = '', int $value = 0 ) : int
{
if ( str_starts_with( $unit, 'с' ) or str_starts_with( $unit, 's' ) )
$duration = time() + $value;
else if ( str_starts_with( $unit, 'м' ) or str_starts_with( $unit, 'm' ) )
$duration = time() + ( $value * 60 );
else if ( str_starts_with( $unit, 'ч' ) or str_starts_with( $unit, 'h' ) )
$duration = time() + ( $value * 60 * 60 );
else if ( str_starts_with( $unit, 'д' ) or str_starts_with( $unit, 'd' ) )
$duration = time() + ( $value * 60 * 60 * 24 );
else
$duration = 1.e10;
return $duration;
}
protected function record( array $arr, string $path ) : false|int
{
$str = "<?php\n\nreturn " . var_export( $arr, true ) . ";\n";
return file_put_contents( $path, $str, LOCK_EX );
}
Теперь переходим непосредственно к написанию бота. Создаём php-файл, подключаем библиотеку, создаём экземпляр класса Bot и инициализируем необходимые перменные:
<?php
require_once __DIR__ . '/telekot/autoload.php'; // Подключение библиотеки
$tg = \telekot\Bot::create( '*************************' ) // Создаём экземпляр класса Bot, передаём в метод create() токен бота
->initData( $data )
->initChatId( $chat_id ) // Инициализируем айди чата, из которого поступают боту сообщения (например, это может быть айди пользователя, написавшего боту)
->initUserId( $user_id ) // Инициализация ID пользователя
->initMessage( $message ); // Инициализируем текст сообщения, которе было отправлено боту
Мы уже рассмотрели метод isMuted(), поэтому теперь смело можем его применять. А применять мы его будем для того, чтобы удалять сообщения юзеров, которые были замучены:
if ( $tg->isMuted( $chat_id, $user_id ) )
{
$tg->deleteMessage( $chat_id, $data['message']['message_id'] );
}
Теперь все сообщения от заткнутых пользователей бот будет автоматически подчищать.
Далее переходим к реализации самого мута. Чтобы такая привилегия была исключительно у администраторов - проверяем роль пользователя, который ввёл команду, с помощью метода memberStatus():
else if ( str_starts_with( $message, '/' ) )
{
if ( $tg->memberStatus( $chat_id, $user_id ) )
{
// Тут продолжим писать код
}
}
Условие выполнится только если будет возвращена строка (creator или left). Напомню, что для обычных пользователей возвращается false.
Теперь, когда проверка пройдена - можно раздробить команду на части через пробелы и далее обработать её:
$message_data = explode( ' ', $message );
switch ( $message_data[0] )
{
case '/мут':
{
$tg->mute( $chat_id, $data['message']['reply_to_message']['from']['id'], $message_data[2], $message_data[1], $message_data[3] ?? '' );
$tg->reply( 'Пользователь заткнут' );
break;
}
case '/размут':
{
$tg->unMute( $chat_id, $data['message']['reply_to_message']['from']['id'] );
$tg->reply( 'Пользователь размучен' );
break;
}
}
И на этом, пожалуй, всё 🙃
Нашли ошибку?
Вы можете сообщить об этом администрации.
Выделив текст нажмите CTRL+Enter