#clash #api #supercell #clash-of-clans #coc

coc-rs

A Rust crate wrapper around the Clash of Clans public API

55 releases (5 breaking)

Uses new Rust 2021

0.6.9 Sep 16, 2022
0.6.8 Sep 10, 2022
0.5.9 Sep 6, 2022
0.4.9 Sep 3, 2022
0.1.9 Aug 26, 2022

#29 in HTTP client

Download history 452/week @ 2022-08-25 472/week @ 2022-09-01 394/week @ 2022-09-08 173/week @ 2022-09-15 82/week @ 2022-09-22

1,157 downloads per month

MIT license

185KB
4.5K SLoC

coc.rs

A Clash of Clans API wrapper written in rust!

Key feature

  • Asynchronous code
  • Entire coverage of Clash of clans API
  • Email and Password Login
  • Multiple Accounts Login to handle concurrent requests
  • API Events!
  • Clash of Stats support

Getting Started

Installing

Add the version from here in your Cargo.toml

[dependencies]
coc-rs = "x.x.x"

Alternatively with cargo add

$ cargo add coc-rs

Quick Example

#[tokio::main]
async fn main() {
    let credentials = CredentialsBuilder::new()
        .add_credential(env::var("username").unwrap(), env::var("password").unwrap())
        .build();
    let client = Client::new(credentials).await;

    let player = client.get_player("#2PP".to_string()).await.unwrap();

    println!("Player: {:?}", player);
}

How to Handle Errors

#[tokio::main]
async fn main() {
    let credentials = CredentialsBuilder::new()
        .add_credential(env::var("username").unwrap(), env::var("password").unwrap())
        .build();
    let client = Client::new(credentials).await;

    let clan = match client.get_clan("#IncorrectTag".to_string()).await {
        Ok(c) => {
            println!("Clan: {:?}", clan);
        }
        Err(err) => {
            match err {
                APIError::BadRequest(err) => {} // caused when a BadRequest is made, such as invalid url parameters 
                APIError::RequestFailed(err) => {} // Request never made it to the API
                APIError::BadResponse(msg, code) => {
                    match code {
                        StatusCode::NOT_FOUND => {
                            println!("Player Not found")
                        },
                        _ => {
                            //There are other status code that the api can return in case of error.
                        }
                    }
                } // this is common error you will face and will be expected to handle it almost everytime
                APIError::InvalidParameters(err) => {}
            }
        }
    };
}

Basic Events

First we need to make a Event handler struct, that will implement the trait EventHandler

struct Handler;

#[async_trait]
impl events::EventHandler for S {
    /// Next we bring the player method in scope, and define the behaviour
    async fn player(&self, _old_player: Option<player::Player>, _new_player: player::Player) {
        println!("new player")
    }

    ///  to handle errors in the events task we need a separate error handler
    async fn handle_error(
        &self,
        _error: APIError,
        _tag: Option<String>,
        _event_type: EventType,
    ) {
        println!("Houston we have a problem!")
    }
}

Next in the main function, we will create the main function, login and add the Player and clan tags we want to keep pulling the data from API.

#[tokio::test]
async fn main() {
    //...
    /// see above example on how to create a client

    let task = tokio::spawn(async move {
        /// staring the API events in a separate thread
        let mut x = events::EventsListenerBuilder::new(client);
        x.add_player("#2PP".to_string()).await;
        x.add_players(vec!["#CVJLQOLR".to_string()])
            .await
            .build(Handler) /// Building the eventListener struct 
            .init() /// starting the continuous polling of the clan/player/current_war endpoints
            .await;
    });
    task.await.unwrap();
}

Features

To Enable cos feature, add this to your Cargo.toml

[dependencies]
coc-rs = { version = "x.x.x", features = ["cos"] }
  • Alternately with cargo add
$ cargo add coc-rs --features cos

Note: Each endpoint has a different cache refresh time. Each event will be fired at the exact time of new cache data in the API.

Possible Error Code

400 -> BadRequestException
403 -> AuthException
404 -> NotFoundException
429 -> RateLimitException
503 -> MaintenanceException

Note

src/test.rs & src/test_cos.rs contains examples for every endpoint in more detail.

Contributing

Contributing is fantastic and much welcomed! If you have an issue, feel free to open an issue and start working on it.

Disclaimer

This content is not affiliated with, endorsed, sponsored, or specifically approved by Supercell and Supercell is not responsible for it. For more information see Supercell'S Fan Content Policy.

Dependencies

~9–18MB
~358K SLoC