techthoughts2 / poshgram Goto Github PK
View Code? Open in Web Editor NEWSend messages via the Telegram Bot API using PowerShell
Home Page: https://poshgram.readthedocs.io
License: MIT License
Send messages via the Telegram Bot API using PowerShell
Home Page: https://poshgram.readthedocs.io
License: MIT License
Use this method to send phone contacts. On success, the sent Message is returned.
#if the module is already in memory, remove it
In a ForEach you could easily message multipe chat groups that your bot is a member of
There is no built-in method to retrieve Chat Id from a telegram bot. It would be useful to have it as a CmdLet.
Could be added to the Test-BotToken or created as a separate CmdLet.
& '.\Program Files\PowerShell\6-preview\pwsh.exe' -command Import-Module PoshGram;$token = "<span class="pl-c">#########:xxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxx</span>";$chat = "<span class="pl-c">-#########</span>";Send-TelegramTextMessage -BotToken $token -ChatID $chat -Message "Test from 5.1 calling 6.1 to send Telegram Message via PoshGram"
When DisableNotification parameter is provided to Send-TelegramSticker it should not notify the receiver.
A notification is being sent when a sticker is sent regardless if the DisableNotification is specified.
Send-TelegramSticker `
-BotToken $token `
-ChatID $channel `
-StickerSetName STPicard `
-Shortcode ':slightly_smiling_face:' `
-DisableNotification
All versions
When the DisableNotification is provided Send-TelegramSticker should not notify the receiving party.
There is an issue with the function "Send-TelegramPoll". (PoshGram/src/PoshGram/Public/Send-TelegramPoll.ps1)
Line 238 has the wrong if statement.
($null -eq $QuizAnswer -or $QuizAnswer -lt 0 -or $QuizAnswer -gt 10)
Poll answers are starting from 0. Telegram API > Poll
($null -eq $QuizAnswer -or $QuizAnswer -lt 1 -or $QuizAnswer -gt 10)
To change 1 to 0.
I recognized an issue with UTF-8 characters in the messages
As example in the function Send-TelegramTextMessage
Send-TelegramTextMessage -BotToken $Alarm_Token -ChatID $Alarm_Chatids -Message "Testmessage UTF8 Hallö" -verbose
VERBOSE: Sending message...
VERBOSE: POST https://api.telegram.org/bot{Token}/sendMessage with 141-byte payload
VERBOSE: received 88-byte response of content type application/json
WARNING: An error was encountered sending the Telegram message:
Send-TelegramTextMessage : {"ok":false,"error_code":400,"description":"Bad Request: text must be encoded in UTF-8"}
According to my analysis it can be fixed as follows, to convert the Body to UTF-8
(all functions with text messages)
Current code:
try {
Write-Verbose -Message "Sending message..."
$results = 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
}#try_messageSend
Fixed code:
try {
Write-Verbose -Message "Sending message..."
$results = Invoke-RestMethod -Uri ("https://api.telegram.org/bot{0}/sendMessage" -f $BotToken)
-Method Post -ContentType "application/json"
-Body ([System.Text.Encoding]::UTF8.GetBytes((ConvertTo-Json -Compress -InputObject $payload))) `
-ErrorAction Stop
}#try_messageSend
Haven't determined a way to properly mock Invoke-WebRequest exceptions yet - which this function depends on. If anyone has any suggestions I'd love to hear them.
File Function Line Command
---- -------- ---- -------
Private\Resolve-ShortLink.ps1 Resolve-ShortLink 29 $result = $null
Private\Resolve-ShortLink.ps1 Resolve-ShortLink 30 $a = $null
Private\Resolve-ShortLink.ps1 Resolve-ShortLink 31 [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProt...
Private\Resolve-ShortLink.ps1 Resolve-ShortLink 33 $a = Invoke-WebRequest -Uri $uri -MaximumRedirection 0 -ErrorAc...
Private\Resolve-ShortLink.ps1 Resolve-ShortLink 37 if ($_.Exception.Message -like "*Moved*") {...
Private\Resolve-ShortLink.ps1 Resolve-ShortLink 38 $a = $_
Private\Resolve-ShortLink.ps1 Resolve-ShortLink 39 Write-Verbose -Message 'Moved detected.'
Private\Resolve-ShortLink.ps1 Resolve-ShortLink 41 $result = $a.Exception.Response.Headers.Location.AbsoluteUri
Private\Resolve-ShortLink.ps1 Resolve-ShortLink 44 Write-Warning -Message 'An Error was encountered resolving a po...
Private\Resolve-ShortLink.ps1 Resolve-ShortLink 45 Write-Error $_
Private\Resolve-ShortLink.ps1 Resolve-ShortLink 48 return $result
In many functions parameters such as DisableNotification have been set to bool. It would be more interesting and standardized if they were set to Switch.
Thanks
Bot API 4.5 introduced a new parse mode MarkdownV2.
Add support for MarkdownV2 to PoshGram.
During this change I am thinking about changing the default parse mode for all telegram message and captions to HTML.
This is primarily due to how the default of Markdown currently doesn't handle underscores, asterisks, and other symbols without escaping.
The majority of bot type messaging is likely preferred to default to HTML type formatting.
I will leave this issue open for a bit so others can share thoughts on that change prior to implementation.
Use this method to send static .WEBP or animated .TGS stickers. On success, the sent Message is returned.
Use this method to get a sticker set. On success, a StickerSet object is returned.
Email question:
I am using your PoshGram package from GitHub for sending messages from a few desktop PCs on a schedule to my telegram account. I am trying to add Emojis to the messages to help differentiate them, but I cannot seem to get Emojis inline with text (or even by themselves) - I can only get stickers to send.
I think I'm doing something silly, and was wondering if you'd be able to assist me?
Quick start section of README is missing comments on a few examples
Hi, I am new to bot coding. I am using this module and it works great when I send text message.
But I am not able to understand how to frame complex url like keyboard buttons, inline button , async methods...
Can someone provide code snippets on how to achieve this? Please.
Use this method to send a native poll. A native poll can't be sent to a private chat. On success, the sent Message is returned.
Bot API 4.6 introduced Polls v2.0
Add support for new Polls v2.0 options.
I hope to see editMessageText API support in the future
I’m looking to implement PoshBot, but we would like to use Telegram as the chat platform backend. How difficult would it be to make PoshBot work with Telegram using PshGram?
Anyhow, as I’m really impressed with PoshGram from your video on youtube!
Grts,
Marc Vanderstraeten
[email protected]
Hello!
When I try to send a file with cyrillic characters in name to telegram
$botToken = "xxxx"
$chat = "xxxx"
$file = "C:\абв г.txt"
$sendTelegramLocalDocumentSplat = @{
BotToken = $botToken
ChatID = $chat
File = $file
Caption = "Check out this file"
ParseMode = 'MarkdownV2'
DisableNotification = $true
Verbose = $true
}
Send-TelegramLocalDocument @sendTelegramLocalDocumentSplat
I get the file with this name
= utf-8 B 0LDQsdCyINCzLnR4dA== =
There are no such problems with names in English or numbers.
Use this method to send information about a venue. On success, the sent Message is returned.
the script should instruct my telegram bot to send me a notification when the remaining free space on the drive that i specify is below 70%.
However the bot always sends this notification, even if there is more than 70% left. Also, it does not specify the actual percentage of free space. I cannot understand where the problem comes from because i checked the $percentFree variables and they all match in the code.
I am learning powershell and scripting so i probably messed up somewhere.
param (
[Parameter(Mandatory = $true)]
[string]
$Drive
)
#log directory
if ($PSVersionTable.Platform -eq 'Unix') {
$logpath = '/tmp'
}
else {
$logpath = 'Y:\Desktop\Logs'
}
$logfile ="$logpath\driveCheck.log" #logfile
#verify if log directory exists
try {
if (-not (Test-Path -Path $logpath -ErrorAction Stop)) {
#output dir not found. Create the dir
New-Item -ItemType Directory -Path $logpath -ErrorAction Stop | Out-Null
New-Item -ItemType File -Path $logfile -ErrorAction Stop | Out-Null
}
}
catch {
throw
}
Add-Content -Path $logfile -Value '[INFO] Running $PSCommandPath'
#verify if Poshgram is installed
if (-not (Get-Module -Name PoshGram -ListAvailable)) {
Add-Content -Path $logfile -Value '[ERROR] PoshGram is not installed.'
throw
}
else {
Add-Content -Path $logfile -Value '[INFO] PoshGram is installed.'
}
#get hard drive information
try {
if ($PSVersionTable.Platform -eq 'Unix')
{
# used
# free
$volume = Get-PSDrive -Name $Drive -ErrorAction Stop
#verify volume actually exists
if ($volume) {
$total = $volume.Used + $volume.Free
$percentFree = [int](($volume.Free / $total) * 100)
Add-Content -Path $logfile -Value "[INFO] Percent free: $percentFree%."
else {
Add-Content -Path $logfile -Value '[ERROR] Drive is not found.'
throw
}
}
else {
if ($volume) {
$total = $volume.Size
$percentFree = [int](($volume.SizeRemaining / $total) * 100)
Add-Content -Path $logfile -Value "[INFO] Percent free: $percentFree%."
else {
Add-Content -Path $logfile -Value '[ERROR] Drive is not found.'
throw
}
}
}
}
}
catch {
Add-Content -Path $logfile -Value '[ERROR] Unable to retrieve volume information.'
Add-Content -Path $logfile -Value $
throw
}
#send telegram message if the drive is low
if ($percentFree -le 70) {
try {
Import-Module -Name Poshgram -ErrorAction Stop
Add-Content -Path $logfile -Value '[INFO] Imported Poshgram successfully.'
}
catch {
Add-Content -Path $logfile -Value '[ERROR] Poshgram could not be imported:'
Add-Content -Path $logfile -Value $_
}
Add-Content -Path $logfile -Value '[INFO] Sending Telegram notification.'
$MessageSplat = @{
Message = "[LOW SPACE] Hero, your drive is at: $percentFree%."
ChatID = "-444846118"
BotToken = "1287418460:AAGBCvO75O40-d3IP_oEsTxvVMnnNkhh9Lc"
ErrorAction = 'Stop'
}
try { Send-TelegramTextMessage @MessageSplat
Add-Content -Path $logfile -Value '[INFO] Message sent successfully.'
}
catch {
Add-Content -Path $logfile -Value '[ERROR] Error encountered sending message:'
Add-Content -Path $logfile -Value $_
throw
}
}
Name Value
PSVersion 7.0.3
PSEdition Core
GitCommitId 7.0.3
OS Microsoft Windows 10.0.18363
Platform Win32NT
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
WSManStackVersion 3.0
Microsoft Windows 10.0.18363
the telegram notification the bot sends me does not show the % of free space on the specified Drive.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.