我正在尝试让我的 python 推特机器人整点每 30 分钟发一次推文。我应该怎么办?

I am trying to get my python twitter bot to tweet every 30 minutes on the hour. What should I do?

机器人需要整点每 30 分钟发一次推文(即 12:30 然后 1:00 然后 1:30...)。我理解 tweepy 和所有这些。我只需要弄清楚如何让计时器工作。我在想这样的事情:

if (time = "12:00") or (time = "12:30") or (time = "1:00") or...:
    # tweet

我不知道要使用什么包或如何设置它。

我会查看 PyPI 调度模块:

https://pypi.org/project/schedule/

您可以使用 Scheduler 库启动 here。试试这个作为它如何工作的例子,你显然可以在本地做,但不推荐这样做:

import schedule  

def job():  
    print("A Simple Python Scheduler.")  

# run the function job() every 30 minutes  
schedule.every(30).minutes.do(job)  

while True:  
    schedule.run_pending()  

所以使用 datetime 你实际上可以获得这样的分钟数:

from datetime import datetime

time = datetime.now()

minutes = time.minute

或一行:

from datetime import datetime

minutes = datetime.now().minute

现在有了分钟,if 语句可以简化下来,因为你不看小时。

if minutes == 0 or minutes == 30:
    # do tweet

编辑:

您评论问: "Also curious, does that mean I need to run my program on the hour of :00 because the time is created through the now function?"

所以理论上这里有几种方法可以回答这个问题。首先将您的代码包装在一个函数中并不断调用它:

def tweet_check(minutes):
    minutes = datetime.now().minutes

    if minutes == 0 or minutes == 30:
        # do tweet

if __name__ == '__main__':
    # This would be how it constantly runs the check
    while true:
        tweet_check()

选项 1:

然后,只要您希望您的机器人每 30 分钟发送一次推文,您就可以手动 运行 脚本。

选项 2

通过检查 if main == 'main' 您将能够将此脚本导入另一个脚本,然后 运行 以你自己的方式。作为导入的脚本,您可以在特定时间使用调度程序运行。

选项 3:

运行 将其作为系统计划任务 (windows) 或 cron 作业 (linux) 使其 运行 启动。

然而,关键是要指出,如果您确实将它用作选项 2 或 3,如果您希望它无论何时都发送,最好将其修改为可以传入可选变量的位置。

所以我会这样修改它:

def tweet_check(time_check=True):
    if time_check:
        minutes = datetime.now().minutes

        if minutes == 0 or minutes == 30:
            # do tweet

    else:
        # do tweet

这是因为选项 2 和 3 都固有地内置了计时。所以这里再做一次就是 excessive/inefficient 了。在这个简单的例子中,这不会有太大的不同,但在几千条推文的规模下,它会在下一分钟结束,然后会切断一些推文。