linvi / tweetinvi

Tweetinvi, an intuitive Twitter C# library for the REST and Stream API. It supports .NET, .NETCore, UAP (Xamarin)...
MIT License
1.01k stars 219 forks source link

Urls in tweet text #1119

Open Alex-451 opened 3 years ago

Alex-451 commented 3 years ago

Urls in the text of a tweet get changed (shortened) is there a way to get the text of tweets without the replaced urls?

Scobiform commented 3 years ago

twitter.com/user/status/tweetid

gives you the original tweet url. Where is the problem?

KoalaBear84 commented 3 years ago

I didn't really find a way..

You can't stream/filter to text 'in' an URL, or a domain or something, which is sad.

You could get the original with something like this (Don't, see next comment):

static HttpClientHandler HttpClientHandler { get; set; } = new HttpClientHandler()
{
    AllowAutoRedirect = false
};
static Regex TwitterLinkRegex = new Regex("(?<Link>https://t.co/[a-zA-Z0-9]{10})");

MatchCollection twitterLinkMatchCollection = TwitterLinkRegex.Matches(eventReceived.Tweet.Text);

foreach (Match twitterLinkMatch in twitterLinkMatchCollection)
{
    string url = twitterLinkMatch.Groups["Link"].Value;

    try
    {
        HttpResponseMessage httpResponseMessage = await HttpClient.SendAsync(new HttpRequestMessage
        {
            RequestUri = new Uri(url),
            Method = HttpMethod.Head
        }, HttpCompletionOption.ResponseHeadersRead);

        if (httpResponseMessage.IsSuccessStatusCode && httpResponseMessage.Headers?.Location != null)
        {
            string realUrl = httpResponseMessage.Headers.Location.ToString();
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}
Alex-451 commented 3 years ago

@KoalaBear84 does Twitter shorten the urls or is that something the wrapper does?

KoalaBear84 commented 3 years ago

Hmm.. Good question 😂

I see that the info I would like is already present in the JSON / model. So we don't need the above code which is great.

See example: image

KoalaBear84 commented 3 years ago

Have you checked out the latest comment? @AlexanderGipp

Alex-451 commented 3 years ago

Yeah i did, did you manage to actually use that property @KoalaBear84?

KoalaBear84 commented 3 years ago

The Urls property works, and you can easily loop through it, in reverse, and replace this.

For example like this:

string text = tweet.Text;
List<Tweetinvi.Models.Entities.IUrlEntity>? urls = tweet.Urls;
urls.Reverse();

foreach (Tweetinvi.Models.Entities.IUrlEntity? url in urls)
{
  text = text.Remove(url.Indices[0], url.Indices[1] - url.Indices[0]);
  text = text.Insert(url.Indices[0], url.ExpandedURL);
}

Or use DisplayedURL.