C++ wrapper for the Mastodon API
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

example09_streaming_api.cpp 1.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /* This file is part of mastodon-cpp.
  2. * Streaming API example
  3. */
  4. #include <iostream>
  5. #include <string>
  6. #include <cstdint>
  7. #include <thread>
  8. #include <chrono>
  9. #include <memory>
  10. #include <mutex>
  11. #ifdef MASTODON_CPP
  12. #include "mastodon-cpp.hpp"
  13. #else
  14. #include <mastodon-cpp/mastodon-cpp.hpp>
  15. #endif
  16. using Mastodon::API;
  17. int main(int argc, char *argv[])
  18. {
  19. if (argc < 3)
  20. {
  21. std::cerr << "usage: " << argv[0] << " <instance> <access_token>\n";
  22. return 1;
  23. }
  24. static std::string answer;
  25. static std::unique_ptr<Mastodon::API::http> ptr;
  26. std::cout << "Dumping public timeline...\n";
  27. std::thread pub([=]
  28. {
  29. Mastodon::API masto(argv[1], argv[2]);
  30. masto.set_useragent("mastodon-cpp-example/1.3.3.7");
  31. masto.get_stream(API::v1::streaming_public, answer, ptr);
  32. });
  33. std::uint8_t counter = 0;
  34. while (true)
  35. {
  36. std::this_thread::sleep_for(std::chrono::seconds(2));
  37. if (ptr != nullptr)
  38. {
  39. std::lock_guard<std::mutex> lock(ptr->get_mutex());
  40. ++counter;
  41. std::cout << answer;
  42. answer.clear();
  43. if (counter == 10)
  44. {
  45. std::cerr << "Cancelling...\n";
  46. ptr->cancel_stream();
  47. break;
  48. }
  49. }
  50. }
  51. pub.join();
  52. std::cout << '\n';
  53. std::cout << "Dumping the #np tag...\n";
  54. answer = "";
  55. std::thread tag([=]
  56. {
  57. Mastodon::API masto(argv[1], argv[2]);
  58. masto.set_useragent("mastodon-cpp-example/1.3.3.7");
  59. masto.get_stream(API::v1::streaming_hashtag, {{ "hashtag", {"np"} }},
  60. answer, ptr);
  61. });
  62. std::this_thread::sleep_for(std::chrono::seconds(20));
  63. ptr->cancel_stream();
  64. std::cout << answer;
  65. std::cout << '\n';
  66. tag.join();
  67. return 0;
  68. }