Blame view

index copy.js 8.09 KB
a8dde2dd   Surasit Yerpui   firstcommit
1
2
3
4
5
6
7
8
9
10
"use strict";

const line = require("@line/bot-sdk");
const express = require("express");
const config = require("./config.json");
const bodyParser = require("body-parser");
const axios = require("axios");
const fs = require("fs");
const request = require("request");
const moment = require("moment");
eb28d472   Surasit Yerpui   update Service
11
const flexMsg = require("./flexMsg");
a8dde2dd   Surasit Yerpui   firstcommit
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204

// create LINE SDK client
const client = new line.Client(config);

const app = express();

// webhook callback
app.use("/webhook", line.middleware(config));
app.post("/webhook", (req, res) => {
  // req.body.events should be an array of events
  if (!Array.isArray(req.body.events)) {
    return res.status(500).end();
  }
  // handle events separately
  Promise.all(
    req.body.events.map((event) => {
      console.log("event", event);
      // check verify webhook event
      if (
        event.replyToken === "00000000000000000000000000000000" ||
        event.replyToken === "ffffffffffffffffffffffffffffffff"
      ) {
        return;
      }
      return handleEvent(event);
    })
  )
    .then(() => res.end())
    .catch((err) => {
      console.error(err);
      res.status(500).end();
    });
});

// simple reply function
const replyText = (token, texts) => {
  texts = Array.isArray(texts) ? texts : [texts];
  return client.replyMessage(
    token,
    texts.map((text) => ({ type: "text", text }))
  );
};

const tolow = (str) => {
  return str.toLowerCase();
};
const handleEvent = (event) => {
  let payload = {
    type: "text",
    text: "Hello From PUI",
  };

  if (event.message.type == "text") {
    let selecttext = tolow(event.message.text);
    let get_text = mockText()[selecttext];
    if (get_text) {
      payload = get_text;
    }
  } else {
    payload.text = "Other Message =>>>" + JSON.stringify(event);
  }

  return client.replyMessage(event.replyToken, payload);
};
app.use(bodyParser.json());

app.get("/", (req, res) => {
  res.json({ line: "ok" });
});

app.get("/push", bodyParser.json(), (req, res) => {
  let message = {
    type: "text",
    text: `use Push Message! to `,
  };
  client.pushMessage("Uaac2ca5a02feab67a18d5521b572b5aa", message);
  res.json(message);
});

app.post("/save", bodyParser.json(), async (req, res) => {
  console.log("saveFile!");
  try {
    const downloadFile = function (uri, filename, callback) {
      request.head(uri, function (err, res, body) {
        console.log("content-type:", res.headers["content-type"]);
        console.log("content-length:", res.headers["content-length"]);
        console.log("Content-Type:", res.headers["Content-Type"]);
        console.log("res.headers ::", res.headers);

        request(uri, {
          headers: {
            Authorization:
              "Bearer be/XHjQ+gMoypZE78Us7hk0h6PA04TyfpQciMOq+B/OVPmumozdhGzYUwopDgsOMCM7RymTK8m++q20GSj3c6B7gZkgEmuGYEYPvc6j+4as6X5bu7tEg+KAZKMfBVDnk+ekpAorC7FMwVPyt2frGRQdB04t89/1O/w1cDnyilFU=",
          },
        })
          .pipe(fs.createWriteStream(filename))
          .on("close", callback);
      });
    };

    let unquie_file = moment().format("YYYY-MM-DD_HHmmssss");
    let file_name = `filesave_${unquie_file}`;
    let message_id = req.body.message_id;
    let URI = `https://api-data.line.me/v2/bot/message/${message_id}/content`;
    console.log("message_id ::", message_id);
    console.log("file_name ::", file_name);

    axios
      .get(URI, {
        headers: {
          Authorization:
            "Bearer be/XHjQ+gMoypZE78Us7hk0h6PA04TyfpQciMOq+B/OVPmumozdhGzYUwopDgsOMCM7RymTK8m++q20GSj3c6B7gZkgEmuGYEYPvc6j+4as6X5bu7tEg+KAZKMfBVDnk+ekpAorC7FMwVPyt2frGRQdB04t89/1O/w1cDnyilFU=",
        },
      })
      .then(function (response) {
        // handle success
        console.log("axios =>>", response.headers["content-type"]);
        let sp = response.headers["content-type"].split("/");
        let type = sp[sp.length - 1];
        let full_file_name = file_name + "." + type;
        console.log("full_file_name =", full_file_name);
        downloadFile(URI, full_file_name, function () {
          console.log("done!");
          res.json({ LoadFlieName: "Success" });
        });
      })
      .catch(function (error) {
        // handle error
        console.log(error);
        console.error("errorxx ::", error);
        res.json({ error: "error" });
      });
  } catch (error) {
    console.error("errorxx ::", error);
  }
});

