from io import BytesIO import re import tweepy from automeme import TextLine, get_rdrama, strip_markdown import utils import json from meme_generator import get_image_file_from_url def load_key_from_file(filename : str) -> str: with open(utils.get_real_filename(filename), "r") as f: return f.read() TWEET_LENGTH = 280 URL_LENGTH = 23 HASHTAG_REGION = 23424977 IMAGE_URL_REGEX = r"https://rdrama\.net/images/([1234567890]*)\.webp" TWEET_URL_REGEX = r"https://twitter\.com/([a-zA-Z]*)/status/([0-9]*)" consumer_key = load_key_from_file("twitter_api_key") consumer_secret = load_key_from_file("twitter_api_secret") access_token = load_key_from_file("twitter_access_token") access_token_secret = load_key_from_file("twitter_access_token_secret") auth = tweepy.OAuth1UserHandler( consumer_key, consumer_secret, access_token, access_token_secret ) api = tweepy.API(auth) rdrama = get_rdrama() def post_rdrama_tweet(post, api): tweet_url = post['url'] tweet_text = get_tweet_text(post) return api.update_status(tweet_text, attachment_url=tweet_url) def post_rdrama_image(post, api): animated_image = get_image_file_from_url(post['url']) file = BytesIO(initial_bytes=animated_image.get_binary_gif()) media = api.media_upload(filename = "foo.gif", file=file, chunked=True, wait_for_async_finalize = True) media_id = media.media_id_string tweet_text = get_tweet_text(post) return api.update_status(tweet_text, media_ids=[media_id]) def post_rdrama_basic_article(post, api): tweet_text = get_tweet_text(post) return api.update_status(tweet_text) def hashtagify(string, api): trends = api.get_place_trends(id=23424977)[0]['trends'] trend_words = [] for trend in trends: name = trend['name'].lower() if '#' in name: trend_words.append(name[1:]) else: for word in name.split(' '): trend_words.append(word) print(trend_words) input = string for hashtag in trend_words: input = re.sub(f" {hashtag} ", f" #{hashtag} ", input) return input def get_tweet_text(post): rdrama_url = post['permalink'] title = post['title'] text_space = TWEET_LENGTH - URL_LENGTH - 1 actual_title = re.sub(r":[^ ]*:", "", title) #remove marseys actual_title = hashtagify(actual_title, api) if (len(title) > text_space): actual_title = actual_title[0:text_space-3] + "..." else: actual_title = actual_title return f"{actual_title} {rdrama_url}" def post_top_scoring_link(rdrama, api): post = None for current_post in rdrama.get_posts(sort='top', t='hour')['data']: if not current_post['club']: post = current_post break #post = rdrama.get_posts(sort='top', t='hour')['data'][0] #top scoring post if re.match(TWEET_URL_REGEX, post['url']): tweet = post_rdrama_tweet(post, api) elif re.match(IMAGE_URL_REGEX, post['url']): tweet = post_rdrama_image(post, api) else: tweet = post_rdrama_basic_article(post, api) url = f"https://twitter.com/drama_meme/status/{tweet.id}" rdrama.reply_to_post(post['id'], f"Nice post, bro! [I posted it to twitter]({url}).") if __name__ == "__main__": post_top_scoring_link(rdrama, api)