This repository has been archived by the owner on Dec 15, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ebooks.js
403 lines (326 loc) · 11.7 KB
/
ebooks.js
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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
/********************************************
_._ _,-'""`-._
(,-.`._,'( |\`-/|
`-.-' \ )-`( , o o) v. 1.0.1
`- \`_`"'-
licensed under the MIT license
github.com/almondette/ebooks-bot/blob/master/LICENSE
markov tweetbot generator by amelie!
this is my first google script, i
hope it serves you well.
adapted from zach whalen's ssbot,
mostly the bot menu functions.
the rest is mine and i'm proud!
feel free to edit or remove the code
as you wish, with attribution.
********************************************/
/*****************
ADD 'BOT' MENU
*****************/
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Bot')
.addItem('Generate Preview', 'preview')
.addSeparator()
.addItem('Send a Test Tweet', 'makeSingleTweet')
.addItem('Revoke Twitter Authorization', 'authRevoke')
.addSeparator()
.addItem('Start Posting Tweets\/Update Tweet Timing', 'setTiming')
.addItem('Stop Posting Tweets', 'clearTiming')
.addToUi();
};
/*****************
GENERATE PREVIEWS
*****************/
function preview() {
var preview = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('preview');
preview.getRange('B4:B20').setValue(' ');
SpreadsheetApp.getActiveSpreadsheet().setActiveSheet(preview);
for (var p = 0; p < 16; p++) {
var offset = p + 5;
var prv = getEbooksText(10); // change this value if you want more or less preview output
preview.getRange('b' + offset).setValue(prv);
}
}
/*****************
YOUR BBY BOT!
*****************/
function getEbooksText() {
var ebooks = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ebooks.getSheetByName('settings')
var archiveUrl = sheet.getRange('D32').getValue();
var ss = SpreadsheetApp.openByUrl(archiveUrl);
var archive = ss.getSheetByName('Archive');
var lastRow = archive.getLastRow();
var startwords = [];
var endwords = {};
var tweets = {};
var allTweets = archive.getRange('C1:C' + lastRow).getValues();
for (var i = 0; i < allTweets.length; i++) {
var words = allTweets[i][0].split(' ');
endwords[words[words.length - 1]] = true;
startwords.push(words[0]);
for (var j = 0; j < words.length - 1; j++) {
if (tweets.hasOwnProperty(words[j])) {
tweets[words[j]].push(words[j + 1]);
} else {
tweets[words[j]] = [words[j + 1]];
}
}
}
var choice = function (w) {
var i = Math.floor(w.length * Math.random());
return w[i];
};
var shitpost = function (min_length) {
word = choice(startwords);
var msg = [word];
while (tweets.hasOwnProperty(word)) {
var next_words = tweets[word];
word = choice(next_words);
msg.push(word);
if (msg.length > min_length && endwords.hasOwnProperty(word)) break;
}
if (msg.length < min_length) return shitpost(min_length);
return msg.join(' ');
};
var msg = shitpost(5 + Math.floor(5 * Math.random()));
var noLinks = [
"https:\/\/t\.co\/[a-z0-9]+",
"@[a-z0-9_]+",
"RT ",
"#[a-z0-9_]+",
":()"
];
var deleteThese = new RegExp(noLinks.join('|'), 'ig');
msg = msg.replace(deleteThese, '');
return msg;
}
/*****************
CONNECT TO TWITTER
*****************/
function getTwitterService() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('settings');
var twitter_name = sheet.getRange('D7').getValue();
var consumer_key = sheet.getRange('D17').getValue();
var consumer_secret = sheet.getRange('D19').getValue();
var project_key = sheet.getRange('D23').getValue();
var service = OAuth1.createService('twitter');
service.setAccessTokenUrl('https://api.twitter.com/oauth/access_token');
service.setRequestTokenUrl('https://api.twitter.com/oauth/request_token');
service.setAuthorizationUrl('https://api.twitter.com/oauth/authorize');
service.setConsumerKey(consumer_key);
service.setConsumerSecret(consumer_secret);
service.setCallbackFunction('authCallback');
service.setPropertyStore(PropertiesService.getScriptProperties());
return service;
}
function showSidebar() {
var twitterService = getTwitterService();
if (!twitterService.hasAccess()) {
var authorizationUrl = twitterService.authorize();
var template = HtmlService.createTemplate(
'<a href="<?= authorizationUrl ?>" target="_blank">Authorize</a>. ' +
'Reopen the sidebar when the authorization is complete.');
template.authorizationUrl = authorizationUrl;
var page = template.evaluate();
DocumentApp.getUi().showSidebar(page);
} else {
Logger.log('something went wrong. showSidebar()')
}
}
function authCallback(request) {
var service = getTwitterService();
var isAuthorized = service.handleCallback(request);
if (isAuthorized) {
return HtmlService.createHtmlOutput('Success! You can close this page.');
} else {
return HtmlService.createHtmlOutput('Denied. You can close this page');
}
}
function authRevoke() {
msgPopUp('To revoke authorization, you must go to https://twitter.com/settings/applications and select your bot from the list of installed apps. As a sercurity measure, you cannot revoke access from this sheet.');
}
/*****************
TWEET TIMING~
*****************/
function clearTiming() {
// reset any existing triggers
var triggers = ScriptApp.getProjectTriggers();
for (var i = 0; i < triggers.length; i++) {
ScriptApp.deleteTrigger(triggers[i]);
}
}
//calls makeSingleTweet function on a timer. Makes sense!
function setTiming() {
// reset any existing triggers
clearTiming();
var setting = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('settings').getRange('D35').getValue();
switch (setting) {
case "12 hours":
var trigger = ScriptApp.newTrigger("makeSingleTweet")
.timeBased()
.everyHours(12)
.create();
break;
case "8 hours":
ScriptApp.newTrigger("makeSingleTweet")
.timeBased()
.everyHours(8)
.create();
break;
case "6 hours":
ScriptApp.newTrigger("makeSingleTweet")
.timeBased()
.everyHours(6)
.create();
break;
case "4 hours":
ScriptApp.newTrigger("makeSingleTweet")
.timeBased()
.everyHours(4)
.create();
break;
case "2 hours":
ScriptApp.newTrigger("makeSingleTweet")
.timeBased()
.everyHours(2)
.create();
break;
case "1 hour":
ScriptApp.newTrigger("makeSingleTweet")
.timeBased()
.everyHours(1)
.create();
break;
case "30 minutes":
ScriptApp.newTrigger("makeSingleTweet")
.timeBased()
.everyMinutes(30)
.create();
break;
case "15 minutes":
ScriptApp.newTrigger("makeSingleTweet")
.timeBased()
.everyMinutes(15)
.create();
break;
case "10 minutes":
ScriptApp.newTrigger("makeSingleTweet")
.timeBased()
.everyMinutes(10)
.create();
break;
case "5 minutes":
ScriptApp.newTrigger("makeSingleTweet")
.timeBased()
.everyMinutes(5)
.create();
break;
default:
Logger.log('I\'m sorry, but I couldn\'t understand what you were asking.');
}
ScriptApp.newTrigger("makeReply")
.timeBased()
.everyMinutes(5)
.create();
Logger.log(trigger);
}
/*****************
ONE TWEET
*****************/
//grabs a tweet! This is invoked when you hit Send a test tweet and by the spreadsheet on the timer you set.
function makeSingleTweet() {
var tweet = getEbooksText();
doTweet(tweet);
}
//sends the tweet!
function doTweet(tweet) {
var service = getTwitterService();
if (service.hasAccess()) {
var status = 'https://api.twitter.com/1.1/statuses/update.json';
var payload = "status=" + getEbooksText();
} else {
var authorizationUrl = service.authorize();
msgPopUp('<p>Please visit the following URL and then re-run "Send a Test Tweet": <br/> <a target="_blank" href="' + authorizationUrl + '">' + authorizationUrl + '</a></p>');
}
var parameters = {
"method": "POST",
"escaping": false,
"payload": payload
};
try {
var result = service.fetch('https://api.twitter.com/1.1/statuses/update.json', parameters);
//Logger.log(result.getContentText());
} catch (e) {
Logger.log(e.toString());
}
}
function makeReply() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('settings');
var username = sheet.getRange('D8').getValue();
var service = getTwitterService();
if (service.hasAccess()) {
var search = ('https://api.twitter.com/1.1/search/tweets.json?q=to%3A' + username);
} else {
var authorizationUrl = service.authorize();
msgPopUp('<p>Please visit the following URL and then re-run "Send a Test Tweet": <br/> <a target="_blank" href="' + authorizationUrl + '">' + authorizationUrl + '</a></p>');
}
var parameters = {
"method": "GET",
"result_type": "recent"
}
var results = service.fetch(search, parameters);
var json = results.getContentText();
var data = JSON.parse(json);
var user = data.statuses[0].user.screen_name;
var id = data.statuses[0].id_str;
var check = sheet.getRange('D40').getValue(); //gets id to reference
var re = new RegExp(id, 'g');
if (check.match(re)) {
Logger.log('already replied to @' + user);
} else {
doReply(user, id);
Logger.log(user + ' ' + id);
var log = Logger.getLog();
sheet.getRange('D40').setValue(log); //logs new id
Logger.log('i will reply to @' + user);
}
}
//sends reply
function doReply(user, id) {
var mention = '@' + user + ' ';
var service = getTwitterService();
if (service.hasAccess()) {
var status = 'https://api.twitter.com/1.1/statuses/update.json';
var payload = "status=" + mention + getEbooksText() + "&in_reply_to_status_id=" + id;
} else {
var authorizationUrl = service.authorize();
msgPopUp('<p>Please visit the following URL and then re-run "Send a Test Tweet": <br/> <a target="_blank" href="' + authorizationUrl + '">' + authorizationUrl + '</a></p>');
}
var parameters = {
"method": "POST",
"escaping": false,
"payload": payload
}
try {
var result = service.fetch('https://api.twitter.com/1.1/statuses/update.json', parameters);
//Logger.log(result.getContentText());
} catch (e) {
Logger.log(e.toString());
}
}
/*****************
STYLES POPUP MSG
*****************/
function msgPopUp(msg) {
var content = '<div style="font-family: Verdana;font-size: 22px; text-align:left; width: 95%; margin: 0 auto;">' + msg + '</div>';
var htmlOutput = HtmlService
.createHtmlOutput(content)
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setWidth(600)
.setHeight(500);
SpreadsheetApp.getUi().showModalDialog(htmlOutput, ' ');
}