Let's make a websocket client with Python. (Access token authentication)

I happened to have a chance to mess with the API of Nulab's Typetalk app (https://developer.nulab-inc.com/ja/docs/typetalk), so I implemented websocket. Note that I have never done it with python

Development environment

MaxOSX 10.10.3 Python 2.7.9

Installation

Install the required packages with python

pip install websocket-client

To install python websocket-client.

implementation of websocket

This time, since we used Typetalk, we will introduce how to get access token from type talk and define websocketclient. With this code, you can check all the behaviors of registered users.

main.py


#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys
import urllib
import urllib2
import json
import string

import websocket
import requests

class TypeTalkSample:
    access_token = None

    def __init__(self):
    	#Get an access token from typetalk
        client_id = "xxxxxxx"
        client_secret = "xxxxxxx"
        params = {
            'client_id': client_id,
            'client_secret': client_secret,
            'grant_type': 'client_credentials',
            'scope': 'topic.read,topic.post',
        }
        data = urllib.urlencode(params)
        res = urllib2.urlopen(urllib2.Request('https://typetalk.in/oauth2/access_token', data))
        
        #Hold access token
        self.access_token = json.load(res)['access_token']

		#Define websocket, here you can set websocket using access token by registering authorization in header.
        websocket.enableTrace(True)
        ws = websocket.WebSocketApp("wss://typetalk.in/api/v1/streaming", header=["Authorization: Bearer %s" % self.access_token], on_open=self.on_open, on_message=self.on_message, on_error=self.on_error, on_close=self.on_close)
        
        #Start websocket. Ctrl+Make sure it ends with C.
        try:
            ws.run_forever()
        except KeyboardInterrupt:
            ws.close()

	#The method defined here becomes the callback function of websocket.
	#When receiving a message
    def on_message(self, ws, message):
        print message

	#When an error occurs
    def on_error(self, ws, error):
        print error

	#When closing websocket
    def on_close(self, ws):
        print 'disconnected streaming server'

	#When opening websocket
    def on_open(self, ws):
        print 'connected streaming server'


if __name__ == "__main__":
    typetalk = TypeTalkSample()

Link

Typetalk api (https://developer.nulab-inc.com/ja/docs/typetalk)

Recommended Posts

Let's make a websocket client with Python. (Access token authentication)
Let's make a GUI with python.
Let's make a graph with python! !!
Let's make a shiritori game with Python
Let's make a voice slowly with Python
Let's make a web framework with Python! (1)
Let's make a Twitter Bot with Python!
Let's make a web framework with Python! (2)
Let's make a web chat using WebSocket with AWS serverless (Python)!
Let's replace UWSC with Python (5) Let's make a Robot
Access a site with client certificate authentication with Requests
Make a fortune with Python
[Let's play with Python] Make a household account book
Let's make a simple game with Python 3 and iPhone
[Super easy] Let's make a LINE BOT with Python.
Let's make a breakout with wxPython
Make a recommender system with python
Let's make a supercomputer with xCAT
Let's create a free group with Python
Let's make a simple language with PLY 1
[Python] Let's make matplotlib compatible with Japanese
Write a TCP client with Python Twisted
"First Elasticsearch" starting with a python client
Let's make a tic-tac-toe AI with Pylearn 2
Let's make a combination calculation in Python
Make a desktop app with Python with Electron
[Ev3dev] Let's make a remote control program by Python with RPyC protocol
Make a Twitter trend bot with heroku + Python
[Python] Make a game with Pyxel-Use an editor-
I want to make a game with Python
Try to make a "cryptanalysis" cipher with Python
[Python] Make a simple maze game with Pyxel
Try to make a dihedral group with Python
[Chat De Tornado] Make a chat using WebSocket with Tornado
Let's make a module for Python using SWIG
Let's make a nervous breakdown application with Vue.js and Django-Rest-Framework [Part 6] ~ User Authentication 2 ~
Let's make a nervous breakdown application with Vue.js and Django-Rest-Framework [Part 5] ~ User authentication ~
If you want to make a discord bot with python, let's use a framework
WebSocket with Python + uWSGI
Make one repeating string with a Python regular expression.
Try to make a command standby tool with python
[Practice] Make a Watson app with Python! # 2 [Translation function]
[Practice] Make a Watson app with Python! # 1 [Language discrimination]
Make a simple Slackbot with interactive button in python
Make a breakpoint on the c layer with python
Let's make dependency management with pip a little easier
[For play] Let's make Yubaba a LINE Bot (Python)
Make a CSV formatting tool with Python Pandas PyInstaller
Let's make a Mac app with Tkinter and py2app
Let's make a spherical grid with Rhinoceros / Grasshopper / GHPython
What is God? Make a simple chatbot with python
[Piyopiyokai # 1] Let's play with Lambda: Creating a Python script
[Practice] Make a Watson app with Python! # 3 [Natural language classification]
Let's make a Discord Bot.
BASIC authentication with Python bottle
Let's run Excel with Python
Associate Python Enum with a function and make it Callable
Let's create a script that registers with Ideone.com in Python.
Experiment to make a self-catering PDF for Kindle with Python
Let's create a PRML diagram with Python, Numpy and matplotlib.
Let's make Othello with wxPython