Building Twitter profile image url with Twitter user id - twitter

Is there any way of building a profile image url with user id or screen name? I store user ids in database but i don't want to store profile image url.
edit:
I don't want to make a api call too. I want to put user_id inside a url like
<img src="https://twitter.com/users/profile_pic?user_id=123"> Is there a url to do this?

With API 1.1 you can achieve this using these URLs:
https://twitter.com/[screen_name]/profile_image?size=mini
https://twitter.com/[screen_name]/profile_image?size=normal
https://twitter.com/[screen_name]/profile_image?size=bigger
https://twitter.com/[screen_name]/profile_image?size=original
Official twitter documentation Profile Images and Banners
Example
https://twitter.com/TwitterEng/profile_image?size=original
will redirect to
https://pbs.twimg.com/profile_images/875168599299637248/84CkAq6s.jpg

As of June 2020, both the accepted answer and avatars.io no longer work. Here are two alternatives:
unavatar.io
(formerly unavatar.now.sh)
Unavatar can get pictures from quite a few different places including Twitter. Replace [screen_name] in the URL below with the Twitter username you want.
<img src="https://unavatar.io/twitter/[screen_name]" />
For example:
<img src="https://unavatar.io/twitter/jack" width="100" height"100" />
If the demo above ever stops working, it's probably because unavatar.io is no longer available.
Unavatar is open source though, so if it does go down, you can deploy it yourself from the GitHub repo — it even has "Deploy to Vercel/Heroku" buttons. The code to fetch Twitter avatars specifically is here, so you could also use that as part of your own backend.
twivatar.glitch.me
⚠️ As of July 2021 this option no longer works, see the one above instead!
If you want an alternative, you can also use twivatar.glitch.me. Replace [screen_name] in the URL below with the Twitter username you want.
<img src="https://twivatar.glitch.me/[screen_name]" />
For example:
<img src="https://twivatar.glitch.me/jack" width="100" height"100" />
If the demo above ever stops working, it's probably because twivatar.glitch.me is no longer available.
By the way, I didn't build either of these services, they were both made by other people.

Introducing the easiest way to get a Twitter Profile Image without using the Twitter API:
Using http://avatars.io/
As #AlexB, #jfred says, it doesn't work at all on mobile devices.
And it's quite a hard way to get a redirected URL using common frameworks like PHP or JavaScript in your single page.
Simply call http://avatars.io/twitter/ruucm at your image tag, like
<img src="https://avatars.io/twitter/ruucm" alt="twt_profile" border="0" width="259"/>
I've tested it with Angular 2+ and it works without any problem.

As of February 20, 2020 it would appear this is impossible. Using the API seems like the only option at the moment. For more info see my question I've opened here: Twitter profile picture images now blocked on most domains

Based on the answer by #Cristiana214
The following PHP snippet can be used to make the https://twitter.com/[screen_name]/profile_image?size=normal trick work on mobile.
Due to twitters redirect to the mobile version of the site links such as https://twitter.com/[screen_name]/profile_image?size=normal get broken on mobile devices
So the script gets the redirect response (to the user avatar) extracts the address then redirects the page itself
if (!isset($_GET['id'])) $_GET['id'] = 'twitter';
$urlget = curl_init();
curl_setopt($urlget, CURLOPT_URL, 'https://twitter.com/' . $_GET['id'] . '/profile_image?size=normal');
curl_setopt($urlget, CURLOPT_HEADER, true);
curl_setopt($urlget, CURLOPT_RETURNTRANSFER, 1);
$res = curl_exec($urlget);
preg_match_all("/location: (.*)/", $res, $found);
header('Location: ' . $found[1][0]);
So this could be accesses as twitteravatar.php?id=twitter which (at time of writing) reloads to https://pbs.twimg.com/profile_images/767879603977191425/29zfZY6I_normal.jpg
Not pretty but works.

You can get it using the users/show method of the Twitter API -- it does exactly what you described. You give it a the ID or the screen name, and it returns a bunch of data, including profile_image_url.

