import tweepy import logging import os import time import json logging.basicConfig(level=logging.INFO) logger = logging.getLogger() class FavRetweetListener(tweepy.StreamListener): def __init__(self, api): self.api = api self.me = api.me() def on_status(self, tweet): logger.info("Processing tweet id {tweet}".format(tweet=tweet.id)) if tweet.in_reply_to_status_id is not None or \ tweet.user.id == self.me.id: # This tweet is a reply or I'm its author so, ignore it return if not tweet.favorited: # Mark it as Liked, since we have not done it yet try: tweet.favorite() except Exception as e: logger.error("Error on fav", exc_info=True) if not tweet.retweeted: # Retweet, since we have not retweeted it yet try: tweet.retweet() except Exception as e: logger.error("Error on fav and retweet", exc_info=True) def on_error(self, status): logger.error(status) class BotAPITwitter(object): def __init__(self, consumer_key, consumer_secret, access_token, access_token_secret): # consumer_key = os.getenv("u1AhUuvfyrcFLokrVfnB6q2U6") # consumer_secret = os.getenv("ted7kbOY0xBVrJYVBCDWghLt6MAqu87Vy422zjKW8DWdLADn9N") # access_token = os.getenv("1267420049117233153-o4Q9Rxh4nsIreZuYpvdbFVunXh13lS") # access_token_secret = os.getenv("vLNRXdYftQq81tN1jJJ8Iz47tiOphOW4HrQIddlpmlUcU") self.consumer_key = consumer_key self.consumer_secret = consumer_secret self.access_token = access_token self.access_token_secret = access_token_secret self.api = self._create_api() def _create_api(self): auth = tweepy.OAuthHandler(self.consumer_key, self.consumer_secret) auth.set_access_token(self.access_token, self.access_token_secret) api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True) try: api.verify_credentials() except Exception as e: logger.error("Error creating API", exc_info=True) raise e logger.info("API created") return api def fav_retweet(self, keywords): """ Give a fav and RT to the tweets that contains some keyword. e.g. If @atresmedia writes a tweet with the keyword #srmconecta, then @SRM_Consulting fav and RT the tweet Fav and RT when you lunch the app to all new coincidences Parameters ---------- keywords list of strings e.g. ["#srmconecta", "srm_accidente"] Returns ------- """ tweets_listener = FavRetweetListener(self.api) stream = tweepy.Stream(self.api.auth, tweets_listener) stream.filter(track=keywords) def follow_followers(self): # import botAPItwitter; botAPItwitter().follow_followers() """ Follow the new followers of the Twitter account. e.g. @atresmedia follow @SRM_Consulting, then @SRM_Consulting follows @atresmedia Returns ------- """ while True: # follow_followers(api) logger.info("Retrieving and following followers") for follower in tweepy.Cursor(self.api.followers).items(): if not follower.following: logger.info("Following {follower}".format(follower=follower.name)) follower.follow() logger.info("Waiting...") time.sleep(60) # logger.info("Retrieving and following followers") # for follower in tweepy.Cursor(api.followers).items(): # if not follower.following: # logger.info(f"Following {follower.name}") # follower.follow() def auto_tweets(self, tweet_user, tweet): """ Writes a tweet to the user Parameters ---------- user str The name Twitter user with or without @ e.g. @SRM_Consulting tweet str Message that you write to the Twitter user e.g. "Use the technology of SRM" Returns ------- """ # api = create_api() print("user",tweet_user) if tweet_user[0] == "@": tweet_user = tweet_user[1:] if len("@" + tweet_user + " " + tweet) > 279: raise ValueError("tweet demasiado largo (máximo 280 caracteres") # print(len("@" + user + " " + tweet)) self.api.update_status("@" + tweet_user + " " + tweet) def auto_reply(self, keywords, message): """ Parameters ---------- keywords list of strings e.g. ["help", "support"] message str e.g. "Please reach us via DM" (279 characters max.) Returns ------- """ since_id = 1 while True: # since_id = check_mentions(self.api, ["help", "support"], since_id) logger.info("Retrieving mentions") new_since_id = since_id for tweet in tweepy.Cursor(self.api.mentions_timeline, since_id=since_id).items(): # print(str(tweet.id)) new_since_id = max(tweet.id, new_since_id) if tweet.in_reply_to_status_id is not None: continue if any(keyword in tweet.text.lower() for keyword in keywords): if not tweet.user.following: tweet.user.follow() try: self.api.update_status( status="@" + tweet.user.screen_name + " " + message, in_reply_to_status_id=tweet.id ) logger.info("Answering to {tweet}".format(tweet=tweet.user.name)) except: pass # new_since_id = tweet.id since_id = new_since_id logger.info("Waiting...") time.sleep(60) def direct_message(self,tweet_user,dm): user_id = self.api.get_user(screen_name=tweet_user) tweepy.API.send_direct_message(self.api, user_id.id, dm) def rt_comment(self, keywords, message_rt): """ If a Twitter user writes the keyword, it does RT and add a coment to the RT. Parameters ---------- keywords list of strings e.g. ["#srmconecta", "srm_accidente"] message_rt str e.g. "Crash car location" Returns ------- """ since_id = 1 for tweet in tweepy.Cursor(self.api.mentions_timeline, since_id=since_id).items(): new_since_id = max(tweet.id, since_id) since_id = new_since_id while True: # since_id = check_mentions(self.api, ["help", "support"], since_id) logger.info("Retrieving mentions") new_since_id = since_id for tweet in tweepy.Cursor(self.api.mentions_timeline, since_id=since_id).items(): # print(str(tweet.id)) new_since_id = max(tweet.id, new_since_id) if tweet.in_reply_to_status_id is not None: continue if any(keyword in tweet.text.lower() for keyword in keywords): try: # self.api.update_status("tweet" + " " + "https://twitter.com/tweet.user.screen_name/status/since_id") # self.api.update_status(message_rt + " " + "https://twitter.com/" + "CipresCiudad" + "/status/" + "1285526394206920705") self.api.update_status( message_rt + " " + "https://twitter.com/" + tweet.user.screen_name + "/status/" + str(tweet.id)) if len(message_rt) > 279: raise ValueError("Tweet demasiado largo (máximo 280 caracteres") logger.info("Answering to {tweet}".format(tweet=tweet.useer.name)) new_since_id = tweet.id except: print("MAL") pass since_id = new_since_id logger.info("Waiting...") time.sleep(60) # RTcomentado(list("help".split(",")),) if __name__ == "__main__": bots = BotAPITwitter("u1AhUuvfyrcFLokrVfnB6q2U6", "ted7kbOY0xBVrJYVBCDWghLt6MAqu87Vy422zjKW8DWdLADn9N", "1267420049117233153-o4Q9Rxh4nsIreZuYpvdbFVunXh13lS", "vLNRXdYftQq81tN1jJJ8Iz47tiOphOW4HrQIddlpmlUcU") bots.follow_followers() bots.auto_tweets() bots.auto_reply() bots.fav_retweet() bots.rt_comment()