-
Notifications
You must be signed in to change notification settings - Fork 266
Expand file tree
/
Copy pathmain.cpp
More file actions
62 lines (51 loc) · 2.05 KB
/
Copy pathmain.cpp
File metadata and controls
62 lines (51 loc) · 2.05 KB
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
#include <array>
#include <cstdlib>
#include <exception>
#include <iostream>
#include <memory>
#include <string>
#include <tgbot/tgbot.h>
int main() {
// The proxy URLs below are examples. Replace them with your own.
constexpr std::array<const char*, 4> proxies {
nullptr,
"socks5://user:password@10.20.30.40:1080",
"http://user:password@192.168.50.70:3128",
"http://user:password@192.168.80.90:3128",
};
constexpr auto connectTimeout = 10L;
std::size_t proxyIndex = 0;
const auto token = std::string(std::getenv("TOKEN"));
TgBot::CurlHttpClient curlHttpClient;
TgBot::Bot bot(token, curlHttpClient);
bot.getEvents().onCommand("start", [&bot](std::shared_ptr<TgBot::Message> message) {
bot.getApi().sendMessage(message->chat->id, "Hi!");
});
bot.getEvents().onAnyMessage([&bot](std::shared_ptr<TgBot::Message> message) {
const auto text = message->text.value_or("");
std::cout << "User wrote " << text << std::endl;
if (text.starts_with("/start")) {
return;
}
bot.getApi().sendMessage(message->chat->id, "Your message is: " + text);
});
const auto currentProxyName = [&] {
return proxies[proxyIndex] != nullptr ? proxies[proxyIndex] : "direct";
};
const auto handleError = [&](const std::exception& error) {
std::cout << "Proxy[" << proxyIndex << "] (" << currentProxyName() << ") error: " << error.what() << std::endl;
proxyIndex = (proxyIndex + 1) % proxies.size();
curlHttpClient.setProxy(proxies[proxyIndex], connectTimeout);
std::cout << "Switched to proxy[" << proxyIndex << "] (" << currentProxyName() << ")" << std::endl;
};
try {
std::cout << "Bot username: " << bot.getApi().getMe()->username.value_or("") << std::endl;
bot.getApi().deleteWebhook();
TgBot::TgLongPoll longPoll(bot);
longPoll.startLoop(handleError);
} catch (const std::exception& error) {
handleError(error);
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}