Skip to content

How to use library features

Alexander Legotin edited this page Feb 4, 2018 · 16 revisions

Installation

Add sources to project

Reference dll

Reference from nuget or DEV version (always latest build) from myget

Constructor

Create API instance, can be used as singletone in your application

var apiInstance = new InstaApiBuilder()
                .UseLogger(new SomeLogger())
                .UseHttpClient(new SomeHttpClient())
                .SetUser(new UserCredentials(...You user...))
                .Build();

Set up proxy

 var httpHndler = new HttpClientHandler();
 httpHndler.Proxy = new MyProxy();
 var apiInstance = new InstaApiBuilder()
                .UseHttpClientHandler(httpHndler)
                .Build();

Where MyProxy - some implementation of IWebProxy, WebProxy, for example.

How to set delay between requests (10 seconds in example)?

 var apiInstance = new InstaApiBuilder()
                .SetRequestDelay(TimeSpan.FromSeconds(10))
                .Build();

How can I do like media?

 apiInstance.LikeMediaAsync(mediaId);

How can I get comments on media and post new comment?

 apiInstance.GetMediaCommentsAsync(mediaId, maxPagesToLoad);
 apiInstance.CommentMediaAsync(mediaId, text);

How can I upload new photo post/story?

var mediaImage = new MediaImage
            {
                Height = 1080,
                Width = 1080,
                URI = new Uri(@"image.jpg", UriKind.Absolute).LocalPath
            };
var result = await apiInstance.UploadPhotoAsync(mediaImage, caption);
var anotherResult = await apiInstance.UploadStoryPhotoAsync(mediaImage, caption);

How to work with followers?

 apiInstance.GetUserFollowersAsync(username, maxPagesToLoad);
 apiInstance.FollowUserAsync(userId);

How to get friendship status?

 apiInstance.GetFriendshipStatusAsync(userPk);

How to get location, its feed?

 // search for related locations near location with latitude = 55.753923, logitude = 37.620940
 // additionaly you can specify search query or just empty string
 var result = await apiInstance.SearchLocation(55.753923, 37.620940, "square");
 Console.WriteLine($"Found {result.Value.Count} locations");
 var locationFeed = await apiInstance.GetLocationFeed(long.Parse(firstLocation.ExternalId), PaginationParameters.MaxPagesToLoad(5));

How to work with collections?

// get all collections of current user
var collections = await apiInstance.GetCollectionsAsync();
// get specific collection by id
var collectionId = 1234567890;
var collection = await apiInstance.GetCollectionAsync(collectionId);
// create collection
var createResult = await apiInstance.CreateCollectionAsync("My collection");
// add items to collection
var mediaItems = new[] { "2658893121999767931" };
var addResult = await apiInstance.AddItemsToCollectionAsync(collectionId, mediaItems);

How to use pagination?

To be able to skip some of the pages and limit results there is class PaginationParameters, you should use it with every method which can return paginated data. NextId property you can find in most lists. For more info please check Basic Demo Sample

// load everything
PaginationParameters.Empty
// load 5 pages at max starting from the very beginning
PaginationParameters.MaxPagesToLoad(5)
// load 10 pages at max starting from id
PaginationParameters.MaxPagesToLoad(10).StartFromId("AQAC8w90POWyM7zMjHWmO9vsZNL_TuLp6FR506_C_y3fUAjlCclrIDI2RdSGvur5UjLrq4Cq7NJN8QUhHG-vpbT6pCLB5X9crDxBOHUEuNJ4fA")
// access next id property 
var followers = await apiInstance.GetUserFollowersAsync("username", PaginationParameters.MaxPagesToLoad(5)));
Console.WriteLine($"Next id will be: '{followers.Value.NextId}'");

How to get followers/following/media count for the user?

//from that var you can get all the info about user by user PK
var userinfo = await _instaApi.GetUserInfoByIdAsync(user.Pk);

Unable to load complete list of followers/media/comments?

Sometimes IG services dropping connections and limit our requests when loading too many reconrds. There is no direct solutions for that, but you can workaround it by using following code. Play around it and find most suitable solution.

var user = await _instaApi.GetUserAsync("aeroflot");
var info = await _instaApi.GetUserInfoByIdAsync(user.Value.Pk);

async Task<List<InstaUserShort>> GetFollowersList(PaginationParameters parameters, List<InstaUserShort> followers)
{
	if(followers == null)
		followers = new List<InstaUserShort>();
	// load more followers
	Console.WriteLine($"Loaded so far: {followers.Count}, loading more");
	var result = await _instaApi.GetUserFollowersAsync(user.Value.UserName, parameters);

	// merge results
	if (result.Value != null)
		followers = result.Value.Union(followers).ToList();
	if (result.Succeeded)
		return followers;

	// prepare nex id
	var nextId = result.Value?.NextId ?? parameters.NextId;

	// setup some delay
	var delay = TimeSpan.FromSeconds(new Random(DateTime.Now.Millisecond).Next(60, 120));
	if (result.Info.ResponseType == ResponseType.RequestsLimit)
		delay = TimeSpan.FromSeconds(new Random(DateTime.Now.Millisecond).Next(120, 360));
	Console.WriteLine($"Not able to load full list of followers, retry in {delay.TotalSeconds} seconds");
	await Task.Delay(delay);
	return await GetFollowersList(parameters.StartFromId(nextId), followers);
}

var followersList = await GetFollowersList(PaginationParameters.Empty, null);

similar recursive approaching of media list

async Task<InstaMediaList> GetMediaList(PaginationParameters parameters)
{
	var mediaList = new InstaMediaList();
	var result = await _instaApi.GetUserMediaAsync(user.Value.UserName, parameters);
	var needRetry = !result.Succeeded;
	var nextId = result.Value?.NextId ?? string.Empty;
	if(result.Value != null)
		mediaList.AddRange(result.Value);
	var delay = TimeSpan.FromSeconds(10);
	if (result.Info.ResponseType == ResponseType.RequestsLimit)
		delay = TimeSpan.FromMinutes(3);
	while (needRetry)
	{
		Console.WriteLine($"Not able to load full list of media, retry in {delay.TotalSeconds} seconds");
		return await GetMediaList(PaginationParameters.MaxPagesToLoad(int.MaxValue).StartFromId(nextId));
	}
	return mediaList;
}

var media = await GetMediaList(PaginationParameters.Empty);

How to search for the specific follower or following?

var followers = await _instaApi..GetUserFollowersAsync("username", PaginationParameters.MaxPagesToLoad(5), "searchQuery");
var following = await _instaApi..GetUserFollowingAsync("username", PaginationParameters.MaxPagesToLoad(5), "searchQuery");