Posting to Twitter from 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.

About these ads
This entry was posted in F#. Bookmark the permalink.

2 Responses to Posting to Twitter from F#

  1. Pingback: F# Weekly #2, 2013 « Sergey Tihon's Blog

  2. Pingback: Tracking a new year’s resolution with F# and FSharpChart | I've got the byte on my side

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s