LoginSignup
5
5

More than 5 years have passed since last update.

【ぴよぴよ会#1】Lambdaで遊ぼう:Pythonスクリプトの作成

Last updated at Posted at 2016-04-26

ハンズラボ ぴよぴよ会#1の https://handslab.doorkeeper.jp/events/42327 資料です。

前提条件

  • AWSのアカウントを持っている
  • 当該のアカウントでAWS Lambdaを操作する権限を持っている
  • TwitterのAPIキーとアクセストークンを持っている
  • ターミナルにてpipコマンドが使用できる

スクリプトの作成

テキストエディタを用いて、クライアントで作業します。

  • Pythonスクリプト"lambda_function.py"を作成します。
  • 使用するモジュールを作業ディレクトリに準備します
  • 作業ディレクトリをZIP化します

作業ディレクトリの準備

ユーザーディレクトリ配下に作業用ディレクトリを準備します。
ターミナルで下記コマンドを実行して下さい

コマンド
cd ~
mkdir piyopiyo2
確認
ls | grep piyopiyo2
結果
piyopiyo2

作業ディレクトリに移動して作業します。

コマンド
cd piyopiyo2
確認
pwd
結果
/Users/****/piyopiyo2

外部モジュールのインストール

使用する外部モジュールを作業ディレクトリにインストールします。
今回はモジュールとしてtweepyを使用します
参考:リファレンス

コマンド
pip install tweepy -t ./
確認
ls
結果
examples                requests_oauthlib-0.6.1.dist-info
oauthlib                six-1.10.0.dist-info
oauthlib-1.0.3-py2.7.egg-info       six.py
requests                six.pyc
requests-2.9.1.dist-info        tweepy
requests_oauthlib           tweepy-3.5.0.dist-info

'xxxxxxxxxxxxxxxxxxxx' になっている''の間に取得したキーで置換してください

lamba_function.pyの作成

Pythoスクリプトを作成します。
現在のディレクトリ(pipでモジュールをインストールしたディレクトリ)に lamba_function.py の名前でスクリプトを作成してください。

Pythonの基本的な部分をざっとまとめました
参考:AWS Lambdaを使うためにPythonを勉強したまとめ

lamba_function.py
import json
import tweepy

CONSUMER_KEY = 'xxxxxxxxxxxxxxxxxxxx'
CONSUMER_SECRET = 'xxxxxxxxxxxxxxxxxxxx'
ACCESS_TOKEN = 'xxxxxxxxxxxxxxxxxxxx'
ACCESS_TOKEN_SECRET = 'xxxxxxxxxxxxxxxxxxxx'



def lambda_handler(event, context):

    client = tweepy_client()
    post_message = 'Hands-Lab piyopiyo kai'
    post_twitter(client, post_message)




def post_twitter(client, message):
    API = client
    text = message
    req = API.update_status(text)

    return req




def tweepy_client():

    consumer_key = CONSUMER_KEY
    consumer_secret = CONSUMER_SECRET
    access_token = ACCESS_TOKEN
    access_token_secret = ACCESS_TOKEN_SECRET

    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    api = tweepy.API(auth)

    return api

zip化する

作業ディレクトリにて下記コマンドを実行します

コマンド
zip -r myfunc ./

以上で完了です

5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5