Reputation:
Just written a short and simple Python script to post on Twitter. I'm having issues where after 30 minutes the tweet appears multiple times where it should only be posted once every half an hour. How can I solve this? Thanks in advance.
import random
import tweepy
import schedule
import time
from auth import consumer_secret, consumer_key, access_token_secret, access_token
twitter_auth_keys = {
'consumer_secret': consumer_secret,
'consumer_key': consumer_key,
'access_token_secret': access_token_secret,
'access_token': access_token
}
def main():
auth = tweepy.OAuthHandler(
twitter_auth_keys['consumer_key'],
twitter_auth_keys['consumer_secret']
)
auth.set_access_token(
twitter_auth_keys['access_token'],
twitter_auth_keys['access_token_secret']
)
api = tweepy.API(auth)
file = open('words.txt', 'r')
random_word = random.choice(file.readlines())
tweet = ('The %s tree.' % random_word.strip())
api.update_status(status=tweet)
print('Tweeted: %s' % tweet)
schedule.every(30).minutes.do(main)
while True:
schedule.run_pending()
time.sleep(1)
return
if __name__ == '__main__':
main()
Upvotes: 1
Views: 1532
Reputation: 1355
This seems recursive. You tell schedule to do main
every 30 minutes, and main will also call schedule. Try separating them.
From the docs:
def job():
print("I'm working...")
schedule.every(1).minutes.do(job)
while True:
schedule.run_pending()
time.sleep(1)
What you are (sorta) doing:
def rec_job():
print("I'm working...")
schedule.every(1).minutes.do(rec_job)
while True:
schedule.run_pending()
time.sleep(1)
if __name__ == '__main__':
rec_job()
You can separate your code like this:
def send_message():
auth = tweepy.OAuthHandler(
twitter_auth_keys['consumer_key'],
twitter_auth_keys['consumer_secret']
)
auth.set_access_token(
twitter_auth_keys['access_token'],
twitter_auth_keys['access_token_secret']
)
api = tweepy.API(auth)
file = open('words.txt', 'r')
random_word = random.choice(file.readlines())
tweet = ('The %s tree.' % random_word.strip())
api.update_status(status=tweet)
print('Tweeted: %s' % tweet)
def main():
schedule.every(30).minutes.do(send_message)
while True:
schedule.run_pending()
time.sleep(1)
return
if __name__ == '__main__':
main()
Upvotes: 2