Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Chanmoro committed Jun 15, 2016
0 parents commit 3cd6fa0
Show file tree
Hide file tree
Showing 13 changed files with 363 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# linebot
1 change: 1 addition & 0 deletions linebot-client/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
env
107 changes: 107 additions & 0 deletions linebot-client/linebot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
# -*- coding: utf-8 -*-
import websocket
import json
import ssl
import time
import random
import os
import sys


# websocket event
def on_message(ws, data):
print('### on message ###')
json_data = json.loads(data)

for received_data in json_data['result']:
print(received_data)
dialog(received_data)


def on_error(ws, error):
print('### on error ###')
print(error)


def on_close(ws):
print('### connection closed ###')


def on_open(ws):
print('### connection open ###')


# dialog and action
scenario = []
scenario.append({'msg': ['hello'], 'res': ['hi'], 'action': 'debug'})
scenario.append({'msg': ['hi'], 'res': ['hi\nwhat\'s up?']})
scenario.append({'msg': ['how', 'are', 'you'],
'res': ['not bad\nhow about you?']})

random_response = ['oh', 'good', 'uh-huh', 'right', 'I see']


def debug(received_data):
print('### debug ###')
print(received_data)


def dialog(received_data):
print('### dialog ###')
bot_message = None
hit_pattern = None

for pattern in scenario:
hit = False
for i, word in enumerate(pattern['msg']):
received_message = received_data['content']['text'].lower()
if received_message.find(word) == -1:
break
elif i == len(pattern['msg']) - 1:
hit = True
hit_pattern = pattern
if hit:
break

if hit_pattern is None:
bot_message = random_response[
random.randint(0, len(random_response) - 1)]
send_message(received_data, bot_message)
else:
if 'res' in hit_pattern:
for res in hit_pattern['res']:
bot_message = res
send_message(received_data, bot_message)

if hit_pattern is not None:
if 'action' in hit_pattern:
func_name = hit_pattern['action']
eval(func_name)(received_data)


# send bot message to user
def send_message(received_data, message):
print('### send_message ###')
print(message)

send_data = {}
send_data['to'] = [received_data['content']['from']]
send_data['toChannel'] = 1383378250 # fixed value
send_data['eventType'] = '140177271400161403' # fixed value
send_data['content'] = {'messageNotified': 0,
'messages': [{'contentType': 1, 'text': message}]}
ws.send(json.dumps(send_data, ensure_ascii=False))
time.sleep(0.3)


if __name__ == '__main__':
websocket.enableTrace(True)
# ws =
URL = 'wss://<url to linebot-proxy>'
ws = websocket.WebSocketApp(URL,
on_message=on_message,
on_error=on_error,
on_close=on_close)
ws.on_open = on_open
ws.run_forever(ping_interval=5)
# ws.run_forever(sslopt={'cert_reqs': ssl.CERT_NONE})
1 change: 1 addition & 0 deletions linebot-client/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
websocket-client==0.37.0
17 changes: 17 additions & 0 deletions linebot-proxy/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Node build artifacts
node_modules
npm-debug.log

# Local development
*.env
*.dev
.DS_Store

# Docker
Dockerfile
docker-compose.yml

