Retrieving tweets from a timeline

In the previous script, we can add a get_mentions() function for checking and retrieving new tweets from our mentions timeline. For this task, we can use the timeline endpoint at https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-mentions_timeline.html.

You can find the following code in the twitter_mentions.py file:

#! /usr/bin/python3
import requests
import requests_oauthlib
import sys
import json

def init_auth(file):
(CONSUMER_KEY,CONSUMER_SECRET,OAUTH_TOKEN,OAUTH_TOKEN_SECRET) = open(file, 'r').read().splitlines()
auth_obj = requests_oauthlib.OAuth1(CONSUMER_KEY, CONSUMER_SECRET,
OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
if verify_credentials(auth_obj):
print('Validated credentials OK')
return auth_obj
else:
print('Credentials validation failed')
sys.exit(1)

def verify_credentials(auth_obj):
url = 'https://api.twitter.com/1.1/account/verify_credentials.json'
response = requests.get(url, auth=auth_obj)
return response.status_code == 200

def get_mentions(since_id, auth_obj):
params = {'count': 200, 'since_id': since_id,'include_rts': 0, 'include_entities': 'false'}
url = 'https://api.twitter.com/1.1/statuses/mentions_timeline.json'
response = requests.get(url, params=params, auth=auth_obj)
#Checking if the request is successful.
#It will raise an HTTPError if the request returned an unsuccessful status code.
response.raise_for_status()
return json.loads(response.text)

if __name__ == '__main__':
auth_obj = init_auth('credentials.txt')
since_id = 1
for tweet in get_mentions(since_id, auth_obj):
print(tweet['text'])

Using get_mentions(), we check for and download any tweets that mention our app account by connecting to the statuses/mentions_timeline.json endpoint. We supply a number of parameters, which Requests passes on as a query string. These parameters are specified by Twitter and they control how the tweets will be returned to us. They are as follows:

  • 'count': This specifies the maximum number of tweets that will be returned. Twitter will allow 200 tweets to be received by a single request made to this endpoint.
  • 'include_entities': This is used for trimming down some extraneous information from the tweets retrieved.
  • 'include_rts': This tells Twitter not to include any retweets. We don't want the user to receive another time update if someone retweets our reply.
  • 'since_id': This tells Twitter to only return the tweets with IDs above this value. Every tweet has a unique 64-bit integer ID, and later tweets have higher value IDs than earlier tweets. By remembering the ID of the last tweet we processed and then passing it as this parameter, Twitter will filter out the tweets that we've already seen.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset