Error in instagramapisharp code when i want like users id

  Kiến thức lập trình

I need to create a bot to perform a reaction to whomever likes my Instagram posts. The reaction is that whomever liked my Instagram posts the bot likes his/her last 3 Instagram posts. And I want it done through Instagram ApiSharp
means get linke notification and get users and like post of them

i use instagramapisharp by ramtin

my code is :

public static UserSessionData user = new UserSessionData()
        {
            UserName = Class1._username
         ,
            Password = Class1._Password
        };
        public static IInstaApi api = InstaApiBuilder.CreateBuilder()
            .SetUser(user).UseLogger(new DebugLogger(LogLevel.All))
            .Build();

public static async void Login()
        {
            try
            {
                if (File.Exists("DataUser.bin"))
                {
                    MessageBox.Show("Load From File");
                    using (var filestream = File.OpenRead("DataUser.bin"))
                    {
                        api.LoadStateDataFromStream(filestream);
                        MessageBox.Show("Logged:)");
                    }
                }
            }
            catch (Exception e) { MessageBox.Show(e.ToString()); }
            if (!api.IsUserAuthenticated)
            {
                var requestlogin = await api.LoginAsync();
                if (requestlogin.Succeeded)
                { MessageBox.Show("You Logged"); }
                else { MessageBox.Show("You Not Logged"); }
            }
            var state = api.GetStateDataAsStream();
            using (var filestream = File.Create("DataUser.bin"))
            {
                state.Seek(0, SeekOrigin.Begin);
                state.CopyTo(filestream);
            }
        }
 private void Button1_Click(object sender, EventArgs e)
        {
            Login();

        }
  private void Button4_Click(object sender, EventArgs e)
        {
            System.Threading.Thread.Sleep(1000);
            backgroundWorker1.RunWorkerAsync();
        }
  private async void BackgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            var recentActivity = api.UserProcessor.GetRecentActivityFeedAsync(PaginationParameters.MaxPagesToLoad(10)).Result;
            for (int i = 0; i < recentActivity.Value.Items.Count; i++)
            {
                this.txtactivityresualt.Invoke((MethodInvoker)delegate ()
                {
                    txtactivityresualt.Text += recentActivity.Value.Items[i].ProfileId + Environment.NewLine;
                    if (recentActivity.Succeeded)
                    {
                        txthazftekrari.Text = string.Join(Environment.NewLine, txtactivityresualt.Lines.Distinct()) + Environment.NewLine;

                        var trimmedNumber = txthazftekrari.Text.TrimStart('0');

                        txthazzero.Text = trimmedNumber + Environment.NewLine;
                        //////////////////////////////////
                        string text = txthazzero.Text;
                        string newText = Regex.Replace(text, @"^s*$n|", string.Empty, RegexOptions.Multiline).TrimEnd() + Environment.NewLine;
                        txtresualtactivity.Text = newText;
                    }
                });

            }
System.Threading.Thread.Sleep(5000);

            for (int j = 0; j < txtresualtactivity.Lines.Length; j++)
            {
                //    // Reset the like count at the beginning of each day
                //    if (DateTime.Now.Hour == 0 && DateTime.Now.Minute == 0)
                //    {
                //        likeCount = 0;
                //        likedPosts.Clear(); // Clear the set of liked posts for the new day
                //    }

                //    if (likeCount < MaxLikesPerDay)
                //    {
                // Simulate receiving a notification for a like event
                long userId =long.Parse(txtactivityresualt.Lines[j]); // Get the user ID who liked your post

                // Get the 3 latest posts of the user who liked your post
                var userPosts = await api.UserProcessor.GetUserMediaByIdAsync(userId, PaginationParameters.MaxPagesToLoad(1));

                if (userPosts.Succeeded)
                {
                    for (int k = 0; k <= 3; k++)
                    {
                        var post = userPosts.Value[k];

                        // Check if the post has already been liked
                        if (likedPosts.Contains(post.InstaIdentifier))
                        {
                            continue; // Skip the post if it has already been liked
                        }

                        // Like the post of the user who liked your post
                        var likeResult = await api.MediaProcessor.LikeMediaAsync(post.InstaIdentifier);

                        if (likeResult.Succeeded)
                        {
                            likeCount++;
                            likedPosts.Add(post.InstaIdentifier); // Add the liked post to the set
                            LogTextBox.AppendText($"Liked post {k + 1} of user {userId}n");
                        }
                        else
                        {
                            LogTextBox.AppendText($"Failed to like post {k + 1} of user {userId}n");
                        }

                        // Check if the maximum likes per day limit has been reached
                        if (likeCount >= MaxLikesPerDay)
                        {
                            break; // Exit the loop
                        }

                        // Sleep for the specified delay before processing the next action
                        await Task.Delay(TimeSpan.FromSeconds(DelayInSeconds));
                    }
                }
                else
                {
                    LogTextBox.AppendText("User does not have enough posts to like.n");
                }

            }

in the this lines of program have error :

var post = userPosts.Value[k];

LogTextBox.AppendText($"Liked post {k + 1} of user {userId}n");

error for var post :

'Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index'

error for logtextbox.appendtext:

Cross-thread operation not valid: Control 'LogTextBox' accessed from a thread other than the thread it was created on

New contributor

Milad So is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT