Skip to content

Instantly share code, notes, and snippets.

@skolo-online
Created January 8, 2022 22:41
Show Gist options
  • Save skolo-online/0d438349ea83392d8018974aa8b4ab77 to your computer and use it in GitHub Desktop.
Save skolo-online/0d438349ea83392d8018974aa8b4ab77 to your computer and use it in GitHub Desktop.
Twitter API V2 search
import tweepy
import config
import json
def getClient():
client = tweepy.Client(bearer_token=config.BEARER_TOKEN,
consumer_key=config.API_KEY,
consumer_secret=config.API_KEY_SECRET,
access_token=config.ACCESS_TOKEN,
access_token_secret=config.ACCESS_TOKEN_SECRET)
return client
def searchTweets(client, query, max_results):
tweets = client.search_recent_tweets(query=query, max_results=max_results)
tweet_data = tweets.data
results = []
if not tweet_data is None and len(tweet_data) > 0:
for tweet in tweet_data:
obj = {}
obj['id'] = tweet.id
obj['text'] = tweet.text
results.append(obj)
return results
def writeJsonLinesFile(list):
filename = 'tweet-training.jsonl'
with open(filename, 'w') as f:
for line in list:
f.write(json.dumps(line))
f.write('\n')
def return50Tweets(query):
query = '{} lang:en -is:retweet'.format(query)
client = getClient()
tweets = searchTweets(client, query, 50)
objs = []
if len(tweets) > 0:
for tweet in tweets:
obj = {}
obj['text'] = tweet['text']
objs.append(obj)
writeJsonLinesFile(objs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment