Connecting with the Twitter API

To be able to use the Twitter API, it is necessary to create an object based on the twitter.Twitter class, which will result in an object capable of interacting with the Twitter API that must be defined using the auth parameter:

>>> twitter.Twitter (auth = <object twitter.oauth.OAuth>)

The argument for the auth parameter must be an instantiated object of the twitter.oauth.OAuth class for which the Twitter access credentials must be entered:

>>> twitter.oauth.OAuth(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_TOKEN,ACCESS_TOKEN_SECRET)

For example, this function allows you to read the credentials from a file whose path will be entered as a parameter and to return a twitter.Twitter object with an active connection to the Twitter API:

def twitter_connection(path_file):
with open(path_file, 'r') as file:
(CONSUMER_KEY,
CONSUMER_SECRET,
ACCESS_TOKEN,
ACCESS_TOKEN_SECRET) = archivo.read().splitlines()
auth = twitter.oauth.OAuth(ACCESS_TOKEN,
ACCESS_TOKEN_SECRET,
CONSUMER_KEY,
CONSUMER_SECRET)
return twitter.Twitter(auth=auth)

In this case, the credentials will be read from the data/credentials.txt file. We can invoke the previous function with the credentials file as a parameter:

>>> twitter = twitter_connection("data/credentials.txt")

From here, you can create scripts that allow you to extract information of interest, such as taking a list of tweets from a specific account or searching for a specific hashtag.

The following example allows you to extract the first 10 tweets that match the "#python" hashtag. You can find the following code in the get_info_account.py file:

import twitter 

def get_info_twitter(tw):
if tw is not None:
query = tw.search.tweets(q="#python", lang="en", count="10")["statuses"]
for q in query:
for key,value in q.items():
if(key=='text'):
print(value+' ')

def main():
try:
tw = twitter_connection("credentials.txt")
get_info_twitter(tw)
except Exception as e:
print(str(e))

if __name__ == "__main__":
main()

In this screenshot, we can see the execution of the previous script:

..................Content has been hidden....................

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