[Python] How to use Typetalk API

Introduction

This article will show you how to use the Typetalk API in Python. By the way, I made a curry judgment bot. 1599655883672.jpg

Advance preparation

Create a bot and get a token and URL.

Bot creation

Open the Bot tab from Topic Settings. Screenshot 2020-09-09 153331.jpg

Press Add New to open the bot settings screen. Screenshot 2020-09-09 153945.jpg

The items are as follows. Please set each.

item Description
Bot ID Unique ID of the bot
Bot name Bot username
Description ボットのDescription
API scope Bot permissions
Outgoing Webhook Not used in this article

After setting, press Create. You should see the token and URL at the bottom. 1599635765682.jpg

Get

When prompted, make a note of the token and URL.

This completes the preparations.

environment

Python 3.8.5

Library installation

We use Python's HTTP communication library called Requests.

pip install requests

Source code

Enter the token and URL you wrote down in token and ʻurl`.

sample

The Official Samples has been slightly modified.

sample.py


import requests

token = ''
url = ''

data = {'message':'Hello, Typetalk!'}
headers = {'X-TYPETALK-TOKEN': token}
r = requests.post(url, json = data, headers = headers)
print(r.status_code)
print(r.json())

When run, the bot should post Hello, Typetalk! To the topic. You should also see a response. Contains detailed information about the message you posted. Screenshot 2020-09-09 201544.jpg

Get message

Get the message. Use pprint to make the response easier to read.

get.py


import requests
import pprint

token = ''
url = ''

headers = {'X-TYPETALK-TOKEN': token}
r = requests.get(url, headers = headers)
print(r.status_code)
pprint.pprint(r.json())
Response example

[Official example](https://developer.nulab.com/ja/docs/typetalk/api/1/get-messages/#%E3%83%AC%E3%82%B9%E3%83%9D% E3% 83% B3% E3% 82% B9% E3% 81% AE% E4% BE% 8B) was quoted.

example.json


{
    "bookmark": {
        "postId": 172371,
        "updatedAt": "2019-03-11T08:37:40Z"
    },
    "exceedsAttachmentLimit": false,
    "postContentsSettings": {
        "collapsedAccountIds": []
    },
    "myTopic": {
        "id": 15376,
        "topicId": 3557,
        "accountId": 2488,
        "kind": "grouped",
        "topicGroupId": 1703,
        "exTopicGroupId": 1702,
        "orderNo": 0,
        "createdAt": "2019-02-13T08:27:22Z",
        "updatedAt": "2019-02-13T08:27:22Z"
    },
    "topic": {
        "createdAt": "2016-02-05T06:13:44Z",
        "lastPostedAt": "2019-03-11T08:38:04Z",
        "isArchived": false,
        "suggestion": "UX improvement",
        "name": "UX improvement",
        "description": "This is a topic about improving UX.\n Feel free to talk about design, UX, and anything else you notice.\n\n Summary Wiki about site improvement\n- https://xxxxx.backlog.jp/wiki/WEBSITE/Kaizen\n\n We will also publicize related events on this topic.",
        "isDirectMessage": false,
        "id": 3557,
        "updatedAt": "2018-10-18T01:54:18Z"
    },
    "onboarding": null,
    "hasNext": false,
    "team": null,
    "mySpace": {
        "space": {
            "key": "XXXXXXX",
            "name": "Nulab Inc",
            "enabled": true,
            "imageUrl": "https://apps.nulab.com/spaces/XXXXXXX/photo/large"
        },
        "myRole": "ADMIN",
        "isPaymentAdmin": true,
        "invitableRoles": [
            "ADMIN",
            "USER",
            "GUEST"
        ],
        "myPlan": {
            "plan": {
                "key": "typetalk.standard25",
                "name": "Standard 25 users",
                "limitNumberOfUsers": 25,
                "limitNumberOfAllowedAddresses": 25,
                "limitTotalAttachmentSize": 268435456000
            },
            "enabled": true,
            "trial": null,
            "numberOfUsers": 5,
            "numberOfAllowedAddresses": 0,
            "totalAttachmentSize": 14356,
            "createdAt": "2016-01-19T09:29:10Z",
            "updatedAt": "2019-08-28T08:19:49Z"
        }
    },
    "favorite": true,
    "posts": [
        {
            "attachments": [
                {
                    "attachment": {
                        "contentType": "application/octet-stream",
                        "fileKey": "1",
                        "fileName": "1.jpg ",
                        "fileSize": 472263
                    },
                    "webUrl": "https://typetalk.com/topics/3557/posts/154010/attachments/1/1.jpg ",
                    "apiUrl": "https://typetalk.com/api/v1/topics/3557/posts/154010/attachments/1/1.jpg "
                },
                {
                    "attachment": {
                        "contentType": "application/octet-stream",
                        "fileKey": "2",
                        "fileName": "2.jpg ",
                        "fileSize": 494376
                    },
                    "webUrl": "https://typetalk.com/topics/3557/posts/154010/attachments/2/2.jpg ",
                    "apiUrl": "https://typetalk.com/api/v1/topics/3557/posts/154010/attachments/2/2.jpg "
                },
                {
                    "attachment": {
                        "contentType": "application/octet-stream",
                        "fileKey": "3",
                        "fileName": "5.jpg ",
                        "fileSize": 218100
                    },
                    "webUrl": "https://typetalk.com/topics/3557/posts/154010/attachments/3/5.jpg ",
                    "apiUrl": "https://typetalk.com/api/v1/topics/3557/posts/154010/attachments/3/5.jpg "
                },
                {
                    "attachment": {
                        "contentType": "application/octet-stream",
                        "fileKey": "4",
                        "fileName": "6.jpg ",
                        "fileSize": 627926
                    },
                    "webUrl": "https://typetalk.com/topics/3557/posts/154010/attachments/4/6.jpg ",
                    "apiUrl": "https://typetalk.com/api/v1/topics/3557/posts/154010/attachments/4/6.jpg "
                }
            ],
            "quotedPosts": [],
            "message": "I was able to improve the top screen. http://nulab-inc.com/ja/",
            "mention": null,
            "createdAt": "2019-03-02T06:13:44Z",
            "topicId": 3557,
            "contents": null,
            "mentions": [],
            "talks": [],
            "replyTo": null,
            "links": [
                {
                    "id": 3148,
                    "url": "http://nulab-inc.com/ja/",
                    "contentType": "text/html; charset=UTF-8",
                    "title": "Further collaboration with the team|Nulab",
                    "description": "Millions of users are using Nulab's services to improve team communication. Make your team's work even more enjoyable with Nulab's online collaboration tools.",
                    "imageUrl": "https://nulab-inc.com/ogp_dft.png ",
                    "embed": null,
                    "createdAt": "2015-06-15T06:41:24Z",
                    "updatedAt": "2017-03-03T10:11:08Z"
                }
            ],
            "id": 154010,
            "account": {
                "id": 2492,
                "name": "hayashi",
                "fullName": "hayashi",
                "suggestion": "hayashi",
                "imageUrl": "https://typetalk.com/accounts/2492/profile_image.png?t=1453871047310",
                "isBot": false,
                "createdAt": "2016-01-26T08:19:01Z",
                "updatedAt": "2019-09-04T07:25:45Z"
            },
            "likes": [],
            "updatedAt": "2019-03-02T06:13:44Z"
        },
        {
            "attachments": [],
            "quotedPosts": [],
            "message": "Masa-san, what do you think of the colors on this screen?",
            "mention": null,
            "createdAt": "2019-03-03T06:13:44Z",
            "topicId": 3557,
            "contents": null,
            "mentions": [],
            "talks": [],
            "replyTo": null,
            "links": [],
            "id": 154011,
            "account": {
                "id": 2489,
                "name": "yoshizawa",
                "fullName": "Yoshi",
                "suggestion": "Yoshi",
                "imageUrl": "https://typetalk.com/accounts/2489/profile_image.png?t=1564389095614",
                "isBot": false,
                "createdAt": "2016-01-26T08:18:12Z",
                "updatedAt": "2019-09-04T07:25:45Z"
            },
            "likes": [],
            "updatedAt": "2019-03-03T06:13:44Z"
        }
    ]
}

Of these, the one to pay attention to is posts.

posts.json


"posts": [
        {
            "attachments": [
                {
                    "attachment": {
                        "contentType": "application/octet-stream",
                        "fileKey": "1",
                        "fileName": "1.jpg ",
                        "fileSize": 472263
                    },
                    "webUrl": "https://typetalk.com/topics/3557/posts/154010/attachments/1/1.jpg ",
                    "apiUrl": "https://typetalk.com/api/v1/topics/3557/posts/154010/attachments/1/1.jpg "
                },
                {
                    "attachment": {
                        "contentType": "application/octet-stream",
                        "fileKey": "2",
                        "fileName": "2.jpg ",
                        "fileSize": 494376
                    },
                    "webUrl": "https://typetalk.com/topics/3557/posts/154010/attachments/2/2.jpg ",
                    "apiUrl": "https://typetalk.com/api/v1/topics/3557/posts/154010/attachments/2/2.jpg "
                },
                {
                    "attachment": {
                        "contentType": "application/octet-stream",
                        "fileKey": "3",
                        "fileName": "5.jpg ",
                        "fileSize": 218100
                    },
                    "webUrl": "https://typetalk.com/topics/3557/posts/154010/attachments/3/5.jpg ",
                    "apiUrl": "https://typetalk.com/api/v1/topics/3557/posts/154010/attachments/3/5.jpg "
                },
                {
                    "attachment": {
                        "contentType": "application/octet-stream",
                        "fileKey": "4",
                        "fileName": "6.jpg ",
                        "fileSize": 627926
                    },
                    "webUrl": "https://typetalk.com/topics/3557/posts/154010/attachments/4/6.jpg ",
                    "apiUrl": "https://typetalk.com/api/v1/topics/3557/posts/154010/attachments/4/6.jpg "
                }
            ],
            "quotedPosts": [],
            "message": "I was able to improve the top screen. http://nulab-inc.com/ja/",
            "mention": null,
            "createdAt": "2019-03-02T06:13:44Z",
            "topicId": 3557,
            "contents": null,
            "mentions": [],
            "talks": [],
            "replyTo": null,
            "links": [
                {
                    "id": 3148,
                    "url": "http://nulab-inc.com/ja/",
                    "contentType": "text/html; charset=UTF-8",
                    "title": "Further collaboration with the team|Nulab",
                    "description": "Millions of users are using Nulab's services to improve team communication. Make your team's work even more enjoyable with Nulab's online collaboration tools.",
                    "imageUrl": "https://nulab-inc.com/ogp_dft.png ",
                    "embed": null,
                    "createdAt": "2015-06-15T06:41:24Z",
                    "updatedAt": "2017-03-03T10:11:08Z"
                }
            ],
            "id": 154010,
            "account": {
                "id": 2492,
                "name": "hayashi",
                "fullName": "hayashi",
                "suggestion": "hayashi",
                "imageUrl": "https://typetalk.com/accounts/2492/profile_image.png?t=1453871047310",
                "isBot": false,
                "createdAt": "2016-01-26T08:19:01Z",
                "updatedAt": "2019-09-04T07:25:45Z"
            },
            "likes": [],
            "updatedAt": "2019-03-02T06:13:44Z"
        },
        {
            "attachments": [],
            "quotedPosts": [],
            "message": "Masa-san, what do you think of the colors on this screen?",
            "mention": null,
            "createdAt": "2019-03-03T06:13:44Z",
            "topicId": 3557,
            "contents": null,
            "mentions": [],
            "talks": [],
            "replyTo": null,
            "links": [],
            "id": 154011,
            "account": {
                "id": 2489,
                "name": "yoshizawa",
                "fullName": "Yoshi",
                "suggestion": "Yoshi",
                "imageUrl": "https://typetalk.com/accounts/2489/profile_image.png?t=1564389095614",
                "isBot": false,
                "createdAt": "2016-01-26T08:18:12Z",
                "updatedAt": "2019-09-04T07:25:45Z"
            },
            "likes": [],
            "updatedAt": "2019-03-03T06:13:44Z"
        }
    ]

You can get various things such as message IDs, attachments, and the number of likes.

reply

The message ID is used to reply to the message posted by the bot by itself. Use json to work with JSON strings.

reply_to_me.py


import requests
import pprint
import json

token = ''
url = ''

msg = {'message':'Hello, Typetalk!'}
headers = {'X-TYPETALK-TOKEN': token}
r = requests.post(url, json = msg, headers = headers)

dict = json.loads(r.text)
id = dict['post']['id']

reply = {'message':'Hello!', 'replyTo': id}
q = requests.post(url, json = reply, headers = headers)
print(q.status_code)
pprint.pprint(q.json())

When you run, the bot is Hello! You should reply . Screenshot 2020-09-09 211038.jpg

Commentary
dic = json.loads(r.text)

Converts a JSON string to a dictionary type.

id = dict['post']['id']

[Official response example](https://developer.nulab.com/ja/docs/typetalk/api/1/post-message/#%E3%83%AC%E3%82%B9%E3%83% From 9D% E3% 83% B3% E3% 82% B9% E3% 81% AE% E4% BE% 8B), you can see that the message ID is the value of the ʻid key under the post` key.

