我正在编写一个脚本,它发送 facebook 消息,告诉日出和日落时间。时间在上午 10 点发送到接收者列表。我计算时间的方法是:当脚本运行时,我得到时间,然后我从网页上抓取日出/日落时间,计算到最快的时间(比如说日出),然后睡觉发送消息,然后睡到日落并发送另一条消息,等等。该脚本适用于第一条消息,但不适用于第二条消息。发送第一条消息后,它会显示在第二条消息之前它将休眠多长时间,并且它始终是正确的时间量,但是,它似乎并没有从该睡眠中醒来。关于这里发生的事情的任何想法/是否有更好的方法来完成任务?
from fbchat import Client
import sunset2
import time
email, password = [********, ********]
client = Client(email, password)
receivers = [receiver1 , receiver2, receiver3, receiver4] # Fb friends names
while True:
# Check out the get_msg() function below
# Get the appropriate message and send it to all receivers
msg = sunset2.get_msg(url)
for receiver in receivers:
client.send(Message(text = msg), thread_id = receiver,
thread_type=ThreadType.USER)
time.sleep(60) # sleep for a minute so that you don't send more than one message to the users
def get_msg(url):
# Calculate the time to the sunrise and sunset, pick the smallest and return a message accordingly
# get sunrise and sunset times from another function
sunrise, sunset = get_sunrise_sunset(url)
now = datetime.datetime.now()
t_now = now.strftime("%I:%M %p")
until_sunset = diff(t_now, sunset) # get difference in seconds
until_10 = diff(t_now, '12:00 PM') # get difference in seconds
wait_time = min(until_sunset, until_10)
# for debug
print('{}:{} left!'.format(wait_time //3600, wait_time //60%60))
time.sleep(rem - 20) # 20 seconds earlier because sending the messages takes about 20 seconds
if until_sunset < until_10:
return 'It's sunset!!'
else:
return f'Sunset today: {sunset}\nSunrise today: {sunrise}'