Bye Bye Moore

PoCソルジャーな零細事業主が作業メモを残すブログ

websocketで来た内容をIFTTTに投稿してみる

Python製軽量WEB鯖Bottleを使い、websocketで来た内容をIFTTTに投稿してみます。
……jQueryクソ雑魚勢なので、やたら苦労しました……。

実際のところ

構成

ファイル構成は以下の記事と同様
shuzo-kino.hateblo.jp

$ tree
.
├── app.py
├── static
│   └── js
│       └── client.js
└── templates
    └── base.jade

3 directories, 3 files

スクリプト

app.py
from bottle import route, get, post, request, run, redirect, static_file, Bottle
#jade対応
from bottle_jade import JadePlugin
#websocket対応
from bottle.ext.websocket import GeventWebSocketServer
from bottle.ext.websocket import websocket
#static対応
from os import path as op
#IFTTT投稿用
import requests


#初期化
app = Bottle()
templates = op.dirname(op.abspath(__file__)) + '/templates/'
jade = app.install(JadePlugin(template_folder=templates))

#静的ファイル置き場
@route('/static/:path#.+#', name='static')
def static(path):
    return static_file(path, root='static')

#ページ群本体
@get('/page')
def topPage():
	context = {"body": "basePage"} 
	return jade.render('base.jade', **context)     

@post('/page')
def postAction():
	theText = request.params.get('message')
	if theText:
		data = {"value1": theText, "value2": "def", "value3": "ghi"}
		headers = {'Content-Type': "application/json"}
		url = 'https://maker.ifttt.com/trigger/{{YOURAPPNAME}}/with/key/{{YOURACCOUNT}}'
		response = requests.post(url, json=data, headers=headers)
		messageString = "you posted: %s to IFTTT" % theText 
		print(messageString)
	return "You didn't post anything."

@get('/websocket', apply=[websocket])
def echo(ws):
    while True:
        msg = ws.receive()
        if msg is not None:
            ws.send(msg)
        else: break

#アプリ起動
run(host='localhost', port=8080, server=GeventWebSocketServer)

client.js

$(document).ready(function() {
            if (!window.WebSocket) {
                if (window.MozWebSocket) {
                    window.WebSocket = window.MozWebSocket;
                } else {
                    $('#messages').html("<li id=messages>Your browser doesn't support WebSockets.</li>");
                }
            }
            ws = new WebSocket('ws://127.0.0.1:8080/websocket');
            ws.onopen = function(evt) {
                $('#messages').append('<li id="messages">WebSocket connection opened.</li>');
            }
            ws.onmessage = function(evt) {
                $('#messages').html('<li id="messages">' + evt.data + '</li>');
            }
            ws.onclose = function(evt) {
	        $('#messages').append('<li id="messages">WebSocket connection closed.</li>');
            }
            $('#send').submit(function() {
                ws.send($('input:first').val());
                $('input:first').val('').focus();
                return false;
            });

	//ajax
      $('#ajax').submit(function(e) {
        var msg = $('li#messages').text();
        $.ajax({
            type: 'POST',
            url: '/page',
            data: "message=" + msg,
            success: function(response) {
                $('#ajaxP').html(response);
            }
        });
        e.preventDefault();
      });
});
index.jade
head
    meta charset="utf-8"
    title jQuerySample
    script(src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js")
    script(src="/static/js/client.js")

body
  h2 #{body}

  form#send(action='.')
    input(type="text" value="message")
    input(type="submit" value="Send")
  div#messages

  hr
  
  form#ajax(action="/page" method="post")
    input(type="submit" value="Post to IFTTT")

動作

開くとこんな塩梅。
上の方のメッセージは投稿で上書きされる形式
f:id:shuzo_kino:20171021160934p:plain
今回、受け取り先はIFTTTのWEB HOCK経由でメール受信です。
なのでこんな感じで回答がきます
f:id:shuzo_kino:20171021162225p:plain