LoginSignup
6
2

More than 5 years have passed since last update.

C++でMastodonへ呟いてみた

Last updated at Posted at 2018-07-24

はじめに

mastodon-cppというC++からMastodon APIをよしなにしてくれるライブラリがあったので使ってみた。

その時のあれこれをまとめたもの

使ったもの

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クライアントとか作れそうかもね

参考

mastodon-cpp

6
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
2