commit 24cfa32bffaa9c4770b6be4dab84333d5fbbc257
parent 46db0392b4ca37cc17e2bfd7fd52829adb1942eb
Author: Jonas Platte <jplatte+git@posteo.de>
Date: Mon, 12 Aug 2019 20:08:50 +0200
Add BotBuilder::state
Diffstat:
2 files changed, 18 insertions(+), 7 deletions(-)
diff --git a/examples/echo.rs b/examples/echo.rs
@@ -11,7 +11,7 @@ use ruma_bot::{command_handler, Bot, BotBuilder, MsgContent, State};
type AppState = Arc<Mutex<HashMap<String, String>>>;
#[command_handler]
-async fn help(bot: Bot, msg_content: MsgContent) -> Fallible<()> {
+async fn help(bot: Bot, msg_content: MsgContent, state: State<AppState>) -> Fallible<()> {
println!("help called!");
Ok(())
@@ -22,15 +22,15 @@ async fn help(bot: Bot, msg_content: MsgContent) -> Fallible<()> {
// Ok(())
//}
-//#[command_handler(command = "fetch {id}")]
-//#[command_handler(command = regex("a(B|CD) (\w+)"))]
-
//#[reaction_handler]
+//async fn handle_reaction(state: State<AppState>) -> Fallible<()> {
+// Ok(())
+//}
#[tokio::main]
async fn main() {
let bot = BotBuilder::new()
- //.state(Arc::new(Mutex::new(HashMap::<String, String>::new())))
+ .state(Arc::new(Mutex::new(HashMap::<String, String>::new())))
.register(help)
.build()
.unwrap();
diff --git a/src/lib.rs b/src/lib.rs
@@ -58,9 +58,10 @@ struct ConnectionDetails {
password: String,
}
-/// A builder that the `Bot` type
+/// A builder for the `Bot` type
pub struct BotBuilder {
handlers: HandlerFnMap,
+ state: AnyMap,
homeserver_url: Option<Url>,
username: Option<String>,
password: Option<String>,
@@ -71,6 +72,7 @@ impl BotBuilder {
pub fn new() -> Self {
Self {
handlers: HashMap::new(),
+ state: AnyMap::new(),
homeserver_url: None,
username: None,
password: None,
@@ -94,6 +96,15 @@ impl BotBuilder {
self
}
+ /// Register some state to be used across calls to event handlers
+ pub fn state<T>(mut self, initial_value: T) -> Self
+ where
+ T: CloneAny + Send + Sync,
+ {
+ self.state.insert(initial_value);
+ self
+ }
+
/// Set the homeserver url (must be an `https` url currently)
///
/// If the homeserver url is not set with this method, `build` will fall back to the environment
@@ -134,7 +145,7 @@ impl BotBuilder {
None,
)?,
handlers: Arc::new(self.handlers),
- state: AnyMap::new(),
+ state: self.state,
connection_details: Some(ConnectionDetails {
username: self
.username