Telegram, Bot e PowerShell, uma máquina de alerta

Getting your Trinity Audio player ready...

Como DBA´s estamos sujeitos a jobs, alertas, sistemas, coisas do além, gerentes, desenvolvedores, intervenções místicas, etc. executando ações no banco de dados.

Não da pra ficar olhando de perto o ambiente a todo o momento analisando cada ação, monitorando tudo o que ocorre, se preparando para o pior.

Sendo um bom DBA, você deve ter um monte de Jobs, Alertas, Operadores, Sistemas de Monitoração, aquele estagiário sendo escalpelado, entre outras formas de monitorar seus bancos, a ideia aqui é trazer mais uma opção para atazanar sua vida monótona.

Vamos a receita do desastre,,, Para isso vamos precisar:

  1. Que você tenha uma conta no Telegram
  2. Instale o aplicativo do Telegram no seu Windows
  3. Crie um Bot
  4. Configure o Bot
  5. Crie um canal e adicione esse Bot como administrador a um canal
  6. Mande uma mensagem para esse canal para criar um ID
  7. Acesse uma URL do Telegram com a chave do BOT para pegar o ID do canal
  8. Crie uma função no Powershell
  9. Declare a variável com o nome do Bot e a chave
  10. Mande uma mensagem

Vamos começar,,,

Conta do Telegram

  • PQ está lendo essa parte? vai para a próxima,,, se não sabe fazer isso nem adianta continuar…

Instale o aplicativo do Telegram no seu Windows

  • Esse ponto é interessante, acesse o cliente web do Telegram e baixe a versão para seu SO, as configurações do Bot serão feitas através do cliente e não pelo celular ou Web

Crie um Bot

  • Com sua contra criada e app instalado, acesse essa URL https://t.me/BotFather . Ele é o Bot que cria os Bot´s
  • Para criar digite /start
  • Depois digite /newbot
  • De um nome para seu Bot
  • Agora crie um username para seu bot, ele tem que terminar com bot
  • Você vai receber uma mensagem de resposta com um textão e a parte que interessa que é o TOKEN. ANOTA ISSO!
  • Aqui vale uma dica, o Bot vai aparecer em pesquisa para qualquer pessoa que use o Telegram, mas só quem tem o token vai poder realmente usar ele.

Configure o Bot

  • Adicione uma descrição para ele, uma hora você ou alguém vai fazer manutenção e vai ter que lembrar para que ele serve
  • Usando /setdescription adicione uma descrição

Crie um canal e adicione esse Bot como administrador a um canal

  • Agora usando o cliente do SO, Web ou o app do celular, crie um canal no Telegram e deixe como privado.
  • Adicione um novo membro para esse canal, nesse caso o seu Bot, vai aparecer um alerta de que o Bot precisa ser administrador do canal e bla bla bla

Mande uma mensagem para esse canal para criar um ID

  • Só o fato de criar um canal não efetiva cria o canal, até esse momento ele não tem um ID
  • Mande uma mensagem qualquer para o canal para ele criar a estrutura com o ID

Acesse uma URL do Telegram com a chave do BOT para pegar o ID do canal

  • Após mandar a mensagem acesse a URL com o token do seu Bot
  • a URL é alguma coisa assim: https://api.telegram.org/bot<aquele token do seu Bot>/getUpdates
  • deixa escrito o nome bot, remove o < e o > e cola o token
  • deve abrir uma página com alguma coisa parecida com:
{"ok":true,"result":[{"update_id":129494597,
"message":{"message_id":3,"from":{"id":XXXXXX,"is_bot":false,"first_name":"Ricardo","last_name":"Leka"},"chat":{"id":XXXXXX,"first_name":"Ricardo","last_name":"Leka","type":"private"},"date":1614187816,"text":"/start","entities":[{"offset":0,"length":6,"type":"bot_command"}]}},{"update_id":129494598,
"message":{"message_id":4,"from":{"id":XXXXXX,"is_bot":false,"first_name":"Ricardo","last_name":"Leka","language_code":"pt-br"},"chat":{"id":XXXXXX,"first_name":"Ricardo","last_name":"Leka","type":"private"},"date":1614187832,"text":"/getchatid","entities":[{"offset":0,"length":10,"type":"bot_command"}]}},{"update_id":129494599,
"channel_post":{"message_id":2,"sender_chat":{"id":-XXXX,"title":"MC1_Notify","type":"channel"} ,"chat":{"id":-XXXX,"title":"Nome_Do_Canal","type":"channel"} ,"date":1614187878,"text":"teste"}}]}

O que interessa para nós é um desses últimos “id” que estão com um símbolo de menos na frente “id”:-XXXX

Crie uma função no Powershell

  • Agora a parte mágica, vamos usar um powershell para criar a função que vai conectar na API do Telegram e mandar a mensagem…
<#
.Synopsis
    Sends Telegram text message via Bot API
.DESCRIPTION
    Uses Telegram Bot API to send text message to specified Telegram chat. Several options can be specified to adjust message parameters.
.EXAMPLE
    $bot = "#########:xxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxx"
    $chat = "-#########"
    Send-TelegramTextMessage -BotToken $bot -ChatID $chat -Message "Hello"
