はじめに
mastodon-cppというC++からMastodon APIをよしなにしてくれるライブラリがあったので使ってみた。
その時のあれこれをまとめたもの
使ったもの
- Google Computer Engine(Ubuntu 18.04LTS)
- mastodon-cpp
mastodon-cpp のインストール
curl/curlpp/jsoncpp のインストール
mastodon-cppではcurl/curlpp/jsoncppを使用しているので、それらをまずはインストール
sudo apt install libcurl-dev libcurlpp-dev libjsoncpp-dev
mastodon-cpp のインストール
まずはソースコードをclone
git clone https://schlomp.space/tastytea/mastodon-cpp.git
ディレクトリを移動して、build
ディレクトリを作成する。
cd mastodon-cpp
mkdir build
build
ディレクトリに移動し、mastodon-cppをインストール
cmake ..
make
make install
これで mastodon-cpp が使用できるようになる
実際のコード
mastodon-cppのサンプルコードを参考に以下のコードを書いてみた。
toot.cpp
/* This file is part of mastodon-cpp.
* Post a status, then delete it.
*/
#include <iostream>
#include <vector>
#include <string>
#include <cstdint>
#include <chrono>
#include <thread>
#ifdef MASTODON_CPP
#include "mastodon-cpp.hpp"
#else
#include <mastodon-cpp/mastodon-cpp.hpp>
#endif
using Mastodon::API;
int main(int argc, char *argv[])
{
if (argc < 3)
{
std::cerr << "usage: " << argv[0] << " <instance> <access token>\n";
return 1;
}
Mastodon::API masto(argv[1], argv[2]);
masto.set_useragent("mastodon-cpp-example/1.3.3.7");
std::string answer;
std::uint16_t ret;
std::string toot;
std::string id;
std::cout << "Toot: ";
std::cin >> toot;
API::parametermap parameters =
{
{ "status", { toot } },
{ "visibility", { "unlisted" } }
};
ret = masto.post(API::v1::statuses, parameters, answer);
return 0;
}
コンパイルした後は、TootしたいMastodonインスタンスからアクセストークンを取得してくる。
最後に、以下のように実行するだけ
./a.out <MastodonインスタンスのURL> <アクセストークン>
おわりに
C++からMastodonへTootできるようになったので、cvuiとか使ってC++でMastodonクライアントとか作れそうかもね