Skip to content

Instantly share code, notes, and snippets.

@habibg1232191
Created September 6, 2024 18:43
Show Gist options
  • Save habibg1232191/6a4ca21ae2081bff62a426af443e6fb7 to your computer and use it in GitHub Desktop.
Save habibg1232191/6a4ca21ae2081bff62a426af443e6fb7 to your computer and use it in GitHub Desktop.
<?php
use Longman\TelegramBot\Exception\TelegramException;
use Longman\TelegramBot\Telegram;
use Longman\TelegramBot\Request;
require_once "vendor/autoload.php";
class BalanceDb {
private static false|mysqli $db_connect;
/**
* @throws Exception
*/
static function init(): void {
//$connect_string = "host=localhost port=5432 dbname=sun user=postgres password=postgres";
BalanceDb::$db_connect = mysqli_connect(
"127.0.0.1",
"root",
database: "example"
);
mysqli_query(BalanceDb::$db_connect, "CREATE TABLE IF NOT EXISTS balance (
user_id FLOAT NOT NULL,
balance FLOAT NOT NULL
);");
}
static function showAll(): void
{
$self_connection = BalanceDb::$db_connect;
$result = mysqli_query($self_connection, "SELECT * FROM balance")->fetch_all();
print_r($result);
}
static function find(int $user_id): bool|array {
$self_connection = BalanceDb::$db_connect;
$result = mysqli_query($self_connection, "SELECT * FROM balance WHERE user_id = $user_id")->fetch_all();
if (empty($result)) {
return false;
}
return [
'user_id' => $user_id,
'balance' => $result[0][1]
];
}
static function updateBalance(int $user_id, float $balance): void {
$self_connection = BalanceDb::$db_connect;
mysqli_query(
$self_connection,
"UPDATE balance SET balance = $balance WHERE user_id = $user_id"
);
}
static function insertUser(array $data): void {
$self_connection = BalanceDb::$db_connect;
$user_id = $data["user_id"];
$balance = $data["balance"];
$query = "INSERT INTO balance (user_id, balance)
VALUES ($user_id, $balance);";
$result = mysqli_query($self_connection, $query);
}
static function isExists(int $user_id): bool
{
$self_connection = BalanceDb::$db_connect;
$result = mysqli_query($self_connection, "SELECT * FROM balance WHERE user_id = $user_id")->fetch_all();
if (empty($result)) {
return false;
}
return true;
}
static function closeConnection(): void {
mysqli_close(BalanceDb::$db_connect);
}
}
class BalanceUser {
private int $user_id;
private float $balance;
public function __construct(int $user_id, float $balance=null) {
$result = BalanceDb::find($user_id);
if (empty($result)) {
BalanceDb::insertUser([
'user_id' => $user_id,
'balance' => $balance == null ? 0 : $balance
]);
$this->__construct($user_id, $balance);
}
$old_balance = $result['balance'];
$new_balance = $balance !== null ? $balance : $old_balance;
$this->user_id = $user_id;
$this->balance = $new_balance;
}
public function addToBalance(float $amount): void {
$this->balance += $amount;
if($this->balance <= 0) {
$this->balance = 0;
}
BalanceDb::updateBalance($this->user_id, $this->balance);
}
public function removeFromBalance(float $amount): void {
$this->balance -= $amount;
BalanceDb::updateBalance($this->user_id, $this->balance);
}
public function getBalance(): float {
$result = BalanceDb::find($this->user_id);
$this->balance = $result['balance'];
return $this->balance;
}
public function getUserId(): int {
return $this->user_id;
}
}
function floatvalue($val): false|float {
$val = str_replace(",",".",$val);
$val = preg_replace('/\.(?=.*\.)/', '', $val);
if (empty(floatval($val))) {
return false;
}
return floatval($val);
}
class Watcher {
private Telegram $api;
function __construct($api) {
$this->api = $api;
}
function run() {
while (true) {
$server_response = $this->api->handleGetUpdates();
if ($server_response->isOk()) {
$result = $server_response->getResult();
foreach ($result as $message_item) {
$message = $message_item->getMessage();
$message_chat_id = $message->getFrom()->getId();
$message_text = $message->getText();
$count = floatvalue($message_text);
if(!$count) {
Request::sendMessage([
'chat_id' => $message_chat_id,
'text' => 'Введите корректные данные.',
]);
continue;
}
if(BalanceDb::isExists($message_chat_id)) {
$balance = new BalanceUser($message_chat_id);
$balance->addToBalance($count);
Request::sendMessage([
'chat_id' => $message_chat_id,
'text' => 'Ваш баланс состовляет: $' . $balance->getBalance(),
]);
} else {
BalanceDb::insertUser([
'user_id' => $message_chat_id,
'balance' => $count,
]);
Request::sendMessage([
'chat_id' => $message_chat_id,
'text' => 'Здраствуйте. Ваш первоначальный баланс состовляет: $' . $count,
]);
}
}
}
}
}
}
$bot_api_key = '6416835660:AAEtrTOVR3sCcQYUWqXbrKBW0CntxMiqyCI';
$bot_username = 'balance_example_app_bot';
try {
$telegram = new Longman\TelegramBot\Telegram($bot_api_key, $bot_username);
$telegram->useGetUpdatesWithoutDatabase();
BalanceDb::init();
$watcher = new Watcher($telegram);
$watcher->run();
BalanceDb::closeConnection();
} catch (TelegramException $e) {
echo $e->getMessage();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment