PythonでChatwork APIを使ってチャットを取得・書き込み

Takuya Kobayashi⛰
2024.05.28

Chatwork APIを利用することで外部プログラムでChatworkを操作できるようになっています。
PythonでChatworkを操作してみましょう。

APIトークンを取得

右上の自分のアイコンのプルダウン→サービス連携→APIトークン:
https://www.chatwork.com/service/packages/chatwork/subpackages/api/token.php

ここでAPIトークンを取得できます。

APIトークンはID・Passwordと同じくらいの価値を持つので取り扱いには気をつけましょう。

また、APIのリクエスト数は、5分あたり300回 までとなります。

ルーム一覧を取得

取得したAPIトークンを使用してPythonでルーム一覧を取得します。

import requests

url = "https://api.chatwork.com/v2/rooms"
headers = {
    "accept": "application/json",
    "x-chatworktoken": "APIトークン"
}

def chatwork_get_rooms():
    response = requests.get(url, headers=headers)
    if response.status_code == 200:
        messages = response.json()
        return messages
    else:
        print(f"レスポンスコード:{response.status_code}")
        return []

chatwork_rooms = chatwork_get_rooms()
for room in chatwork_rooms:
    room_id = room['room_id']
    room_name = room['name']
    room_task_num = room['task_num']
    print(f"{room_id}:{room_name}({room_task_num})");

実行すると、ルームの一覧「ルームID:ルーム名(タスク数)」が表示されます。

機密情報は隠しています。

ルーム内のメッセージを取得

import requests

url = "https://api.chatwork.com/v2/rooms/84152049/messages" #マイチャットのエンドポイント
headers = {
    "accept": "application/json",
    "x-chatworktoken": "APIトークン"
}

def chatwork_get_messages():
    response = requests.get(url, headers=headers)
    if response.status_code == 200:
        messages = response.json()
        return messages
    else:
        print(f"レスポンスコード:{response.status_code}")
        return []

chatwork_messages = chatwork_get_messages()
for msg in chatwork_messages:
    #受信メッセージ確認
    account_id = msg['account']['account_id']
    body = msg['body']
    print(f"Account ID: {account_id}, Message: {body}")


APIの仕様によって自動的に差分が取得されます。取得済みのメッセージを再度取得するにはエンドポイントのURLに「?force=1」を追記することで最新の最大100件を取得することができます。

ルームにメッセージを送信

import requests

url = "https://api.chatwork.com/v2/rooms/84152049/messages" #マイチャットのエンドポイント
headers = {
    "accept": "application/json",
    "x-chatworktoken": "APIトークン"
}
def chatwork_send_message(send_message_txt):
    data = {'body': send_message_txt}
    response = requests.post(url, headers=headers, data=data)
    return response.status_code

message_body = "Pythonでメッセージを送っています。"
send_message = chatwork_send_message(message_body)
print(f"送信内容:{message_body}")
print(f"送信結果:{send_message}")

いかがでしたか

PythonでChatwork APIを使用してルーム一覧の表示・読み書きの操作をしてみました。
以下のリファレンスにすべての操作に関する情報が載っているので照らし合わせながらオリジナルのプログラムを動かしてみましょう。

Chatwork エンドポイント一覧:https://developer.chatwork.com/reference/get-me