reply = {'message':'Hello!', 'replyTo': id}

You can do various things by setting parameters. In message posting, you can reply by writing message ID in replyTo.

How nice

Like the message posted by the bot yourself.

like.py


import requests
import pprint
import json

token = ''
url = ''

msg = {'message':'Hello, Typetalk!'}
headers = {'X-TYPETALK-TOKEN': token}
r = requests.post(url, json = msg, headers = headers)

dic = json.loads(r.text)
id = dic['post']['id']

like = url + '/posts/' + str(id) + '/like'
q = requests.post(like, headers = headers)
print(q.status_code)
pprint.pprint(q.json())

When you do, your bot should like it. Screenshot 2020-09-09 212838.jpg

Commentary
like = url + '/posts/' + str(id) + '/like'

You can do various things by setting URL parameters. Like addition

https://typetalk.com/api/v1/topics/:topicId/posts/:postId/like

It has become.

in conclusion

The above is the introduction of how to use. There are many other things you can do, such as deleting messages and downloading attachments. You can see the various parameters from the drawer Typetalk API to the left of the Typetalk API docs (https://developer.nulab.com/en/docs/typetalk/). With the above method, you can access only the APIs in the topic.post and topic.read scopes.

References

Recommended Posts

[Python] How to use Typetalk API
How to use OpenPose's Python API
python3: How to use bottle (2)
[Python] How to use list 1
How to use Python argparse
Python: How to use pydub
[Python] How to use checkio
How to use Python lambda
[Python] How to use virtualenv
python3: How to use bottle (3)
python3: How to use bottle
How to use Python bytes
[BigQuery] How to use BigQuery API for Python -Table creation-
Python: How to use async with
[Python] How to use Pandas Series
How to use Requests (Python Library)
How to use SQLite in Python
[Python] How to use list 3 Added
How to use Mysql in python
How to use ChemSpider in Python
How to use FTP with Python
Python: How to use pydub (playback)
How to use PubChem in Python
How to use bing search api
How to use python zip function
[Python] Summary of how to use pandas
How to install and use pandas_datareader [Python]
[python] How to use __command__, function explanation
[Python] How to use import sys sys.argv
[Python] Organizing how to use for statements
Memorandum on how to use gremlin python
[Python2.7] Summary of how to use unittest
python: How to use locals () and globals ()
How to use __slots__ in Python class
How to use "deque" for Python data
How to use Python zip and enumerate
[Python] Understand how to use recursive functions
Summary of how to use Python list
How to use GCP's Cloud Vision API
[Python2.7] Summary of how to use subprocess
How to use is and == in Python
[Blender x Python] How to use modifiers
[Question] How to use plot_surface of python
How to use Python-shell
How to use tf.data
How to use virtualenv
How to use Seaboan
How to use shogun
How to use Pandas 2
How to use Virtualenv
How to use numpy.vectorize
How to use pytest_report_header
How to install python
How to use partial
How to use Bio.Phylo
How to use SymPy
How to use x-means
How to use IPython
How to use virtualenv
How to use Matplotlib
How to use numpy