about summary refs log tree commit diff stats
path: root/ebooks.cpp
blob: 3918b78c5ef3986df7b20f8480c415bdef730291 (plain) (blame)
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
#include <cstdio>
#include <list>
#include <map>
#include "kgramstats.h"
#include <fstream>
#include <iostream>
#include <twitter.h>
#include <yaml-cpp/yaml.h>
#include <thread>
#include <chrono>
#include <algorithm>
#include <random>

const auto QUEUE_TIMEOUT = std::chrono::minutes(1);
const auto POLL_TIMEOUT = std::chrono::minutes(5);

int main(int argc, char** args)
{
  std::random_device randomDevice;
  std::mt19937 rng(randomDevice());

  YAML::Node config = YAML::LoadFile("config.yml");
  int delay = config["delay"].as<int>();

  twitter::auth auth(
    config["consumer_key"].as<std::string>(),
    config["consumer_secret"].as<std::string>(),
    config["access_key"].as<std::string>(),
    config["access_secret"].as<std::string>());

  twitter::client client(auth);

  std::ifstream infile(config["corpus"].as<std::string>().c_str());
  std::string corpus;
  std::string line;
  while (getline(infile, line))
  {
    if (line.back() == '\r')
    {
      line.pop_back();
    }

    corpus += line + "\n";
  }

  // Replace old-style freevars while I can't be bothered to remake the corpus yet
  std::vector<std::string> fv_names;
  std::ifstream namefile("names.txt");
  if (namefile.is_open())
  {
    while (!namefile.eof())
    {
      std::string l;
      getline(namefile, l);
      if (l.back() == '\r')
      {
        l.pop_back();
      }

      fv_names.push_back(l);
    }
  }

  namefile.close();

  std::cout << "Preprocessing corpus..." << std::endl;
  rawr kgramstats;
  kgramstats.addCorpus(corpus);
  kgramstats.compile(5);
  kgramstats.setTransformCallback([&] (std::string, std::string form) {
    size_t pos = form.find("$name$");
    if (pos != std::string::npos)
    {
      int fvInd = std::uniform_int_distribution<int>(0, fv_names.size()-1)(rng);
      form.replace(pos, 6, fv_names[fvInd]);
    }

    return form;
  });

  std::list<std::tuple<std::string, bool, twitter::tweet_id>> postQueue;

  auto startedTime = std::chrono::system_clock::now();

  auto queueTimer = std::chrono::system_clock::now();
  auto pollTimer = std::chrono::system_clock::now();
  auto genTimer = std::chrono::system_clock::now();

  for (;;)
  {
    auto currentTime = std::chrono::system_clock::now();

    if (currentTime >= genTimer)
    {
      std::string doc = kgramstats.randomSentence(140, rng);
      doc.resize(140);

      postQueue.emplace_back(std::move(doc), false, 0);

      int genwait = std::uniform_int_distribution<int>(1, delay)(rng);

      genTimer = currentTime + std::chrono::seconds(genwait);
    }

    if (currentTime >= pollTimer)
    {
      pollTimer = currentTime;

      try
      {
        std::list<twitter::tweet> newTweets =
          client.getMentionsTimeline().poll();

        for (const twitter::tweet& tweet : newTweets)
        {
          auto createdTime =
            std::chrono::system_clock::from_time_t(tweet.getCreatedAt());

          if (
            // Ignore tweets from before the bot started up
            createdTime > startedTime
            // Ignore retweets
            && !tweet.isRetweet()
            // Ignore tweets from yourself
            && tweet.getAuthor() != client.getUser())
          {
            std::string doc = tweet.generateReplyPrefill(client.getUser());
            doc += kgramstats.randomSentence(140 - doc.length(), rng);
            doc.resize(140);

            postQueue.emplace_back(std::move(doc), true, tweet.getID());
          }
        }
      } catch (const twitter::rate_limit_exceeded&)
      {
        // Wait out the rate limit (10 minutes here and 5 below = 15).
        pollTimer += std::chrono::minutes(10);
      } catch (const twitter::twitter_error& e)
      {
        std::cout << "Twitter error while polling: " << e.what() << std::endl;
      }

      pollTimer += std::chrono::minutes(POLL_TIMEOUT);
    }

    if ((currentTime >= queueTimer) && (!postQueue.empty()))
    {
      auto post = postQueue.front();
      postQueue.pop_front();

      try
      {
        if (std::get<1>(post))
        {
          client.replyToTweet(std::get<0>(post), std::get<2>(post));
        } else {
          client.updateStatus(std::get<0>(post));
        }
      } catch (const twitter::twitter_error& error)
      {
        std::cout << "Twitter error while tweeting: " << error.what()
          << std::endl;
      }

      queueTimer = currentTime + std::chrono::minutes(QUEUE_TIMEOUT);
    }

    auto soonestTimer = genTimer;

    if (pollTimer < soonestTimer)
    {
      soonestTimer = pollTimer;
    }

    if ((queueTimer < soonestTimer) && (!postQueue.empty()))
    {
      soonestTimer = queueTimer;
    }

    int waitlen =
      std::chrono::duration_cast<std::chrono::seconds>(
        soonestTimer - currentTime).count();

    if (waitlen == 1)
    {
      std::cout << "Sleeping for 1 second..." << std::endl;
    } else if (waitlen < 60)
    {
      std::cout << "Sleeping for " << waitlen << " seconds..." << std::endl;
    } else if (waitlen == 60)
    {
      std::cout << "Sleeping for 1 minute..." << std::endl;
    } else if (waitlen < 60*60)
    {
      std::cout << "Sleeping for " << (waitlen/60) << " minutes..."
        << std::endl;
    } else if (waitlen == 60*60)
    {
      std::cout << "Sleeping for 1 hour..." << std::endl;
    } else if (waitlen < 60*60*24)
    {
      std::cout << "Sleeping for " << (waitlen/60/60) << " hours..."
        << std::endl;
    } else if (waitlen == 60*60*24)
    {
      std::cout << "Sleeping for 1 day..." << std::endl;
    } else {
      std::cout << "Sleeping for " << (waitlen/60/60/24) << " days..."
        << std::endl;
    }

    std::this_thread::sleep_until(soonestTimer);
  }

  return 0;
}