You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现Twitter推文机器人每30分钟自动运行?

实现推文机器人每30分钟自动运行的方案

方法一:Windows任务计划程序(系统级定时,推荐)

这是Windows自带的稳定工具,无需额外依赖,适合长期后台运行。

操作步骤:

  1. 打开「任务计划程序」(开始菜单搜索即可找到)
  2. 点击「创建基本任务」,按向导完成设置:
    • 任务名称:比如“推文定时发布任务”,描述按需填写
    • 触发器选「每天」,设置重复间隔为30分钟,持续时间选「无限期」
    • 操作选「启动程序」
    • 程序/脚本填Python的完整路径(可在PowerShell输入where python查询),比如C:\Python311\python.exe
    • 添加参数填脚本的完整路径:"C:\Users\xxx\module1.py"
    • 完成后可右键任务选择「运行」测试是否正常执行

方法二:修改脚本内置定时循环

直接在Python代码里实现定时逻辑,无需系统工具,但需保持脚本运行状态。

修改后的完整代码:

from typing import Text
import tweepy
import requests
from bs4 import BeautifulSoup
import time

# 初始化Tweepy客户端
client = tweepy.Client(
    consumer_key="XXXXXX",
    consumer_secret="XXXXXX",
    access_token="XXXXXX",
    access_token_secret="XXXXXX"
)

def post_wiki_tweet():
    try:
        # 获取随机维基百科标题
        url = requests.get("https://he.wikipedia.org/wiki/Special:Random")
        soup = BeautifulSoup(url.content, "html.parser")
        title = soup.find(class_="firstHeading").text
        print(title)
        
        # 发布推文
        client.create_tweet(text="לשטח את " + title)
        print("וואלה יופי הצלחת יא בתול")
        print("יא קינג יא אלוף אין עליך יא גאון מחשבים")
    except tweepy.errors.TweepyException as e:
        print("שגיאה על הראש שלך")
        print("יא אפס")
        print(f"错误详情: {e}")  # 新增错误信息,方便排查问题
    except Exception as e:
        print(f"其他异常: {e}")

# 每30分钟执行一次任务
while True:
    post_wiki_tweet()
    time.sleep(30 * 60)  # 30分钟转换为秒

补充说明:

  • 运行脚本后不能关闭终端窗口,否则任务会中断
  • 如需后台无窗口运行,可改用pythonw.exe执行:
    pythonw.exe "C:\Users\xxx\module1.py"
    

方法三:使用第三方schedule库

依赖第三方库实现更灵活的定时规则,需先安装库:pip install schedule

示例代码:

from typing import Text
import tweepy
import requests
from bs4 import BeautifulSoup
import schedule
import time

client = tweepy.Client(
    consumer_key="XXXXXX",
    consumer_secret="XXXXXX",
    access_token="XXXXXX",
    access_token_secret="XXXXXX"
)

def post_wiki_tweet():
    try:
        url = requests.get("https://he.wikipedia.org/wiki/Special:Random")
        soup = BeautifulSoup(url.content, "html.parser")
        title = soup.find(class_="firstHeading").text
        print(title)
        
        client.create_tweet(text="לשטח את " + title)
        print("וואלה יופי הצלחת יא בתול")
        print("יא קינג יא אלוף אין עליך יא גאון מחשבים")
    except tweepy.errors.TweepyException as e:
        print("שגיאה על הראש שלך")
        print("יא אפס")
        print(f"错误详情: {e}")
    except Exception as e:
        print(f"其他异常: {e}")

# 设置每30分钟执行一次任务
schedule.every(30).minutes.do(post_wiki_tweet)

# 启动调度循环
while True:
    schedule.run_pending()
    time.sleep(1)

优缺点:

  • 优势:语法简洁,支持复杂定时规则(如指定时段执行)
  • 劣势:需保持脚本运行,依赖第三方库

内容的提问来源于stack exchange,提问作者toma0711

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 09:27:55