summaryrefslogtreecommitdiff
path: root/users.py
blob: e61d3c22cc74c55d2f6fdb5457f880c350e4ebab (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
#!/usr/bin/python3
# -*- coding: utf-8 -*-


import tweepy
from config import accounts
from db import open_db, LikeMemory, TrackMemory
from taste import analyse
import os
import pickle
from random import shuffle


CACHE_FILENAME = 'ids.cache'


class UsersListener():
    """A listener handles tweets are the received from the stream."""

    def __init__(self, api):
        """Build the Python object."""

        super().__init__()

        self._api = api

        open_db()

        self._memory = LikeMemory(api)
        self._tracker = TrackMemory()

        self._compute_ids_to_follow(True)


    def _compute_ids_to_follow(self, cached):
        """Get the list of accounts to track."""

        if not os.path.isfile(CACHE_FILENAME):
            cached = False

        if cached:

            ids = pickle.load(open(CACHE_FILENAME, 'rb'))

            print('[i] Reloaded %u accounts' % len(ids))

        else:

            ids = []

            for master in accounts.split(' '):

                count = 0

                try:

                    for page in tweepy.Cursor(self._api.followers_ids, screen_name=master).pages():

                        count += len(page)
                        ids.extend(page)

                    print('[i] Got %u accounts following %s' % (count, master))

                except:

                    print('[!] Error while receiving followers for %s...' % master)


            pickle.dump(ids, open(CACHE_FILENAME, 'wb'))

            print('[i] Loaded %u accounts' % len(ids))

            ids = list(set(ids))

            print('[i] Kept %u accounts' % len(ids))

        # Remove all account natively followed

        already = []

        for page in tweepy.Cursor(self._api.followers_ids, screen_name=self._api.me().name).pages():
            already.extend(page)

        print('[i] I am followed by %u accounts' % len(already))

        self._ids = [ x for x in ids if x not in already ]

        shuffle(self._ids)

        print('[i] Tracking %u accounts...' % len(self._ids))


    def start(self, auth):
        """Start the listener."""

        while True:

            for uid in self._ids:

                since = self._tracker.get_last_seen_for(uid)

                last = []

                try:

                    last = self._api.user_timeline(uid, since)

                except tweepy.error.TweepError as e:

                    # Private account
                    # tweepy.error.TweepError: Not authorized.
                    if e.response.status_code == 401:
                        pass

                    # Nothing new!
                    # tweepy.error.TweepError: [{'message': 'Sorry, that page does not exist.', 'code': 34}]
                    elif e.response.status_code == 404:
                        pass

                    else:
                        print(e, e.response.status_code)
                        assert(False)

                first = None

                for status in last:

                    sid = status.id
                    uid = status.author.id
                    username = status.author.screen_name

                    while hasattr(status, 'retweeted_status'):
                        status = status.retweeted_status

                    analyse(sid, username, status.text, self._api, self._memory)

                    if first is None:
                        first = uid, username, sid

                if not(first is None):
                    uid, username, sid = first
                    self._tracker.set_last_seen_for(uid, username, sid)



def listen_to_users(auth, api):
    """Track all tweets written by users."""


    data = api.rate_limit_status()

    for c in data['resources'].keys():

        print('%s' % c)

        category = data['resources'][c]

        for p in category.keys():

            props = category[p]
            changed = props['remaining'] != props['limit']

            print(' %s %s: %d / %d' % ('!!' if changed else '  ', p, props['remaining'], props['limit']))






    if True:

        listener = UsersListener(api)

        ####listener.start(auth)

        #stream = Stream(auth, listener)
        #stream.filter(follow=new)