I found such a solution with C#:
public string Text_toTextFinder(string text, string Fromhere, string Here)
{
int start = text.IndexOf(Fromhere) + Fromhere.Length;
int finish = text.IndexOf(Here, start);
return text.Substring(start, finish - start);
}
string getPhotoURL(string UserName, string size ="x96")
{
using (WebClient client = new WebClient())
{
client.Headers[HttpRequestHeader.UserAgent] = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2";
string htmlCode = client.DownloadString("https://twitter.com/" + UserName);
return Text_toTextFinder(Text_toTextFinder(htmlCode, "<td class=\"avatar\">", "</td>"), "src=\"", "\"").Replace("normal",size);
}
}
For use:
MessageBox.Show(getPhotoURL("screen_name")); //size = 96x96
MessageBox.Show(getPhotoURL("screen_name","normal"));
MessageBox.Show(getPhotoURL("screen_name","200x200"));
MessageBox.Show(getPhotoURL("screen_name","400x400"));

There is no way to do that. In fact Twitter doesn't provide a url to do that like facebook does ( https://graph.facebook.com//?fields=picture)
The issue is report but the status is: 'WontFix', take a look:
https://code.google.com/p/twitter-api/issues/detail?can=2&start=0&num=100&q=&colspec=ID%20Stars%20Type%20Bug%20Status%20Summary%20Opened%20Modified%20Component&groupby=&sort=&id=242#makechanges

Well I'm using a tricky way via PHP Dom Parser
include('simple_html_dom.php');
$html = file_get_html('http://twitter.com/mnckry');
$img = array();
foreach($html->find('img.size73') as $e)
$img[] = $e->src;
foreach($html->find('.profile-header-inner') as $e)
$img[] = str_replace("')", "", str_replace("url('", "", $e->{'data-background-image'}));
echo $img[0];//Avatar
echo "<br>";
echo end($img);//ProfileBG
This will give you something like this;
https://pbs.twimg.com/profile_images/378800000487958092/e04a191de329fcf8d000ca03073ad594_bigger.png
to get 2 other size; for big version remove, "_bigger" for smaller version replace "_bigger" with "_normal"

With version 1.1, use
http://a0.twimg.com/profile_images/XXXXX/afpecvf41m8f0juql78p_normal.png
where XXXXX is the User Id

Related

Image is not shown in email MVC

I have a strange problem.
I need to send an e-mail from an MVC site. I have an html template for the email, which looks like this(the image part):
...
<img class="auto-style4" src="{PictureSrc}" /><br />
<img src="data:image/png;base64,{pictureBase64}">
....
From the controller I'm replacing the parameters like this:
case "PictureSrc":
string imagePath = "";
imagePath = "~/Images/email-logo.png";
//string base64 = Convert.ToBase64String(System.IO.File.ReadAllBytes(HttpContext.Server.MapPath(imagePath)));
//content = content.Replace("{pictureBase64}", base64);
content = content.Replace("{" + property + "}", HttpContext.Server.MapPath(imagePath));
break;
1.First I have tried to add the path for the image. This way works on my local machine, but not on the server where the live site is.
I've tried to add the URL for the image. WhenI have pasted the URL in to the browser, the image was shown, but in the sent email the image was not shown, not in my local machine, not on the server.
The interesting thing is that I'm sending these mails to outlook accounts. There the images are not shown, but if I send the mail to my yahoo account there the image is shown.
I've tried to convert image to base 64, as you can see on the code and replacing this way the image src. This way again the image was not shown, not on my local machine, not on the server side if I send the mail to outlook accounts. If I send the mail to a yahoo account, the mail is shown.
Can you please advise what can I try in order to resolve this problem?
I ran into this same issue with Outlook a few months ago. While researching, I learned that Outlook tends to strip emails of embedded images. I resolved it by using the CID technique. This technique consists of attaching the image to the email and referencing it in the email template with the image's CID.
First, you would need to get your image's CID. There are plenty of CID converters online to do this. Then, you just need to use the CID in the img src attribute of your template: <img src="cid:" + yourCID + "/>".
Note: this WILL increase the size of your email due to the image being attached.

Accessing public Instagram content via Instagram API without expiring accesstoken

