What you can do with API vol.1

Introduction

This time, I would like to introduce what you can do with the API.

The API here is something like a function that can be called at any time if you are connected to the Internet.

We are planning to introduce what is open to the public by companies and individuals.

smilingly

How to create my list and register my list with Nico Nico Douga

With reference to the here page, I wrote a Nico Nico video that creates and registers my list.

nico_mylist_add.py


#!/usr/bin/env python
#coding: utf8
import sys, re, cgi, urllib, urllib2, cookielib, xml.dom.minidom, time, netrc
import json
 
#netrc
netrc = netrc.netrc()
userid,a,passwd = netrc.authenticators("nicovideo")
 
def getToken():
    html = urllib2.urlopen("http://www.nicovideo.jp/my/mylist").read()
    for line in html.splitlines():
        mo = re.match(r'^\s*NicoAPI\.token = "(?P<token>[\d\w-]+)";\s*',line)
        if mo:
            token = mo.group('token')
            break
    assert token
    return token
 
def mylist_create(name):
    cmdurl = "http://www.nicovideo.jp/api/mylistgroup/add"
    q = {}
    q['name'] = name.encode("utf8")
    q['description'] = ""
    q['public'] = 0
    q['default_sort'] = 0
    q['icon_id'] = 0
    q['token'] = token
    cmdurl += "?" + urllib.urlencode(q)
    j = json.load( urllib2.urlopen(cmdurl), encoding='utf8')
    return j['id']
 
def addvideo_tomylist(mid,smids):
    for smid in smids:
        cmdurl = "http://www.nicovideo.jp/api/mylist/add"
        q = {}
        q['group_id'] = mid
        q['item_type'] = 0
        q['item_id'] = smid
        q['description'] = u""
        q['token'] = token
        cmdurl += "?" + urllib.urlencode(q)
        j = json.load( urllib2.urlopen(cmdurl), encoding='utf8')
        time.sleep(0.5)
 
#Login
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookielib.CookieJar()))
urllib2.install_opener(opener)
urllib2.urlopen("https://secure.nicovideo.jp/secure/login",
                urllib.urlencode( {"mail":userid, "password":passwd}) )
#Get token
token = getToken()
 
#argv
myn = sys.argv[1]
argvs = sys.argv[2:]
 
#Create my list and register videos
mid = mylist_create(myn)
addvideo_tomylist(mid, argvs )

It's easy to use and gives execute permission to the file. Then, pass the URL and execute it.

python


$ chmod +x nico_mylist_add.py

$ ./nico_mylist_add.py mylistname sm9 sm1097445 sm1715919

The changes are (1) the login information is obtained from netrc, and (2) the name and URL of My List are obtained from the arguments.

Get login information from netrc

The netrc looks like this:

python


$ cat ~/.netrc
 
#############################
machine   nicovideo
login     [email protected]
password  pass123
#############################

The processing is as follows.

python


#!/usr/bin/env python
import netrc
netrc = netrc.netrc()
l, a, p = netrccfg.authenticators("nicovideo")
print "My Login = %s" % (l)
print "My Password = %s" % (p)
print "My Account= %s" % (a)

Get the name and URL of My List from the argument

python


#!/usr/bin/env python
import sys
mylistname = sys.argv[1]
argvs = sys.argv[2:]
print mylistname
print argvs

How to register to an existing My List with Nico Nico Douga

For example, to register the URL in the existing My List, make the following changes.

