dircord/src/main.rs

97 lines
2.2 KiB
Rust
Raw Normal View History

2021-12-26 15:35:49 -06:00
use std::{env, sync::Arc};
2021-12-26 15:13:09 -06:00
2021-12-26 16:05:53 -06:00
use serenity::{
async_trait,
http::Http,
model::{
channel::Message,
id::{ChannelId, UserId},
prelude::Ready,
},
prelude::*,
};
2021-12-26 15:13:09 -06:00
struct Handler;
#[async_trait]
impl EventHandler for Handler {
async fn message(&self, ctx: Context, msg: Message) {
let nick = {
if let Some(member) = msg.member {
match member.nick {
Some(n) => n,
2021-12-26 16:05:53 -06:00
None => msg.author.name,
2021-12-26 15:13:09 -06:00
}
} else {
msg.author.name
}
};
2021-12-26 16:05:53 -06:00
let (http, channel_id, user_id) = {
2021-12-26 15:35:49 -06:00
let data = ctx.data.read().await;
let http = data.get::<HttpKey>().unwrap().to_owned();
let channel_id = data.get::<ChannelIdKey>().unwrap().to_owned();
2021-12-26 16:05:53 -06:00
let user_id = data.get::<UserIdKey>().unwrap().to_owned();
2021-12-26 15:35:49 -06:00
2021-12-26 16:05:53 -06:00
(http, channel_id, user_id)
2021-12-26 15:35:49 -06:00
};
2021-12-27 10:25:42 -06:00
if user_id != msg.author.id && !msg.author.bot {
2021-12-26 16:05:53 -06:00
send_message(&http, &channel_id, &format!("{}: {}", nick, msg.content))
.await
.unwrap();
}
}
async fn ready(&self, ctx: Context, info: Ready) {
let id = info.user.id;
let mut data = ctx.data.write().await;
data.insert::<UserIdKey>(id);
2021-12-26 15:13:09 -06:00
}
2021-12-26 14:04:47 -06:00
}
2021-12-26 15:13:09 -06:00
2021-12-26 15:35:49 -06:00
struct HttpKey;
struct ChannelIdKey;
2021-12-26 16:05:53 -06:00
struct UserIdKey;
2021-12-26 15:35:49 -06:00
impl TypeMapKey for HttpKey {
type Value = Arc<Http>;
}
impl TypeMapKey for ChannelIdKey {
type Value = ChannelId;
}
2021-12-26 16:05:53 -06:00
impl TypeMapKey for UserIdKey {
type Value = UserId;
}
2021-12-26 15:13:09 -06:00
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let token = env::var("DISCORD_TOKEN").expect("DISCORD_TOKEN not set");
2021-12-26 16:05:53 -06:00
let mut client = Client::builder(&token).event_handler(Handler).await?;
2021-12-26 15:13:09 -06:00
let channel_id = ChannelId(831255708875751477);
2021-12-26 15:35:49 -06:00
{
let mut data = client.data.write().await;
data.insert::<HttpKey>(client.cache_and_http.http.clone());
data.insert::<ChannelIdKey>(channel_id);
}
2021-12-26 15:13:09 -06:00
client.start().await?;
Ok(())
}
2021-12-26 16:05:53 -06:00
async fn send_message(
http: &Http,
channel_id: &ChannelId,
content: &str,
) -> anyhow::Result<Message> {
2021-12-26 15:13:09 -06:00
Ok(channel_id.say(http, content).await?)
2021-12-26 16:05:53 -06:00
}