-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
output.py
352 lines (309 loc) · 10.4 KB
/
output.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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
#
# twitterbot2
#
# edoardottt
# edoardoottavianelli.it
# https://github.com/edoardottt/twitterbot2
#
# This repository is under GPL-3 License.
#
# This file contains the functions to create and write
# the output files (CSV / JSON / HTML).
# The user can input a username to write in the output file
# the data related only to that user (and the output file will be
# twitterbot2-output/{username}.{csv,json,html}) or the word 'ALL'
# to write in the output file the data related to all the users
# in the database (and the output file will be
# twitterbot2-output/ALL.{csv,json,html}).
#
import logging
import os
import db
import csv
import json
import sys
import datetime
version_str = "0.2"
def version():
return version_str
def print_version():
print(version_str + "\n")
def print_banner():
print(" _ _ _ _ _ _ ____")
print("| |___ _(_) |_| |_ ___ _ __| |__ ___ | |_|___ \\")
print("| __\\ \\ /\\ / / | __| __/ _ \\ '__| '_ \\ / _ \\| __| __) |")
print("| |_ \\ V V /| | |_| || __/ | | |_) | (_) | |_ / __/")
print(
" \\__| \\_/\\_/ |_|\\__|\\__\\___|_| |_.__/ \\___/ \\__|_____| "
+ version()
)
print("")
print(" > edoardottt, https://www.edoardoottavianelli.it")
print(" > https://github.com/edoardottt/twitterbot2")
print("")
def tweet_banner(message):
"""
This is a standard tweet to spread info about the bot.
"""
tweet = str(datetime.datetime.now()) + "\n"
tweet += "This is a bot at the service of @" + globals.user + ".\n"
tweet += "https://github.com/edoardottt/twitterbot2\n"
tweet += message + "\n"
return tweet
logger = logging.getLogger("__main__")
def create_output_folder():
"""
This function creates (only if not exists already) the
`twitterbot2-output` folder.
"""
directory = "twitterbot2-output"
if not os.path.exists(directory):
os.makedirs(directory)
def create_output_file(filename):
"""
This function creates (only if not exists already) the
output file in the `twitterbot2-output` folder.
"""
directory = "twitterbot2-output"
if not os.path.exists(directory + "/" + filename):
_ = open(directory + "/" + filename, "w+")
else:
answer = ask_confirmation()
if not answer:
sys.exit()
else:
_ = open(directory + "/" + filename, "w+")
return directory + "/" + filename
def ask_confirmation():
"""
This function checks if the user wants to override the already
existing output file.
"""
answer = str(input("The file already exists. Do you want to override? (Y/n)"))
if answer.lower() == "y" or answer.lower() == "yes" or answer.lower() == "":
return True
return False
def output_csv(user):
"""
This function writes in the CSV output file the results got
from the database for the specified user or for all of them
(if ALL is inputted).
"""
conn = db.conn_db()
if user == "ALL":
values = db.all_stats(conn)
else:
values = db.user_stats(conn, user)
if len(values) == 0:
logger.warning("There aren't data for this user.")
sys.exit()
else:
create_output_folder()
filename = create_output_file(user + ".csv")
with open(filename, "w", newline="") as myfile:
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
for elem in values:
wr.writerow(elem)
logger.info("All data has been written into " + filename)
def output_json(user):
"""
This function writes in the JSON output file the results got
from the database for the specified user or for all of them
(if ALL is inputted).
"""
conn = db.conn_db()
if user == "ALL":
values = db.all_stats(conn)
else:
values = db.user_stats(conn, user)
if len(values) == 0:
logger.warning("There aren't data for this user.")
sys.exit()
else:
create_output_folder()
filename = create_output_file(user + ".json")
dict = {}
for elem in values:
if not elem[0] in dict.keys():
dict[elem[0]] = {}
dict[elem[0]][elem[1]] = {
"tweets": elem[2],
"likes": elem[3],
"retweets:": elem[4],
"followers:": elem[5],
}
with open(filename, "w") as f:
json.dump(dict, f)
logger.info("All data has been written into " + filename)
def banner_html():
banner = """<html>
<head>
<title>Twitterbot2 output</title>
<style>
* {
box-sizing: border-box;
font-family: Arial, Helvetica, sans-serif;
}
body {
margin: 0;
font-family: Arial, Helvetica, sans-serif;
}
/* Style the top navigation bar */
.topnav {
overflow: hidden;
background-color: #333;
}
/* Style the topnav links */
.topnav a {
float: left;
display: block;
color: #f2f2f2;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}
/* Change color on hover */
.topnav a:hover {
background-color: #ddd;
color: black;
}
/* Style the content */
.content {
background-color: #ddd;
padding: 10px;
height: 200px;
}
/* Style the footer */
.footer {
background-color: #f1f1f1;
padding: 10px;
bottom: 0;
text-align:center;
width: 100%;
position: fixed;
}
</style>
</head>
<body>
<div class="topnav">
<a href="https://github.com/edoardottt/twitterbot2">Twitterbot2 on GitHub</a>
<a href="https://github.com/edoardottt/twitterbot2#contributing-">Contribute</a>
<a href="https://github.com/edoardottt/twitterbot2/blob/main/README.md">Docs</a>
<a href="https://github.com/edoardottt/twitterbot2/blob/main/LICENSE">License</a>
</div>
"""
return banner
def footer_html():
footer = """<div class="footer">
<p>twitterbot2 by <a href='https://github.com/edoardottt'>@edoardottt</a></p>
</div>
<br><br><br><br><br><br><br><br>
</body>
</html>
"""
return footer
def html_table(lol):
out_string = """<table border="1" cellspacing="15"><th scope="col">User</th>
<th scope="col">Date</th>
<th scope="col">Tweets</th>
<th scope="col">Likes</th>
<th scope="col">Retweets</th>
<th scope="col">Followers</th>"""
for sublist in lol:
out_string += " <tr><td>"
out_string += " </td><td>".join(list(map(str, sublist)))
out_string += " </td></tr>"
out_string += "</table>"
return out_string
def output_html(user):
"""
This function writes in the HTML output file the results got
from the database for the specified user or for all of them
(if ALL is inputted).
"""
conn = db.conn_db()
if user == "ALL":
values = db.all_stats(conn)
else:
values = db.user_stats(conn, user)
if len(values) == 0:
logger.warning("There aren't data for this user.")
sys.exit()
else:
create_output_folder()
filename = create_output_file(user + ".html")
with open(filename, "w") as f:
f.write(banner_html())
f.write(html_table(values))
f.write(footer_html())
logger.info("All data has been written into " + filename)
def data_json(values):
"""
This function tranforms the input values
in a py dictionary useful for json.
"""
dict = {}
for elem in values:
if not elem[0] in dict.keys():
dict[elem[0]] = {}
dict[elem[0]][elem[1]] = {
"tweets": elem[2],
"likes": elem[3],
"retweets:": elem[4],
"followers:": elem[5],
}
return dict
def usage():
"""
usage: twitterbot2.py [-h] [-v | -t | -k KEYWORD | -nu | -nl | -nr \
| -s STATS | -oc OUTPUT_CSV | -oj OUTPUT_JSON | -oh OUTPUT_HTML]
Twitterbot v2
optional arguments:
-h, --help show this help message and exit
-v, --version Show the version of this program.
-t, --timeline Search for tweets in the bot and user's timeline.
-k KEYWORD, --keyword KEYWORD
Search for tweets with defined keyword(s). If more than one,
comma separated enclosed in double quotes.
-nu, --no-user Don't like and retweet user tweets.
-nl, --no-like Don't like tweets, just retweet.
-nr, --no-retweet Don't retweet tweets, just like.
-s STATS, --stats STATS
Show the statistics of the inputted bot (username).
-oc OUTPUT_CSV, --output-csv OUTPUT_CSV
Produce a csv file containing the stats for the inputted used (ALL for anyone).
-oj OUTPUT_JSON, --output-json OUTPUT_JSON
Produce a json file containing the stats for the inputted used (ALL for anyone).
-oh OUTPUT_HTML, --output-html OUTPUT_HTML
Produce a html file containing the stats for the inputted used (ALL for anyone).
"""
print("usage: twitterbot2.py [-h] [-v | -t | -k KEYWORD | -s]")
print("")
print("Twitterbot v2")
print("")
print("optional arguments:")
print(" -h, --help show this help message and exit")
print(" -v, --version Show the version of this program.")
print(" -t, --timeline Search for tweets in the bot and user's timeline.")
print(" -k KEYWORD, --keyword KEYWORD")
print(
" Search for tweets with defined keyword(s). If more than one,"
)
print(" comma separated enclosed in double quotes.")
print(" -nu, --no-user Don't like and retweet user tweets.")
print(" -nl, --no-like Don't like tweets, just retweet.")
print(" -nr, --no-retweet Don't retweet tweets, just like.")
print(" -s STATS, --stats STATS")
print(" Show the statistics of the inputted bot (username).")
print(" -oc OUTPUT_CSV, --output-csv OUTPUT_CSV")
print(
" Produce a csv file containing the stats for the inputted used (ALL for anyone)."
)
print(" -oj OUTPUT_JSON, --output-json OUTPUT_JSON")
print(
" Produce a json file containing the stats for the inputted used (ALL for anyone)."
)
print(" -oh OUTPUT_HTML, --output-html OUTPUT_HTML")
print(
" Produce a html file containing the stats for the inputted used (ALL for anyone)."
)