【Tweepy】感謝砲のバグ修正(重複の削除とランダム抽出)[Python]

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

Tweepy

前にTwitter制御ライブラリTweepyを使って、リツイート・リプライ・メンションをくれた方へ感謝ツイート(感謝砲)をするプログラムを作成しました。

運用してみるとちょっと気になったところがあったので、修正してみようと思います。

気になった点とは、感謝砲に載せるユーザー名は10人にしているのですが、前のプログラムだと重複をしてしまう点、また10人以上の場合、ランダムに抽出できるか不安な点です。

前者に関しては間違いなく起こりうるバグです。

後者に関しては「.join」を使っている点で作成されたリスト内の要素の順序がランダムに決まるため、多分今のままでも問題ないとは思うのですが、もう少し明確にランダム性を持たせた方がいいかなと感じています。

ということで上記2点を修正したいと思います。

まずは前のおさらいから。

<セル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 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
<セル5>

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感謝砲")
<セル6>

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)
<セル7>

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

randomのインポート

最初に修正するのはライブラリのインポート部分です。

今のところ、「tweepy」と「datetime」をインポートしていますが、さらにランダムを扱うため;「random」ライブラリをインポートします。

import tweepy
import datetime
import random

<セル5>ツイートするユーザーの抽出

あと今回修正するのは、<セル5>のユーザーの抽出部分です。

修正したプログラムがこちらです。

<セル5 修正後>

def user_tweet(users, time_now):

    if len(users) != 0:
        if len(users) < 10:
            tweet_content = '\n'.join(set(users))
        else:
            random_users = random.sample(set(users), 10)
            tweet_content = '\n'.join(random_users)
        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感謝砲")

変わったのはこの部分。

if len(users) != 0:
        if len(set(users)) <= 10:
            tweet_content = '\n'.join(set(users))
        else:
            random_users = random.sample(set(users), 10)
            tweet_content = '\n'.join(random_users)

リツイート・リプライ・メンションしてくれたユーザーが0人でなかった場合、10人以下かそうでないかで分岐させています。

またset関数を使うことで、リスト内の要素が重複していない形で判定しています。

if len(set(users)) <= 10:

重複をしていないユーザーが10人以下の場合は全員紹介しますので、そのまま連結します。

tweet_content = '\n'.join(set(users))

次に「else」でそれ以外、つまり10人より多い場合、ランダムに10人選んだのち、ユーザー名を連結します。

random_users = random.sample(set(users), 10)
tweet_content = '\n'.join(random_users)

これで修正は完了です。

また様子を見て、バグ等がありましたら、修正していきたいと思います。

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

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

コメント

コメントする

目次