def __init__(self,path_to_key_json="twitter_keys.json",path_to_text_files="tweet_text_files"): print("Fetching API keys...") key_dict = json.load(open(path_to_key_json)) print("Instantiating client....") self.client = tweepy.Client( consumer_key=key_dict["api_key"], consumer_secret=key_dict["api_key_secret"], access_token=key_dict["access_token"], access_token_secret=key_dict["access_secret"] ) print("Pulling files with tweets to choose from....") tweet_files = glob.glob(path_to_text_files + '/*.txt') print("Found {} files containing tweets to choose from".format(str(len(tweet_files)))) if self.DEBUG_MODE: print(tweet_files) tweets_to_send_list = [] for tweet_file in tweet_files: with open(tweet_file, 'r') as file: tweet_body = file.read().replace('\n', '') tweets_to_send_list.append(tweet_body) if self.DEBUG_MODE: print(tweets_to_send_list) self.tweets_to_send_list = tweets_to_send_list
def __init__(self): ''' Class constructor or initialization method. ''' # load environment variables load_dotenv() # keys and tokens from the Twitter Dev Console consumer_key = os.getenv('CONSUMER_KEY') consumer_secret = os.getenv('CONSUMER_SECRET') access_token = os.getenv('ACCESS_TOKEN') access_token_secret = os.getenv('ACCESS_TOKEN_SECRET') bearer_token = os.getenv('BEARER_TOKEN') # attempt authentication try: # create OAuthHandler object self.auth = OAuthHandler(consumer_key, consumer_secret) # set access token and secret self.auth.set_access_token(access_token, access_token_secret) # create tweepy API object to fetch tweets self.api = tweepy.Client(bearer_token=bearer_token, consumer_key=consumer_key, consumer_secret=consumer_secret, access_token=access_token, access_token_secret=access_token_secret) except: print("Error: Authentication Failed")
def get_users(ids): client = tweepy.Client(bearer_token=get_twitter_bearer_token()) if 1 <= len(ids) <= 100: response = client.get_users(ids=ids, user_fields=['public_metrics']) return response.data return []
def main(): twitter_client = tweepy.Client( bearer_token=os.environ.get('TWITTER_BEARER_TOKEN')) credentials = AuthCredentials(user_file="me") site = EsportsClient("lol", credentials=credentials) response = site.cargo_client.query( tables="NewsItems=NI", fields="NI.Source, NI._pageName=pageName, NI.N_LineInDate", where='NI.Source IS NOT NULL AND NI.Date_Sort >= "{}"'.format( check_from_date), order_by="NI.Date_Sort DESC") for item in response: source_list = item["Source"].split(":::") data_page = item["pageName"] line_in_date = item["N LineInDate"] for source_string in source_list: if not source_string: continue source = source_string.split(";;;") link = source[0] if source[2] != "twitter.com": continue # now we definitely have an existing source that's definitely from twitter tweet_id = re.search(r"status/([0-9]+)", link)[1] if not tweet_id: site.log_error_content("Can't get tweet id", text="Link: {0}".format(link)) continue try: r = twitter_client.get_tweet(tweet_id) except tweepy.TooManyRequests: time.sleep(30) r = twitter_client.get_tweet(tweet_id) if not r.errors: continue if r.errors[0]["title"] == TWEET_NOT_FOUND_ERROR: site.log_error_content( f"{data_page}", text=f"Tweet not found! Link: {link} - Line {line_in_date}" ) else: site.log_error_content( "Failure trying to get tweet", text= "Other error! Link: {0}, Status Id: {1}, Error title: {2}". format(str(link), str(tweet_id), str(r.errors[0]["title"]))) site.report_all_errors("Deleted Tweets")
def __init__(self, credentials, wait_on_rate_limit=True, enable_v2=False): self.enable_v2 = enable_v2 self._check_credentials(credentials) auth = tweepy.OAuth1UserHandler(credentials["api_key"], credentials["api_secret"], credentials["access_token"], credentials["access_token_secret"]) self.api = tweepy.API(auth, wait_on_rate_limit=True) if self.enable_v2: self.client = tweepy.Client(credentials["bearer_token"]) else: self.client = None
def login(self): try: self.client = tweepy.Client( bearer_token=self.bot.data.config['twitter']['bearer']) self.client.get_user(username='******', user_fields=[ 'description', 'profile_image_url', 'pinned_tweet_id' ]) return True except: self.client = None # disable if error return False
def get_tweets(searchtext, limit=100): client = tweepy.Client(bearer_token=get_twitter_bearer_token()) tweets = [] for i, tweet in enumerate( tweepy.Paginator(client.search_recent_tweets, searchtext, tweet_fields=[ 'author_id', 'public_metrics', 'lang', 'attachments' ], user_fields=['public_metrics'], max_results=100).flatten(limit=limit)): tweets.append(tweet) return tweets
def tweetAndGetResponse(output): logger.info("tweetAndGetResponse() running...") # Load twitter credentials from file into an object try: secret = get_secret_dict() # logger.info("Secret dict retrieved = " + str(secret)) ## YOU SHOULDN'T WRITE SECRETS INTO LOGS except: logger.critical("Error while opening credentials.") raise; # Log into Twitter # "**" expands credentials object into parameters logger.info("Logging into Twitter") try: # Use the API ck = secret['consumer_key'] logger.info(ck) logger.info(type(ck)) # These credentials need to have been created with WRITE permissions to tweet twitterv2Client = tweepy.Client( consumer_key=secret['consumer_key'], consumer_secret=secret['consumer_secret'], access_token=secret['access_token'], access_token_secret=secret['access_token_secret']) logger.info(secret) tweepyResponse = twitterv2Client.create_tweet(text=output) # Store the id tweeted logger.info("Tweeted; response = " + str(tweepyResponse)) return tweepyResponse except Exception as ee: logger.error("Exception while attempting to tweet: " + str(ee)) raise
#authentification oauth_dict={} with open('twitter_keys.txt','r') as f: for line in f: data=line.split() oauth_dict[data[0]]=data[1] # v1 for streaming auth = tweepy.OAuthHandler(oauth_dict['API_KEY'], oauth_dict['API_SECRET']) auth.set_access_token(oauth_dict['TOKEN'], oauth_dict['TOKEN_SECRET']) api = tweepy.API(auth, wait_on_rate_limit=True) # v2 for conversation api_v2 = tweepy.Client( consumer_key=oauth_dict['API_KEY'], consumer_secret=oauth_dict['API_SECRET'], access_token=oauth_dict['TOKEN'], access_token_secret=oauth_dict['TOKEN_SECRET'], wait_on_rate_limit=True) # read follow list for the stream filter data=pd.read_csv("ids.csv",sep=",") ids=list(data['0']) # time to wait before collecting the conversation conv_lifetime=4 # threads set up tweets_queue = Queue() tweets_process_thread = ProcessTweets(tweets_queue) tweets_replies_thread = GetReplies(conv_lifetime,api_v2) #First arg is the max number of Tweets you want to collect
import tweepy bearer_token = "" client = tweepy.Client(bearer_token) # Get User's Tweets # This endpoint/method returns Tweets composed by a single user, specified by # the requested user ID user_id = 2244994945 response = client.get_users_tweets(user_id) # By default, only the ID and text fields of each Tweet will be returned for tweet in response.data: print(tweet.id) print(tweet.text) # By default, the 10 most recent Tweets will be returned # You can retrieve up to 100 Tweets by specifying max_results response = client.get_users_tweets(user_id, max_results=100)
import json import os import emoji import tweepy LOC = os.path.abspath(os.path.join(__file__, "../../../auth_secrets.json")) with open(LOC, "r", encoding="utf-8") as auth_file: KEYS = json.load(auth_file) API = tweepy.Client( consumer_key=KEYS["ApplSec"]["api_key"], consumer_secret=KEYS["ApplSec"]["api_key_secret"], access_token=KEYS["ApplSec"]["access_token"], access_token_secret=KEYS["ApplSec"]["access_token_secret"], return_type=dict, ) def arrange_elements(tweet_text: list, item: str) -> None: """ Arrange elements so that each element in tweet_text is under 240 characters. Each element is a tweet inside of a thread. """ if len(emoji.emojize(tweet_text[-1] + item, language="alias")) < 240: tweet_text[-1] += item else: tweet_text.append(item)
import os import time import schedule import tweepy import logging import tarotDeck from credentials import * # Creating api reference client = tweepy.Client(bearerToken) auth = tweepy.OAuthHandler(apiKey, apiSecret) auth.set_access_token(accessToken, accessSecret) twit = tweepy.API(auth) logging.basicConfig(level=logging.INFO) logger = logging.getLogger() # Tarot Reading Objects hermes = tarotDeck.Reader() deck = tarotDeck.Deck() deck.shuffle() def dailycard(): hermes.dailyDraw(deck) cardRank, cardSuit = hermes.read() cardRank = str(cardRank) # Navigating to card assets # TODO: Re-do path to navigate, not hardcode cardPath = r"C:\Users\Hermes\Documents\Code Projects\Python\HermesTwitter\BookOfShadows"
user_token = os.getenv('access-token') user_token_secret = os.getenv('access-token-secret') bearer_token = os.getenv('bearer-token') import logging logging.basicConfig(level=logging.DEBUG) # use user authentication tokens # auth = tweepy.OAuthHandler(api_key, api_secret) # auth.set_access_token(user_token,user_token_secret) # api = tweepy.API(auth, wait_on_rate_limit=True) client = tweepy.Client(bearer_token=bearer_token, consumer_key=api_key, consumer_secret=api_secret, access_token=user_token, access_token_secret=user_token_secret, wait_on_rate_limit=True) # # show all lists owned by a user (default: current user) # lists = api.get_lists() # .get_lists(screen_name='j_graber') # for li in lists: # print(f"{li.id} - {li.name} ({li.mode}) - [{li.member_count}]") # print("-" * 50) # # show timeline of a list # list_id = 1498823450231771137 # timeline = api.list_timeline(list_id=list_id) # for s in timeline:
def setUp(self): self.client = tweepy.Client(bearer_token, consumer_key, consumer_secret, access_token or user_id, access_token_secret)
# Your app's bearer token can be found under the Authentication Tokens section # of the Keys and Tokens tab of your app, under the # Twitter Developer Portal Projects & Apps page at # https://developer.twitter.com/en/portal/projects-and-apps bearer_token = "" # Your app's API/consumer key and secret can be found under the Consumer Keys # section of the Keys and Tokens tab of your app, under the # Twitter Developer Portal Projects & Apps page at # https://developer.twitter.com/en/portal/projects-and-apps consumer_key = "" consumer_secret = "" # Your account's (the app owner's account's) access token and secret for your # app can be found under the Authentication Tokens section of the # Keys and Tokens tab of your app, under the # Twitter Developer Portal Projects & Apps page at # https://developer.twitter.com/en/portal/projects-and-apps access_token = "" access_token_secret = "" # You can authenticate as your app with just your bearer token client = tweepy.Client(bearer_token=bearer_token) # You can provide the consumer key and secret with the access token and access # token secret to authenticate as a user client = tweepy.Client(consumer_key=consumer_key, consumer_secret=consumer_secret, access_token=access_token, access_token_secret=access_token_secret)
def twitter_v2_api() -> tweepy.Client: """Connect to Twitter API v2 using a Bearer token.""" return tweepy.Client(bearer_token=get_secret("TWITTER_BEARER"))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import tetueSrc import tweepy # tetueSrc.log_event_warning("") read_successful, cfg_owner = tetueSrc.get_configuration("twitter") client = tweepy.Client(bearer_token=cfg_owner["bearer_token"], consumer_key=cfg_owner["consumer_key"], consumer_secret=cfg_owner["consumer_secret"], access_token=cfg_owner["access_token"], access_token_secret=cfg_owner["access_token_secret"]) registered_hashtags = set( tetueSrc.get_string_list("twitter_bot", "start_hashtags")) max_hashtags = tetueSrc.get_int_element("twitter_bot", "max_hashtags") hashtag_min_size = tetueSrc.get_int_element("twitter_bot", "hashtag_min_size") tweet_max_length = tetueSrc.get_int_element("twitter_bot", "tweet_max_length") def register_hashtag(bot, user, hashtag, *args): global registered_hashtags if len(registered_hashtags) >= max_hashtags: return registered_hashtags.add(hashtag) def main() -> None: pass if __name__ == "__main__":
pd.set_option('max_colwidth', 100) def get_api_auth_token(): with open('side_projects/twitter_api_keys.json', 'r') as f: api_keys = json.load(f) api_bearer_token = api_keys["bearer_token"] return api_bearer_token def get_user_id(client, username): user = client.get_user(username=username) return user.data.id client = tw.Client(bearer_token=get_api_auth_token()) user_id = get_user_id(client, USERNAME) # get the tweets tweets = tw.Paginator( client.get_users_tweets, id=user_id, tweet_fields=['id', 'public_metrics', 'created_at', 'text'], exclude='retweets', max_results=100).flatten(limit=5000) tweet_data = [[ tweet.id, tweet.public_metrics['like_count'], tweet.public_metrics['retweet_count'], tweet.public_metrics['quote_count'], tweet.created_at, tweet.text ] for tweet in tweets]
def __init__(self, bearer_token): self.api = tweepy.Client(bearer_token) self.tweets = {} self.search_history = []
# read keys from .env api_key = os.getenv('api-key') api_secret = os.getenv('api-key-secret') consumer_key = os.getenv('client-id') consumer_secret = os.getenv('client-secret') user_token = os.getenv('access-token') user_token_secret = os.getenv('access-token-secret') bearer_token = os.getenv('bearer-token') # use user authentication tokens auth = tweepy.OAuthHandler(api_key, api_secret) auth.set_access_token(user_token, user_token_secret) api = tweepy.API(auth, wait_on_rate_limit=True) client = tweepy.Client(bearer_token=bearer_token, access_token=user_token, access_token_secret=user_token_secret, wait_on_rate_limit=True) # list friends friends = [] screen_name = 'j_graber' print(f"Friends (accounts {screen_name} follows)") # for page in tweepy.Cursor(api.get_friends, screen_name=screen_name, # count=200).pages(10): # for user in page: # name = f"{user.id} - {user.name} (@{user.screen_name})" # # print(name) # friends.append(name) # print(len(page)) friends = []
Keys = {} Keys['Consumer Key (API Key)'] = input('Enter the Twitter API Consumer Key\n') Keys['Consumer Secret (API Secret)'] = input('Enter tdhe Twitter API Consumer Secret Key\n') Keys['Bearer Token'] = input('Enter the Bearer Token\n') Keys['Owner'] = input('Enter your Twitter username associated with the API keys\n') else: print(e) return(Keys) #### Get keys Keys = get_api_keys() #### Access Twitter API using Tweepy & key dictionary definitions client = tweepy.Client( Keys['Bearer Token'] ) auth = tweepy.OAuth2AppHandler( Keys['Consumer Key (API Key)'], Keys['Consumer Secret (API Secret)'] ) api = tweepy.API(auth) #### Fetch the user id's of those listed in the exceptions list def get_exceptions_list(): listed = [] protect_list = [] for page in tweepy.Cursor(api.list_members, user, exception_title).pages(): listed.extend(page) for x in listed: protect_list.append(x.id) return(protect_list) #### Checks id against exceptions list