예제 #1
0
	def search(self):
		global timer_dm
		global favorites_list
		try:
			logging.debug("looking for new favorites")
			new_favs = api.favorites(count=190)
			for fav in new_favs:
				if fav.id not in favorites_list:
					load_module.load_new_tweet("https://twitter.com/i/status/" + str(fav.id), from_fav=True)
					logging.info("Loaded tweet with id:" + str(fav.id))
					favorites_list.append(fav.id)
		except Exception as e:
			print("Error trying to get the last favs:", e)
			logging.warning("Couldn't recover the last favs: " + str(e))


		try:
			last_dms = api.list_direct_messages()
			logging.debug("Getting the last DMs")
		except Exception as e:
			print("Error trying to get the last DMs:", e)
			logging.warning("Couldn't recover the DM list :" + str(e))
			timer_dm = threading.Timer(MDListener.read_dm_timeout, self.search)
			logging.info("Starting timer to the next DM search (with extended timeout)")
			timer_dm.start()
		else:
			for messages in last_dms:
				if int(messages.id) <= int(MDListener.lastID):
					break
				if 'message_data' in messages.message_create:
					text = messages.message_create['message_data']['text']
					user = messages.message_create['sender_id']

					if user in self.permitted_ids:
						print("\nLoad possible tweet")
						print(text, "from:", user)
						if user in self.permitted_ids:
							try:
								if text[0:5] == "text:" or text[0:5] == "Text:":
									Data.access_list(mode=Data.insert, info=Data(text[5:].strip()))
									logging.info("Inserted next tweet")
								else:
									import requests
									site = requests.get(text)
									load_module.load_new_tweet(site.url)

							except Exception as e:
								print("Error:", e)
								logging.error("Error recovering the tweet: " + str(e))
					else:
						logging.warning("Not authorized person sent a DM to the bot")

			if len(last_dms) > 0:
				if int(last_dms[0].id) > int(MDListener.lastID):
					MDListener.lastID = last_dms[0].id
					self.save_last_dm()

			timer_dm = threading.Timer(MDListener.read_dm, self.search)
			logging.debug("Starting timer to the next DM search")
			timer_dm.start()
예제 #2
0
def load_tweets():
    tweets = load_from_json()
    if tweets is None:
        old_tweets = old_load()
        # Save the files as a JSON
        parse_to_json(old_tweets)
        # Load from that JSON
        tweets = load_from_json()

    logging.info("Loaded: " + str(len(tweets)) + " tweets")
    print("Loaded", len(tweets), "tweets")
    print("Success!\n")

    Data.access_list(mode=Data.set, info=tweets)
예제 #3
0
def save(output=False):
    try:
        save_to_json(Data.access_list(mode=Data.get_list))
        if output:
            print("Tweets had been saved")
        logging.info("Tweets were saved")
    except Exception as e:
        print("Error while trying to save the tweets")
        logging.error("Error: " + str(e))
예제 #4
0
	def tweet(self):

		if Data.access_list(mode=Data.length) == 0:
			print("We run out of Tweets!")
			logging.warning("There are no tweets")
			load_module.save(output=True)
			# Trying it again in Tweet.delay_without_tweets seconds
			Tweet.timer_tweet = threading.Timer(Tweet.delay_without_tweets, self.tweet)
			Tweet.timer_tweet.start()

			Tweet.hadTweet = True
			return

		try:
			to_tweet = Data.access_list(mode=Data.extract)

			if len(to_tweet.text) <= 280:  # Less than 281 chars

				print("To tweet:\n" + to_tweet.text)
				print("------------------------------------------------------------")
				logging.info("Tweeting: " + to_tweet.text)
				print("Trying to tweet...")
				p = None

				append_url = None
				if len(to_tweet.text) > 1:
					try:
						if to_tweet.text.find("https://t.co/") != -1 and to_tweet.text.find("https://t.co/") != 0:
							p = re.split("https://t.co/", to_tweet.text)

							if len(p) == 2:
								to_tweet.text = p[0]
								append_url = requests.get("https://t.co/" + p[1]).url

							if len(p) == 1:
								to_tweet.text = ""
								append_url = requests.get("https://t.co/" + p[0]).url

					except Exception as e:
						print(e)

				if to_tweet.img is not None:
					print("Media: " + str(to_tweet.img))
					media = []
					if isinstance(to_tweet.img, list):
						for image in to_tweet.img:
							print("Uploading", image)
							media.append(api.media_upload(image).media_id)
							logging.info("Upload: " + image)

						api.update_status(media_ids=media, status=to_tweet.text, attachment_url=append_url)

						print("Tweet with pic/s published")
						logging.info("Tweet with pic/s published")
					else:  # Not used any more but legacy option just in case
						print("Uploading", to_tweet.img)
						api.update_with_media(to_tweet.img, to_tweet.text)
						logging.info("Tweet with pic published")
				else:
					try:
						api.update_status(status=to_tweet.text, attachment_url=append_url)
					except:  # This will happen if the appended url is a video, so we have to recover the shorten url
						if p is not None:
							if len(p) == 2:
								append_url = "https://t.co/" + p[1]
								to_tweet.text = to_tweet.text + append_url

							if len(p) == 1:
								append_url = "https://t.co/" + p[0]
								to_tweet.text = to_tweet.text + append_url  # = append_url should be valid too

							api.update_status(status=to_tweet.text)

					logging.info("Tweet published")

				print("Tweeted!", end=" ")
				seconds_to_wait = random.randint(Tweet.intervals[0], Tweet.intervals[1])

				now = datetime.datetime.now()  # get a datetime object containing current date and time
				if now.hour in range(1, 9):
					seconds_until_end_of_night_mode = (now.replace(hour=9, minute=0, second=0, microsecond=0) - now).total_seconds()
					if seconds_until_end_of_night_mode < Tweet.night_mode_extra_delay:
						seconds_to_wait = seconds_to_wait + seconds_until_end_of_night_mode
					else:
						seconds_to_wait = seconds_to_wait + Tweet.night_mode_extra_delay

				next_time = (now + datetime.timedelta(0, seconds_to_wait)).strftime(
					"%H:%M:%S")  # Get the time when the next tweet will be post, and format it to make it easier to
				# read in the console
				Tweet.set_next_tweet_t(next_time)


				print("Next tweet in:", seconds_to_wait, "seconds at " + str(next_time) + ". Remaining tweets:",
					Data.access_list(mode=Data.length))
				print("------------------------------------------------------------")
				logging.info("Tweeted successfully, next tweet at " + str(next_time))
				Tweet.timer_tweet = threading.Timer(seconds_to_wait, self.tweet)
				Tweet.timer_tweet.start()
				Tweet.counter = 0

				Tweet.hadTweet = True  # Flag to indicate that it has tweeted and therefore, the timer can be cancelled
				load_module.save()

			else:
				print("That tweet couldn't be printed!")
				print("------------------------------------------------------------")
				logging.warning("Tweet to long to tweet")
				self.tweet()

		except Exception as e:
			logging.error("Tweet couldn't be tweeted: " + str(e))
			Tweet.counter = Tweet.counter + 1
			Data.access_list(mode=Data.insert_last, info=to_tweet)

			if Tweet.counter >= 5:
				print("5 times in a row a tweet couldn't be used, the program will exit")
				os._exit(1)
			else:
				print("Something went wrong trying to tweet, trying to tweet in 100/1000 seconds")
				print("------------------------------------------------------------")
				now = datetime.datetime.now()
				if now.hour in range(1, 9):
					time_to_wait = 1000
				else:
					time_to_wait = 100

				next_time = (now + datetime.timedelta(0, time_to_wait)).strftime(
					"%H:%M:%S")  # Get the time when the next tweet will be post, and format it to make it easier to
				# read in the console
				Tweet.set_next_tweet_t(next_time)

				Tweet.timer_tweet = threading.Timer(time_to_wait, self.tweet)
				Tweet.timer_tweet.start()
