mod common;
use botrs::{Client, Context, EventHandler, GroupMessage, Intents, Ready, Token};
use common::{Config, init_logging};
use std::env;
use tracing::{info, warn};
struct GroupReplyHandler;
#[async_trait::async_trait]
impl EventHandler for GroupReplyHandler {
async fn ready(&self, _ctx: Context, ready: Ready) {
info!("robot 「{}」 on_ready!", ready.user.username);
}
async fn group_message_create(&self, ctx: Context, message: GroupMessage) {
let content = match &message.content {
Some(content) => content,
None => return,
};
info!("Received group message: {}", content);
let group_openid = match &message.group_openid {
Some(openid) => openid,
None => {
warn!("Group message has no group_openid");
return;
}
};
let msg_id = message.id.as_deref();
let reply_content = format!("收到了消息:{content}");
let params = botrs::models::message::GroupMessageParams {
msg_type: 0,
content: Some(reply_content),
msg_id: msg_id.map(|s| s.to_string()),
..Default::default()
};
match ctx
.api
.post_group_message_with_params(&ctx.token, group_openid, params)
.await
{
Ok(response) => {
info!("Successfully sent group message reply");
info!("Response: {:?}", response);
}
Err(e) => warn!("Failed to send group message reply: {}", e),
}
}
async fn error(&self, error: botrs::BotError) {
warn!("Event handler error: {}", error);
}
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
init_logging();
info!("Starting group reply text demo...");
let config = Config::load_with_fallback(
Some("examples/config.toml"),
env::args().nth(1), env::args().nth(2), )?;
info!("Configuration loaded successfully");
let token = Token::new(config.bot.app_id, config.bot.secret);
if let Err(e) = token.validate() {
panic!("Invalid token: {e}");
}
info!("Token validated successfully");
let intents = Intents::default().with_public_messages();
info!("Configured intents: {}", intents);
let handler = GroupReplyHandler;
let mut client = Client::new(token, intents, handler, true)?;
info!("Client created, starting bot...");
client.start().await?;
info!("Bot stopped");
Ok(())
}