Skip to content

Instantly share code, notes, and snippets.

@jdhitsolutions
Created December 21, 2022 20:19
Show Gist options
  • Save jdhitsolutions/7bb8fe659cd32a7bfb2debdb7f0bfcfc to your computer and use it in GitHub Desktop.
Save jdhitsolutions/7bb8fe659cd32a7bfb2debdb7f0bfcfc to your computer and use it in GitHub Desktop.
A PowerShell function to post a Mastodon status.
#requires -version 5.1
<#
Based on a function from https://gist.github.com/dhmacher/2203582502c7ab13015db8f52e94da45
You need an access token that has at least write access to your status
* go to settings -> Development
* Click "New Application"
* Enter a name
* Allow "write:statuse
* Click Submit
* Click on the new application to review the keys
* Copy and securely store the "Access token" for your script.
I use PSDefaultParameterValues.
$PSDefaultParameterValues["Send-MastodonPost:HostName"] = "techhub.social"
$PSDefaultParameterValues["Send-MastodonPost:AccessToken"] = $token
This code is freely available to use and or modify.
#>
#TODO: Post an image with a status including ALT text for the description
Function Send-MastodonPost {
[cmdletbinding(SupportsShouldProcess)]
[alias("toot")]
param (
[Parameter(Position = 0, Mandatory)]
[ValidateNotNullOrEmpty()]
[string] $Message,
[Parameter(Mandatory, HelpMessage = "Enter your Mastodon instance name, like techhub.social")]
[ValidateNotNullOrEmpty()]
[string] $HostName,
[Parameter(Mandatory, HelpMessage = "Enter your Mastodon access token")]
[ValidateNotNullOrEmpty()]
[string] $AccessToken,
[Parameter(HelpMessage = "Enter a date and time to schedule the post. It must be at least 5 minutes in the future.")]
[ValidateScript({
($_ - (Get-Date)).totalMinutes -ge 5
})]
[DateTime]$Scheduled
)
$uri = "https://$hostname/api/v1/statuses?access_token=$Accesstoken"
Write-Verbose "Posting to $uri"
$body = @{
status = $message
}
Write-Verbose "Posting $($body.status)"
if ($Scheduled) {
$isoDate = ("{0:u}" -f $scheduled.ToUniversalTime()).replace(" ", "T")
$body.add("scheduled_at", $isoDate)
Write-Verbose "Sending at $($body.scheduled_at)"
}
#parameters to splat to Invoke-RestMethod
$paramHash = @{
uri = $uri
Method = "POST"
ContentType = "application/x-www-form-urlencoded"
Body = $body
ErrorAction = "Stop"
}
Write-Verbose "Using these parameters:"
$paramHash | Out-String | Write-Verbose
if ($pscmdlet.ShouldProcess($message, "Posting to $hostname")) {
Invoke-RestMethod @paramHash
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment