store Http and ChannelId globally

This commit is contained in:
Yash Karandikar 2021-12-26 15:35:49 -06:00
parent 3d3921cf04
commit e8d4b9adac
Signed by untrusted user: karx
GPG key ID: A794DA2529474BA5

View file

@ -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::<HttpKey>().unwrap().to_owned();
let channel_id = data.get::<ChannelIdKey>().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<Http>;
}
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::<HttpKey>(client.cache_and_http.http.clone());
data.insert::<ChannelIdKey>(channel_id);
}
client.start().await?;
Ok(())
}
async fn send_message(client: &Client, channel_id: &ChannelId, content: &str) -> anyhow::Result<Message> {
let http = client.cache_and_http.http();
async fn send_message(http: &Http, channel_id: &ChannelId, content: &str) -> anyhow::Result<Message> {
Ok(channel_id.say(http, content).await?)
}