twikit icon indicating copy to clipboard operation
twikit copied to clipboard

two errors, one message is : status: 400, message: "{"errors":[{"code":399,"message":"Incorrect. Please try again.

Open dh12306 opened this issue 1 year ago • 12 comments

the first error is that login was blocked, and I try again after a while ,the problem seems to be solved

Traceback (most recent call last):
  File "E:\crawler\twikit\examples\mytest.py", line 37, in <module>
    asyncio.run(main())
  File "D:\rj\ana3\envs\py106\lib\asyncio\runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "D:\rj\ana3\envs\py106\lib\asyncio\base_events.py", line 646, in run_until_complete
    return future.result()
  File "E:\crawler\twikit\examples\mytest.py", line 19, in main
    await client.login(
  File "E:\crawler\twikit\twikit\client\client.py", line 414, in login
    raise TwitterException(flow.response['subtasks'][0]['cta']['secondary_text']['text'])
twikit.errors.TwitterException: We blocked an attempt to access your account because we weren't sure it was really you.

This happens when we notice unusual login activity, like an attempt to log in too many times, or from a different location or device.

You'll need to wait before trying to log in again. Some blocks are removed automatically.

Get help with login issues.

by the way , my proxy is 'https://127.0.0.1:7897' ,is that fine ?

client = Client('en-US',proxy = 'https://127.0.0.1:7897' )

then the second one was happened,error message was here:

Traceback (most recent call last):
  File "E:\crawler\twikit\examples\mytest.py", line 37, in <module>
    asyncio.run(main())
  File "D:\rj\ana3\envs\py106\lib\asyncio\runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "D:\rj\ana3\envs\py106\lib\asyncio\base_events.py", line 646, in run_until_complete
    return future.result()
  File "E:\crawler\twikit\examples\mytest.py", line 19, in main
    await client.login(
  File "E:\crawler\twikit\twikit\client\client.py", line 439, in login
    await flow.execute_task({
  File "E:\crawler\twikit\twikit\utils.py", line 88, in execute_task
    response, _ = await self._client.v11.onboarding_task(
  File "E:\crawler\twikit\twikit\client\v11.py", line 90, in onboarding_task
    return await self.base.post(
  File "E:\crawler\twikit\twikit\client\client.py", line 214, in post
    return await self.request('POST', url, **kwargs)
  File "E:\crawler\twikit\twikit\client\client.py", line 185, in request
    raise BadRequest(message, headers=response.headers)
twikit.errors.BadRequest: status: 400, message: "{"errors":[{"code":399,"message":"Incorrect. Please try again. g;173510882678047688:-1735108827231:4juRWUb2RpjGJ7ySiGNelgdX:9"}]}"

and I just want to search something on x:

import asyncio

from twikit import Client

# Enter your account information
USERNAME = ''
EMAIL = ''
PASSWORD = ''
totp_secret = ''
client = Client('en-US') #'https://127.0.0.1:7897'

async def main():
    # Asynchronous client methods are coroutines and
    # must be called using `await`.
    await client.login(
        auth_info_1=USERNAME,
        auth_info_2=EMAIL,
        password=PASSWORD,
        totp_secret = totp_secret
    )
    ###########################################
    print('--login done--')
    # Search Latest Tweets
    tweets = await client.search_tweet('girl', 'Latest')
    for tweet in tweets:
        print(tweet)
    # Search more tweets
    more_tweets = await tweets.next()
    for tweet in more_tweets:
        print('--'*10)
        print(tweet)

asyncio.run(main())

can you help me @d60 thx

dh12306 avatar Dec 25 '24 06:12 dh12306

remove two-factor authentication method

nno-official avatar Jan 01 '25 03:01 nno-official

remove two-factor authentication method

nno-official avatar Jan 01 '25 03:01 nno-official

remove two-factor authentication method

How can I do it? Thank you

snowtank avatar Jan 10 '25 12:01 snowtank

I fixed it like this:

For 2FA, I created my own class and rewrote the login function:

import pyotp

from twikit import Client
from twikit.utils import (
    Flow,
    find_dict,
)
from twikit.errors import TwitterException


class CustomClient(Client):

    async def login(
        self,
        *,
        auth_info_1: str,
        auth_info_2: str | None = None,
        password: str,
        totp_secret: str | None = None
    ) -> dict:
        """
        Logs into the account using the specified login information.
        `auth_info_1` and `password` are required parameters.
        `auth_info_2` is optional and can be omitted, but it is
        recommended to provide if available.
        The order in which you specify authentication information
        (auth_info_1 and auth_info_2) is flexible.

        Parameters
        ----------
        auth_info_1 : :class:`str`
            The first piece of authentication information,
            which can be a username, email address, or phone number.
        auth_info_2 : :class:`str`, default=None
            The second piece of authentication information,
            which is optional but recommended to provide.
            It can be a username, email address, or phone number.
        password : :class:`str`
            The password associated with the account.
        totp_secret : :class:`str`
            The TOTP (Time-Based One-Time Password) secret key used for
            two-factor authentication (2FA).

        Examples
        --------
        >>> await client.login(
        ...     auth_info_1='example_user',
        ...     auth_info_2='[email protected]',
        ...     password='00000000'
        ... )
        """
        self.http.cookies.clear()
        guest_token = await self._get_guest_token()

        flow = Flow(self, guest_token)

        await flow.execute_task(params={'flow_name': 'login'}, data={
            'input_flow_data': {
                'flow_context': {
                    'debug_overrides': {},
                    'start_location': {
                        'location': 'splash_screen'
                    }
                }
            },
            'subtask_versions': {
                'action_list': 2,
                'alert_dialog': 1,
                'app_download_cta': 1,
                'check_logged_in_account': 1,
                'choice_selection': 3,
                'contacts_live_sync_permission_prompt': 0,
                'cta': 7,
                'email_verification': 2,
                'end_flow': 1,
                'enter_date': 1,
                'enter_email': 2,
                'enter_password': 5,
                'enter_phone': 2,
                'enter_recaptcha': 1,
                'enter_text': 5,
                'enter_username': 2,
                'generic_urt': 3,
                'in_app_notification': 1,
                'interest_picker': 3,
                'js_instrumentation': 1,
                'menu_dialog': 1,
                'notifications_permission_prompt': 2,
                'open_account': 2,
                'open_home_timeline': 1,
                'open_link': 1,
                'phone_verification': 4,
                'privacy_options': 1,
                'security_key': 3,
                'select_avatar': 4,
                'select_banner': 2,
                'settings_list': 7,
                'show_code': 1,
                'sign_up': 2,
                'sign_up_review': 4,
                'tweet_selection_urt': 1,
                'update_users': 1,
                'upload_media': 1,
                'user_recommendations_list': 4,
                'user_recommendations_urt': 1,
                'wait_spinner': 3,
                'web_modal': 1
            }
        })
        await flow.sso_init('apple')
        await flow.execute_task({
            "subtask_id": "LoginJsInstrumentationSubtask",
            "js_instrumentation": {
                "response": await self._ui_metrix(),
                "link": "next_link"
            }
        })
        await flow.execute_task({
            'subtask_id': 'LoginEnterUserIdentifierSSO',
            'settings_list': {
                'setting_responses': [
                    {
                        'key': 'user_identifier',
                        'response_data': {
                            'text_data': {'result': auth_info_1}
                        }
                    }
                ],
                'link': 'next_link'
            }
        })

        if flow.task_id == 'LoginEnterAlternateIdentifierSubtask':
            await flow.execute_task({
                'subtask_id': 'LoginEnterAlternateIdentifierSubtask',
                'enter_text': {
                    'text': auth_info_2,
                    'link': 'next_link'
                }
            })

        if flow.task_id == 'DenyLoginSubtask':
            raise TwitterException(flow.response['subtasks'][0]['cta']['secondary_text']['text'])

        await flow.execute_task({
            'subtask_id': 'LoginEnterPassword',
            'enter_password': {
                'password': password,
                'link': 'next_link'
            }
        })

        if flow.task_id == 'DenyLoginSubtask':
            raise TwitterException(flow.response['subtasks'][0]['cta']['secondary_text']['text'])

        if flow.task_id == 'LoginAcid':
            print(find_dict(flow.response, 'secondary_text', find_one=True)[0]['text'])

            await flow.execute_task({
                'subtask_id': 'LoginAcid',
                'enter_text': {
                    'text': input('>>> '),
                    'link': 'next_link'
                }
            })
            return flow.response

        # await flow.execute_task({
        #     'subtask_id': 'AccountDuplicationCheck',
        #     'check_logged_in_account': {
        #         'link': 'AccountDuplicationCheck_false'
        #     }
        # })

        if not flow.response['subtasks']:
            return

        self._user_id = find_dict(flow.response, 'id_str', find_one=True)[0]

        if flow.task_id == 'LoginTwoFactorAuthChallenge':
            if totp_secret is None:
                print(find_dict(flow.response, 'secondary_text', find_one=True)[0]['text'])
                totp_code = input('>>>')
            else:
                totp_code = pyotp.TOTP(totp_secret).now()
                print(totp_code)

            await flow.execute_task({
                'subtask_id': 'LoginTwoFactorAuthChallenge',
                'enter_text': {
                    'text': totp_code,
                    'link': 'next_link'
                }
            })

        return flow.response

Just-Night avatar Jan 22 '25 13:01 Just-Night

I am getting:

We blocked an attempt to access your account because we weren't sure it was really you.

This happens when we notice unusual login activity, like an attempt to log in too many times, or from a different location or device.

You'll need to wait before trying to log in again. Some blocks are removed automatically.

Get help with login issues.

Without using 2FA. Anyway to fix this?

edit: fixed by updating httpx library

Jacobfinn123 avatar Jan 25 '25 22:01 Jacobfinn123

edit: fixed by updating httpx library

Interesting! What was the version before and the one after?

JulienMaille avatar Jan 26 '25 06:01 JulienMaille

edit: fixed by updating httpx library

Interesting! What was the version before and the one after?

Not sure exactly but the version I had the asyncclient wasn't expecting the proxy parameter which probably caused the error.

Jacobfinn123 avatar Jan 26 '25 06:01 Jacobfinn123

by any case, i got this error. Anyone knows something? status: 400, message: "{"errors":[{"code":366,"message":"flow name LoginFlow is currently not accessible g;173787681989000460:-1737876820112:XNpGMP97bNUaAhOhGcmzS4oa:3"}]}"

handalkhom avatar Jan 26 '25 07:01 handalkhom

We blocked an attempt to access your account because we weren't sure it was really you.

This happens when we notice unusual login activity, like an attempt to log in too many times, or from a different location or device.

You'll need to wait before trying to log in again. Some blocks are removed automatically.

Get help with login issues.

WHen You have this, you have to wait 15 min to connect again.

InvestigUser avatar Feb 05 '25 19:02 InvestigUser

status: 400, message: "{"errors":[{"code":398,"message":"We were unable to confirm you're human. Please try again. g;173888669791909171:-1738886698120:ib5EZSlPHZcwmRcX4Tjn3fhI:5"}]}"

h3dev avatar Feb 07 '25 00:02 h3dev

As I see it, the problem was fixed in the release https://github.com/d60/twikit/releases/tag/version2.2.2

Just-Night avatar Apr 15 '25 11:04 Just-Night

#We blocked an attempt to access your account because we weren't sure it was really you.

Ce problème est indépendant de Twikit. Pour le débloquer, connectez vous via votre navigateur habituel sir le même ordi, puis une fois réalisé, relancez le script qui fonctionnera. (Parfois non, et j'ai remarqué que c'était le cas quand c'était une adresse gmail utilisée)

J'ai personnellement pour mon application X-Monitoring réalisée 2 scripts de connexions différents pour sécuriser l'accès : le premier via Twikit (problématique avec toit compte qui a un compte gmail associé) Le second via le navigateur classique qui récupérer le cookie et stocke pour ne plus avoir besoin de se connecter via Twikit.

Mp si vous souhaitez ce morceau de mon code.

InvestigUser avatar Apr 15 '25 11:04 InvestigUser