・ MAC (PC) ・ AWS Lambda ・ Twitter API ・ Twitter account
Apply for Twitter API from the URL below. https://developer.twitter.com/ja/docs
Get the API key & secret and Access token & secret.
Write the source code for Twitter authentication. You don't have to separate the files separately.
keys.go
package keys
import
(
//This is the import required for the Twitter API. If not, install it.
"github.com/ChimeraCoder/anaconda"
)
func GetTwitterApi() *anaconda.TwitterApi {
anaconda.SetConsumerKey("API Key")
anaconda.SetConsumerSecret("API secret Key")
api := anaconda.NewTwitterApi("token", "token secret")
return api
}
Write the source code of the tweet body. This can also be done without separating the files. I try to tweet the date and text.
text.go
package text
import (
"fmt"
"time"
)
func TextTweet() string {
//I'll write a tweet
tweetText := "test"
d := time.Now().Day()
m := time.Now().Month()
//Store the text to tweet.
TweetContent := tweetText
TweetOfToday := fmt.Sprintf("【%d month%d day]\n %s", m, d, TweetContent)
return TweetOfToday
}
Write the source to actually tweet.
main.go
package main
import (
"fmt"
. "fmt"
. "./keys"
. "./text"
)
func main(){
api := GetTwitterApi()
text := TextTweet()
tweet, err := api.PostTweet(text, nil)
if err != nil {
panic(err)
}
Print(tweet.Text)
fmt.Println("Finish!")
}
By the way, the folder structure is as follows.
autoTweet
∟main.go
∟keys
∟keys.go
∟text
∟text.go
Upload the Go source code to AWS Lambda as a zip file. ↓ was very helpful. https://dev.classmethod.jp/articles/aws-lambda-supports-go/
You need a binary file to upload and run to AWS Lambda. I put them together in one file (main.go) into a binary file. The binary file creation command is ↓. Only binary files can be zipped.
#GOOS=linux GOARCH=amd64 go build main.go
If you get an error creating the binary file, try the following:
#go get -u golang.org/x/sys/unix
#set GOOS=linux
#set GOARCH=amd64
#set CGO_ENABLED=0
If you test it with Lambda and you don't get an execution error, go to Twitter! It should have been tweeted!
Run Lambda periodically with the Cron expression of CloudWatch Events. The Cron expression can be executed once every two months or at any time depending on the setting. Reference URL: https://docs.aws.amazon.com/ja_jp/lambda/latest/dg/services-cloudwatchevents-expressions.html
For reference, I will describe the cron expression that is executed at 12:00 every day. (Because of UTC, it will be -9 hours)
crons expression:
00 3 * * ? *
It's OK if you tweet at the set time!
I wrote it quite roughly, but I hope it helps someone. .. ..
Recommended Posts