[Lambda] [Python] Post to Twitter from Lambda!

The weather is bad. This is Yoshida. I especially like Lambda for AWS services. Set aside whether you are mastering it Maybe it's because Lambda has recently made Python available.

I listen to Lambda material in Python!

What a cool Node.js! I was wondering if I'm out of date! ?? (Dismay)

Because I felt such anxiety, I tried my best with Python for about 4 hours.


0. Purpose

Lambda is fired with awsSNS as a trigger and SNS messages are posted on Twitter.

_ The image looks like this _

プレゼンテーション1.jpg

This time, I will use a sample SNS message to post "Hello from SNS!" To my account.

Prerequisites

--I have a Twitter account --Your phone number has been registered in your Twitter account --Python is installed and you can use the pip command

1. Twitter post preparation

Get ready to work with Twitter

https://dev.twitter.com/

Accessing the above URL will take you to the Twitter developer site.

If you used to register Twitter apps or did it a long time ago, here

Twitter画面1.jpg

Twitter_Developers2.jpg

If you haven't signed in to your Twitter account, click Sign In in the upper right to sign in.

Twitter_Application_Management.jpg

Create_an_application___Twitter_Application_Management.jpg

When you're done writing, scroll down and if you can read the attention, read and agree.

sample2yukiyoshid___Twitter_Application_Management.jpg

2sample2yukiyoshid___Twitter_Application_Management.jpg

003.jpg

004.jpg If you can confirm the above four keys, preparations on Twitter are complete.

2. Preparing to create a Lambda Function

Now that Twitter is ready, I'll write it right away.

Usage environment: Mac

First, create a working directory and install the external modules to be used in it. This time I created it right under the home. After creating the directory, create a file to write the script.

mkdir lambda_function`
cd lambda_function
vi function.py

Next, install the external module used by lambda. This time, we will use a module called "Requests-OAuthlib", so install it.

pip install requests_oauthlib -t ./


 ___ Hit the command in the directory you just created ___
 You can install it by specifying the current directory after the ___ -t option. ___

3.fnction.py
 Here is the script I wrote this time


#### **`function.py`**
```python


from requests_oauthlib import OAuth1Session

# Consumer Key 			: CK
# Consumer Secret 		: CS
# Access Token 			: AT
# Accesss Token Secert 	: AS

CK = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
CS = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
AT = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
AS = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

URL = 'https://api.twitter.com/1.1/statuses/update.json'


def handler(event, context):
	msg = event['Records'][0]['Sns']['Message']
	params = {"status": msg }

	twitter = OAuth1Session(CK, CS, AT, AS)
	req = twitter.post(URL, params = params)

	if req.status_code == 200:
		return msg
	else:	
		return req.status_code


Thanks to this script, Python Virgin has been promoted to 4 hours of Python history. No, it doesn't work! This alone (sweat The URL seems to be a special URL for posting.

4. Zip the created environment to AWS

Let's zip the environment created this time and bring it to AWS Note that ___ you will get angry if you can't find the module unless you compress the contents of the created directory ___ I was addicted to this for about an hour ...

cd lambda_function

