diff --git a/src/BotYamPoster.py b/src/BotYamPoster.py index 4873c49..8a2a9f7 100644 --- a/src/BotYamPoster.py +++ b/src/BotYamPoster.py @@ -1,11 +1,20 @@ import tweepy import random +import re +import requests from connector import Connector def init_streamobject(conn): print("Loading Stream object...") return BotYamPoster(conn.get_bearer()) +def expand_tco_url(url): + response = requests.head(url, allow_redirects=False) + if 'location' in response.headers: + return response.headers['location'] + else: + return url + def post_reply(conn, victim_bank, tweet, words, reply_text_bank, postcounter): # Search for word in word bank if any(word in tweet.data['text'] for word in words): @@ -23,7 +32,6 @@ def post_reply(conn, victim_bank, tweet, words, reply_text_bank, postcounter): return postcounter class BotYamPoster(tweepy.StreamingClient): - # Define a callback function to handle tweets def on_tweet(self, tweet): # Make it easy on Yashar @@ -96,3 +104,51 @@ class BotYamPoster(tweepy.StreamingClient): def on_error(self, status_code): # Print the error code print("ERROR: " + status_code) + + def on_direct_message(self, message): + # Check if the message is from the authenticated user + if message['sender_id'] == self.user_id: + return + + conn = Connector() + + # Get the text of the message + text = message['text'] + + # Find the URL of the tweet in the message + tweet_url_regex = r'https?://twitter.com/\w+/status/(\d+)(?:\?.*)?$' + tweet_url_match = re.search(tweet_url_regex, text) + + if not tweet_url_match: + try: + conn.api.send_direct_message(recipient_id=message['sender_id'], text="אין לי את הפונקציה הזאת עדיין סורי נשמה") + print("Sent a message back - command unsupported.") + except: + print("Couldn't even send the message. Eef.") + return + + tweet_id = tweet_url_match.group(1) + + # Get the tweet using the API + tweet = conn.api.get_tweet(tweet_id) + + tco_regex = r'https?://t.co/\w+' + tco_url = re.findall(tco_regex, tweet.data["text"]) + + if not tco_url: + try: + conn.api.send_direct_message(recipient_id=message['sender_id'], text="אין פה סרטון או משהו שאפשר לפרש, זיבי ביי.") + print("Sent a message back - command unsupported.") + except: + print("Couldn't even send the message, and no video in this tweet. Eef.") + return + + videon_url = expand_tco_url(tco_url[0]) + + # Create a response message with the tweet's text + try: + conn.api.send_direct_message(recipient_id=message['sender_id'], text="טוב ליסן, מצאתי פה קישור משהו לוקסוס. רק צריך להעתיק לפוסט, לדאוג שזה אחרון בפוסט, ויצא לך אמבד מושלם.") + conn.api.send_direct_message(recipient_id=message['sender_id'], text=videon_url) + print(f"SENT URL: {videon_url}") + except: + print(f"Sorry, couldn't send url {videon_url}") \ No newline at end of file