twikit icon indicating copy to clipboard operation
twikit copied to clipboard

create_tweet() error

Open tkacsun opened this issue 1 year ago • 25 comments

When create_tweet() is executed, an error occurs, but the message below appears and the detailed cause of the error cannot be determined. use twikit 2.1.3

python code: File "C:\Users\xxxx\Documents\mytool\twtestv2.py", line 79, in main tweet_ = await client.create_tweet(text=text_, media_ids=media_, is_note_tweet = True) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\venv\Lib\site-packages\twikit\client\client.py", line 1222, in create_tweet _result = response['data']['create_tweet']['tweet_results'] ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^ KeyError: 'create_tweet'

tkacsun avatar Sep 02 '24 23:09 tkacsun

Usually KeyError is designed to handle most of the common exceptions for example, when you try to access a key that isn’t in a dictionary.

Check the documentation here to ensure everything is as it should be. At first glance, I can't tell if there's a problem with your code but if you provide more of your code I can take a look.

manudev-1 avatar Sep 03 '24 10:09 manudev-1

I have the same error with this code

    # Publicar un tweet cada 5 minutos con la información de cada fila del DataFrame
    if 'df' in locals():
        for index, row in result.iterrows():
            
            tweet1 = f"Grupo de Interés: {row['group_name']}\n" \
                     f"Periódico: {row['Periodico']}\n" \
                     f"Título: {row['title']}\n" \
                     f"{row['link']}\n"
            
            # Calcular el total de porcentaje sumando los valores de negativo y positivo
            total_percentage = row['negative'] + row['positive']
            
            # Calcular el porcentaje de negativo y positivo en relación con el total de porcentaje
            negative_percentage = (row['negative'] / total_percentage) * 100
            positive_percentage = (row['positive'] / total_percentage) * 100
            
            # Formatear el texto del tweet incluyendo los porcentajes
            tweet2 = f"Negativo: {row['negative']} ({negative_percentage:.2f}%)\n" \
                     f"Positivo: {row['positive']} ({positive_percentage:.2f}%)\n"
            
            # Calcular el total de palabras sumando las emociones específicas
            total_words = row['anger'] + row['anticipation'] + row['disgust'] + row['fear'] + row['joy'] + row['sadness'] + row['surprise'] + row['trust']
        
            
            tweet3 = f"Ira: {row['anger']} ({(row['anger'] / total_words) * 100:.2f}%)\n" \
                     f"Anticipación: {row['anticipation']} ({(row['anticipation'] / total_words) * 100:.2f}%)\n" \
                     f"Disgusto: {row['disgust']} ({(row['disgust'] / total_words) * 100:.2f}%)\n" \
                     f"Miedo: {row['fear']} ({(row['fear'] / total_words) * 100:.2f}%)\n" \
                     f"Alegría: {row['joy']} ({(row['joy'] / total_words) * 100:.2f}%)\n" \
                     f"Tristeza: {row['sadness']} ({(row['sadness'] / total_words) * 100:.2f}%)\n" \
                     f"Sorpresa: {row['surprise']} ({(row['surprise'] / total_words) * 100:.2f}%)\n" \
                     f"Confianza: {row['trust']} ({(row['trust'] / total_words) * 100:.2f}%)\n"
            
            #tweet4 = f"Cuenta de twitter del Grupo de Interes: {row['twitter_link']}\n" \
                     #f"Cuenta de twitter del Periódico: {row['Cuenta_Twitter']}" 
            
            texts = [tweet1, tweet2, tweet3]#, tweet4]
            
            reply_to = None
            
            try:                
                for text in texts:
                    tweet = await client.create_tweet(text, reply_to=reply_to)
                    reply_to = tweet.id
                    time.sleep(30)
                    
            except Exception as e:
                print(f"Error al enviar el tweet: {e}")
                continue  # Continuar con la siguiente iteración del bucle si hay un error
            
                # Esperar un tiempo aleatorio entre 2 y 4 minutos antes de enviar el siguiente tweet
            wait_time = random.randint(120, 240)
            print(f"Esperando {wait_time} segundos antes de enviar el siguiente tweet...")
            time.sleep(wait_time)
                
    else:
        print("No se pudo crear el DataFrame debido a un error.")

