LoginSignup
0
4

More than 1 year has passed since last update.

【Python】pythonで毎時0分にtweetするようにしてみた

Last updated at Posted at 2022-06-12

概要

pythonで毎時0分にtweetするようにしてみた。

前提条件

Pythonが既にインストールされていること。
tweepyがすでにインストールされていること。
APIキーとアクセスキー、トークンの取得ができていること。
【Python】pythonでtweetしてみたの続編です。)

定期実行関数モジュール(schedule)のインストール

コンソールを開いて下記のコマンドを実行する。

pip install schedule

tweetプログラムに定期実行処理を追加

tweetプログラムにschedule関数を追加して毎時0分に実行できるようにする。

実際に実行したプログラムは下記になります。

import tweepy
import schedule
from time import sleep
import datetime

# Twitter Deverloper Portalで取得
ck = 'xxxxxxxxxxxx'
cs = 'xxxxxxxxxxxx'
at = 'xxxxxxxxxxxx'
ats = 'xxxxxxxxxxxx'

client = tweepy.Client(consumer_key=ck, consumer_secret=cs, access_token=at, access_token_secret=ats)

#01 定期実行する関数を準備
def tweet():
    dt_now = datetime.datetime.now()
    client.create_tweet(text="時報:只今" + dt_now.strftime('%H時です。'))

#02 スケジュール登録
schedule.every().hour.at(":00").do(tweet)

#03 イベント実行
while True:
    schedule.run_pending()
    sleep(1)

処理の内容は下記になります。
schedule.run_pending()でschedule.every()を呼び出し
schedule.every()の条件に当てはまればtweet()を呼び出して実行
sleep()で1秒待機(カッコ内は秒数)

schedule.every()の実行条件の詳細は下記URLに記載されてます。
https://di-acc2.com/programming/python/4574/#index_id4

実行結果

実行した結果は以下のようになります。
キャプチャ.PNG

余談

来月のBUMPのライブが楽しみです。

0
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
4