|
| 1 | +#![feature(proc_macro_hygiene, decl_macro)] |
| 2 | + |
| 3 | +#[macro_use] |
| 4 | +extern crate rocket; |
| 5 | + |
| 6 | +extern crate line_bot_sdk_rust as line; |
| 7 | + |
| 8 | +use dotenv::dotenv; |
| 9 | +use std::env; |
| 10 | + |
| 11 | +use rocket::http::Status; |
| 12 | + |
| 13 | +use line::bot::LineBot; |
| 14 | +use line::events::{EventType, Events}; |
| 15 | +use line::messages::Emoji; |
| 16 | +use line::messages::{SendMessageType, StickerMessage, TextMessage}; |
| 17 | +use line::support::rocket_support::{Body, Signature}; |
| 18 | + |
| 19 | +#[post("/callback", data = "<body>")] |
| 20 | +fn callback(signature: Signature, body: Body) -> Status { |
| 21 | + // Get channel secret and access token by environment variable |
| 22 | + let channel_secret: &str = |
| 23 | + &env::var("LINE_CHANNEL_RECRET").expect("Failed getting LINE_CHANNEL_RECRET"); |
| 24 | + let access_token: &str = |
| 25 | + &env::var("LINE_CHANNEL_ACCESS_TOKEN").expect("Failed getting LINE_CHANNEL_ACCESS_TOKEN"); |
| 26 | + |
| 27 | + // LineBot |
| 28 | + let bot = LineBot::new(channel_secret, access_token); |
| 29 | + |
| 30 | + // Request body parse |
| 31 | + let result: Result<Events, &'static str> = |
| 32 | + bot.parse_event_request(&signature.key, &body.string); |
| 33 | + |
| 34 | + // Success parsing |
| 35 | + if let Ok(res) = result { |
| 36 | + for event in res.events { |
| 37 | + // MessageEvent only |
| 38 | + if let EventType::MessageEvent(message_event) = event.r#type { |
| 39 | + // Create Vec of messages to be sent |
| 40 | + let mut messages: Vec<SendMessageType> = Vec::new(); |
| 41 | + // Add TextMessage |
| 42 | + messages.push(SendMessageType::TextMessage(TextMessage { |
| 43 | + text: String::from("text message"), |
| 44 | + emojis: None, |
| 45 | + })); |
| 46 | + // Add TextMessage with Emoji |
| 47 | + messages.push(SendMessageType::TextMessage(TextMessage { |
| 48 | + text: String::from("$ EMOJI!"), |
| 49 | + emojis: Some(vec![Emoji { |
| 50 | + index: 0, |
| 51 | + product_id: String::from("5ac1bfd5040ab15980c9b435"), |
| 52 | + emoji_id: String::from("001"), |
| 53 | + }]), |
| 54 | + })); |
| 55 | + // Add StickerMessage |
| 56 | + messages.push(SendMessageType::StickerMessage(StickerMessage { |
| 57 | + package_id: String::from("1"), |
| 58 | + sticker_id: String::from("1"), |
| 59 | + })); |
| 60 | + println!("{:?}", messages); |
| 61 | + // Reply message with reply_token |
| 62 | + let _res = bot.reply_message(&message_event.reply_token, messages); |
| 63 | + } |
| 64 | + } |
| 65 | + return Status::new(200, "OK"); |
| 66 | + } |
| 67 | + // Failed parsing |
| 68 | + else if let Err(msg) = result { |
| 69 | + return Status::new(500, msg); |
| 70 | + } |
| 71 | + Status::new(500, "Internal Server Error") |
| 72 | +} |
| 73 | + |
| 74 | +fn main() { |
| 75 | + dotenv().ok(); |
| 76 | + rocket::ignite().mount("/", routes![callback]).launch(); |
| 77 | +} |
0 commit comments