-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathchatbot.js
104 lines (96 loc) · 2.84 KB
/
chatbot.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
const Twit = require('twit')
const { Configuration, OpenAIApi } = require('openai')
const { tweetTopics } = require('./tweetTopics')
require('dotenv').config()
const twitter = new Twit({
consumer_key: process.env.TWITTER_API_KEY,
consumer_secret: process.env.TWITTER_API_SECRET,
access_token: process.env.TWITTER_ACCESS_TOKEN,
access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET,
timeout_ms: 60 * 1000,
strictSSL: false,
})
const configuration = new Configuration({
apiKey: process.env.OPEN_AI_SECRET,
})
const openai = new OpenAIApi(configuration)
// Use open ai to create a tweet on a given topic
function postTweet() {
let tweet
// Generate a random topic for a tweet
function randomTopic() {
let randomNum = Math.floor(Math.random() * tweetTopics.length)
return `You are a smart twitter bot that sends quality tweets. Generate a unique tweet about ${tweetTopics[randomNum]} without hashtags.`
}
async function runCompletion() {
const completion = await openai.createCompletion({
model: 'text-davinci-003',
prompt: randomTopic(), // Pass randomTopic() to chatgpts prompt
max_tokens: 200,
})
// Store the result as a tweet
tweet = completion.data.choices[0].text
}
// Function to post our tweet
function postTweet() {
twitter.post(
'statuses/update',
{
status: tweet, // Pass in generated tweet as the status
},
(err, data, response) => {
if (err) {
console.log(err)
} else {
console.log('Posted tweet: ', tweet)
}
}
)
}
// Wait for the tweet, then post it
runCompletion().then(() => {
postTweet()
})
}
console.log('Running task...')
// Search tweets containing a topic and follow that user
function searchAndFollowUser() {
twitter.get(
'search/tweets',
{
q: 'apexlegends', // Change the query to be any tweet you want to search on twitter
result_type: 'mixed',
},
(err, data, response) => {
if (err) {
console.log(err)
} else {
let randomIndex = Math.floor(Math.random() * data.statuses.length)
let userId = data.statuses[randomIndex].user.id_str
let isEnglishUser =
data.statuses[randomIndex].lang === 'en' ? true : false
if (typeof userId != 'undefined' && isEnglishUser) {
twitter.post(
'friendships/create',
{ id: userId },
(err, data, response) => {
if (err) {
console.log(err)
} else {
console.log(`Followed a random user! with user id ${userId}`)
}
}
)
}
}
}
)
}
// Follow a user every hour, if conditions are met.
setInterval(() => {
searchAndFollowUser()
}, 1000 * 60 * 60)
// Post a tweet every hour
setInterval(() => {
postTweet()
}, 1000 * 60 * 60)