everybody-mov/tweetbot.py

97 lines
3.1 KiB
Python
Raw Normal View History

#!/usr/bin/env python3
import os
import sys
from typing import List, Tuple
import tweepy
from time import sleep
from random import shuffle
# Return our credentials from environment variables as UTF-8 bytes.
2022-08-26 06:52:09 +00:00
def get_arguments() -> Tuple[bytes, bytes, bytes, bytes]:
consumer_key: bytes = os.environ['CONSUMER_KEY'].encode('utf8')
consumer_secret: bytes = os.environ['CONSUMER_SECRET'].encode('utf8')
access_token: bytes = os.environ['ACCESS_TOKEN'].encode('utf8')
access_token_secret: bytes = os.environ['ACCESS_TOKEN_SECRET'].encode('utf8')
return consumer_key, consumer_secret, access_token, access_token_secret
# Copy the file lines to a new List[str] and shuffle it.
def populate_array(file_lines: List[str]) -> List[str]:
array: List[str] = file_lines.copy()
# Scramble like an egg.
shuffle(array)
return array
# Main function.
def main() -> None:
consumer_key: bytes
consumer_secret: bytes
access_token: bytes
access_token_secret: bytes
# Access and set authentication method to our Twitter credentials.
consumer_key, consumer_secret, access_token, access_token_secret = get_arguments()
auth: tweepy.OAuth1UserHandler = tweepy.OAuth1UserHandler(consumer_key=consumer_key, consumer_secret=consumer_secret,
access_token=access_token, access_token_secret=access_token_secret)
# Creating an API object with our authentication method.
api: tweepy.API = tweepy.API(auth=auth)
array: List[str]
with open('./everybody.txt', 'r', encoding='utf-8') as my_file:
# Read lines one by one from my_file and assign to file_lines variable
file_lines: List[str] = [x.strip() for x in my_file.readlines()]
# Close file.
my_file.close()
# Create List[str] from file_lines.
array = populate_array(file_lines)
# Driving loop.
while True:
while array:
# Grab last element and then remove it.
tweet: str = array.pop()
try:
# Output the last element, which will be the tweet.
print(tweet)
# Create a tweet through the API.
api.update_status(tweet)
# Chill out for 1800 seconds.
sleep(1800)
except tweepy.Forbidden as fe:
# We probably tried to create a duplicate tweet, but say what happened.
print(fe.api_errors)
# Chill out for 30 seconds.
sleep(30)
except tweepy.BadRequest as be:
# Something is wrong with our client, so say what happened.
print(be.api_errors)
# Bail. We shouldn't keep trying.
sys.exit(1)
except tweepy.TweepyException as te:
# Something very unexpected happened, so say what happened.
print(te)
# Bail. We shouldn't keep trying.
sys.exit(1)
# Let's do the time warp again.
array = populate_array(file_lines)
# Do not delete.
if __name__ == '__main__':
main()