vision-bot/interaction/script.py

67 lines
2.1 KiB
Python
Raw Permalink Normal View History

#!/usr/local/bin/python3.9
import tweepy
import time
import os
import sys
from datetime import datetime, timedelta
import re
import math
print(datetime.now().strftime("%H:%M:%S"))
callback_uri = 'oob' # https://cfe.sh/twitter/callback
auth = tweepy.OAuthHandler(os.getenv('API_TOKEN'), os.getenv('API_KEY_SECRET'), callback_uri)
auth.set_access_token(os.getenv('ACCESS_TOKEN'), os.getenv('ACCESS_TOKEN_SECRET'))
api = tweepy.API(auth)
lastSeenFile = 'last_seen.txt'
if not os.path.isfile(lastSeenFile):
with open(lastSeenFile, 'w+') as fileWrite:
fileWrite.write(str(0))
def getLastSeen(filename):
with open(filename, 'r') as fileRead:
lastSeen = int(fileRead.read().strip())
return lastSeen
def storeLastSeen(filename, lastSeen):
with open(filename, 'w') as fileWrite:
fileWrite.write(str(lastSeen))
return
def searchTweets(query):
print('Searching for tweets')
lastSeen = getLastSeen(lastSeenFile)
tweets = api.search(query, since_id=lastSeen)
return tweets
def interactions():
tweets = searchTweets('persevering')
for tweet in reversed(tweets):
if not tweets:
print('No new tweets found.')
return
if re.search('what is.*if not.*persevering',tweet.text.lower()):
if not tweet.text.lower().startswith('rt') and tweet.user != api.me():
print(f'Tweet {tweet.text} by @{tweet.author.screen_name}', flush = True)
t = api.get_status(tweet.id)
if not t.favorited:
print('Not favourited.')
api.create_favorite(tweet.id)
if not t.retweeted:
print('Not retweeted.')
api.retweet(tweet.id)
storeLastSeen(lastSeenFile, tweet.id)
now = datetime.now()
nextFifth = 5-(now.minute%5)
later = (now + timedelta(minutes=nextFifth)).replace(second=0,microsecond=0)
tdelta = later - datetime.now()
sec = math.floor(tdelta.total_seconds())
print(f'Waiting until {later} for first search interaction cycle, sleeping for {sec} seconds.')
time.sleep(sec)
while True:
interactions()
print('Sleeping for 5 minutes')
time.sleep(300)