[PYTHON] I will teach you the Twitter tweet bot in the easiest way in Japan.

About the author

--Students of Toyo University Faculty of Information Technology

Preparation

--Environment where python can be executed --I want you to have a heroku account --I want you to be able to use the Twitter API as well.

Let's start! Here source code ** There is "requirements.txt" in the source code. ** ** ** These are the modules installed by heroku. ** **

tweet.py



import urllib
from requests_oauthlib import OAuth1Session
import requests
import sys
import os
import datetime

#Put the key etc. in the environment variable
CK = os.environ.get("CK")
CS = os.environ["CS"]
AT = os.environ["AT"]
ATS = os.environ["ATS"]

#It's like creating a signature URL
twitter = OAuth1Session(CK, CS, AT, ATS)

# statues/Use update. (The same tweet content in a short period of time will be blocked)
url = "https://api.twitter.com/1.1/statuses/update.json"

# ex.Good morning! !! December 11, 2019 08:51:56
dtNow = datetime.datetime.now() + datetime.timedelta(hours=9)
tweet = "Good morning! !!" + dtNow.strftime('%Y year%m month%d day%H:%M:%S')

params = {
    "status": tweet
}

res = twitter.post(url, params=params)

if res.status_code == 200:
    print("SUCCESS")
else:
    print(res)


Caution

statues / update ** will be blocked if you make the same tweet in a short period of time. ** (403 is back) So I used datetime to add a different time zone to the string each time.

heroku cli settings

Do the following in your terminal: It is considered that the initial settings have been made.

terminal


$ heroku login

$ heroku create [app name]

$ git init

$ git remote add heroku https://git.heroku.com/[your app name].git

$ git add .
$ git commit -m "First commit to heroku"
$ git push heroku master

Set Twitter API key in heroku environment variable

terminal


$ heroku config:set CK=APIkey CS=APIsecretkey AT=Accesskey token ATS=Accesstokensecret

Check if it actually runs on heroku

terminal


$ heroku run python tweet.py

OK if SUCCESS is returned! !! !! !!

Setting up cron (scheduler) on heroku

It is assumed that the credit card has been registered.

terminal


$ heroku addons:add scheduler:standard

go to heroku

--Since there is an created app, click the scheduler in it --I think there is create add, so click it.

スクリーンショット 2019-12-11 9.30.39.png

Set as above and you're done! !! Let's check it in 10 minutes! !!

thank you for your hard work!

Recommended Posts

I will teach you the Twitter tweet bot in the easiest way in Japan.
Tweet using the Twitter API in Python
The easiest way to set up Last-Modified in Flask
The easiest line bot in the world to lose weight
The easiest way to get started in Slack socket mode (Go)
What is Jenkins? ] Installation-how to use-automatic test / automatic deployment will be explained in the world's easiest way