i want to show public contents from instagram related to a specific hashtag (everything works fine with that) but i can't to renew the access_token everytime it expires.
("do not assume your access_token is valid forever." -
https://www.instagram.com/developer/authentication/)
To renew it manually is not an option i have to make sure there is a valid access_token at ANY time without re-authenticating.
Any ideas or questions? :)
I have one idea, but without API (and access_token). You can make requests to the web-version of Instagram with ?__a=1 parameter. I do not know how long it will work but now there is workflow:
You want to show public content with hashtag space, for example.
Add it to url and add GET-parameter ?__a=1: https://www.instagram.com/explore/tags/space/?__a=1
Make the GET-request. It returns json with nodes in top_posts (8) and media (18). Each node has owner, caption, number of comments and likes. But the most important part is in thumbnail_src and display_src.
There is page_info in media object which helps to paginate results. You need end_cursor (for example, J0HWE9rjAAAAF0HWE9qvgAAAFiYA)
Add the value from end_cursor to the url: https://www.instagram.com/explore/tags/space/?__a=1&max_id=J0HWE9rjAAAAF0HWE9qvgAAAFiYA
Repeat 3-6 to get newest posts with specific hashtag.
Update to the ?__a=1 url param. This appears to have stopped working with users '/account/?__a=1' endpoints.:( Still works on tags apparently.
Instagram shut down their public API. Here's a quick and dirty workaround in PHP:
<?php
function getPublicInfo($username) {
$url = sprintf("https://www.instagram.com/$username");
$content = file_get_contents($url);
$content = explode("window._sharedData = ", $content)[1];
$content = explode(";</script>", $content)[0];
$data = json_decode($content, true);
return $data['entry_data']['ProfilePage'][0];
}
Not sure for how long it's gonna work. Here's one for Javascript.

Twitter API 1.1 - render twitter's t.co links

I want to display the tweets of an account in my website. The problem is that the tweets appear always with the format http://t.co/..., instead of the full link as desired by me.
For instance, I obtain:
the rules of the game are all implemented - local players can play together in this link: http://t.co/Nf7j4TaB
if you are very curious... then, here is the link to the xodul's section under development: http://t.co/6Zbti36T
etc...
and I want that these tweets appear like this:
the rules of the game are all implemented - local players can play together in this link: http://xodul.com/tests/js/
if you are very curious... then, here is the link to the xodul's section under development: http://xodul.com/tests
etc...
To make my application I've followed the instructions from:
Simplest PHP example for retrieving user_timeline with Twitter API version 1.1 (from here we can get the text of each tweet, with the links coming in the format: http://t.co/...)
Rendering links in tweet when using Get Statuses API 1.1 (the code of the highest scored answer, in this link replaces, for instance, the text "http://t.co/Nf7j4TaB" with the hyperlink "<a target='_blank' href='http://t.co/Nf7j4TaB'>http://t.co/Nf7j4TaB</a>")
I appreciate very much any help on how to render the twitter's links!
With the tutorial you followed you can use these attributes to show actual link.
Note: In API v1.1, entities will always be included unless you set include_entities to False or 0.
The urls entity
An array of URLs extracted from the Tweet text. Each URL entity comes with the following attributes:
url: The URL that was extracted
display_url: (only for t.co links) Not a URL but a string to display instead of the URL
expanded_url: (only for t.co links) The fully resolved URL
indices: The character positions the URL was extracted from
https://dev.twitter.com/docs/tweet-entities
JavaScript only solution for now to get Twitter posts on your site without using new 1.1 API and actually returns the full url in posts, not the twitter shortened version :-) http://goo.gl/JinwJ
Thank you for your answers.
After analyzing the JSON in the suggested link (https://dev.twitter.com/docs/tweet-entities), I wrote a solution to the exposed problem:
// ...
$twitter_data = json_decode($json); // last line of the code in: http://stackoverflow.com/questions/12916539
// print the tweets, with the full URLs:
foreach ($twitter_data as $item) {
$text = $item->text;
foreach ($item->entities->urls as $url) {
$text = str_replace($url->url, $url->expanded_url, $text);
}
echo $text . '<br /><br />';
// optionally, here, the code from: http://stackoverflow.com/questions/15610968/
// can be added, too.
}

Feed link doesn't work

I'm using the Facebook PHP SDK to developp my app.
From this morning, when I publish an automatic post on a user's feed, everything is ok but the link doesn't work anymore... (no reaction on click)
Once the feed is published, the target of the link is "http://www.facebook.com/connect/uiserver.php?app_id=2711...site.com/annonce?a=62&response_type=code&display=page" (and doesn't work)
I replace the name of my website by mysite.com for this example
Here is my code :
$feed_message = utf8_encode("J'ai besoin de : ".$A_titre);
$feed_picture = "http://www.mysite.com/graph/icon.png";
$feed_link = "http://www.mysite.com/annonce?a=".$ins_id; // go to my website not app
$feed_linkname = utf8_encode($A_titre);
$feed_description = utf8_encode($me_firstname)." a besoin de...";
$result = $fb->api('/me/feed/','post',array('message'=>$feed_message,'picture'=>$feed_picture,'link'=>$feed_link,'name'=>$feed_linkname,'description'=>$feed_description));
Do you have any idea of what i can do to fix it ?
Thanks
I have the same problem. It seems that it's linked to the new "Enhanced Auth Dialog".
I deactivated it since the timeline is not ready anyway, and there's no more http://www.facebook.com/connect/uiserver.php?app_id= appended to the links on the user's wall.

Is there a way to get the twitter share count for a specific URL?

I looked through the API documentation but couldn't find it. It would be nice to grab that number to see how popular a url is. Engadget uses the twitter share button on articles if you're looking for an example. I'm attempting to do this through javascript. Any help is appreciated.
You can use the following API endpoint,
http://cdn.api.twitter.com/1/urls/count.json?url=http://stackoverflow.com
Note that the http://urls.api.twitter.com/ endpoint is not public.)
The endpoint will return a JSON string similar to,
{"count":27438,"url":"http:\/\/stackoverflow.com\/"}
On the client, if you are making a request to get the URL share count for your own domain (the one the script is running from), then an AJAX request will work (e.g. jQuery.getJSON). Otherwise, issue a JSONP request by appending callback=?:
jQuery.getJSON('https://cdn.api.twitter.com/1/urls/count.json?url=http://stackoverflow.com/&callback=?', function (data) {
jQuery('#so-url-shares').text(data.count);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="so-url-shares">Calculating...</div>
Update:
As of 21st November 2015, this way of getting twitter share count, does not work anymore. Read more at: https://blog.twitter.com/2015/hard-decisions-for-a-sustainable-platform
This is not possible anymore as from today, you can read more here:
https://twitter.com/twitterdev/status/667836799897591808
And no plans to implement it back, unfortunately.
Up vote so users do not lose time trying out.
Update:
It is however possible via http://opensharecount.com, they provide a drop-in replacement for the old private JSON URL based on searches made via the API (so you don't need to do all that work).
It's based on the REST API Search endpoints. Its still new system, so we should see how it goes. In the future we can expect more of similar systems, because there is huge demand.
this is for url with https (for Brodie)
https://cdn.api.twitter.com/1/urls/count.json?url=YOUR_URL
No.
How do I access the count API to find out how many Tweets my URL has had?
In this early stage of the Tweet Button the count API is private. This means you need to use either our javascript or iframe Tweet Button to be able to render the count. As our systems scale we will look to make the count API public for developers to use.
http://dev.twitter.com/pages/tweet_button_faq#custom-shortener-count
Yes,
https://share.yandex.ru/gpp.xml?url=http://www.web-technology-experts-notes.in
Replace "http://www.web-technology-experts-notes.in" with "your full web page URL".
Check the Sharing count of Facebook, Twitter, LinkedIn and Pinterest
http://www.web-technology-experts-notes.in/2015/04/share-count-and-share-url-of-facebook-twitter-linkedin-and-pininterest.html
Update:
As of 21st November 2015, Twitter has removed the "Tweet count endpoint" API.
Read More: https://twitter.com/twitterdev/status/667836799897591808
The approved reply is the right one. There are other versions of the same endpoint, used internally by Twitter.
For example, the official share button with count uses this one:
https://cdn.syndication.twitter.com/widgets/tweetbutton/count.json?url=[URL]
JSONP support is there adding &callback=func.
I know that is an old question but for me the url http://cdn.api.twitter.com/1/urls/count.json?url=http://stackoverflow.com did not work in ajax calls due to Cross-origin issues.
I solved using PHP CURL, I made a custom route and called it through ajax.
/* Other Code */
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
CURLOPT_ENCODING => "", // handle compressed
CURLOPT_USERAGENT => "test", // name of client
CURLOPT_AUTOREFERER => true, // set referrer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // time-out on connect
CURLOPT_TIMEOUT => 120, // time-out on response
);
$url = $_POST["url"]; //whatever you need
if($url !== ""){
$curl = curl_init("http://urls.api.twitter.com/1/urls/count.json?url=".$url);
curl_setopt_array($curl, $options);
$result = curl_exec($curl);
curl_close($curl);
echo json_encode(json_decode($result)); //whatever response you need
}
It is important to use a POST because passsing url in GET request cause issues.
Hope it helped.
This comment https://stackoverflow.com/a/8641185/1118419 proposes to use Topsy API. I am not sure that API is correct:
Twitter response for www.e-conomic.dk:
http://urls.api.twitter.com/1/urls/count.json?url=http://www.e-conomic.dk
shows 10 count
Topsy response fro www.e-conomic.dk:
http://otter.topsy.com/stats.json?url=http://www.e-conomic.dk
18 count
This way you can get it with jquery. The div id="twitterCount" will be populated automatic when the page is loaded.
function getTwitterCount(url){
var tweets;
$.getJSON('http://urls.api.twitter.com/1/urls/count.json?url=' + url + '&callback=?', function(data){
tweets = data.count;
$('#twitterCount').html(tweets);
});
}
var urlBase='http://http://stackoverflow.com';
getTwitterCount(urlBase);
Cheers!
Yes, there is. As long as you do the following:
Issue a JSONP request to one of the urls:
http://cdn.api.twitter.com/1/urls/count.json?url=[URL_IN_REQUEST]&callback=[YOUR_CALLBACK]
http://urls.api.twitter.com/1/urls/count.json?url=[URL_IN_REQUEST]&callback=[YOUR_CALLBACK]
Make sure that the request you are making is from the same domain as the [URL_IN_REQUEST]. Otherwise, it will not work.
Example:
Making requests from example.com to request the count of example.com/page/1. Should work.
Making requests from another-example.com to request the count of example.com/page/1. Will NOT work.
I just read the contents into a json object via php, then parse it out..
<script>
<?php
$tweet_count_url = 'http://urls.api.twitter.com/1/urls/count.json?url='.$post_link;
$tweet_count_open = fopen($tweet_count_url,"r");
$tweet_count_read = fread($tweet_count_open,2048);
fclose($tweet_count_open);
?>
var obj = jQuery.parseJSON('<?=$tweet_count_read;?>');
jQuery("#tweet-count").html("("+obj.count+") ");
</script>
Simple enough, and it serves my purposes perfectly.
This Javascript class will let you fetch share information from Facebook, Twitter and LinkedIn.
Example of usage
<p>Facebook count: <span id="facebook_count"></span>.</p>
<p>Twitter count: <span id="twitter_count"></span>.</p>
<p>LinkedIn count: <span id="linkedin_count"></span>.</p>
<script type="text/javascript">
var smStats=new SocialMediaStats('https://google.com/'); // Replace with your desired URL
smStats.facebookCount('facebook_count'); // 'facebook_count' refers to the ID of the HTML tag where the result will be placed.
smStats.twitterCount('twitter_count');
smStats.linkedinCount('linkedin_count');
</script>
Download
https://404it.no/js/blog/SocialMediaStats.js
More examples and documentation
Javascript Class For Getting URL Shares On Facebook, Twitter And LinkedIn

Resources