Easy! Implement a Twitter bot that runs on Heroku in Python

I will show you how to implement a Twitter bot that runs on Heroku in Python. I think it's exhausted, but it's the 2016 version.

The solution is to deploy a Python script on Heroku and use Heroku Scheduler to run the script on a regular basis.

The source code of the completed version is below. https://github.com/k-enomoto/minimum_twitter_bot

What to explain in this article

--Minimum source code for Twitter Bot --Deploy to Heroku --Heroku Scheduler settings

Not explained in this article

--How to use Heroku --How to use pip --How to create a Twitter API account

There are other detailed articles for each, so please refer to them.

Library preparation

Install the library you want to use.

$ pip install python-twitter
$ pip install bottle

We need to tell Heroku which library to use, so create requirements.txt.

$ pip freeze -l > requirements.txt

Maybe it will be like this.

bottle==0.12.9
future==0.15.2
oauthlib==1.1.2
python-twitter==3.1
requests==2.10.0
requests-oauthlib==0.6.2

Code to access the Twitter API

Get the Twitter API consumer_key, consumer_secret, ʻaccess_token_key, ʻaccess_token_secret in advance. Please refer to the following article for the acquisition method. Tweet using Twitter API in Ruby Also, each key is set in an environment variable from the viewpoint of security. How to set environment variables on Heroku will be described later.

Please feel free to arrange the content of the tweet as soon as you take it from the Web API.

tweet.py


# -*- coding: utf-8 -*-

import os
from datetime import datetime

import twitter


api = twitter.Api(consumer_key=os.environ["CONSUMER_KEY"],
                  consumer_secret=os.environ["CONSUMER_SECRET"],
                  access_token_key=os.environ["ACCESS_TOKEN_KEY"],
                  access_token_secret=os.environ["ACCESS_TOKEN_SECRET"]
                  )
api.PostUpdate("system time is %s" % datetime.now())

Web application code (dummy)

This is the point of this time. Prepare a dummy web app to keep the process running on Heroku. In this article, we used the lightweight web framework bottle. The sample code in bottle documentation is used as is.

index.py


# -*- coding: utf-8 -*-

import os
from bottle import route, run


@route("/")
def hello_world():
    return "" #Whatever you return here

run(host="0.0.0.0", port=int(os.environ.get("PORT", 5000)))

Procfile The Procfile contains the commands to be executed in the Heroku container. The command to start the above dummy web application is described.

Procfile


web: python index.py

runtime.txt This is point 2. Create runtime.txt and describe the runtime to use.

runtime.txt


python-3.5.2

Deploy

Now you have all the files you need.

index.py
tweet.py
requirements.txt
runtime.txt
Procfile

Files must be managed in Git in order to deploy to Heroku. Commit to Git.

git add .
git commit -m "Initial commit"

Deploy to Heroku. Also, the environment variables mentioned above are set here. Replace your_cosumer_key, your_consumer_secret, your_access_token_key, and your_access_token_secret with your own values.

$ heroku create --stack cedar
$ git push heroku master
$ heroku config:set CONSUMER_KEY=your_cosumer_key CONSUMER_SECRET=your_consumer_secret ACCESS_TOKEN_KEY=your_access_token_key ACCESS_TOKEN_SECRET=your_access_token_secret

Make sure that you can deploy properly.

$ heroku logs

Registering a scheduler task

Finally, register the task with Heroku Scheduler. Enter the following command to bring up the scheduler registration page.

$ heroku addons:create scheduler:standard
$ heroku addons:open scheduler

Set the command to be executed by the scheduler and the frequency. Let's set up a Python script to tweet.

$ python tweet.py
scsho.png

This completes the Twitter bot.

Recommended Posts

Easy! Implement a Twitter bot that runs on Heroku in Python
Make a Twitter trend bot with heroku + Python
Create a list in Python with all followers on twitter
Summary of points to keep in mind when writing a program that runs on Python 2.5
I made a program to collect images in tweets that I liked on twitter with Python
Use Heroku in python to notify Slack when a specific word is muttered on Twitter
A class that summarizes frequently used methods in twitter api (python)
[Python] Create a LineBot that runs regularly
Create a bot that boosts Twitter trends
Let's make a Twitter Bot with Python!
Introducing a library that was not included in pip on Python / Windows
[Python] Created a Twitter bot that generates friend-like tweets using Markov chains
I made a Discord bot in Python that translates when it reacts
twitter on python3
A memo of a tutorial on running python on heroku
A memo that I wrote a quicksort in Python
A program that removes duplicate statements in Python
A note on optimizing blackbox functions in Python
A story about running Python on PHP on Heroku
Steps to create a Twitter bot with python
A memorandum for touching python Flask on heroku
A memo that I stumbled upon when doing a quote RT on Twitter Bot
[Beginner] What happens if I write a program that runs in php in Python?
In Python, I made a LINE Bot that sends pollen information from location information.
Implement Enigma in python
Create a data collection bot in Python using Selenium
I made a Twitter BOT with GAE (python) (with a reference)
[Python] This is easy! Search for tweets on Twitter
A template that I often use when making Discord BOT in Python (memorial note)
A note on the library implementation that explores hyperparameters using Bayesian optimization in Python
Until drawing a 3D graph in Python on windows10
Implement recommendations in Python
I made a VM that runs OpenCV for Python
I tried to implement a pseudo pachislot in Python
Implement XENO in python
What's in that variable (when running a Python script)
I made a LINE BOT with Python and Heroku
In Python, create a decorator that dynamically accepts arguments Create a decorator
A note on handling variables in Python recursive functions
Write a log-scale histogram on the x-axis in python
The Linux emulator "iSH" that runs on the iPad is a hot topic in me
Implement sum in Python
A note that runs an external program in Python and parses the resulting line
[Super easy] Let's make a LINE BOT with Python.
Implement Traceroute in Python 3
MALSS, a tool that supports machine learning in Python
A Python program in "A book that gently teaches difficult programming"
A general-purpose program that formats Linux command strings in python
A memorandum of stumbling on my personal HEROKU & Python (Flask)
Published a library that hides character data in Python images
[Python] Create a linebot that draws any date on a photo
Let's create a script that registers with Ideone.com in Python.
Use a macro that runs when saving python with vscode
A note on touching Microsoft's face recognition API in Python
I tried "a program that removes duplicate statements in Python"
Run LINE Bot implemented in Python (Flask) "without using Heroku"
Create a Twitter BOT with the GoogleAppEngine SDK for Python
Create code that outputs "A and pretending B" in python
[MQTT / Python] Implemented a class that does MQTT Pub / Sub in Python
A story about trying to implement a private variable in Python.
A set of script files that do wordcloud in Python3