Azure Functions で X API の無料枠をつかってポストする
はじめに
tweepy を Azure Functions で使って、Xの無料枠でポストしてみました。
Azure Functionsのデプロイ方法
こちらの記事をご確認ください。
tweepy
をつかう
Azure Functions
で Python
を使ったコードをデプロイします。
その際に、tweepy
をインポートして利用します。
X API
の認証情報の確認
tweeoy で OAuth 1.0a の認証を利用して投稿しますので、X Developer Portal
から4つの情報を取得します。
X APIの利用には、英語で申請が必要です。(この辺りはWebで調べるといっぱいでてくるので検索してみてください。)
- API Key(Consumer Key)
- API Key Secret(Consumer Secret)
- Access Token
- Access Token Secret
Azure Functions
の 環境変数の設定
X API の認証情報を環境変数として設定する必要があります。Azure Portal で Azure Functions の「設定 > 環境変数」セクションから以下のキーを追加します。
API_KEY
API_SECRET
ACCESS_TOKEN
ACCESS_SECRET
追加
から環境変数を追加していきます。
各環境変数には、X Developer ポータルで確認したキーを入力してください。
ディレクトリ構成
VS Code などで下記の構成にします。
TweetFunction/
├── __init__.py
├── function.json
host.json
requirements.txt
__init__.py
メインの関数です。
環境変数未設定時に設定していない環境変数を返答するようにしました。(2025/08/11)
import logging
import azure.functions as func
import tweepy
import os
import json
def main(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Tweet function triggered.')
# 環境変数の確認
required_env_vars = ["API_KEY", "API_SECRET", "ACCESS_TOKEN", "ACCESS_SECRET"]
missing_vars = [var for var in required_env_vars if var not in os.environ]
if missing_vars:
missing_vars_str = ", ".join(missing_vars)
logging.error(f"Missing environment variables: {missing_vars_str}")
return func.HttpResponse(
f"Server configuration error: Missing environment variables: {missing_vars_str}",
status_code=500
)
try:
req_body = req.get_json()
tweet_text = req_body.get('text')
if not tweet_text:
logging.warning("Request body missing 'text'")
return func.HttpResponse("Missing 'text' in request body", status_code=400)
# 認証情報(環境変数から取得)
client = tweepy.Client(
consumer_key=os.environ["API_KEY"],
consumer_secret=os.environ["API_SECRET"],
access_token=os.environ["ACCESS_TOKEN"],
access_token_secret=os.environ["ACCESS_SECRET"]
)
response = client.create_tweet(text=tweet_text)
logging.info(f"Tweet created successfully with ID: {response.data['id']}")
# Tweepyのバージョンを取得
tweepy_version = tweepy.__version__
return func.HttpResponse(
json.dumps({
"status": "success",
"tweet_id": response.data["id"],
"tweepy_version": tweepy_version
}),
status_code=200
)
except tweepy.TweepyException as te:
logging.error(f"Tweepy error: {te}")
return func.HttpResponse("Failed to post tweet. Please try again later.", status_code=500)
except Exception as e:
logging.error(f"Unexpected error: {e}")
return func.HttpResponse("An unexpected error occurred. Please try again later.", status_code=500)
function.json
Azure Functions のトリガーやバインディングを定義する設定ファイルです。HTTP トリガーを使っているので、以下のような内容になります。
{
"bindings": [
{
"authLevel": "function",
"type": "httpTrigger",
"direction": "in",
"name": "req",
"methods": ["post"]
},
{
"type": "http",
"direction": "out",
"name": "$return"
}
]
}
host.json
{
"version": "2.0"
}
requirements.txt
Python の依存パッケージを定義するファイルです。tweepy を使っているので、以下のようになります。
azure-functions
tweepy
VS Code
での作業
コードの構成
VS Codeで下記のような構成を設定します。
TweetFunction/
├── __init__.py
├── function.json
host.json
requirements.txt
Azure Tool
のインストール
拡張機能
から Azure Tool
をインストールします。
Azure つかうならこれ便利なので入れておいて損はない気がします。
Azure にサインインします。
Azure Functions へコードをデプロイ
Azure サブスクリプションの中から、前回作成したリソースを右クリックします。
Deploy to Function Apps...
をクリックします。
構成ファイルが入っているフォルダを選択します。
デプロイが完了しました。
Azure Portal
で確認
デプロイしたスクリプトもここから確認(多分編集もできる)できます。
Azure Functions のトリガー条件と実行結果の流れが確認できます。(わかりやすい)
HTTP リクエスト
Method
POST
URI
既定のドメイン
と関数名
は、Azure Functions
のポータルから確認できます。
https://{Azure Functions の既定のドメイン}/api/{関数名}
Headers
{
"Content-Type" : "application/json"
}
Queries
{
"code" : "{secret Key}"
}
シークレットキー
も Azure Functions
のポータルから確認できます。
Body
{
"text": "今日も暑いね"
}
さいごに
Azure Functions を経由して、Xの無料枠を利用してポストできるようになりました。
Xの無料枠は制限が大きいため、そんな頻繁にポストできませんが、ちょっとしたお知らせとかなら便利そうですね。
今のままだと、どこからでも HTTP リクエスト
できてしますので、セキュリティの設定も考慮したいところです。
Discussion