File size: 1,517 Bytes
5355a08
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
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
/**
 * LINE bot main class
 */
class LineBot {
  /**
   * Constructor
   * @param {string} channelId
   * @param {string} channelSecret
   * @param {string} accessToken
   */
  constructor(channelId, channelSecret, accessToken) {
    this.channelId = channelId;
    this.channelSecret = channelSecret;
    this.accessToken = accessToken;
    this.lineApi = 'https://api.line.me/v2/';
  }

  /**
   * Handle incoming message
   * @param {object} event
   */
  handleMessage(event) {
    var message = event.message;
    var replyToken = event.replyToken;
    var userId = event.source.userId;
    var messageText = message.text;

    // Handle message
    var response = this.handleMessageText(messageText, userId);
    this.replyMessage(replyToken, response);
  }

  /**
   * Handle message text
   * @param {string} messageText
   * @param {string} userId
   * @return {string}
   */
  handleMessageText(messageText, userId) {
    // Simple echo bot
    return messageText;
  }

  /**
   * Reply message
   * @param {string} replyToken
   * @param {string} message
   */
  replyMessage(replyToken, message) {
    var options = {
      'method': 'POST',
      'headers': {
        'Authorization': 'Bearer ' + this.accessToken,
        'Content-Type': 'application/json'
      },
      'payload': JSON.stringify({
        'replyToken': replyToken,
        'messages': [{
          'type': 'text',
          'text': message
        }]
      })
    };
    UrlFetch.fetch(this.lineApi + 'messages/reply', options);
  }
}