I've just started to play around with Python and I've decided to create a little script that post tweets every hour (cronjob on Ubuntu) telling what time it is.
I'm not sure if I follow best practices or if I can make the code even shorter/cleaner/nicer? I'm a C# developer so I miss a few things in Python, like string.Empty
and list.First()
. Do these features exist in Python?
from twitter import *
from datetime import datetime
import pytz
TOKEN = "SECRET_STUFF"
TOKEN_KEY = "SECRET_STUFF"
API_KEY = "SECRET_STUFF"
API_SECRET = "SECRET_STUFF"
def init(timestamp = datetime.now(pytz.timezone('Europe/Stockholm')).time()):
number_of_rings = get_number_of_times_to_display_alarm(timestamp)
send_tweet(compose_tweet(number_of_rings, timestamp))
def get_number_of_times_to_display_alarm(timestamp):
# Convert our timestamp to 12h format, split it, select first element(hours)
# and cast to int to remove leading 0 (e.g. 09.00 will give us 9)
return int(timestamp.strftime("%I:%M %p").split(':')[0])
def compose_tweet(number_of_rings, timestamp):
# Creates a tweet, e.g. "BONG...BONG...BONG #03:00
ALERT_SOUND = "BONG"
tweet = ""
for i in range(number_of_rings):
tweet += "%s%s" %(ALERT_SOUND, "..." if i < (number_of_rings - 1) else "")
tweet += " #%s:%s" %(str(timestamp.hour).zfill(2), str(timestamp.minute).zfill(2))
return tweet
def send_tweet(tweet):
auth = OAuth(TOKEN, TOKEN_KEY, API_KEY, API_SECRET)
t = Twitter(auth=auth)
t.statuses.update(status=tweet)
init()
UPDATE Based on the great feedback I got from @LiavK I've now updated my code as follows:
from twitter import OAuth, Twitter
from datetime import datetime
import pytz
TOKEN = "SECRET_STUFF"
TOKEN_KEY = "SECRET_STUFF"
API_KEY = "SECRET_STUFF"
API_SECRET = "SECRET_STUFF"
MY_TZ = pytz.timezone('Europe/Stockholm')
now = datetime.now(MY_TZ).time()
def get_current_hour(timestamp):
return timestamp.hour % 12
def compose_tweet(number_of_rings, timestamp):
# Creates a tweet, e.g. "BONG...BONG...BONG #03:00
ALERT_SOUND = "BONG..."
tweet = (ALERT_SOUND * number_of_rings)[:-3] # Removes last ...
tweet += " #%s:%s" %(str(timestamp.hour).zfill(2), str(timestamp.minute).zfill(2))
return tweet
def send_tweet(tweet):
auth = OAuth(TOKEN, TOKEN_KEY, API_KEY, API_SECRET)
t = Twitter(auth=auth)
t.statuses.update(status=tweet)
def main(timestamp = now):
number_of_rings = get_current_hour(timestamp)
send_tweet(compose_tweet(number_of_rings, timestamp))
if __name__ == "__main__":
main()
if not foo:
, because only non-empty strings evaluate toTrue
. As for getting the first item from an iterator, usenext(foo)
ornext(foo, YOUR_DEFAULT)
(whereYOUR_DEFAULT
is the value that will be returned if there are no values left in the iterator). For a list though, I would just usefirst = your_list[0]
or sequence unpacking:first, *rest = your_list
. \$\endgroup\$