This is the output, somethimes works and sometimes doesn't

Error al enviar el tweet: 'create_tweet' Error al enviar el tweet: 'create_tweet' Error al enviar el tweet: 'create_tweet' Error al enviar el tweet: 'create_tweet' Error al enviar el tweet: 'create_tweet' Error al enviar el tweet: 'create_tweet' Error al enviar el tweet: 'create_tweet' Esperando 219 segundos antes de enviar el siguiente tweet... Error al enviar el tweet: 'create_tweet' Error al enviar el tweet: 'create_tweet' Error al enviar el tweet: 'create_tweet' Error al enviar el tweet: 'create_tweet' Error al enviar el tweet: 'create_tweet' Error al enviar el tweet: 'create_tweet' Error al enviar el tweet: 'create_tweet' Error al enviar el tweet: 'create_tweet' Error al enviar el tweet: 'create_tweet' Esperando 197 segundos antes de enviar el siguiente tweet... Esperando 240 segundos antes de enviar el siguiente tweet... Error al enviar el tweet: 'create_tweet' Esperando 139 segundos antes de enviar el siguiente tweet... Esperando 233 segundos antes de enviar el siguiente tweet... Error al enviar el tweet: 'create_tweet' Error al enviar el tweet: 'create_tweet' Error al enviar el tweet: 'create_tweet' Error al enviar el tweet: 'create_tweet' Error al enviar el tweet: 'create_tweet'

AritzUMA avatar Sep 03 '24 14:09 AritzUMA

Error al enviar el tweet: 'create_tweet'

Can you provide more information about the error?

manudev-1 avatar Sep 03 '24 14:09 manudev-1

KeyError: 'create_tweet'
Error al enviar el tweet: 'create_tweet'
Traceback (most recent call last):
  File "c:\proyectos\monitoreo de grupos de interés twitter\lobby_spain_twitter.py", line 263, in main
    tweet = await client.create_tweet(text, reply_to=reply_to)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\USUARIO\anaconda3\Lib\site-packages\twikit\client\client.py", line 1241, in create_tweet
    _result = response['data']['create_tweet']['tweet_results']
              ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^
              

AritzUMA avatar Sep 03 '24 14:09 AritzUMA

When fails

Error al enviar el tweet: 'create_tweet'
Error al enviar el tweet: 'create_tweet'
Error al enviar el tweet: 'create_tweet'
Error al enviar el tweet: 'create_tweet'
Error al enviar el tweet: 'create_tweet'

when the 3 tweets are posted

Esperando 139 segundos antes de enviar el siguiente tweet...
Esperando 233 segundos antes de enviar el siguiente tweet...

AritzUMA avatar Sep 03 '24 15:09 AritzUMA

async def create_tweet(
        self,
        ...
    ) -> Tweet:
...
response, _ = await self.gql.create_tweet(
            is_note_tweet, text, media_entities, poll_uri,
            reply_to, attachment_url, community_id, share_with_followers,
            richtext_options, edit_tweet_id, limit_mode
        )
print(response)
_result = response['data']['create_tweet']['tweet_results']

Through a test, I found out that the problem probably is that you are trying to create a tweet that already exists:

import asyncio
from twikit import Client

async def main():
    client = Client('en-US')

    await client.login(
        auth_info_1="***",
        auth_info_2="***",
        password="***"
    )

    await client.create_tweet("test")

if __name__ == '__main__':
    asyncio.run(main())

The first time I executed this script response was:

{'data': {'create_tweet': {'tweet_results': { ... }}}}

The second time response changed to:

{'errors': [{'message': 'Authorization: Status is a duplicate. (187)', 'locations': [{'line': 18, 'column': 3}], 'path': ['create_tweet'], 'extensions': {'name': 'AuthorizationError', 'source': 'Client', 'code': 187, 'kind': 'Permissions', 'tracing': {'trace_id': '0016b2cbaf47a4fc'}}, 'code': 187, 'kind': 'Permissions', 'name': 'AuthorizationError', 'source': 'Client', 'tracing': {'trace_id': '0016b2cbaf47a4fc'}}], 'data': {}}```

manudev-1 avatar Sep 03 '24 15:09 manudev-1

I change the text of the tweets adding the date of scrape for each tweet, to test your hypothesis.

       for index, row in result.iterrows():
            
            tweet1 = f"Grupo de Interés: {row['group_name']}\n" \
                     f"Periódico: {row['Periodico']}\n" \
                     f"Título: {row['title']}\n" \
                     f"Fecha de extracción de noticia: {row['scrape_date']}\n" \
                     f"{row['link']}\n"
            
            # Calcular el total de porcentaje sumando los valores de negativo y positivo
            total_percentage = row['negative'] + row['positive']
            
            # Calcular el porcentaje de negativo y positivo en relación con el total de porcentaje
            negative_percentage = (row['negative'] / total_percentage) * 100
            positive_percentage = (row['positive'] / total_percentage) * 100
            
            # Formatear el texto del tweet incluyendo los porcentajes
            tweet2 = f"Negativo: {row['negative']} ({negative_percentage:.2f}%)\n" \
                     f"Positivo: {row['positive']} ({positive_percentage:.2f}%)\n" \
                     f"Fecha de análsis de Sentimiento: {row['scrape_date']}\n"
            
            # Calcular el total de palabras sumando las emociones específicas
            total_words = row['anger'] + row['anticipation'] + row['disgust'] + row['fear'] + row['joy'] + row['sadness'] + row['surprise'] + row['trust']
        
            
            tweet3 = f"Ira: {row['anger']} ({(row['anger'] / total_words) * 100:.2f}%)\n" \
                     f"Anticipación: {row['anticipation']} ({(row['anticipation'] / total_words) * 100:.2f}%)\n" \
                     f"Disgusto: {row['disgust']} ({(row['disgust'] / total_words) * 100:.2f}%)\n" \
                     f"Miedo: {row['fear']} ({(row['fear'] / total_words) * 100:.2f}%)\n" \
                     f"Alegría: {row['joy']} ({(row['joy'] / total_words) * 100:.2f}%)\n" \
                     f"Tristeza: {row['sadness']} ({(row['sadness'] / total_words) * 100:.2f}%)\n" \
                     f"Sorpresa: {row['surprise']} ({(row['surprise'] / total_words) * 100:.2f}%)\n" \
                     f"Confianza: {row['trust']} ({(row['trust'] / total_words) * 100:.2f}%)\n" \
                     f"Fecha de análsis de Emociones: {row['scrape_date']}\n"
            
            #tweet4 = f"Cuenta de twitter del Grupo de Interes: {row['twitter_link']}\n" \
                     #f"Cuenta de twitter del Periódico: {row['Cuenta_Twitter']}" 
            
            texts = [tweet1, tweet2, tweet3]#, tweet4]

this is the result

Error al enviar el tweet: 'create_tweet'
Traceback (most recent call last):
  File "c:\proyectos\monitoreo de grupos de interés twitter\lobby_spain_twitter.py", line 266, in main
    tweet = await client.create_tweet(text, reply_to=reply_to)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\USUARIO\anaconda3\Lib\site-packages\twikit\client\client.py", line 1241, in create_tweet
    _result = response['data']['create_tweet']['tweet_results']
              ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^
KeyError: 'create_tweet'
Error al enviar el tweet: 'create_tweet'
Traceback (most recent call last):
  File "c:\proyectos\monitoreo de grupos de interés twitter\lobby_spain_twitter.py", line 266, in main
    tweet = await client.create_tweet(text, reply_to=reply_to)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\USUARIO\anaconda3\Lib\site-packages\twikit\client\client.py", line 1241, in create_tweet
    _result = response['data']['create_tweet']['tweet_results']
              ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^
KeyError: 'create_tweet'
Error al enviar el tweet: 'create_tweet'
Traceback (most recent call last):
  File "c:\proyectos\monitoreo de grupos de interés twitter\lobby_spain_twitter.py", line 266, in main
    tweet = await client.create_tweet(text, reply_to=reply_to)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\USUARIO\anaconda3\Lib\site-packages\twikit\client\client.py", line 1241, in create_tweet
    _result = response['data']['create_tweet']['tweet_results']
              ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^
KeyError: 'create_tweet'
Error al enviar el tweet: 'create_tweet'
Traceback (most recent call last):
  File "c:\proyectos\monitoreo de grupos de interés twitter\lobby_spain_twitter.py", line 266, in main
    tweet = await client.create_tweet(text, reply_to=reply_to)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\USUARIO\anaconda3\Lib\site-packages\twikit\client\client.py", line 1241, in create_tweet
    _result = response['data']['create_tweet']['tweet_results']
              ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^
KeyError: 'create_tweet'
Error al enviar el tweet: 'create_tweet'
Traceback (most recent call last):
  File "c:\proyectos\monitoreo de grupos de interés twitter\lobby_spain_twitter.py", line 266, in main
    tweet = await client.create_tweet(text, reply_to=reply_to)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\USUARIO\anaconda3\Lib\site-packages\twikit\client\client.py", line 1241, in create_tweet
    _result = response['data']['create_tweet']['tweet_results']
              ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^
KeyError: 'create_tweet'
Error al enviar el tweet: 'create_tweet'
Traceback (most recent call last):
  File "c:\proyectos\monitoreo de grupos de interés twitter\lobby_spain_twitter.py", line 266, in main
    tweet = await client.create_tweet(text, reply_to=reply_to)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\USUARIO\anaconda3\Lib\site-packages\twikit\client\client.py", line 1241, in create_tweet
    _result = response['data']['create_tweet']['tweet_results']
              ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^
KeyError: 'create_tweet'
Error al enviar el tweet: 'create_tweet'
Traceback (most recent call last):
  File "c:\proyectos\monitoreo de grupos de interés twitter\lobby_spain_twitter.py", line 266, in main
    tweet = await client.create_tweet(text, reply_to=reply_to)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\USUARIO\anaconda3\Lib\site-packages\twikit\client\client.py", line 1241, in create_tweet
    _result = response['data']['create_tweet']['tweet_results']
              ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^
KeyError: 'create_tweet'

AritzUMA avatar Sep 03 '24 17:09 AritzUMA

for index, row in result.iterrows():

        tweet1 = f"Grupo de Interés: {row['group_name']}\n" \
                 f"Periódico: {row['Periodico']}\n" \
                 f"Título: {row['title']}\n" \
                 f"Fecha de extracción de noticia: {row['scrape_date']}\n" \
                 f"{row['link']}\n"
        
        # Calcular el total de porcentaje sumando los valores de negativo y positivo
        total_percentage = row['negative'] + row['positive']
        
        # Calcular el porcentaje de negativo y positivo en relación con el total de porcentaje
        negative_percentage = (row['negative'] / total_percentage) * 100
        positive_percentage = (row['positive'] / total_percentage) * 100
        
        # Formatear el texto del tweet incluyendo los porcentajes
        tweet2 = f"Negativo: {row['negative']} ({negative_percentage:.2f}%)\n" \
                 f"Positivo: {row['positive']} ({positive_percentage:.2f}%)\n" \
                 f"Fecha de análsis de Sentimiento: {row['scrape_date']}\n"
        
        # Calcular el total de palabras sumando las emociones específicas
        total_words = row['anger'] + row['anticipation'] + row['disgust'] + row['fear'] + row['joy'] + row['sadness'] + row['surprise'] + row['trust']
    
        
        tweet3 = f"Ira: {row['anger']} ({(row['anger'] / total_words) * 100:.2f}%)\n" \
                 f"Anticipación: {row['anticipation']} ({(row['anticipation'] / total_words) * 100:.2f}%)\n" \
                 f"Disgusto: {row['disgust']} ({(row['disgust'] / total_words) * 100:.2f}%)\n" \
                 f"Miedo: {row['fear']} ({(row['fear'] / total_words) * 100:.2f}%)\n" \
                 f"Alegría: {row['joy']} ({(row['joy'] / total_words) * 100:.2f}%)\n" \
                 f"Tristeza: {row['sadness']} ({(row['sadness'] / total_words) * 100:.2f}%)\n" \
                 f"Sorpresa: {row['surprise']} ({(row['surprise'] / total_words) * 100:.2f}%)\n" \
                 f"Confianza: {row['trust']} ({(row['trust'] / total_words) * 100:.2f}%)\n" \
                 f"Fecha de análsis de Emociones: {row['scrape_date']}\n"
        
        #tweet4 = f"Cuenta de twitter del Grupo de Interes: {row['twitter_link']}\n" \
                 #f"Cuenta de twitter del Periódico: {row['Cuenta_Twitter']}"

Are you sure that every tweet is different? can you try to print the tweet to make sure all of them are different?

manudev-1 avatar Sep 03 '24 17:09 manudev-1

This is only for the first one, but yes all are diferent

tweet1 = f"Grupo de Interés: {row['group_name']}\n" \
         f"Periódico: {row['Periodico']}\n" \
         f"Título: {row['title']}\n" \
         f"Fecha de extracción de noticia: {row['scrape_date']}\n" \
         f"{row['link']}\n"
print(tweet1)
# Calcular el total de porcentaje sumando los valores de negativo y positivo
total_percentage = row['negative'] + row['positive']

# Calcular el porcentaje de negativo y positivo en relación con el total de porcentaje
negative_percentage = (row['negative'] / total_percentage) * 100
positive_percentage = (row['positive'] / total_percentage) * 100

# Formatear el texto del tweet incluyendo los porcentajes
tweet2 = f"Negativo: {row['negative']} ({negative_percentage:.2f}%)\n" \
         f"Positivo: {row['positive']} ({positive_percentage:.2f}%)\n" \
         f"Fecha de análsis de Sentimiento: {row['scrape_date']}\n"
print(tweet2)
# Calcular el total de palabras sumando las emociones específicas
total_words = row['anger'] + row['anticipation'] + row['disgust'] + row['fear'] + row['joy'] + row['sadness'] + row['surprise'] + row['trust']


tweet3 = f"Ira: {row['anger']} ({(row['anger'] / total_words) * 100:.2f}%)\n" \
         f"Anticipación: {row['anticipation']} ({(row['anticipation'] / total_words) * 100:.2f}%)\n" \
         f"Disgusto: {row['disgust']} ({(row['disgust'] / total_words) * 100:.2f}%)\n" \
         f"Miedo: {row['fear']} ({(row['fear'] / total_words) * 100:.2f}%)\n" \
         f"Alegría: {row['joy']} ({(row['joy'] / total_words) * 100:.2f}%)\n" \
         f"Tristeza: {row['sadness']} ({(row['sadness'] / total_words) * 100:.2f}%)\n" \
         f"Sorpresa: {row['surprise']} ({(row['surprise'] / total_words) * 100:.2f}%)\n" \
         f"Confianza: {row['trust']} ({(row['trust'] / total_words) * 100:.2f}%)\n" \
         f"Fecha de análsis de Emociones: {row['scrape_date']}\n"
print(tweet3)
#tweet4 = f"Cuenta de twitter del Grupo de Interes: {row['twitter_link']}\n" \
         #f"Cuenta de twitter del Periódico: {row['Cuenta_Twitter']}" 

texts = [tweet1, tweet2, tweet3]#, tweet4]
reply_to = None

Grupo de Interés: Telefónica
Periódico: Europa Press
Título: El Ibex cierra plano el arranque del mes de septiembre, en 11.395 puntos
Fecha de extracción de noticia: 2024/09/03 08:00:39
https://www.europapress.es/economia/bolsa-00348/noticia-ibex-cierra-plano-arranque-mes-septiembre-11395-puntos-20240902183119.html

Negativo: 10 (38.46%)
Positivo: 16 (61.54%)
Fecha de análsis de Sentimiento: 2024/09/03 08:00:39

Ira: 3 (6.82%)
Anticipación: 10 (22.73%)
Disgusto: 2 (4.55%)
Miedo: 6 (13.64%)
Alegría: 3 (6.82%)
Tristeza: 5 (11.36%)
Sorpresa: 2 (4.55%)
Confianza: 13 (29.55%)
Fecha de análsis de Emociones: 2024/09/03 08:00:39`

AritzUMA avatar Sep 03 '24 18:09 AritzUMA

Hmm, can I see your create_tweet call function?

manudev-1 avatar Sep 03 '24 18:09 manudev-1

here complete, thanks for the help by the way @manudev-1

    # Publicar un tweet cada 5 minutos con la información de cada fila del DataFrame
    if 'df' in locals():
        for index, row in result.iterrows():
            
            tweet1 = f"Grupo de Interés: {row['group_name']}\n" \
                     f"Periódico: {row['Periodico']}\n" \
                     f"Título: {row['title']}\n" \
                     f"Fecha de extracción de noticia: {row['scrape_date']}\n" \
                     f"{row['link']}\n"
            print(tweet1)
            # Calcular el total de porcentaje sumando los valores de negativo y positivo
            total_percentage = row['negative'] + row['positive']
            
            # Calcular el porcentaje de negativo y positivo en relación con el total de porcentaje
            negative_percentage = (row['negative'] / total_percentage) * 100
            positive_percentage = (row['positive'] / total_percentage) * 100
            
            # Formatear el texto del tweet incluyendo los porcentajes
            tweet2 = f"Negativo: {row['negative']} ({negative_percentage:.2f}%)\n" \
                     f"Positivo: {row['positive']} ({positive_percentage:.2f}%)\n" \
                     f"Fecha de análsis de Sentimiento: {row['scrape_date']}\n"
            print(tweet2)
            # Calcular el total de palabras sumando las emociones específicas
            total_words = row['anger'] + row['anticipation'] + row['disgust'] + row['fear'] + row['joy'] + row['sadness'] + row['surprise'] + row['trust']
        
            
            tweet3 = f"Ira: {row['anger']} ({(row['anger'] / total_words) * 100:.2f}%)\n" \
                     f"Anticipación: {row['anticipation']} ({(row['anticipation'] / total_words) * 100:.2f}%)\n" \
                     f"Disgusto: {row['disgust']} ({(row['disgust'] / total_words) * 100:.2f}%)\n" \
                     f"Miedo: {row['fear']} ({(row['fear'] / total_words) * 100:.2f}%)\n" \
                     f"Alegría: {row['joy']} ({(row['joy'] / total_words) * 100:.2f}%)\n" \
                     f"Tristeza: {row['sadness']} ({(row['sadness'] / total_words) * 100:.2f}%)\n" \
                     f"Sorpresa: {row['surprise']} ({(row['surprise'] / total_words) * 100:.2f}%)\n" \
                     f"Confianza: {row['trust']} ({(row['trust'] / total_words) * 100:.2f}%)\n" \
                     f"Fecha de análsis de Emociones: {row['scrape_date']}\n"
            print(tweet3)
            #tweet4 = f"Cuenta de twitter del Grupo de Interes: {row['twitter_link']}\n" \
                     #f"Cuenta de twitter del Periódico: {row['Cuenta_Twitter']}" 
            
            texts = [tweet1, tweet2, tweet3]#, tweet4]
            
            reply_to = None
            
            try:                
                for text in texts:
                    tweet = await client.create_tweet(text, reply_to=reply_to)
                    reply_to = tweet.id
                    time.sleep(30)
                        
            except Exception as e:
                # Imprimir el mensaje del error
                print(f"Error al enviar el tweet: {e}")
                
                # Imprimir la traza completa del error para más detalles
                traceback.print_exc()
                
                continue  # Continuar con la siguiente iteración del bucle si hay un error
        
            
                # Esperar un tiempo aleatorio entre 2 y 4 minutos antes de enviar el siguiente tweet
            wait_time = random.randint(120, 240)
            print(f"Esperando {wait_time} segundos antes de enviar el siguiente tweet...")
            time.sleep(wait_time)
                
    else:
        print("No se pudo crear el DataFrame debido a un error.")
        
     ```

AritzUMA avatar Sep 03 '24 18:09 AritzUMA

Can you provide the data frame used?

manudev-1 avatar Sep 03 '24 18:09 manudev-1

print(df.info())
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 27 entries, 0 to 26
Data columns (total 20 columns):
 #   Column           Non-Null Count  Dtype  
---  ------           --------------  -----  
 0   Periodico        27 non-null     object 
 1   title            27 non-null     object 
 2   link             27 non-null     object 
 3   texto            27 non-null     object 
 4   scrape_date      27 non-null     object 
 5   texto_limpio     27 non-null     object 
 6   texto_sentiment  27 non-null     object 
 7   group_name       27 non-null     object 
 8   short_url        0 non-null      float64
 9   anger            27 non-null     int64  
 10  anticipation     27 non-null     int64  
 11  disgust          27 non-null     int64  
 12  fear             27 non-null     int64  
 13  joy              27 non-null     int64  
 14  sadness          27 non-null     int64  
 15  surprise         27 non-null     int64  
 16  trust            27 non-null     int64  
 17  negative         27 non-null     int64  
 18  positive         27 non-null     int64  
 19  Best_match       25 non-null     object 
dtypes: float64(1), int64(10), object(9)
memory usage: 4.3+ KB
None

AritzUMA avatar Sep 03 '24 18:09 AritzUMA

通常KeyError、辞書にないキーにアクセスしようとした場合など、一般的な例外のほとんどを処理するように設計されています。

すべてが正しく動作していることを確認するには、ここのドキュメントを確認してください。一見したところ、コードに問題があるかどうかはわかりませんが、コードをもっと提供していただければ確認することができます。

It is as follows

try:
    media_ = []
    media_.append(await client.upload_media(r'C:\Users\tkacsun\Documents\1.png'))
    time.sleep(5)
    media_.append(await client.upload_media(r'C:\Users\tkacsun\Documents\2.png'))
    time.sleep(5)

    print('pass3')
    now_ = datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')
    pre_ = '1111111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000\n' * 5
    pre_ = '1111111111\n'
    text_ = pre_ + 'テスト投稿 by twikit\n' + now_
    tweet_ = await client.create_tweet(text=text_, media_ids=media_, is_note_tweet = True)
    print('pass4')
    time.sleep(5)
    print(tweet_)

except Exception as excpt_:
    print(f"Tweet creation error: {excpt_}")
    msg_ = "Exception Type: {}\n".format(type(excpt_).__name__) \
            + "Exception Message: {}\n".format(str(excpt_)) \
            + "Stack Trace:\n" \
            + "".join(traceback.format_exception(None, excpt_, excpt_.__traceback__))
    print(msg_)

Also, when I dumped response of client.py, it seems that a key called "notetweet_create" is set.

tkacsun avatar Sep 04 '24 01:09 tkacsun

Usually KeyError is designed to handle most of the common exceptions for example, when you try to access a key that isn’t in a dictionary.

Check the documentation here to ensure everything is as it should be. At first glance, I can't tell if there's a problem with your code but if you provide more of your code I can take a look.

Also, when I dumped response of client.py, it seems that a key called "notetweet_create" is set. Is this the expected key? insert print() on twikit/client/client.py , line 1241

{'data': {'notetweet_create': {'tweet_results': {'result': {'rest_id': '1831209171418812435', 'core': {'user_results': {'result':

tkacsun avatar Sep 04 '24 06:09 tkacsun

whats the conclusion guys?

deep0072 avatar Sep 04 '24 07:09 deep0072

whats the conclusion guys?

The conclusion is that for the function create_tweet there are tons of errors that are not handled in twikit, now we should try to find all the types of response that are not handled to try to raise a more meaningful errors to the developer

print(df.info())
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 27 entries, 0 to 26
Data columns (total 20 columns):
 #   Column           Non-Null Count  Dtype  
---  ------           --------------  -----  
 0   Periodico        27 non-null     object 
 1   title            27 non-null     object 
 2   link             27 non-null     object 
 3   texto            27 non-null     object 
 4   scrape_date      27 non-null     object 
 5   texto_limpio     27 non-null     object 
 6   texto_sentiment  27 non-null     object 
 7   group_name       27 non-null     object 
 8   short_url        0 non-null      float64
 9   anger            27 non-null     int64  
 10  anticipation     27 non-null     int64  
 11  disgust          27 non-null     int64  
 12  fear             27 non-null     int64  
 13  joy              27 non-null     int64  
 14  sadness          27 non-null     int64  
 15  surprise         27 non-null     int64  
 16  trust            27 non-null     int64  
 17  negative         27 non-null     int64  
 18  positive         27 non-null     int64  
 19  Best_match       25 non-null     object 
dtypes: float64(1), int64(10), object(9)
memory usage: 4.3+ KB
None

in your case probably the issue generated is that Twitter needs to stay under 240 characters in length by tweet

manudev-1 avatar Sep 04 '24 09:09 manudev-1

No, I paid for a basic suscription that allows me for longer tweets

AritzUMA avatar Sep 04 '24 09:09 AritzUMA

No, I paid for a basic suscription that allows me for longer tweets

Probably you can't create similar tweets in a small range of time, I noticed from an official forum of the developer community of x: here

manudev-1 avatar Sep 04 '24 12:09 manudev-1

By range of time, we mean days or hours? I tweet this tweets every day in the morning, I don't know if is in off

AritzUMA avatar Sep 04 '24 15:09 AritzUMA

By range of time, we mean days or hours? I tweet this tweets every day in the morning, I don't know if is in off

I don't know, I created #202 to try to handle these errors

manudev-1 avatar Sep 05 '24 08:09 manudev-1

Can this error be solved. Please help me guy's.

Gyanendra30 avatar Sep 07 '24 17:09 Gyanendra30

Let's see what @d60 say, I am dealing with this error every day I tweet automatcly.

AritzUMA avatar Sep 07 '24 18:09 AritzUMA

Let's see what @d60 say, I am dealing with this error every day I tweet automatcly.

Do I need to upgrade Tweakit version, because i am currently using twikit==2.1.3?

Gyanendra30 avatar Sep 07 '24 18:09 Gyanendra30

Can this error be solved. Please help me guy's.

You can't prevent this type of error because it's caused directly by the original Twitter API, the only thing that we can do is to handle this type of error by making it more meaningful to the developer as I did in #202

manudev-1 avatar Sep 07 '24 18:09 manudev-1

try version 2.2.0

d60 avatar Dec 01 '24 11:12 d60