pikadick/commands/tic_tac_toe/
board.rs

1use crate::{
2    checks::ENABLED_CHECK,
3    ClientDataKey,
4};
5use serenity::{
6    builder::{
7        CreateAttachment,
8        CreateMessage,
9    },
10    client::Context,
11    framework::standard::{
12        macros::command,
13        Args,
14        CommandResult,
15    },
16    model::prelude::*,
17};
18use tracing::error;
19
20#[command]
21#[description("Print the current Tic-Tac-Toe board")]
22#[usage("")]
23#[example("")]
24#[min_args(0)]
25#[max_args(0)]
26#[bucket("ttt-board")]
27#[checks(Enabled)]
28pub async fn board(ctx: &Context, msg: &Message, _args: Args) -> CommandResult {
29    let data_lock = ctx.data.read().await;
30    let client_data = data_lock
31        .get::<ClientDataKey>()
32        .expect("missing client data");
33    let tic_tac_toe_data = client_data.tic_tac_toe_data.clone();
34    let db = client_data.db.clone();
35    drop(data_lock);
36
37    let guild_id = msg.guild_id;
38    let author_id = msg.author.id;
39
40    match db
41        .get_tic_tac_toe_game(guild_id.into(), author_id.into())
42        .await
43    {
44        Ok(Some(game)) => {
45            let file = match tic_tac_toe_data
46                .renderer
47                .render_board_async(game.board)
48                .await
49            {
50                Ok(file) => {
51                    CreateAttachment::bytes(file, format!("ttt-{}.png", game.board.encode_u16()))
52                }
53                Err(error) => {
54                    error!("Failed to render Tic-Tac-Toe board: {error}");
55                    msg.channel_id
56                        .say(
57                            &ctx.http,
58                            format!("Failed to render Tic-Tac-Toe board: {error}"),
59                        )
60                        .await?;
61                    return Ok(());
62                }
63            };
64            let message_builder = CreateMessage::new().add_file(file);
65            msg.channel_id
66                .send_message(&ctx.http, message_builder)
67                .await?;
68        }
69        Ok(None) => {
70            let response = "Failed to print board as you have no games in this server".to_string();
71            msg.channel_id.say(&ctx.http, response).await?;
72            return Ok(());
73        }
74        Err(error) => {
75            error!("{error:?}");
76            msg.channel_id.say(&ctx.http, "database error").await?;
77        }
78    };
79
80    Ok(())
81}