LoginSignup
2

More than 1 year has passed since last update.

Rustで簡単にDiscordBotを動かしてみる

Last updated at Posted at 2021-11-30

自己紹介

  • 名前:牛島涼介

  • 趣味:ゲーム(LOL, Steam, PS4)

  • 所属:ユニークビジョン株式会社(半年)

  • 半年前に仕事でRustを触り始めました

  • 前職ではC言語を書いてました


Discordとは

  • 音声のコミュニケーションツール

  • 軽くて簡易的に配信ができる代物

  • ボットなどのアプリケーションが作りやすいようにアクセストークンが簡単に手に入る

  • チャンネルとメッセージの既読情報を追跡する「Read States」をRust言語で実装している

    https://discord.com/blog/why-discord-is-switching-from-go-to-rust


使用するライブラリとアクセストークン

  • Rust製のDiscordBot用ライブラリ cerenity を使用

  • Discordのアクセストークンが必要となる

  • exampleがあり、Botがすぐ動かせる

アクセストークンを取得

  1. 開発者用のページからアプリケーションを作成

  2. その後、BOTタブからBOTを作成

  3. Oauth2からURL Generatorを選択

  4. botにチェックを入れ、URLをコピー

  5. コピーしたURLにアクセスし、サーバー選択 + 認証で紐づけ完了


cerenityのpingpongを動かす

$ export DISCORD_TOKEN=xxxxxxxxxx
$ git clone https://github.com/serenity-rs/serenity.git
$ cd serenity/examples/e01_basic_ping_bot
$ cargo run

実行結果
image.png


pingpongBotを変更

メッセージを返信している個所
    async fn message(&self, ctx: Context, msg: Message) {
        if msg.content == "!ping" {
            // Sending a message can fail, due to a network error, an
            // authentication error, or lack of permissions to post in the
            // channel, so log to stdout when some error happens, with a
            // description of it.
            if let Err(why) = msg.channel_id.say(&ctx.http, "Pong!").await {
                println!("Error sending message: {:?}", why);
            }
        }
    }

pingpongBotを変更

メッセージを追加
    async fn message(&self, ctx: Context, msg: Message) {
        if msg.content == "!ping" {
            // Sending a message can fail, due to a network error, an
            // authentication error, or lack of permissions to post in the
            // channel, so log to stdout when some error happens, with a
            // description of it.
            if let Err(why) = msg.channel_id.say(&ctx.http, "Pong!").await {
                println!("Error sending message: {:?}", why);
            }
        }
        if msg.content == "!hi" {
            // Sending a message can fail, due to a network error, an
            // authentication error, or lack of permissions to post in the
            // channel, so log to stdout when some error happens, with a
            // description of it.
            if let Err(why) = msg.channel_id.say(&ctx.http, "Hi, I'm TestApp!").await {
                println!("Error sending message: {:?}", why);
            }
        }
    }

実行結果

image.png


まとめ

  • DiscordのBotを簡単に動かせる

  • exampleから出力する文字列やデータを変更することで、表示も変えられる

  • 自由に関数が加えられるので、別のAPIと連携して何かアプリを作ったりもできる


参考文献

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
2