Skip to content

Instantly share code, notes, and snippets.

@TrywaR
Last active November 15, 2023 11:24
Show Gist options
  • Save TrywaR/2e0bdad504545ed61a1ebb1059bd7fce to your computer and use it in GitHub Desktop.
Save TrywaR/2e0bdad504545ed61a1ebb1059bd7fce to your computer and use it in GitHub Desktop.
Telegram bot mini
<?php
// Telegram bot
// https://gist.github.com/TrywaR/2e0bdad504545ed61a1ebb1059bd7fce
// _____
// INFO
// Create bot go to telegram chat @BotFather
// send message "/createbot"
// copy and add ApiKey
// user send message to new bot
// and that bot send message to user, user go to chat witch bot, send message /start
// Telegram->send_to_user(message,username);
// %2b - adaptation sign +
class Telegram
{
static $sApiKey = ''; # Telegram API key
static $sChatId = ''; # chatid for responce message
static $sUserName = ''; # username for response message
public $sApiUrl = "https://api.telegram.org/bot";
// Bot messages response
function get_bot(): string
{
$sUrl = $this->sApiUrl . $this->sApiKey . "/getUpdates";
return file_get_contents($sUrl);
}
// Bot get chat id for username
function get_chat_id(String $sUserName): string
{
if (empty($sUserName)) die('Error: not parametre sUserName');
$oBot = json_decode($this->get_bot());
if (empty($oBot->result[0])) die('Error: not result');
foreach ($oBot->result as $oMessageResult) {
if (empty($oMessageResult->message)) continue;
foreach ($oMessageResult->message as $sKey => $oMessage) {
if ($sKey=='from' ){
if ($oMessage->username == $sUserName) {
return $oMessage->id;
}
}
}
}
die('Error: not find id');
}
// Bot send message to chat id
function send_to_chat(String $sMessage, String $sChatId): bool
{
if (empty($sMessage)) die('Error: not parametre sMessage');
if (empty($sChatId)) {
if (empty($this->sChatId)) die('Error: not parametre sChatId');
else $sChatId = $this->sChatId;
}
if ($this->send($sMessage, $sChatId)) return true;
else return false;
}
// Bot send message to username
function send_to_user(String $sMessage, String $sUserName): bool
{
if (empty($sMessage)) die('Error: not parametre sMessage');
if (empty($sUserName)) {
if (empty($this->sUserName)) die('Error: not parametre sUserName');
else $sUserName = $this->sUserName;
}
$sChatId = $this->get_chat_id($sUserName);
if ($this->send($sMessage, $sChatId)) return true;
else return false;
}
// Bot only send message
function send(String $sMessage, String $sChatId): bool
{
$sUrl = $this->sApiUrl . $this->sApiKey . "/sendMessage?chat_id=$sChatId&parse_mode=Markdown&text=$sMessage";
if (file_get_contents($sUrl)) return false;
return true;
}
function __construct(String $sApiKey)
{
$this->sApiKey = $sApiKey;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment