I am building a Telegram bot that will forward Elon Musk's latest Twitter. Even if it works without any problems, occasionly index error is occured. "api_user_timeline" returns empty list.
To find out the problem, print() was added and driven, but an error occurred in the second iteration of while().
import telepot
import os
import tweepy
import time
import requests
token = '' #telepot bot token
user_list=[''] #user id
bot = telepot.Bot(token)
consumer_key = "" # Twitter API Key
consumer_secret = "" # Twitter API Secret Key
access_token = "" # Twitter Access Key
access_token_secret = "" # Twitter Access Secret Key
auth = tweepy.OAuthHandler(consumer_key,consumer_secret)
auth.set_access_token(access_token,access_token_secret)
api = tweepy.API(auth, wait_on_rate_limit=True)
user_id='44196397'
status = api.user_timeline(user_id=user_id,exclude_replies=True,include_rts=False, tweet_mode = 'extended')
print("[status] "+status_present[0].full_text)
while True:
time.sleep(30)
status_present = api.user_timeline(user_id=user_id,exclude_replies=True, include_rts=False, tweet_mode = 'extended')
print("[status_present] "+status_present[0].full_text)
if status[0].full_text!=status_present[0].full_text:
for i in user_list:
bot.sendMessage(i,status_present[0].full_text)
status=status_present
here's output print() message & error message below I ran it in jupyter notebook.
[status] Given that Twitter serves as the de facto public town square, failing to adhere to free speech principles fundamentally undermines democracy.
[status_present] Given that Twitter serves as the de facto public town square, failing to adhere to free speech principles fundamentally undermines democracy.
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_9460/139022525.py in <module>
56 time.sleep(30)
57 status_present = api.user_timeline(user_id=user_id,exclude_replies=True, include_rts=False, tweet_mode = 'extended')
---> 58 print("[status_present] "+status_present[0].full_text)
59 if status[0].full_text!=status_present[0].full_text:
60 for i in user_list:
IndexError: list index out of range
I want to know why this phenomenon occurs. I would appreciate it if you could let me know if there is anything to fix in the code. Thanks