tg-rs / carapax

A Telegram Bot API framework
MIT License
115 stars 12 forks source link

webhook reply #53

Closed incker closed 4 years ago

incker commented 4 years ago

Hello!

I have found out that webhook can reply with message. See link

I have test it, and it is true. Here is a primitive webhook WORKING example

#[post("/telegram/test-dev", format = "application/json", data = "<telegram_update>")]
pub fn telegram_webhook(telegram_update: Json<tgbot::types::Update>) -> Result<Json<JsonValue>, String> {
    let Json(update) = telegram_update;

    if let UpdateKind::Message(message) = update.kind {
        if let Some(text) = message.get_text() {
            let chat_id: i64 = message.get_chat_id();

            let val = json!({
                "method": "sendMessage",
                "chat_id": chat_id,
                "text" : "My Webhook answer..."
            });

            return Ok(Json(val));
        }
    }

    Err("".into())
}

So, the question is, how can I build an answer using SendMessage struct? something like this:

SendMessage::new(chat_id, "My Webhook answer...")

instead of hand-write json!({ }). I have noticed that SendMessage struct have no "method" field and RequestBuilder seems like something other.

If there will be a working example how to handle if - will be ideal Forward thank you for your answer

rossnomann commented 4 years ago

Hi! You can write your own wrapper for methods: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=dffd072e8950417f3fafe10c415c69ad

incker commented 4 years ago

Оh, thank you!! That makes sense. Didn't know about #[serde(flatten)] macro

Maybe once you will have want add MethodWrapper that will work something like

let method_wrapper: MethodWrapper<SendMessage> = SendMessage::new(chat_id, "My Webhook answer...").as_webhook_answer();

But for now flatten macro solution suits me great!) Again thank you