根据关键字转发特定用户的推文

时间:2020-06-22 15:36:12

标签: python tweepy

我一直在关注realpython上的教程,以尝试创建一个Twitter机器人,该机器人根据其推文中的关键字来转发特定用户。通过使用followtrack参数,我应该只能够转发包含goalassist的那些推文,但侦听器似乎会转发所有包含这些关键字的推文。不是特定用户。

#!/usr/bin/env python
# tweepy-bots/bots/retweet.py

import tweepy
import logging
from config import create_api
import json

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger()

class RetweetListener(tweepy.StreamListener):
    def __init__(self, api):
        self.api = api
        self.me = api.me()

    def on_status(self, tweet):
        logger.info(f"Processing tweet id {tweet.id}")
        if tweet.in_reply_to_status_id is not None or \
            tweet.user.id == self.me.id:
            # This tweet is a reply or I'm its author so, ignore it
            return
        if not tweet.retweeted:
            # if 'GOAL' and 'ASSIST' in tweet.full_text:
                # Retweet, since we have not retweeted it yet
            try:
                tweet.retweet()
            except Exception as e:
                logger.error("Error on fav and retweet", exc_info=True)

    def on_error(self, status):
        logger.error(status)

def main(keywords):
    api = create_api()
    tweets_listener = RetweetListener(api)
    stream = tweepy.Stream(api.auth, tweets_listener)
    stream.filter(follow=['761568335138058240'], 
                           track=keywords, languages=["en"])

if __name__ == "__main__":
    main(["Goal Assist"])

1 个答案:

答案 0 :(得分:0)

根据我如何将其合并在一起发布自己的答案,不确定是否是最好的方法,但是它是否有效。

class RetweetListener(tweepy.StreamListener):
    def __init__(self, api):
        self.api = api
        self.me = api.me()

    def on_status(self, tweet):
        logger.info(f"Processing tweet id {tweet.id}")
        if tweet.in_reply_to_status_id is not None or \
            tweet.user.id == self.me.id:
            # This tweet is a reply or I'm its author so, ignore it
            return
        if not tweet.retweeted:                
            if 'Goal -'  and 'Assist -' in tweet.text:
                try:
                    # Retweet, since we have not retweeted it yet
                    tweet.retweet()
                except Exception as e:
                    logger.error("Error on fav and retweet", exc_info=True)

    def on_error(self, status):
        logger.error(status)