# dir
deploy/*
logs/*
!.gitkeep
4 changes: 4 additions & 0 deletions linebot-proxy/build.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
#!/bin/sh
rm -r logs/*
rm -r deploy/*
tar zcvf deploy/modules.tgz index.html index.js package.json config logs
25 changes: 25 additions & 0 deletions linebot-proxy/config/default.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"log4js": {
"appenders": [{
"category": "access",
"type": "dateFile",
"filename": "logs/access.log",
"pattern": "-yyyy-MM-dd",
"backups": 3
},
{
"category": "application",
"type": "dateFile",
"filename": "logs/application.log",
"pattern": "-yyyy-MM-dd",
"backups": 3
},
{
"type": "console"
}],
"levels": {
"access": "ALL",
"application": "ALL"
}
}
}
Empty file.
Empty file added linebot-proxy/deploy/.gitkeep
Empty file.
68 changes: 68 additions & 0 deletions linebot-proxy/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
<html>

<head>
<style>
body {
font-family: "Helvetica Neue", helvetica, arial;
padding: 15px;
}

ul {
list-style: none;
margin: 0;
padding: 0;
}

ul li {
line-height: 1.4;
}
</style>
<script>
var host = location.origin.replace(/^http/, 'ws')
var ws = new WebSocket(host+'/ws');
var last_received = {};
ws.onmessage = function(event) {
var li = document.createElement('li');
li.innerHTML = event.data;
last_received = JSON.parse(event.data);
document.querySelector('#pings').appendChild(li);
};
window.addEventListener('load', function() {
document.getElementById('sendF').addEventListener('submit', function() {
var message = document.getElementById('message');
var to_user = document.getElementById('to');
if (message.value && to_user.value) {
var sendObj = {
to: [to_user.value],
toChannel: 1383378250,
eventType: '140177271400161403',
content: {
messageNotified: 0,
messages: [{
contentType: 1,
text: message.value
}]
}
};

ws.send(JSON.stringify(sendObj));
message.value = '';
message.focus();
}
});
});
</script>
</head>

<body>
<h1>Line proxy tester</h1>
<form id="sendF" action="javascript:void(0);">
to: <input type="text" id="to" />
message: <input type="text" id="message" />
<button id="send" type="submit">send</button>
</form>
<h2>Received message</h2>
<ul id='pings'></ul>
</body>

</html>
116 changes: 116 additions & 0 deletions linebot-proxy/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
var WebSocketServer = require("ws").Server
var http = require("http")
var express = require("express")
var bodyParser = require('body-parser');
var httpRequest = require('request');
var basicAuth = require('basic-auth-connect');
var config = require('config');
var log4js = require('log4js');
var url = require('url')

// Express setting
var app = express()
app.disable('x-powered-by'); // Disable 'X-Powered-By: Express' header
var port = process.env.PORT || 5000

log4js.configure(config.log4js);
var logger = log4js.getLogger('application');

app.use(express.static(__dirname + "/"))
app.use(log4js.connectLogger(log4js.getLogger('access'), { level: log4js.levels.INFO, format: ':remote-addr - - ":method :url HTTP/:http-version" :status :response-timems :content-length ":referrer" ":user-agent"' }));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var router = express.Router();
router.get('/status', function(request, response) {
response.status(200);
response.json({ status: http.STATUS_CODES[200] });
});
router.post('/', function(request, response) {
var json = request.body;
logger.info(json);
broadcast(json);

response.status(200);
response.json({ status: http.STATUS_CODES[200] });
});
app.use('/', router);

app.use(function(request, response, next) {
response.status(404);
response.json({ status: http.STATUS_CODES[404] });
});

var server = http.createServer(app)
server.listen(port)

logger.info("http server listening on %d", port)

// WebSocket server setting
var wss = new WebSocketServer({ server: server, path: '/ws' })
var ws_connections = [];

wss.on("connection", function(ws) {
var location = url.parse(ws.upgradeReq.url, true);
logger.info(location);
logger.info(ws.upgradeReq.headers);
ws_connections.push(ws);

logger.info("websocket connection open");

ws.on('message', function(data) {
var obj = JSON.parse(data);
logger.info("received message");
logger.info(obj);
sendResponse(obj);
});

ws.on("close", function() {
logger.info("websocket connection close");
// remove closed connection from connection list
ws_connections = ws_connections.filter(function(conn, i) {
return (conn === ws) ? false : true;
});

logger.info(ws_connections.length + " connections are remaining");
});
});
logger.info("websocket server created")


// broadcast websocket message
function broadcast(obj) {
logger.info('broadcast');
ws_connections.forEach(function(socket, i) {
socket.send(JSON.stringify(obj));
});
}

// send message to line user
function sendResponse(data) {
var headers = {
'Content-Type': 'application/json; charset=UTF-8',
'X-Line-ChannelID': '', // enter your Channel ID
'X-Line-ChannelSecret': '', // enter your Channel Secret
'X-Line-Trusted-User-With-ACL': '' // enter your MID
};

var options = {
url: 'https://trialbot-api.line.me/v1/events',
// proxy: process.env.FIXIE_URL,
headers: headers,
json: true,
body: data
};
logger.info('--- post data ---')
logger.info(data)

httpRequest.post(options, function(error, response, body) {
if (!error && response.statusCode == 200) {
logger.info(body);
} else {
logger.info('error: ' + JSON.stringify(response));
}
});

}
Empty file added linebot-proxy/logs/.gitkeep
Empty file.
23 changes: 23 additions & 0 deletions linebot-proxy/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"name": "linebot-proxy ",
"version": "0.0.1",
"description": "proxy Line BOT API through web-socket",
"engines": {
"node": "5.9.1"
},
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"dependencies": {
"basic-auth-connect": "^1.0.0",
"body-parser": "^1.15.0",
"config": "^1.20.1",
"ejs": "2.4.1",
"express": "4.13.3",
"log4js": "^0.6.35",
"request": "^2.72.0",
"ws": "^1.1.0"
},
"license": "MIT"
}

0 comments on commit 3cd6fa0

Please sign in to comment.