From e8d4b9adac14fbc63e9aa0c9700a4c784d15a39f Mon Sep 17 00:00:00 2001 From: Yash Karandikar Date: Sun, 26 Dec 2021 15:35:49 -0600 Subject: [PATCH] store Http and ChannelId globally --- src/main.rs | 36 ++++++++++++++++++++++++++++++------ 1 file changed, 30 insertions(+), 6 deletions(-) diff --git a/src/main.rs b/src/main.rs index 81aabc6..6ae8fba 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,6 @@ -use std::env; +use std::{env, sync::Arc}; -use serenity::{prelude::*, async_trait, model::{channel::Message, id::ChannelId}, http::CacheHttp}; +use serenity::{prelude::*, async_trait, model::{channel::Message, id::ChannelId}, http::Http}; struct Handler; @@ -18,10 +18,30 @@ impl EventHandler for Handler { } }; - msg.channel_id.say(&ctx, format!("{}: {}", nick, msg.content)).await.unwrap(); + let (http, channel_id) = { + let data = ctx.data.read().await; + + let http = data.get::().unwrap().to_owned(); + let channel_id = data.get::().unwrap().to_owned(); + + (http, channel_id) + }; + + send_message(&http, &channel_id, &format!("{}: {}", nick, msg.content)).await.unwrap(); } } +struct HttpKey; +struct ChannelIdKey; + +impl TypeMapKey for HttpKey { + type Value = Arc; +} + +impl TypeMapKey for ChannelIdKey { + type Value = ChannelId; +} + #[tokio::main] async fn main() -> anyhow::Result<()> { let token = env::var("DISCORD_TOKEN").expect("DISCORD_TOKEN not set"); @@ -32,13 +52,17 @@ async fn main() -> anyhow::Result<()> { let channel_id = ChannelId(831255708875751477); + { + let mut data = client.data.write().await; + data.insert::(client.cache_and_http.http.clone()); + data.insert::(channel_id); + } + client.start().await?; Ok(()) } -async fn send_message(client: &Client, channel_id: &ChannelId, content: &str) -> anyhow::Result { - let http = client.cache_and_http.http(); - +async fn send_message(http: &Http, channel_id: &ChannelId, content: &str) -> anyhow::Result { Ok(channel_id.say(http, content).await?) } \ No newline at end of file