Skip to content

Instantly share code, notes, and snippets.

@dhmacher
Created December 19, 2022 07:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dhmacher/2203582502c7ab13015db8f52e94da45 to your computer and use it in GitHub Desktop.
Save dhmacher/2203582502c7ab13015db8f52e94da45 to your computer and use it in GitHub Desktop.
Powershell function to post a simple, plaintext status to a Mastodon instance
<#
To create an access token,
* go to settings -> Development
* Click "New Application"
* Enter a name
* Allow "write:statuses"
* Click Submit
* Click on the new application to review the keys
* The "Access token" is the one you need
Example function call:
New-MastodonPost -HostName "dataplatform.social" -AccessToken $token -Message "Hello world"
#>
function New-MastodonPost {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string] $HostName,
[Parameter(Mandatory = $true)]
[string] $AccessToken,
[Parameter(Mandatory = $true)]
[string] $Message
)
# Just in case you don't understand what a hostname is
if ($HostName -like "https://*") { $HostName = $HostName.Substring(8) }
if ($HostName -like "http://*") { $HostName = $HostName.Substring(7) }
if ($HostName -like "*/*") { $HostName = $HostName.Substring(0, $HostName.indexOf("/")) }
# Construct the API URL
$url = "https://" + $HostName + "/api/v1/statuses?access_token=" + [System.Web.HttpUtility]::UrlEncode($AccessToken)
# Do the WebRequest thing
$res = Invoke-WebRequest `
-Uri $url `
-Method "POST" `
-ContentType "application/x-www-form-urlencoded" `
-UseBasicParsing `
-Body ("status=" + [System.Web.HttpUtility]::UrlEncode($Message))
# Return the JSON response
return($res.Content | ConvertFrom-Json)
}
@potatoqualitee
Copy link

Check out the [uri] data type if you haven't yet! I think you'll like it. This is how I do mine

# help 'em out
if ($Server -match '://') {
    $Server = ([uri]$Server).DnsSafeHost
} elseif ($Server -match '/@') {
    $Server = $($Server -split "/@" | Select-Object -First 1)
} elseif ($Server.StartsWith("@") -or $Server -match "@") {
    $Server = $($Server -split "@" | Select-Object -Last 1)
}

@jdhitsolutions
Copy link

I posted a variation using Invoke-RestMethod at https://gist.github.com/jdhitsolutions/7bb8fe659cd32a7bfb2debdb7f0bfcfc

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment