Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

"We've detected automated behavior on your account" scary warning #1776

Open
AliRoshaniDev opened this issue Apr 20, 2024 · 5 comments
Open
Labels
question unconfirmed This issue hasn't been read/confirmed/accepted by an admin

Comments

@AliRoshaniDev
Copy link

I used this library to create a robot for sending video posts based on a schedule, so that only two videos are sent at most each day, and I only ran this robot for two accounts. I adjusted the posting time for each account so that they do not overlap, and I always used the previous session for logging in. However, after about 7 days of usage, when I opened one of the accounts on my phone, I got this warning:
"we've detected automated behavior on your account"

I heard somewhere that Instagram uses machine learning to identify robots. Considering this, does it mean that packages like this are useless, or is there a solution to prevent detection by Instagram and avoid suspension?

@AliRoshaniDev AliRoshaniDev added question unconfirmed This issue hasn't been read/confirmed/accepted by an admin labels Apr 20, 2024
@fawaz-exe
Copy link

1 )Since this is a api-wrapper, Instagram might find it suspicious. On the contrary to that check your async cron schedule, sometimes it runs on loop on the server and instagram might detect as active session which of course is robotic behaviour.

  1. Keep opening your account on a regular interval as well.

@sunmasters
Copy link

Also don't change devices

@se7uh
Copy link

se7uh commented Jan 17, 2025

I also experienced the same issue before. After adding a delay for each search, it now works perfectly without any problems.

retryCount = 0;
const searchMaxRetries = 3;

while (retryCount < searchMaxRetries) {
  try {
    console.log(`Search attempt ${retryCount + 1} for: ${query}`);

    const randomBaseDelay = Math.floor(Math.random() * 1000) + 3000; // 3-4 second base delay

    // Search users
    await this.sleep(randomBaseDelay);
    const users = await this.ig.search.users(query);

    // Search hashtags with delay
    await this.sleep(randomBaseDelay);
    const hashtags = await this.ig.search.tags(query);

    // Search locations with delay
    await this.sleep(randomBaseDelay);
    const locations = await this.ig.search.location(0, 0, query);

    const results: SearchResponse = {
      users: users.map((user: UserRepositorySearchResponseUsersItem) => ({
        pk: user.pk,
        username: user.username,
        full_name: user.full_name,
        is_private: user.is_private,
        profile_pic_url: user.profile_pic_url,
        follower_count: user.follower_count,
      })),
      hashtags: hashtags.map((tag: TagRepositorySearchResponseResultsItem) => ({
        id: tag.id,
        name: tag.name,
        media_count: tag.media_count,
      })),
      locations: locations.map(
        (loc: LocationRepositorySearchResponseVenuesItem) => ({
          pk: loc.external_id.toString(),
          name: loc.name,
          address: loc.address || "",
        })
      ),
    };

    return this.setResponse(
      "Search completed successfully",
      results,
     "success"
    );
  } catch (searchError) {
    const waitTime = 3000 * (retryCount + 1);
    console.log(`Search failed, waiting ${waitTime}ms before retry`);
    await this.sleep(waitTime);
    retryCount++;

    if (retryCount === searchMaxRetries) {
      throw searchError;
    }
  }
}

@AliRoshaniDev
Copy link
Author

I also experienced the same issue before. After adding a delay for each search, it now works perfectly without any problems.

retryCount = 0;
const searchMaxRetries = 3;

while (retryCount < searchMaxRetries) {
try {
console.log(Search attempt ${retryCount + 1} for: ${query});

const randomBaseDelay = Math.floor(Math.random() * 1000) + 3000; // 3-4 second base delay

// Search users
await this.sleep(randomBaseDelay);
const users = await this.ig.search.users(query);

// Search hashtags with delay
await this.sleep(randomBaseDelay);
const hashtags = await this.ig.search.tags(query);

// Search locations with delay
await this.sleep(randomBaseDelay);
const locations = await this.ig.search.location(0, 0, query);

const results: SearchResponse = {
  users: users.map((user: UserRepositorySearchResponseUsersItem) => ({
    pk: user.pk,
    username: user.username,
    full_name: user.full_name,
    is_private: user.is_private,
    profile_pic_url: user.profile_pic_url,
    follower_count: user.follower_count,
  })),
  hashtags: hashtags.map((tag: TagRepositorySearchResponseResultsItem) => ({
    id: tag.id,
    name: tag.name,
    media_count: tag.media_count,
  })),
  locations: locations.map(
    (loc: LocationRepositorySearchResponseVenuesItem) => ({
      pk: loc.external_id.toString(),
      name: loc.name,
      address: loc.address || "",
    })
  ),
};

return this.setResponse(
  "Search completed successfully",
  results,
 "success"
);

} catch (searchError) {
const waitTime = 3000 * (retryCount + 1);
console.log(Search failed, waiting ${waitTime}ms before retry);
await this.sleep(waitTime);
retryCount++;

if (retryCount === searchMaxRetries) {
  throw searchError;
}

}
}

How long have you been using this code? I didn’t have any issues using it either, even after that warning, but there’s still a chance of the account getting suspended. Maybe Instagram is more sensitive about content uploads. On the other hand, I had also added random delays to the code, but I still got that warning.

@se7uh
Copy link

se7uh commented Jan 17, 2025

I’ve been using this method for a while now. Before implementing it, I used to get a checkpoint after more than 5 searches. However, since applying this method, I haven’t encountered any checkpoints anymore.