.EXAMPLE
    $bot = "#########:xxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxx"
    $chat = "-#########"

    Send-TelegramTextMessage `
        -BotToken $bot `
        -ChatID $chat `
        -Message "Hello *chat* _channel_, check out this link: [TechThoughts](http://techthoughts.info/)" `
        -ParseMode Markdown `
        -Preview $false `
        -Notification $false `
        -Verbose
.PARAMETER BotToken
    Use this token to access the HTTP API
.PARAMETER ChatID
    Unique identifier for the target chat
.PARAMETER Message
    Text of the message to be sent
.PARAMETER ParseMode
    Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message. Default is Markdown.
.PARAMETER Preview
    Disables link previews for links in this message. Default is $false
.PARAMETER Notification
    Sends the message silently. Users will receive a notification with no sound. Default is $false
.OUTPUTS
    System.Boolean
.NOTES
    Author: Jake Morrison - @jakemorrison - http://techthoughts.info/
    This works with PowerShell Versions 5.1, 6.0, 6.1
    For a description of the Bot API, see this page: https://core.telegram.org/bots/api
    How do I get my channel ID? Use the getidsbot https://telegram.me/getidsbot
    How do I set up a bot and get a token? Use the BotFather https://t.me/BotFather
.COMPONENT
   PoshGram - https://github.com/techthoughts2/PoshGram
.FUNCTIONALITY
    https://core.telegram.org/bots/api#sendmessage
    Parameters 					Type 				Required 	Description
    chat_id 				    Integer or String 	Yes 		Unique identifier for the target chat or username of the target channel (in the format @channelusername)
    text 						String 				Yes 		Text of the message to be sent
    parse_mode 					String 				Optional 	Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message.
    disable_web_page_preview 	Boolean 			Optional 	Disables link previews for links in this message
    disable_notification 		Boolean 			Optional 	Sends the message silently. Users will receive a notification with no sound.
    reply_to_message_id 	    Integer 			Optional 	If the message is a reply, ID of the original message
#>
function Send-TelegramTextMessage {
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory = $true,
            HelpMessage = '#########:xxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxx')]
        [ValidateNotNull()]
        [ValidateNotNullOrEmpty()]
        [string]$BotToken, #you could set a token right here if you wanted
        [Parameter(Mandatory = $true,
            HelpMessage = '-#########')]
        [ValidateNotNull()]
        [ValidateNotNullOrEmpty()]
        [string]$ChatID, #you could set a Chat ID right here if you wanted
        [Parameter(Mandatory = $true,
            HelpMessage = 'Text of the message to be sent')]
        [ValidateNotNull()]
        [ValidateNotNullOrEmpty()]
        [string]$Message,
        [Parameter(Mandatory = $false,
            HelpMessage = 'HTML vs Markdown for message formatting')]
        [ValidateSet("Markdown", "HTML")]
        [string]$ParseMode = "Markdown", #set to Markdown by default
        [Parameter(Mandatory = $false,
            HelpMessage = 'Disables link previews')]
        [bool]$Preview = $false, #set to false by default
        [Parameter(Mandatory = $false,
            HelpMessage = 'Sends the message silently')]
        [bool]$Notification = $false #set to false by default
    )
    #------------------------------------------------------------------------
    $results = $true #assume the best
    #------------------------------------------------------------------------
    $payload = @{
        "chat_id"                   = $ChatID;
        "text"                      = $Message
        "parse_mode"                = $ParseMode;
        "disable_web_page_preview"  = $Preview;
        "disable_notification"      = $Notification
    }#payload
    #------------------------------------------------------------------------
    try {
        Write-Verbose -Message "Sending message..."
        $eval = Invoke-RestMethod `
            -Uri ("https://api.telegram.org/bot{0}/sendMessage" -f $BotToken) `
            -Method Post `
            -ContentType "application/json" `
            -Body (ConvertTo-Json -Compress -InputObject $payload) `
            -ErrorAction Stop
        if (!($eval.ok -eq "True")) {
            Write-Warning -Message "Message did not send successfully"
            $results = $false
        }#if_StatusDescription
    }#try_messageSend
    catch {
        Write-Warning "An error was encountered sending the Telegram message:"
        Write-Error $_
        $results = $false
    }#catch_messageSend
    return $results
    #------------------------------------------------------------------------
}#function_Send-TelegramTextMessage

Declare a variável com o nome do Bot e a chave

  • Sendo simplista você vai precisar agora criar duas variáveis a com o nome do Token e o ID do chat
$bot = "token"
$chat = "-ID_do_chat"

Mande uma mensagem

  • Agora é só chamar a função e mandar a mensagem…
  • AAHH a máquina precisa ter acesso a internet.
  • Qualquer mensagem de erro a função vai tentar trazer a mensagem para te ajudar no troubleshooting.
$bot = "token"
$chat = "-ID_do_chat"
Send-TelegramTextMessage -BotToken $bot -ChatID $chat -Message "CASA CAIU"

Com isso agora temos um powershell que acessa uma API do Telegram e manda mensagem, junta isso em um JOB que é acionado por um alerta e vc tem o SQL ou outro sistema de monitoração mandando mensagens para seu celular.

Leave a Reply

Your email address will not be published. Required fields are marked *