vendredi 28 avril 2023

How to Sample without Replacement in Python for Tweets

I have a small business with Twitter API and I need to randomly send tweets. I used to program 20 years ago, and thought I'd try ChatGPT to coach me on this. It did fairly well, when it did make mistakes, I was able to fix it quickly or modify it, but it would randomly pick a tweet and add it back to the list.. I need to remove it from the list until it's gone through all of them, then start over (sampling without replacement). So I ended up with the following program:

import tweepy
import random
import time

# Enter your Twitter API credentials
API_key = "secret"
API_secret = "secret"
Access_token = "secret-token"
Access_token_secret = "secret"

# Authenticate with Twitter
auth = tweepy.OAuthHandler(API_key, API_secret)
auth.set_access_token(Access_token, Access_token_secret)

# Create the API object
api = tweepy.API(auth)

# List of tweets to post
tweets = [
"""This is tweet number 1""",
"""This is tweet number 2""",
"""This is tweet number 3""",
"""This is tweet number 4""",
"""This is tweet number 5""",
]

# Initialize the list of used tweets
used_tweets = []

# Loop through the tweets and post them twice an hour, around the clock, 90 days
for i in range(90):
for j in range(24):
        minute = random.randint(1, 1800)   // randomly in 30 min incriments
        # Sample a random tweet from the list without replacement
        tweet = random.sample(set(tweets) - set(used_tweets), 1)[0]
        # Add the tweet to the list of used tweets
        used_tweets.append(tweet)
        # If all tweets have been used, start over
        if len(used_tweets) == len(tweets):
        used_tweets = []
        print(f"NEXT TO PRINT: {tweet}\n")
        # Schedule the tweet
        api.update_status(status=tweet)
        print(f"TWEETED: {tweet}\n")
        print(f"Minutes to wait: {minute/60}\n")
        # Wait for the random time to pass before tweeting again
        time.sleep(m

This gives me an error message, "Population must be a sequence or set", I assume because of the 'used_tweets' list, but I don't know. Can anyone help me get this simple program to work? MUCH appreciation in advance!




Aucun commentaire:

Enregistrer un commentaire