I'VE GOT THE BYTE ON MY SIDE

57005 or alive

Posting to Twitter from F#

Jan 12, 2013 F#

Here’s some quick F# code which enables you to post updates (textual and/or with picture) to Twitter.  This isn’t full-featured or robust, but it gets the job done.

module Twitter

open TweetSharp

type TwitterSettings =
 {
    ConsumerKey : string
    ConsumerSecret : string
    AccessToken : string
    AccessTokenSecret : string
    TwitPicApiKey : string option
 }

/// Post text and/or pictures to Twitter using TweetSharp
let postToTwitter settings status (picture : string option) =
    let service = TwitterService(settings.ConsumerKey, settings.ConsumerSecret)
    service.AuthenticateWith(settings.AccessToken, settings.AccessTokenSecret)

    match (picture, settings) with
    | (None, _) -> // just a text tweet
        service.SendTweet(status) |> ignore
    | (Some(picPath), { TwitPicApiKey = Some(tpKey) }) -> // tweet with picture
        let request = service.PrepareEchoRequest()
        request.Path <- "uploadAndPost.xml"
        request.AddField("key", tpKey)
        request.AddField("consumer_token", settings.ConsumerKey)
        request.AddField("consumer_secret", settings.ConsumerSecret)
        request.AddField("oauth_token", settings.AccessToken)
        request.AddField("oauth_secret", settings.AccessTokenSecret)
        request.AddField("message", status)
        request.AddFile("media", (sprintf "picpoast%d" System.Environment.TickCount), picPath, "image/jpeg")

        let client = Hammock.RestClient(Authority = "http://api.twitpic.com/", VersionPath = "1")
        client.Request(request) |> ignore
    | _ ->
        invalidArg "settings" "Bad parameters, must include TwitPic API key if tweeting a picture"

You’ll need to reference TweetSharp.  Usage is pretty darn simple:

let settings =
    {
        ConsumerKey = "ck"
        ConsumerSecret = "cs"
        AccessToken = "at"
        AccessTokenSecret = "ats"
        TwitPicApiKey = Some("tpak")
    }

 Twitter.postToTwitter settings "I'm posting from #FSharp!" None
 Twitter.postToTwitter settings "Here's a picture" Some("C:\\instagrammedfoodpics\\hamandcheese.jpg")

To fill in the various keys and tokens in the settings, you will need to register an app with Twitter.  Similarly, to post photos you will need to register with TwitPic.

Code mostly cribbed from this Stack Overflow answer.