Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Formatting entities in a Twitter status message (tweet)
private string FormatStatusMessageText(TwitterStatusMessage tweet) {
// Normally we should be able to call tweet.Entities.GetAllReversed() but that method
// will throw an exception if the array of media entities is NULL (which it is if there
// are no media attached to the tweet).
List<TwitterBaseEntity> entities = new List<TwitterBaseEntity>();
entities.AddRange(tweet.Entities.HashTags);
entities.AddRange(tweet.Entities.Urls);
entities.AddRange(tweet.Entities.Mentions);
if (tweet.Entities.Media != null) entities.AddRange(tweet.Entities.Media);
// Get the original text
string text = tweet.Text;
// We read the entities from back to front so we don't break the indices while manipulating the string
foreach (var entity in entities.OrderByDescending(x => x.StartIndex)) {
string before = text.Substring(0, entity.StartIndex);
string current = text.Substring(entity.StartIndex, entity.EndIndex - entity.StartIndex);
string after = text.Substring(entity.EndIndex);
if (entity is TwitterHashTagEntity) {
TwitterHashTagEntity tag = (TwitterHashTagEntity) entity;
text = before + "<a href=\"https://twitter.com/hashtag/" + tag.Text + "?src=hash\">#" + tag.Text + "</a>" + after;
} else if (entity is TwitterUrlEntity) {
TwitterUrlEntity url = (TwitterUrlEntity) entity;
text = before + "<a href=\"" + url.Url + "\">" + url.DisplayUrl + "</a>" + after;
} else if (entity is TwitterMentionEntity) {
TwitterMentionEntity mention = (TwitterMentionEntity) entity;
text = before + "<a href=\"https://twitter.com/" + mention.ScreenName + "\">@" + mention.ScreenName + "</a>" + after;
} else if (entity is TwitterMediaEntity) {
TwitterMediaEntity media = (TwitterMediaEntity) entity;
text = before + "<a href=\"" + media.MediaUrl + "\">" + current + "</a>" + after;
}
}
return text;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment