Telegrams-bot to the system administrator

Telegram-bot for system administrators. It is in any case not a finished project, it needs some work. It is prefabricated and set of techniques which each administrator may be filed under their different tasks.


The article contains examples of several bots and examples of API telegrams from powershell.

this contains info how to zaregat bot and get a token
Before you continue you should have a token for the bot to register your boat and receive a token need to find the user @BotFather and to write to it. We are interested in /newbot then you will need the name and the bot name, you can write whatever you want most importantly at the end put _bot. When the name is selected you BotFather returns to you a token and a link to the bot to quickly add. This bot check the bot ends.

To quickly add a bot and make it possible to quickly add it to itself it is best to use a special link starting with the @ symbol, it can take in the info:




if such a link really may send it he can just click on it to chat with your bot

the

templates adminbots


Simple bot
Pros:

the
    the
  • small — only about 300 lines
  • the
  • to perform the commands described in functions logic
  • the
  • can receive and send messages
  • the
  • can receive files
  • the
  • there is a check for the password
  • the
  • keeps a log of prislanyh teams
  • the
  • can open multiple sessions for simultaneous operation (not implemented fully. But to interact with several people simultaneously

Cons:

the
    the
  • too simple authorization. The password will be in chat on the device. Can't distinguish the device

download simple bot here, the archive contains: 1. help with examples of text layout; 2. the source

To start you need to get a token bot from BotFather as described in the beginning of the article and register in variable $token script. Work should be immediately.



The functionality to add to the function of logic

Complex bot
Plus:

the
    the
  • Small — only about 450 lines
  • the
  • to perform the commands described in functions logic
  • the
  • Can receive and send messages
  • the
  • Can receive files
  • the
  • Is checked on the password can optionally check the chat_id
  • the
  • keeps a log of prislanyh teams
  • the
  • Can open multiple sessions for simultaneous operation (not implemented fully. In the last stage has pricecialis a console if you work in it then other users will hang, and maybe kick by timeout.

The functionality which was implemented for example:

the
    the
  • Can be files, puts them in daddy
  • the
  • Can show files from daddy
  • the
  • Can delete files from the upload folder
  • the
  • Can run the file for execution (via start-process)
  • the
  • Shows list of servers with which you are working (just a list of names in a text file)
  • Pings to the servers from a list and shows which ones are online the

  • Disconnects the computers from the list
  • the
  • Shows users zalgiriukas on the terminal makes a call to an external script (need to install terminal PSTerminalServices)
  • the
  • Makes logoff user at the terminal. Enter the console mode and then write the user name (need to be installed on the terminal PSTerminalServices)
  • the
  • Makes a screenshot of a computer running (but does not pass back)
  • the
  • Opens ssh-the session with device on your network and switches to the mode of entering commands (for example, creditably and address hardcoded in the script. It requires installation on a machine with a be given to the management module ssh into the box poshSSH)
  • That was not implemented, but I would like:

    the
      the
    • Reverse file transfer (write who knows how to do it via powershell)
    • the
    • Incomplete support multi-user collaboration
    • the
    • Defective console mode

    Download bot here, the archive contains:
    1. help with examples of the text markup.
    2. configuration file config.csv;
    3. bot — abormot.ps1;
    4. a set of auxiliary files;
    5. list of computers to work in a text file ping-list.txt

    To start you need to get a token bot from BotFather as described in the beginning of the article and specify in the configuration file config.csv. Work should be immediately.



    The functionality to add to the function of logic

Bot self making Unlock uchetok domain
In some organizations the information security requirements if the password is entered wrong a certain number of times then Loshitsa account for a certain time. To remove the lock the user must call the administrator. This bot is made so that it is possible to write the name of the account and it unlocks, but no more than 3 times a day. If the limit is exceeded it will redirect the user to the system administrator and will send the notification to him to chat.

Download bot here.

To start you need to get a token bot from BotFather to register the token into the variable $token. To put a chat room administrator in $adminChatID. To register the domain address of the machine and creditably to it:



I built the example unlock feature directly into the script, for permanent use it is best to create the response to the event log and to generate the event. The event will run the script to unlock from a site that is only available to admins, so you will not forget the password from the domain in the script. This is important.

Bot that accepts files from a familiar user
for Example, we need to push share photos from users on the road, or just make the files and know from whom they came and whom to send. Below is an example of a bot host photos from familiar users

Download bot here.

To start you need to get a token bot from BotFather to register the token into the variable $token, put your chat in switch 235 of the row. Work should immediately. Don't forget to add your desired chat switch

How to work with bot api


the

1. To receive a message


You need to perform Invoke-WebRequest

the
https://api.telegram.org/bot{Token}/getUpdates?offset={ordinal message-ID}&timeout={timeout before returning, in seconds}

{Token} — the token received from the bot BotFather
{ordinal message-ID} — first 0 for subsequent last + 1. If you specify the last number you will receive each time the last message.
{timeout before returning, in seconds} — the time that telegrams will wait for answer if it's not there before returning back the empty structure. Suitable for creating a delay in the bot. I used Botica delay 1 second to wait for debugging.
the output to get the structure JSON which parsim by ConvertFrom-Json

code Listing No. 1
the
$ChatTimeout = 1
$UpdateId = 0
$token = "token bot"

$URL = "https://api.telegram.org/bot$token/getUpdates?offset=$UpdateId&timeout=$ChatTimeout"

$Request = Invoke-WebRequest -Uri $URL -Method Get
$content = ConvertFrom-Json $Request.content

# if the output of 2 or more of the results we take only the last
$str = $content.result | select -First 1
$str = ($str).message

$props = [ordered]@{ 
ok = $content.ok
UpdateId = ($str).update_id
Message_ID = $str.message_id
first_name = ($str.from).first_name
last_name = ($str.from).last_name
chat_id = ($str.chat).id
text = $str.text
}

$obj

The output in the object $obj will be the message and from whom it came.

the

2. Download the file


If you have uploaded a file in the structure JSON will be passed additional parameters. To get the file we need to get file_id from the message, then go to the url:

the
https://api.telegram.org/bot{token}/getFile?file_id={file_id message}

The request will return a JSON structure containing the path for download. Then download the file from the link

the
https://api.telegram.org/file/bot{token}/{file_path}

Suppose that we have transferred the file, then code to download it will look like this:

the

$ChatTimeout = 1
$UpdateId = 0
$token = "token bot"
$Path = "c:\"

##### Get the message as usual
$URL = "https://api.telegram.org/bot$token/getUpdates?offset=$UpdateId&timeout=$ChatTimeout"

$Request = Invoke-WebRequest -Uri $URL -Method Get
$content = ConvertFrom-Json $Request.content

# if the output of 2 or more of the results we take only the last
$str = $content.result | select -First 1
$str = ($str).message

##### If the message is passed the file will be additional fields
# so for example we can learn that we got a picture
if ( $($str.document).mime_type -eq "image/jpeg" ) { $isJPG = $true }

##### If there is a file_name that means there is something lying
# the document for download is?
if ( $($str.document).file_name -ne $null ) {
### different data e.g. for logging
$DocFileName = ($str.document).file_name
$DocFileID = ($str.document).file_id
$DocFileSize = ($str.document).file_size

# get a reference to the file executing a command bot /getFile
$URL = "https://api.telegram.org/bot$token/getFile?file_id=$DocFileID"
$RequestFile = Invoke-WebRequest -Uri $URL

### in $RequestFile if everything is correct, contains the download link
foreach ( $JSON in $((ConvertFrom-Json $RequestFile.Content).result) ) {
$FilePath = $json.file_path
$URL = "https://api.telegram.org/file/bot$token/$FilePath"
$FilePath = Split-Path -Leaf $FilePath
$OutputFile = "$Path\$FilePath"

# download without validation
Invoke-WebRequest -Uri $URL -OutFile $OutputFile
}
}

the

3. To write something


Telegrams-boat supports 2 modes of text layout markdown and html.

Note: htmlmode br not supported

Examples of markdown markup
*bold text* — bold text
_italic text_ — italic text
[text](http://www.example.com/) — link
`inline fixed-width code` — fixed

text block
``text
pre-formatted fixed-width code block
``

To migrate strings, use the sequence %0A

Example of sending messages

the

$token = "your token"
$сhatid = "ID of the chat to which you want to send a message"
$text = "Hello habr"

$payload = @{ "parse_mode" = "Markdown"; "disable_web_page_preview" = "True" }

$URL = "https://api.telegram.org/bot$token/sendMessage?chat_id=$сhatid&text=$text"

$request = Invoke-WebRequest -Uri $URL -Method Post `
-ContentType "application/json; charset=utf-8" `
-Body (ConvertTo-Json -Compress-InputObject $payload)

If this code would give an error for example when sending a string like this:

the

"$FDownload : file name is ""$($JSON.file_path)""; size $($json.file_size) kb"

You can use the send method a little more complicated:

the

$token = "your token"
$chat_id = "ID chata"
$text = "message"
$markdown = $true

$preview_mode = "True" 
if ($markdown) { $markdown_mode = "Markdown" } else {$markdown_mode = ""}

$payload = @{ "chat_id" = $chat_id;
text = $text
"parse_mode" = $markdown_mode;
"disable_web_page_preview" = $preview_mode;
}

$URL = "https://api.telegram.org/bot$token/sendMessaget"

$request = Invoke-WebRequest -Uri $URL `
-Method Post -ContentType "application/json; charset=utf-8" `
-Body (ConvertTo-Json -Compress-InputObject $payload)

If anyone knows how to upload the file back — throw, I added.
Article based on information from habrahabr.ru

Комментарии

Популярные сообщения из этого блога

Briefly on how to make your Qt geoservice plugin

Database replication PostgreSQL-based SymmetricDS

Developing for Sailfish OS: notifications for example apps for taking notes