iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
😽

Creating a Discord Game Bot with Rust

に公開
2020/12/07

This article is for Day 6 of the Mie University Computing Research Group Advent Calendar 2020.

Background / Overview

I created a game using a Discord bot in Rust for our club members, so I'd like to talk about the crates I used and my impressions of the process.

The inspiration came from a conversation with club members about how we couldn't meet in person, which led to a discussion about a "Ricochet Robots" bot. I ended up making the first version in one burst of energy until morning. As a result, people have played it quite a bit (2,718 problems solved out of a stock of about 650,000 so far), which makes me very happy. I almost ended up destroying a few people's exam studies. It was fun seeing others making their own game bots as well.

serenity (0.9.2)

docs.rs: https://docs.rs/serenity/0.9.2/serenity/
examples: https://github.com/serenity-rs/serenity/tree/current/examples

I used a crate called serenity for handling Discord bot operations.
It allows for an event-driven style of writing, as shown in the code below.
You can store things like DB connection pools inside a struct that implements serenity::client::EventHandler (in the code below, it's stored in Handler).

#[async_trait]
impl EventHandler for Handler {
    // Processing when a message is posted
    async fn message(&self, ctx: Context, msg: Message) {
        // Prevent reacting to other bots
        if msg.author.bot {
            return;
        }
	// Server ID
        eprintln!("guild_id = {:?}", msg.guild_id);
	// Channel name
        let channel_name = msg.channel_id.name(&ctx.cache).await;
        eprintln!("channel_name = {:?}", channel_name);
	// Sending a message
	let content = "Hello, world";
	if let Err(why) = msg.channel_id.say(&ctx.http, content).await {
	    println!("Error sending message: {:?}", why);
	}
        eprintln!();
    }

    // Processing when the bot goes online
    async fn ready(&self, _: Context, ready: Ready) {
        println!("{} is connected!", ready.user.name);
    }
    
    // There are many other events; since there are default implementations, you only need to implement what you need.
}

One thing to note is that serenity::async_trait (originally the async-trait crate) is used since async traits cannot be written directly at this time. Also, it uses tokio 0.2.

The example code is very helpful when using this crate.

sqlx (0.4.1)

docs.rs: https://docs.rs/sqlx/0.4.1/sqlx/
repository (README.md): https://github.com/launchbadge/sqlx
examples: https://github.com/launchbadge/sqlx/tree/master/examples

SQL queries are checked at compile time (by actually accessing the server). It's amazing.
Support for databases other than PostgreSQL seems to be still in development, so using PostgreSQL for the DB appears to be the best choice.

The Quickstart in the repository's README.md is a good reference for using this crate. The README.md is also helpful for configuring features.

The most common way I wrote queries was using query_as! like the following. Besides fetch_one, there are also fetch, fetch_all, etc.

struct NumProblems {
    max: Option<i32>,
}
let res = sqlx::query_as!(
    NumProblems,
    "SELECT max(id) FROM ricochet_robots_problems"
).fetch_one(pool).await?;
struct Problem {
   // ...
}
let res = sqlx::query_as!(
    Problem,
    "SELECT * FROM ricochet_robots_problems WHERE id = $1",
    id
).fetch_one(pool).await?;

sqlx-cli

README.md: https://github.com/launchbadge/sqlx/tree/master/sqlx-cli

A CLI is provided for managing migrations and other tasks when using sqlx. Installation and usage instructions are in the README.md.

ron (0.6.2)

docs.rs: https://docs.rs/ron/0.6.2/ron/

This is a type of serialization representation that can be used with serde. It is written in a Rust-like syntax. While it was nice to be able to store data in the DB as strings that are still human-readable, JSON would probably suffice if you aren't writing it by hand. If you do write it manually, being able to include comments seems like a benefit.

png (0.16.7)

docs.rs: https://docs.rs/png/0.16.7/png/index.html

A crate that allows creating images in PNG format. You can create images by specifying RGBA values.

The program on the top page of docs.rs is helpful when using this crate.

gif (0.11.1)

docs.rs: https://docs.rs/gif/0.11.1/gif/

A crate that allows creating GIFs.

As a point of caution, when creating a Frame, the functions described in the documentation as "Note: This method is not optimized for speed" are really slow. If the number of colors used is small, you can encode quickly by passing a palette to gif::Encoder::new and using the colors provided in that palette with gif::Frame::from_indexed_pixels.

Other than that, the program on the top page of docs.rs serves as a good reference.

By the way, I recall that when posting to Discord, GIFs didn't have anti-aliasing applied. Therefore, I now convert them to mp4 before posting.

fnv (1.0.7)

docs.rs: https://docs.rs/fnv/1.0.7/fnv/

This crate provides a Map/Set that is faster than the standard HashMap/HashSet when the key size is small. One thing to note is that it does not have countermeasures against collision attacks. You should probably avoid using it in places where an attacker can control the keys.

Incidentally, if you only use u64 as a key, I recall it being faster to create a custom implementation of the std::hash::Hasher trait that simply uses the value as the hash without further manipulation. In this project, since the key itself was a hash value, I ultimately did not use fnv. If you want to implement your own Hasher, you might find the source code of fnv helpful as a reference.

Impressions

  • I gained a bit of an understanding of how to use async in Rust.
  • Not being able to await while holding a Mutex lock is a trap—or rather, it's impressive that this can be caught properly at compile time.
  • The number of files under src/bin kept increasing indefinitely; I wonder which is better: splitting files by functionality or splitting functionality via command-line arguments.
  • Keeping the DB data in a usable state even after updates was about 100 times harder than I imagined.
  • This project prompted me to take the Database Specialist examination, but I failed miserably.
  • 2,718 problems—that's a nice round number (e).
  • optimal (not optimal).
  • To avoid destroying my daily life, I made it stop running from midnight to 7:00 AM, but since it's easier to perform maintenance during those hours, my own life was destroyed anyway (lol).

Bonus

Here are a few problems that were quite difficult.

Probably 18 moves minimum

Probably 19 moves minimum

Probably 33 moves minimum

Discussion