zip -r myfunc.zip ./



 The name of the zip file to be compressed is appropriate.

 ![AWS_マネジメントコンソール.jpg](https://qiita-image-store.s3.amazonaws.com/0/52141/fa003804-a627-f200-a1ba-b3288da87c1f.jpeg "AWS_マネジメントコンソール.jpg ")

 ![AWS_Lambda.jpg](https://qiita-image-store.s3.amazonaws.com/0/52141/4a4a5aab-f73f-3f6a-cbbb-5030b5c808f6.jpeg "AWS_Lambda.jpg ")

 ![AWS_Lambda02.jpg](https://qiita-image-store.s3.amazonaws.com/0/52141/6e78ebd2-2b01-0ad7-6d94-c43398432052.jpeg "AWS_Lambda02.jpg ")

 ![AWS_Lambda03.jpg](https://qiita-image-store.s3.amazonaws.com/0/52141/f4c24b7c-61ee-e30e-fe1b-d361ae627909.jpeg "AWS_Lambda03.jpg ")

#### The point is the name of the handler. The reason for becoming a function.handler is as written.

 All you have to do is Create Function and you're done.

4.Test
 Specify the test source as SNS. Then ...
 ![AWS_Lambda-kekka.jpg](https://qiita-image-store.s3.amazonaws.com/0/52141/e182de85-c722-d23b-c4a0-6b1c7b8a31e7.jpeg "AWS_Lambda-kekka.jpg ")

 The log is out properly.
 If you check Twitter ...

 ![ミッスッター_ヨーダ__Yuki_BB3_さん___Twitter.jpg](https://qiita-image-store.s3.amazonaws.com/0/52141/f2164b23-0446-facc-ebab-f843fe508a01.jpeg "ミッスッター_ヨーダ__Yuki_BB3_さん___Twitter.jpg ")

 It's done!


 For this app, when I tried to send the exact same test message, I got a 403 error and couldn't post. Is it a specification?

---

 I did it! !! !! !!
 It's done!

 For example, if you use BOTO to tweet the number of EC2 you have set up in the AWS environment, you can prevent forgetting to erase it, right?

 I'm glad I made something that works with Python, regardless of what I use it for.



### reference
 [Access the Twitter API with Python](http://qiita.com/yubais/items/dd143fe608ccad8e9f85)

 [Creating a Twitter application (Consumer key, Consumer secret, Access token, Access token secret confirmation method)](http://website-planner.com/twitter%E3%82%A2%E3%83%97%E3% 83% AA% E3% 82% B1% E3% 83% BC% E3% 82% B7% E3% 83% A7% E3% 83% B3% E3% 81% AE% E4% BD% 9C% E6% 88% 90% EF% BC% 88consumer-key% E3% 80% 81consumer-secret% E3% 80% 81access-token% E3% 80% 81access-token-secret /)


Recommended Posts

[Lambda] [Python] Post to Twitter from Lambda!
Post from Python to Slack
Post to Twitter using Python
Post from python to facebook timeline
Post images from Python to Tumblr
Easily post to twitter with Python 3
Regularly post to Twitter using AWS lambda!
How to access RDS from Lambda (python)
Changes from Python 3.0 to Python 3.5
Changes from Python 2 to Python 3.0
Post youtube soaring title to twitter with python3
Post to vim → Python → Slack
Cheating from PHP to Python
Twitter post from command line
Post to slack with Python 3
Anaconda updated from 4.2.0 to 4.3.0 (python3.5 updated to python3.6)
Query Athena from Lambda Python
Switch from python2.7 to python3.6 (centos7)
Connect to sqlite from python
How to use Python lambda
Post to Slack in Python
POST messages from python to Slack via incoming webhook
Call Matlab from Python to optimize
[Introduction to Udemy Python 3 + Application] 58. Lambda
Create folders from '01' to '12' with python
Connect to utf8mb4 database from python
Post multiple Twitter images with python
Python (from first time to execution)
How to access wikipedia from python
Python to switch from another language
[Python] Regularly export from CloudWatch Logs to S3 with Lambda
[Nanonets] How to post Memo [Python]
Did not change from Python 2 to 3
Update Python on Mac from 2 to 3
Post a message from IBM Cloud Functions to Slack in Python
Things to note when running Python on EC2 from AWS Lambda
Collecting information from Twitter with Python (Twitter API)
[Python] Fluid simulation: From linear to non-linear
From Python to using MeCab (and CaboCha)
How to update Google Sheets from Python
Send a message from Python to Slack
Private Python handbook (updated from time to time)
Tweet from python with Twitter Developer + Tweepy
I want to use jar from python
Convert from katakana to vowel kana [python]
Push notification from Python server to Android
Connecting from python to MySQL on CentOS 6.4
Post from another account with Twitter API
Porting and modifying doublet-solver from python2 to python3.
Lambda function to take AMI backup (python)
Python> Output numbers from 1 to 100, 501 to 600> For csv
Connect to s3 with AWS Lambda Python
[Road to intermediate Python] Use lambda expressions
Convert from Markdown to HTML in Python
[Amazon Linux] Switching from Python 2 series to Python 3 series
API explanation to touch mastodon from python
Connect to coincheck's Websocket API from Python
UNHEALTHY Workspaces restart Lambda rewritten to python
Updated to Python 2.7.9
twitter on python3
Sum from 1 to 10