clemsbot/src/app/rhai_tools.rs

97 lines
2.9 KiB
Rust

use crate::app::twitch::Twitch;
use std::sync::Arc;
use twitch_api2::types::{UserId, UserName};
use tokio::runtime::Handle;
use twitch_api2::helix::channels::{GetChannelInformationRequest, ChannelInformation};
#[derive(Default, Clone)]
pub struct ExecutorOutput {
pub to_send: Vec<String>,
}
impl ExecutorOutput {
pub fn send<S: Into<String>>(&mut self, s: S) {
self.to_send.push(s.into());
}
}
#[derive(Clone)]
pub struct ExecutorState {
pub runtime: Handle,
pub twitch: Arc<Twitch>,
pub args: Vec<rhai::Dynamic>,
pub initiator: String,
pub initiator_id: UserId,
// TODO
// pub moderator: bool,
// pub broadcaster: bool,
// pub vip: bool,
}
impl ExecutorState {
// FIXME: make this return &str
pub fn initiator(&mut self) -> String {
self.initiator.clone()
}
pub fn initiator_id(&mut self) -> String {
self.initiator_id.to_string()
}
pub fn args(&mut self) -> rhai::Array {
self.args.clone()
}
async fn internal_get_username(&self, id: UserId) -> Option<String> {
self.twitch.client.helix.get_user_from_id(id, &self.twitch.bot_token)
.await
.ok()?
.map(|user| user.login.to_string())
}
pub fn get_username<S: Into<String>>(&mut self, id: S) -> rhai::Dynamic {
match self.runtime.block_on(self.internal_get_username(UserId::new(id.into()))) {
Some(x) => rhai::Dynamic::from(x),
None => rhai::Dynamic::from(()),
}
}
async fn internal_get_id<S: Into<UserName>>(&self, username: S) -> Option<UserId> {
self.twitch.client.helix.get_user_from_login(username, &self.twitch.bot_token)
.await
.ok()?
.map(|user| user.id)
}
pub fn get_user_id<S: Into<UserName>>(&mut self, username: S) -> rhai::Dynamic {
match self.runtime.block_on(self.internal_get_id(username)).map(|user| user.to_string()) {
Some(x) => rhai::Dynamic::from(x),
None => rhai::Dynamic::from(()),
}
}
async fn internal_get_channel_info<S: Into<UserId>>(&self, id: S) -> Option<(String, String, String)> {
let req = GetChannelInformationRequest::builder()
.broadcaster_id(id.into())
.build();
self.twitch.client.helix.req_get(req, &self.twitch.bot_token)
.await
.ok()?
.data
.map(|info: ChannelInformation| (info.broadcaster_name.to_string(), info.broadcaster_login.to_string(), info.game_name.to_string()))
}
pub fn get_channel_info<S: Into<UserId>>(&mut self, id: S) -> rhai::Dynamic {
match self.runtime.block_on(self.internal_get_channel_info(id)) {
Some(x) => rhai::Dynamic::from(vec![
rhai::Dynamic::from(x.0),
rhai::Dynamic::from(x.1),
rhai::Dynamic::from(x.2),
]),
None => rhai::Dynamic::from(()),
}
}
}