-
Notifications
You must be signed in to change notification settings - Fork 2
/
BlockManager.py
193 lines (140 loc) · 7.46 KB
/
BlockManager.py
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
import datetime
import os
import csv
import tweepy
from BlockUserOptions import BlockUserOptions
from DefaultValues import DefaultValues
from Settings import Settings
import os.path
import time
class BlockManager:
@property
def options(self):
return self.__block_user_options
@options.setter
def options(self, value):
self.__block_user_options = value
def __init__(self):
self.__block_user_options = BlockUserOptions()
self.__settings = Settings()
auth = tweepy.OAuthHandler(consumer_key=self.__settings.consumer_key, consumer_secret=self.__settings.consumer_secret)
auth.set_access_token(key=self.__settings.access_token_key, secret=self.__settings.access_token_secret)
self.__api = tweepy.API(auth, wait_on_rate_limit=False)
def __already_in_file(self, screen_name, file_name):
if not os.path.isfile(file_name):
return False
with open(file_name, encoding='utf-8') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
for row in csv_reader:
if len(row) == 0:
continue
if screen_name in row[DefaultValues.SCREEN_NAME]:
return True
return False
def get_friendship(self, follower):
result = ''
if (self.__settings.restricted_accounts is None or len(self.__settings.restricted_accounts) == 0):
return
print(f'Checking friendship of {follower.screen_name} ...')
for account in self.__settings.restricted_accounts:
friendship = self.__api.get_friendship(source_screen_name=follower.screen_name,target_screen_name=account)
# Ajust it to avoid TooManyRequests.
self.__timer(1, show_message=False)
if (friendship[0].following):
print(f'{account} ' + u'\u2713')
result += f'|{account}' if not result == '' else account
else:
print(f'{account} ' + u'\u2715')
return result
def __timer(self, seconds, show_message=True):
while seconds > 0:
mins, secs = divmod(seconds, 60)
timer = '{:02d}:{:02d}'.format(mins, secs)
if show_message:
print(timer, end="\r")
time.sleep(1)
seconds -= 1
def __wait(self, message):
print(message)
self.__timer(60 * 15)
def block_followers(self, options: BlockUserOptions):
""" Scan all your followers and blocks each follower based on the values filled in your environment variables:
e.g:
- not_desired_words: comma separated values.
- exception_words: comma separated values.
- restricted_accounts: comma separeted Twitter account names.
Args:
options: BlockUserOptions type where you can set you preferences, please see more in the file: BlockUserOptions.py.
"""
self.__block_user_options = options
for follower in self.__limit_handled(tweepy.Cursor(self.__api.get_followers, screen_name=self.__settings.my_screen_name, count=200).items()):
self.execute_block(follower)
def __limit_handled(self, cursor):
while True:
try:
yield cursor.next()
except Exception as e:
self.__wait(str(e))
def __write_file(self, file_name, message):
print(f'{file_name}: {message} \n\n')
if not self.__block_user_options.dryrun:
with open(file_name, 'a', encoding='utf-8') as f:
f.write(message + '\n')
def __has_words(self, follower, word_list):
if (word_list is None):
return False
return any(word.lower() in follower.description.lower().replace(',','') for word in word_list) or any(word.lower() in follower.name.lower().replace(',','') for word in word_list)
def __block(self, follower) -> bool:
if (follower.favourites_count == self.__block_user_options.min_favourites_count):
return True
if (follower.protected == True):
return False
if (self.__block_user_options.min_qty_digits_on_screen_name != 0 and len([int(s) for s in follower.screen_name if s.isdigit()]) >= self.__block_user_options.min_qty_digits_on_screen_name):
return True
words_found = self.__intersection(self.__settings.not_desired_words, follower.description.split())
if (self.__block_user_options.min_restricted_words_qty <= len(words_found) and len(words_found) > 0):
return True
words_found = self.__intersection(self.__settings.not_desired_words, follower.name.split())
if (self.__block_user_options.min_restricted_words_qty <= len(words_found) and len(words_found) > 0):
return True
return False
def __intersection(self, list1, list2):
if (list1 is None or list2 is None):
return []
result = [value for value in list1 if value in list2]
return result
def __block_when_friends(self, friends) -> bool:
if (friends is None):
return False
accounts = self.__intersection(self.__settings.restricted_accounts, friends.split('|'))
if (self.__block_user_options.min_restricted_accounts_qty <= len(accounts)):
return True
return False
def execute_block(self, follower):
try:
if self.__already_in_file(screen_name=follower.screen_name, file_name=DefaultValues.NOT_BLOCKED_FILE_NAME) or self.__already_in_file(screen_name=follower.screen_name, file_name=DefaultValues.BLOCKED_FILE_NAME):
print(f'Already in file: {follower.screen_name}')
return
friends = self.get_friendship(follower) if self.__block_user_options.check_firendship else ''
if (not follower.description is None):
block = self.__block(follower=follower) or self.__block_when_friends(friends=friends)
not_block = self.__has_words(follower, self.__settings.exception_words)
else:
block = friends != ''
friends = f',{friends}' if friends != '' and friends != None else ''
name = follower.name.replace(',', '-')
follower_str = f'{follower.id_str},{name},@{follower.screen_name},{follower.created_at.strftime("%d-%m-%Y")},{follower.followers_count}{friends}'
today = datetime.datetime.now()
if ((today - follower.created_at.replace(tzinfo=None)).days <= 90):
block = True
not_block = False
if (follower.followers_count == 0 or (block and not not_block)):
if not self.__block_user_options.dryrun:
self.__api.create_block(user_id=follower.id_str)
self.__write_file(file_name=DefaultValues.BLOCKED_FILE_NAME, message=f'{follower_str}')
else:
self.__write_file(file_name=DefaultValues.NOT_BLOCKED_FILE_NAME, message=f'{follower_str}')
except tweepy.TooManyRequests as e:
self.__wait(str(e))
except Exception as e:
self.__wait(str(e))