예제 #5
0
def menu():
    time.sleep(
        1
    )  # A bit of delay to print properly the other initial messages of the other threads
    logging.info("Started menu")
    while True:
        print(" \t\t--- Remaining tweets: " +
              str(Data.access_list(mode=Data.length)) + " --- ")
        print("------------------------------------------------------------")
        print("1. Print next tweet\t", end="\t")
        print("2. Enter the next tweet")
        print("3. Delete next tweet\t", end="\t")
        print("4. Put the tweet at the end of the queue")
        print("5. Tweet next tweet\t", end="\t")
        print("6. When is next tweet")
        print("7. Copy a tweet (by url)", end="\t")
        print("8. Shuffle list")
        print("9. Reload configuration\t", end="\t")
        print("10. Exit")
        print("------------------------------------------------------------")

        user_input = input()
        try:
            x = int(user_input)
            logging.info("User introduced " + str(x))
            if x == 1:
                if Data.access_list(mode=Data.length) > 0:
                    print(
                        "------------------------------------------------------------\n"
                    )
                    print(Data.access_list(mode=Data.get))
                    logging.info("Printed next tweet")
                else:
                    print("There are not tweets to display")
                    logging.warning("No tweets to print")
            if x == 2:
                Data.access_list(mode=Data.insert,
                                 info=Data(input("Insert the next tweet:")))
                load_module.save()
                logging.info("Inserted next tweet")
            elif x == 3:
                if Data.access_list(mode=Data.length) > 1:
                    Data.access_list(mode=Data.extract)
                    print(
                        "The first tweet in line was deleted, the next one is:"
                    )
                    logging.info("Deleted the first tweet in line")
                    print(Data.access_list(mode=Data.get))
                    load_module.save()
                elif Data.access_list(mode=Data.length) == 1:
                    Data.access_list(mode=Data.extract)
                    print("The last tweet was deleted")
                    logging.info("Printed next tweet")
                    load_module.save()
                else:
                    print("There are not tweets to delete")
            elif x == 4:
                if Data.access_list(mode=Data.length) > 1:
                    Data.access_list(mode=Data.insert_last,
                                     info=Data.access_list(mode=Data.extract))
                    print(
                        "Sent the first tweet in queue to the last position, next:"
                    )
                    print(Data.access_list(mode=Data.get))
                    logging.info(
                        "Sent the first tweet in queue to the last position")
                    load_module.save()
            elif x == 5:
                if Tweet.get_had_tweet():
                    logging.info("Canceling the timer of the next tweet")
                    Tweet.timer_tweet.cancel()
                    logging.info("Starting new Thread to make a new tweet")
                    Tweet.new()
                else:
                    print(
                        "Don't abuse this function, wait until the bot has tweet at least one tweet"
                    )
                    logging.warning(
                        "User tried to cancel timer before the other thread tweeted something"
                    )
            elif x == 6:
                next_t = Tweet.get_next_tweet_t()
                if next_t is None:
                    print("Bot just started, wait some seconds")
                else:
                    logging.info("User recover the time of the next time: " +
                                 Tweet.get_next_tweet_t())
                    print("Next tweet will be tweet at",
                          Tweet.get_next_tweet_t())
            elif x == 7:
                url = input("Insert the URL of the tweet to copy: ")
                logging.info("User introduced " + url + " to copy a tweet")
                load_module.load_new_tweet(url)
            elif x == 8:
                Data.access_list(mode=Data.shuffle)
                print("Next tweet:")
                print(Data.access_list(mode=Data.get))
            elif x == 9:
                logging.info("User try to reload the configuration")
                load(True)
            elif x == 10:
                load_module.save(output=True)
                logging.info("Exiting program")
                exit()
        except ValueError:  # If not a number
            print("Wrong input")
예제 #6
0
def load_new_tweet(url, from_fav=False):
    api = auth.get_api()

    try:
        id = re.split("/", url)[-1]
        if id.find("?") > 0:
            id = id[:id.find("?")]
        status = api.get_status(id, tweet_mode="extended")
        if id in mdlistener.favorites_list:
            return
        mdlistener.favorites_list.append(id)

        if not from_fav:
            api.create_favorite(id)
            print("Tweet with id:", id, "was faved")
            logging.info("Tweet with id: " + id + " was faved")
        else:
            print("Received fav with tweet id: " + str(id))
            logging.info("Received fav with tweet id: " + str(id))
            if 'user_mentions' in status.entities:
                if len(status.entities['user_mentions']) > 0:

                    print(
                        "This could be an answer, so then this is not process\n"
                    )
                    logging.info(
                        "This could be an answer, so then this is not process")
                    print(status.full_text)
                    logging.info("Tweet text: " + status.full_text)
                    print(
                        "------------------------------------------------------------"
                    )
                    return

        logging.info("Tweet text: " + status.full_text)

        print(status.full_text)

        full_real_text = status.full_text

        media_files = []
        download_names = []
        download = False

        if 'media' in status.entities:
            logging.info("Media found")
            download = True
            for photo in status.extended_entities['media']:
                if photo['type'] == 'photo':
                    media_files.append(photo['media_url'])
                    logging.info("Getting info of photo: " +
                                 photo['media_url'])
                else:
                    logging.info(
                        "Get something that is not a photo: no download")
                    download = False
                    break

            if download:
                full_real_text = full_real_text.rsplit("https://t.co", 1)[0]
                logging.info(
                    "Download option enable: removing the last link (t.co)")

        if 'user_mentions' in status.entities:
            if len(status.entities['user_mentions']) > 0:
                logging.info("User mentions found")
            for user in status.entities['user_mentions']:
                to_remove = "@" + user['screen_name']
                full_real_text = full_real_text.replace(to_remove, "")
                logging.info("Removing: " + to_remove)

        if download is False:
            logging.info("Trying to insert without download")
            if from_fav:
                Data.access_list(mode=Data.insert_random,
                                 info=Data(full_real_text))
            else:
                Data.access_list(mode=Data.insert, info=Data(full_real_text))

        else:
            print("To download: ")
            try:
                os.mkdir("images")
                logging.info("Created images directory")
            except FileExistsError:  # If directory already exists
                pass

            for m in media_files:
                print(m)

            for media_file in media_files:
                name = wget.download(media_file)
                download_names.append(shutil.move(src=name, dst="images"))
                logging.info("Downloaded: " + name)

            print("\n")  # Add a extra line

            if from_fav:
                Data.access_list(mode=Data.insert_random,
                                 info=Data(full_real_text, download_names))
            else:
                Data.access_list(mode=Data.insert,
                                 info=Data(full_real_text, download_names))
            save()

        print("------------------------------------------------------------")

    except Exception as e:
        print("Error while trying to get the tweet:", e)
        logging.error(str(e))