-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.py
201 lines (139 loc) · 5.47 KB
/
bot.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
194
195
196
197
198
199
200
201
from faker import Faker
import click
import sys
import yaml
import urllib.request
import random
import json
class Bot:
"""
Bot class
"""
def __init__(self, settings_file):
"""
Bot constructor
:param settings_file: Settings file
"""
with open(settings_file, 'r') as stream:
try:
self.settings = yaml.load(stream)
except yaml.YAMLError as exc:
sys.exit('Failed to load settings!')
self.fake = Faker()
def signup_user(self):
"""
Signup user
:return: User
"""
email = bytearray(self.fake.email(), 'utf-8')
password = bytearray('test123', 'utf-8')
user_data = b'email=%s&password=%s' % (email, password)
request = urllib.request.Request(url='{}users/signup/'.format(self.settings['base_url']),
data=user_data,
method='POST')
response = urllib.request.urlopen(request)
return json.loads(response.read())
def login_user(self, user):
"""
Login user with email and password
:param user: User
:return: Auth token
"""
email = bytearray(user['email'], 'utf-8')
password = bytearray('test123', 'utf-8')
user_data = b'email=%s&password=%s' % (email, password)
request = urllib.request.Request(url='{}token/'.format(self.settings['base_url']),
data=user_data,
method='POST')
response = urllib.request.urlopen(request)
return json.loads(response.read())
def create_post(self, token):
"""
Create Post
:param token: Auth token
:return: Post
"""
content = bytearray(self.fake.text(), 'utf-8')
post_data = b'content=%s' % content
headers = {'Authorization': 'Bearer {}'.format(token)}
request = urllib.request.Request(url='{}posts/'.format(self.settings['base_url']),
data=post_data,
method='POST',
headers=headers)
response = urllib.request.urlopen(request)
return json.loads(response.read())
def get_posts(self, page, token):
"""
Get posts page
:param page: Page number
:param token: Auth token
:return: Posts
"""
total_posts = []
headers = {'Authorization': 'Bearer {}'.format(token)}
request = urllib.request.Request(url='{}posts/?page={}'.format(self.settings['base_url'], page),
method='GET',
headers=headers)
response = urllib.request.urlopen(request)
response_dict = json.loads(response.read())
total_posts += response_dict['results']
if response_dict['next'] is not None:
total_posts += self.get_posts(page+1, token)
return total_posts
def like_post(self, post, token):
"""
Like post
:param post: Post
:param token: Auth token
:return: Like
"""
headers = {'Authorization': 'Bearer {}'.format(token)}
request = urllib.request.Request(url='{}posts/{}/like'.format(self.settings['base_url'], post['id']),
method='GET',
headers=headers)
response = urllib.request.urlopen(request)
return json.loads(response.read())
@click.command()
@click.option('-s', '--settings', 'settings_file', default='bot_settings.yaml', help='Bot settings file.')
def run_bot(settings_file):
bot = Bot(settings_file)
print('Init Bot')
users = []
# Create users and posts:
for u in range(bot.settings['number_of_users']):
new_user = bot.signup_user()
print('Signup user {}'.format(new_user['email']))
user_token = bot.login_user(new_user)
print('Login user')
posts_per_user = random.randint(1, bot.settings['max_posts_per_user'])
for p in range(posts_per_user):
bot.create_post(user_token['access'])
print('Create {} posts'.format(posts_per_user))
new_user['posts_per_user'] = posts_per_user
users.append(new_user)
# Sort users by posts_per_user
sorted_users = sorted(users, key=lambda k: k['posts_per_user'], reverse=True)
print('Sort users')
# Like posts:
for new_user in sorted_users:
user_token = bot.login_user(new_user)
print('Login user {}'.format(new_user['email']))
all_posts = bot.get_posts(1, user_token['access'])
print('Read all posts')
can_like = False
other_posts = []
for current_post in all_posts:
if current_post['user'] != new_user['id']:
other_posts.append(current_post)
if len(current_post['likes']) == 0:
can_like = True
if bot.settings['max_likes_per_user'] <= len(other_posts):
other_posts = random.sample(other_posts, bot.settings['max_likes_per_user'])
if can_like:
for current_post in other_posts:
bot.like_post(current_post, user_token['access'])
print('Like {} posts'.format(len(other_posts)))
else:
print('Nothing to like')
if __name__ == '__main__':
run_bot()