【Tweepy】リプライ・メンションしてくれたユーザーを取得し、感謝ツイート[Python]

  • URLをコピーしました!
目次

Tweepy

前回、Xserver(エックスサーバー)のCron(クロン)を使って、特定期間内にリツイートしてくれたユーザーに感謝ツイートをするプログラムを定期実行するように設定しました。

今回はリツイートだけでなく、リプライやメンションをしてくれたユーザーを取得し、感謝ツイートをするようにプログラムを改変していきましょう。

ということでまずはおさらいから。

<セル1>

import tweepy
import datetime

account = "@Nori_3PySci"
check_days = 1

time_now = datetime.datetime.now()

consumer_key = 'API keyを入力'
consumer_secret = 'API key secretを入力'
access_token = 'Access tokenを入力'
access_token_secret = 'Access token secretを入力'

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)

api = tweepy.API(auth)
<セル2>

def tweet_check(account, check_days, time_now):
    
    tweets = tweepy.Cursor(api.user_timeline, id=account).items(100)

    rt_ids = []

    for tw in tweets:
        if time_now - (tw.created_at + datetime.timedelta(hours=9)) <= datetime.timedelta(days=check_days):
            if (tw.text.startswith('RT')) or (tw.text.startswith('@')):
                pass
            else:
                if tw.retweet_count >= 1:
                    rt_ids.append(tw.id)

    return rt_ids
<セル3>

def rtuser_check(rt_ids):
    
    rt_users = []

    for ids in rt_ids:
        retweets = api.retweets(id=ids)
        for rt in retweets:
            rt_users.append("@" + rt.user.screen_name)

    return rt_users
<セル4>

def rtuser_tweet(rt_users, time_now):

    if len(rt_users) != 0:
        tweet_content = '\n'.join(rt_users[:10])
        api.update_status("(APIテスト中)\n今日もみなさんのリツイート、ありがとうございます!\n\n" +  tweet_content + "\n\n" + time_now.strftime("%Y/%m/%d %H:%M:%S") + "\n\n#RT感謝砲") 
    elif len(rt_users) == 0:
        api.update_status("(APIテスト中)\n今日は残念ながら、リツイートありませんでした..." + "\n\n" + time_now.strftime("%Y/%m/%d %H:%M:%S") + "\n\n#RT感謝砲")
<セル5>

def main(account, check_days, time_now):
    rt_ids = tweet_check(account, check_days, time_now)
    rt_users = rtuser_check(rt_ids)
    rtuser_tweet(rt_users, time_now)
<セル6>

if __name__ == '__main__':
    main(account, check_days, time_now)

リプライ・メンションしてくれたユーザーを取得する関数を定義

まずはリプライ・メンションをしてくれたユーザーを取得する関数を作ります。

その部分がこちら。

def rpuser_check(account, check_days, time_now):
    
    mentions = tweepy.Cursor(api.mentions_timeline, id=account).items(100)
    
    mn_users = []
    
    for mn in mentions:
        if time_now - (mn.created_at + datetime.timedelta(hours=9)) <= datetime.timedelta(days=check_days):
            mn_users.append("@" + mn.user.screen_name)
            
    return mn_users

これまではあるアカウント(@Nori_3PySci)の「user_timeline」を取得してきましたが、今回は「mentions_timeline」を取得します。

この「mentions_timeline」がある特定のアカウントに向けて発せられたツイートを取得するタイムラインのようです。

mentions = tweepy.Cursor(api.mentions_timeline, id=account).items(100)

1番のキモの部分はここであとはこれまで作ってきたリツイート用のプログラムを少し改変していくだけです。

リプライ・メンションしてくれたユーザーを取得する部分はこんな感じです。

    mn_users = []
    
    for mn in mentions:
        if time_now - (mn.created_at + datetime.timedelta(hours=9)) <= datetime.timedelta(days=check_days):
            mn_users.append("@" + mn.user.screen_name)
            
    return mn_users

for文で取得したmentionの一覧から、一つずつ変数mnに格納します。

そしてリツイートの時と同様、この部分で期間を指定します。

if time_now - (mn.created_at + datetime.timedelta(hours=9)) <= datetime.timedelta(days=check_days):

リツイートの時には、リツイートされたツイートを取得したのち、リツイートしてくれたユーザーを取得していますが、リプライ・メンションの場合は直接ユーザー名を取得できました。

mn_users.append("@" + mn.user.screen_name)

ということでこれを<セル3>の後に入れましょう。

main部分の修正

次にmain部分を修正していきます。

def main(account, check_days, time_now):
    rt_ids = tweet_check(account, check_days, time_now)
    rt_users = rtuser_check(rt_ids)
    mn_users = rpuser_check(account, check_days, time_now)
    
    users = rt_users + mn_users

    user_tweet(users, time_now)

まずは先ほど作ったrpuser_checkを使って、リプライ・メンションをくれたユーザー名を取得し、変数mn_usersに格納します。

mn_users = rpuser_check(account, check_days, time_now)

その後、前に取得したリツイートしてくれたユーザーのリストと今回取得したリプライ・メンションしてくれたユーザーのリストを一つにします。

users = rt_users + mn_users

次にその一つにしたユーザーのリストをツイート用の関数user_tweetに渡します。

user_tweet(users, time_now)

これでmain部分の修正は完了です。

ツイート関数部分の修正

次にツイートするための関数を修正していきます。

def user_tweet(users, time_now):

    if len(users) != 0:
        tweet_content = '\n'.join(users[:10])
        api.update_status("(APIテスト中)\n今日もみなさんのリプライとリツイート、ありがとうございます!\n\n" +  tweet_content + "\n\n" + time_now.strftime("%Y/%m/%d %H:%M:%S") + "\n\n#リプRT感謝砲") 
    elif len(users) == 0:
        api.update_status("(APIテスト中)\n今日は残念ながら、リプライもリツイートもありませんでした..." + "\n\n" + time_now.strftime("%Y/%m/%d %H:%M:%S") + "\n\n#リプRT感謝砲")

これで一定期間中にリツイート、リプライ、メンションしてくれた方を紹介できる体制が整いました。

このプログラムはGitHubでも公開していますので、良かったらそちらもどうぞ。

当分、これで運用してみて、さらにいいことが思い浮かんだら、どんどん改善していこうと思います。

追記)バグ修正したので、その時の記事がこちら。

ではでは今回はこんな感じで。

よかったらシェアしてね!
  • URLをコピーしました!

コメント

コメントする

目次