First, change ʻaddvideo_tomylist. Put group_id in the part of xxxx`.

Here, to get the group_id, use http://www.nicovideo.jp/api/mylistgroup/list. Maybe ...

reference: http://efcl.info/wiki/niconicoapi/

def addvideo_tomylist(smids):
    for smid in smids:
        cmdurl = "http://www.nicovideo.jp/api/mylist/add"
        q = {}
        q['group_id'] = xxxxxxxx
        q['item_type'] = 0
        q['item_id'] = smid
        q['description'] = u""
        q['token'] = token
        cmdurl += "?" + urllib.urlencode(q)
        j = json.load( urllib2.urlopen(cmdurl), encoding='utf8')
        time.sleep(0.5)

Also, since it is no longer necessary to pass the name of My List as an argument, change that part.

#argv
#myn = sys.argv[1]
argvs = sys.argv[1:]

Google+

Try to get user information using Google+ API.

In Google Cloud Console, create a project and enable the API to be used.

First, access the following URL with a browser and get the Authorization code.

python


https://accounts.google.com/o/oauth2/auth?client_id=[Client ID]&redirect_uri=[Redirect URI]&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fplus.me&response_type=code

Please note that [] is not included.

Authorization code is the part of the page URL undercode =.

python


$ curl -d client_id=[YOUR Client Id] -d client_secret=[YOUR Client Secret] -d redirect_uri=http%3A%2F%2Flocalhost%2Foauth2callback -d grant_type=authorization_code -d code=[YOUR Authorization code] https://accounts.google.com/o/oauth2/token

ʻAccess_token` etc. will be issued, so you can use that value to get user information. The page of here is very helpful. It will be.

python


$ curl -H "Authorization: OAuth [YOUR Access_token]" https://www.googleapis.com/plus/v1/people/me

Note that ʻaccess_token expires after a certain period of time, so if you want to create an app that uses the Google API, you should use refresh_token`.

reference: http://mba-hack.blogspot.jp/2013/12/google-api.html

reference

https://github.com/sorah/niconico

https://github.com/google/google-api-ruby-client

https://developers.google.com/+/api/latest/?hl=ja

Recommended Posts

What you can do with API vol.1
Python | What you can do with Python
What you can do with programming skills
What you can and cannot do with Tensorflow 2.x
What you can do with the Python standard library statistics
Consider what you can do with Python from the Qiita article
You will be an engineer in 100 days --Day 35 --Python --What you can do with Python
Links to do what you want with Sublime Text
What you can't do with hstack or vstack with dstack
Until you can do simple image recognition with Jupyter
[AWS] What to do when you want to pip with Lambda
What to do if you can't sort files with subscripts
[Python] What do you do with visualization of 4 or more variables?
What to do with Magics install
What to do with PYTHON release?
What to do if you get a UnicodeDecodeError with pip install
What to do if you can't build your project with Maven
Data analysis, what do you do after all?
Until you can use opencv with python
Let's summarize what you want to do.
What to do if you can't find well with grep's -f option
What to do if you get lost in file reference with FileNotFoundError
What to do if you get a TypeError with numpy min, max
What to do if you can't install with pip in babun environment
You can do it with Python! Structural analysis of two-dimensional colloidal crystals
What to do if you get Could not fetch URL 443 with pip
Until you CI what you made with Django with Jenkins
What to do if you get angry with swapon failed: Operation not permitted
You can do it in 5 minutes !? Create a face detection API with FastAPI and OpenCV and publish it on Heroku
What to do if you can't pipenv shell
Until you use the Kaggle API with Colab
Can you challenge Kaggle with just your iPad?
You can easily create a GUI with Python
If you guys in the scope kitchen can do it with a margin ~ ♪
Until you can use the Google Speech API
What are you comparing with Python is and ==?
What to do if you get an error when installing python with pyenv
Is Parallel Programming Hard, And, If So, What Can You Do About It?
What should I do with DICOM in MPEG2?
You can now display slides with nbviewer! [Jupyter]
What are you using when testing with Python?
Consideration when you can do a good job in 10 years with Python3 and Scala3.
What to do if you get an Import Error when importing matplotlib with Jupyter
What to do if you run python in IntelliJ and end with an error
What to do if you can't pip install mysqlclient
No module named What to do if you get'libs.resources'
You can read the analog meter with the example MNIST.
What is pip and how do you use it?
Things to do when you start developing with Django
What to do when you can't bind CaboCha to Python
Make a note of what you want to do in the future with Raspberry Pi
Extrude with Fusion360 API
Do Houdini with Python3! !! !!
What Django renders do
What to do if you get an Undefined error when trying to use pip with pyenv
Until you can install your own Python library with pip
What to do if you are addicted to Windows character code
If you write TinderBot in Python, she can do it
Move what you installed with pip to the conda environment
What to do if you get "coverage unknown" in Coveralls
What to do when an error occurs with import _ssl