-
Notifications
You must be signed in to change notification settings - Fork 13
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Implement Telegram bot with advanced anti-spam features
- Loading branch information
Showing
5 changed files
with
207 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
<?php | ||
|
||
namespace App\Http\Controllers; | ||
|
||
use App\Services\TelegramBot; | ||
use Illuminate\Http\Request; | ||
|
||
class WebHookController extends Controller | ||
{ | ||
/** | ||
* Handle incoming Telegram webhook requests. | ||
* | ||
* @param \Illuminate\Http\Request $request | ||
* @param \App\Services\TelegramBot $telegramBot | ||
* | ||
* @return void | ||
*/ | ||
public function telegram(Request $request, TelegramBot $telegramBot): void | ||
{ | ||
$text = $request->input('message.text'); | ||
$messageId = $request->input('message.message_id'); | ||
$chatId = $request->input('message.chat.id'); | ||
$from = $request->input('message.from.id'); | ||
|
||
// Если сообщение - ответ на другое сообщение, то скорее всего это не спам. | ||
// Давайте не прерывать дискуссию и игнорируем его | ||
if ($request->has('message.reply_to_message') || $request->boolean('message.from.is_bot')) { | ||
return; | ||
} | ||
|
||
if (! $telegramBot->isSpam($text)) { | ||
return; | ||
} | ||
|
||
$telegramBot->deleteMessage($chatId, $messageId); | ||
$telegramBot->muteUserInGroup($chatId, $from); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,115 @@ | ||
<?php | ||
|
||
namespace App\Services; | ||
|
||
use AssistedMindfulness\NaiveBayes\Classifier; | ||
use Illuminate\Http\Client\Response; | ||
use Illuminate\Support\Facades\Http; | ||
use Illuminate\Support\Str; | ||
use NotificationChannels\Telegram\TelegramMessage; | ||
|
||
class TelegramBot | ||
{ | ||
public const SPAM = 'spam'; | ||
public const HAM = 'ham'; | ||
|
||
private $token; | ||
|
||
/** | ||
* Construct a new TelegramBot instance. | ||
* | ||
* @return void | ||
*/ | ||
public function __construct() | ||
{ | ||
$this->token = config('services.telegram-bot-api.token'); | ||
} | ||
|
||
/** | ||
* Mute a user in a group chat. | ||
* | ||
* @param int $chatId | ||
* @param int $userId | ||
* @param int $muteDuration | ||
* | ||
* @return \Illuminate\Http\Client\Response | ||
*/ | ||
public function muteUserInGroup($chatId, $userId, $muteDuration = 60): Response | ||
{ | ||
$url = "https://api.telegram.org/bot{$this->token}/restrictChatMember"; | ||
|
||
return Http::post($url, [ | ||
'chat_id' => $chatId, | ||
'user_id' => $userId, | ||
'until_date' => time() + $muteDuration, | ||
'can_send_messages' => false, | ||
'can_send_media_messages' => false, | ||
'can_send_other_messages' => false, | ||
'can_add_web_page_previews' => false, | ||
]); | ||
} | ||
|
||
/** | ||
* Delete a message from a chat. | ||
* | ||
* @param int $chatId | ||
* @param int $messageId | ||
* | ||
* @return \Illuminate\Http\Client\Response | ||
*/ | ||
public function deleteMessage($chatId, $messageId): Response | ||
{ | ||
$url = "https://api.telegram.org/bot{$this->token}/deleteMessage"; | ||
|
||
return Http::post($url, [ | ||
'chat_id' => $chatId, | ||
'message_id' => $messageId, | ||
]); | ||
} | ||
|
||
/** | ||
* Check if a message is spam. | ||
* | ||
* @param string $message | ||
* | ||
* @return bool | ||
*/ | ||
public function isSpam(string $message): bool | ||
{ | ||
$classifier = new Classifier(); | ||
|
||
$classifier | ||
/** | ||
* Spam | ||
*/ | ||
->learn('Здрaвcтвyйте, прeдостaвляю yдалённyю зaнятoсть. 770$+ в нeдeлю Кoмy интepeсно, пишитe "+" в личные', static::SPAM) | ||
->learn('Всeх привeтствую. Нyжны пaртнёры для удалённoгo сoтрудничeства. Пoдробнoсти в лс', static::SPAM) | ||
|
||
/** | ||
* Hamming | ||
*/ | ||
->learn('а учусь я потому что хочу работу нормальную найти и чтоб дети жили нормально)', static::HAM) | ||
->learn('у тебя переменная передается не так надо массив ->asyncParameters()', static::HAM) | ||
->learn('MVC. Можно ещё там использовать сервис контейнеры, фасады, view-model', static::HAM) | ||
->learn('Попробуем, спасибо 🙏', static::HAM) | ||
->learn('https://laravel.com/docs/', static::HAM) | ||
->learn('Да', static::HAM) | ||
->learn('Получилось', static::HAM); | ||
|
||
TelegramMessage::create() | ||
->to(config('services.telegram-bot-api.chat_id')) | ||
->line('*Сообщение было классифицировано как '.$classifier->most($message)) | ||
->line('') | ||
->line('*📂 Текст сообщения*') | ||
->escapedLine($message) | ||
->send(); | ||
|
||
return Str::of($message)->contains([ | ||
'yдалённyю', | ||
'в нeдeлю', | ||
'интepeсно', | ||
'пaртнёры', | ||
'сoтрудничeств', | ||
]); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters