Search code examples
asp.nettwitterembedlinq-to-twitter

Converting tweet link so that it is embedded in asp.net app


I want to convert a tweet url such as https://twitter.com/LindseyGrahamSC/status/320202348263780352 so that it is automagically embedded. So far the best i have come up with is to use a short code type syntax like [tweet:320202348263780352] which then makes the embdded tweet. But i'd really like to just paste the url in and have it work. I am stuck as to how achieve that. What i have so far:

 var ctxTwitterContext = new TwitterContext(auth);

    if (e.Location != ServingLocation.PostList && e.Location != ServingLocation.SinglePost)
        return;

    string regex__1 = @"\[tweet:.*?\]";
    MatchCollection matches = Regex.Matches(e.Body, regex__1);

    for (int i = 0; i < matches.Count; i++)
    {
        Int32 length = "[tweet:".Length;
        string TweetID = matches[i].Value.Substring(length, matches[i].Value.Length - length - 1);
        var embeddedStatus =
               (from tweet in ctxTwitterContext.Status
                where tweet.Type == StatusType.Oembed &&
                    tweet.ID == TweetID
                select tweet.EmbeddedStatus)
               .SingleOrDefault();

        string html = embeddedStatus.Html;

        e.Body = e.Body.Replace(matches[i].Value, String.Format(html));

Solution

  • The status ID is always the last segment of the URL. So, you can do this:

      string statusUrl = "https://twitter.com/LindseyGrahamSC/status/320202348263780352";
      string tweetID = statusUrl.Substring(statusUrl.LastIndexOf('/') + 1);
    

    Unless I'm not understanding. If so, you can remove the RegEx code and the for loop.