app.post("/saveNew", bodyParser.json(), async (req, res) => {
  console.log("saveFile!");
  try {
    let stream = await client.getMessageContent("14955535936627");
    console.log("stream!", stream);
  } catch (error) {
    console.error(error);
  }
  res.json({ OK: "OK" });
});

app.post("/push", (req, res) => {
  let body = req.body;
  let { user_id } = body;
  console.log("body ::", body);
  let message = {
    type: "text",
    text: `use Push Message! to ${user_id}`,
  };
  client.pushMessage(user_id, message);
  res.json(message);
});

app.post("/multicast", (req, res) => {
  let body = req.body;
  let { user_ids } = body;
  console.log("body ::", body);
  let message = [
    {
      type: "text",
      text: `use multicast Message1! to ${JSON.stringify(user_ids)}`,
    },
    {
      type: "text",
      text: `use multicast Message2! to ${JSON.stringify(user_ids)}`,
    },
  ];
  client.multicast(user_ids, message);
  res.json(message);
});

const port = config.port;
app.listen(port, () => {
  console.log(`listening on ${port}`);
});

const GenContentFlex = (content) => {
  return {
    flex1: {
      type: "flex",
      altText: "GenContentFlex!",
      contents: content,
    },
  };
};

eb28d472   Surasit Yerpui   update Service
205
206
207
208
const genMsgContent = flexMsg.GenContentFlex;
const flexs = flexMsg.flexs;
// console.log(genMsgContent());

a8dde2dd   Surasit Yerpui   firstcommit
209
210
const mockText = () => {
  return {
eb28d472   Surasit Yerpui   update Service
211
212
    flex0: flexs.flex0,
    flex1: flexs.flex1,
a8dde2dd   Surasit Yerpui   firstcommit
213

eb28d472   Surasit Yerpui   update Service
214
215
216
217
218
219
    bub1: flexs.bub1,
    bub2: flexs.bub2,
    bub3: flexs.bub3,
    bub4: flexs.bub4,
    bub5: flexs.bub5,
    bub6: flexs.bub6,
a8dde2dd   Surasit Yerpui   firstcommit
220

eb28d472   Surasit Yerpui   update Service
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
    confirm:{
      "type": "template",
      "altText": "this is a confirm template",
      "template": {
          "type": "confirm",
          "text": "Are you sure?",
          "actions": [
              {
                "type": "message",
                "label": "Yes",
                "text": "yes"
              },
              {
                "type": "message",
                "label": "No",
                "text": "no"
              }
          ]
      }
a8dde2dd   Surasit Yerpui   firstcommit
240
241
    },

a8dde2dd   Surasit Yerpui   firstcommit
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276

    location: {
      type: "text", // ①
      text: "Select your favorite food category or send me your location!",
      quickReply: {
        // ②
        items: [
          {
            type: "action", // ③
            imageUrl: "https://example.com/sushi.png",
            action: {
              type: "message",
              label: "Sushi",
              text: "Sushi",
            },
          },
          {
            type: "action",
            imageUrl: "https://example.com/tempura.png",
            action: {
              type: "message",
              label: "Tempura",
              text: "Tempura",
            },
          },
          {
            type: "action", // ④
            action: {
              type: "location",
              label: "Send location",
            },
          },
        ],
      },
    },
eb28d472   Surasit Yerpui   update Service
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315

    


    //
    image_carousel: {
      "type": "template",
      "altText": "this is a image carousel template",
      "template": {
          "type": "image_carousel",
          "columns": [
              {
                "imageUrl": "https://example.com/bot/images/item1.jpg",
                "action": {
                  "type": "postback",
                  "label": "Buy",
                  "data": "action=buy&itemid=111"
                }
              },
              {
                "imageUrl": "https://example.com/bot/images/item2.jpg",
                "action": {
                  "type": "message",
                  "label": "Yes",
                  "text": "yes"
                }
              },
              {
                "imageUrl": "https://example.com/bot/images/item3.jpg",
                "action": {
                  "type": "uri",
                  "label": "View detail",
                  "uri": "http://example.com/page/222"
                }
              }
          ]
      }
    }
   
a8dde2dd   Surasit Yerpui   firstcommit
316
317
  };
};