forked from karx/dircord
store Http and ChannelId globally
This commit is contained in:
parent
3d3921cf04
commit
e8d4b9adac
36
src/main.rs
36
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;
|
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]
|
#[tokio::main]
|
||||||
async fn main() -> anyhow::Result<()> {
|
async fn main() -> anyhow::Result<()> {
|
||||||
let token = env::var("DISCORD_TOKEN").expect("DISCORD_TOKEN not set");
|
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 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?;
|
client.start().await?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn send_message(client: &Client, channel_id: &ChannelId, content: &str) -> anyhow::Result<Message> {
|
async fn send_message(http: &Http, channel_id: &ChannelId, content: &str) -> anyhow::Result<Message> {
|
||||||
let http = client.cache_and_http.http();
|
|
||||||
|
|
||||||
Ok(channel_id.say(http, content).await?)
|
Ok(channel_id.say(http, content).await?)
|
||||||
}
|
}
|
Loading…
Reference in a new issue