Python3 code. In the case of 2 system, I think that it will work if you change the area around super ()
a little.
import tweepy
consumer_key = "CONSUMER_KEY"
consumer_secret = "CONSUMER_SECRET"
access_token = "ACCESS_TOKEN"
access_secret = "ACCESS_TOKEN_SECRET"
class StreamListener(tweepy.StreamListener):
def __init__(self, api):
super().__init__(api)
self.me = self.api.me()
def on_event(self, event):
if event.event == 'follow':
if self.me.id != source_user["id"]:
source_user = event.source
event._api.create_friendship(source_user["id"])
print("followed by {} {}".format(source_user["name"], source_user["screen_name"]))
if __name__ == "__main__":
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
api = tweepy.API(auth)
stream = tweepy.Stream(auth=api.auth, listener=StreamListener(api))
stream.userstream(_with="user")
In addition to tweets, userstream also has events related to it.
Tweepy's ʻon_event method seems to fire when ʻevent
comes in.
__init__Inside
self.me = self.api.me()
on_In event
if self.me.id != source_user["id"]:
However, as a specification, ʻUser follows someone and ʻUser is followed
flow as the same follow
, and
Description | Source | Target |
---|---|---|
I was followed by someone | Following user | Current user |
I followed someone | Current user | Followed user |
As shown in this table, the position where you and the other party enter may change depending on the situation.
Therefore, when you return a follow, you will try to follow yourself.
In that case, an error will occur, so in order to avoid it, get your own information at the time of instance creation, and change the id
of source_user
to your own ʻid every time the
follow` event flows. I'm comparing.
Also, there is a ʻunfollow in ʻevent
, but this is what happens when you unfollow another user, and you cannot receive the fact that you have been unfollowed by another user.
So, for automatic unfollowing, you need to hit the REST API in a timely manner.
Streaming message types | Twitter Developers
tweepy/streaming.py at master · tweepy/tweepy
Recommended Posts