You might also need to save the deviceId, so you don’t have to generate a new one for each search.

my full code:
private async setupDeviceId(account: IInstagramAccount): Promise <string> {
	if (account.device_id) {
		this.ig.state.deviceId = account.device_id
		this.ig.state.deviceString = account.device_id
		return account.device_id
	}

	this.ig.state.generateDevice(account.username)
	const deviceId = this.ig.state.deviceId
	if (account.id) {
		await this.repository.update(account.id, {
			device_id: deviceId
		})
	}
	return deviceId
}

async handleSearch(
		_event: IpcMainInvokeEvent,
		{ defaultAccount, query }: { defaultAccount: string; query: string }
	): Promise<ServiceResponse<SearchResponse>> {
		try {
			// Enforce delay between searches
			await this.enforceSearchDelay()

			let account = await this.repository.findByUsername(defaultAccount)
			if (!account) {
				account = await this.repository.findByName(defaultAccount)
			}

			if (!account || !account.id) {
				console.error('Search account not found:', defaultAccount)
				return this.setResponse('Account not found', { users: [] }, 'error')
			}

			const session = await this.sessionRepository.findByUserId(account.id)
			if (!session) {
				return this.setResponse('Account not logged in', { users: [] }, 'error')
			}

			// Setup device ID and state
			await this.setupDeviceId(account)
			await this.ig.state.deserializeCookieJar(session.cookieJar)
			await this.ig.state.deserialize(session.session)

			try {
				// Validate session with retry
				let retryCount = 0
				const maxRetries = 2

				while (retryCount <= maxRetries) {
					try {
						await this.ig.account.currentUser()
						break
					} catch (error) {
						if (error instanceof IgCheckpointError) {
							console.error('Checkpoint error during session validation')
							await this.repository.updateStatus(account.id, 'checkpoint')
							return this.setResponse(
								'Account requires verification. Please login through Instagram app first.',
								{ users: [] },
								'error'
							)
						}

						if (
							error instanceof IgLoginRequiredError ||
							retryCount === maxRetries
						) {
							await this.repository.updateStatus(account.id, 'logout')
							return this.setResponse(
								'Session expired, please login again',
								{ users: [] },
								'error'
							)
						}

						console.log(`Retry ${retryCount + 1} for session validation`)
						await this.sleep(1000 * (retryCount + 1))
						retryCount++
					}
				}

				// Perform search with increased delays between retries
				retryCount = 0
				const searchMaxRetries = 3

				while (retryCount < searchMaxRetries) {
					try {
						console.log(`Search attempt ${retryCount + 1} for: ${query}`)

						// Sequential searches with delays
						const randomBaseDelay = Math.floor(Math.random() * 1000) + 3000 // 3-4 second base delay

						// Search users
						await this.sleep(randomBaseDelay)
						const users = await this.ig.search.users(query)

						// Search hashtags with delay
						await this.sleep(randomBaseDelay)
						const hashtags = await this.ig.search.tags(query)

						// Search locations with delay
						await this.sleep(randomBaseDelay)
						const locations = await this.ig.search.location(0, 0, query)

						const results: SearchResponse = {
							users: users.map(
								(user: UserRepositorySearchResponseUsersItem) => ({
									pk: user.pk,
									username: user.username,
									full_name: user.full_name,
									is_private: user.is_private,
									profile_pic_url: user.profile_pic_url,
									follower_count: user.follower_count,
								})
							),
							hashtags: hashtags.map(
								(tag: TagRepositorySearchResponseResultsItem) => ({
									id: tag.id,
									name: tag.name,
									media_count: tag.media_count,
								})
							),
							locations: locations.map(
								(loc: LocationRepositorySearchResponseVenuesItem) => ({
									pk: loc.external_id.toString(),
									name: loc.name,
									address: loc.address || '',
								})
							),
						}

						return this.setResponse(
							'Search completed successfully',
							results,
							'success'
						)
					} catch (searchError) {
						if (searchError instanceof IgCheckpointError) {
							await this.repository.updateStatus(account.id, 'checkpoint')
							return this.setResponse(
								'Account requires verification. Please login through Instagram app first.',
								{ users: [] },
								'error'
							)
						}

						if (searchError instanceof IgLoginRequiredError) {
							await this.repository.updateStatus(account.id, 'logout')
							return this.setResponse(
								'Session expired, please login again',
								{ users: [] },
								'error'
							)
						}

						const waitTime = 3000 * (retryCount + 1)
						console.log(`Search failed, waiting ${waitTime}ms before retry`)
						await this.sleep(waitTime)
						retryCount++

						if (retryCount === searchMaxRetries) {
							throw searchError
						}
					}
				}

				throw new Error('Search failed after max retries')
			} catch (error) {
				console.error('Error during search operation:', error)
				if (error instanceof IgCheckpointError) {
					await this.repository.updateStatus(account.id, 'checkpoint')
					return this.setResponse(
						'Account requires verification. Please login through Instagram app first.',
						{ users: [] },
						'error'
					)
				}
				return this.setResponse(
					'Failed to perform search',
					{ users: [] },
					'error'
				)
			}
		} catch (error) {
			console.error('Fatal error in search handler:', error)
			return this.setResponse(
				'An unexpected error occurred',
				{ users: [] },
				'error'
			)
		}
	}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question unconfirmed This issue hasn't been read/confirmed/accepted by an admin
Projects
None yet
Development

No branches or pull requests

4 participants