LoginSignup
8
1

More than 1 year has passed since last update.

PythonとHerokuで最初のRedditボットを作成する

Last updated at Posted at 2022-06-15

Redditのボットを作るのは簡単なはずですが、そのプロセスはあまり文書化されていません。この記事では、ボット作成の一つ一つのステップを案内していきます。

Redditとは?

redditとは、米国の出版大手コンデナストが運営するソーシャルニュースサイトである。「Digg」と並ぶ代表的なソーシャルニュースの一つとして認知されている。このサイトは色んなコミュニティー入ってまして、例えば 「reddit.com/r/soccer」がサッカーのスレッド、「reddit.com/r/movies」が映画など

前提条件

  • Pythonの基本的な知識
  • コマンドラインの使用
  • Redditのアカウント
  • 電子メール
  • Githubのアカウント

第1部: Redditの開発者アカウントを作成する
2019年以降、Redditはその外観を大きく変えましたが、すべての開発者ツールはまだRedditの旧サイトに収容されています。

https://old.reddit.com でRedditのアカウントにログインします。
プリファレンスをクリック

1_GqnmAnU1SNbCoP6D8-5Mzw.png

「Apps」をクリックする

1_eBTegzScfDQ89icMFnWp5A.png

アプリページの一番下までスクロールし、「are you a developer? Create an app」 ボタンをクリックします。

1_tbF39Nli8gGgdWF7JLX-2A.png

フォームに入力します。アプリケーションは必ず「script」に設定し、対話権限を持たせてください。

1_n_Bsj9Ha4uVqWPWv1dbc6A.png

1_B96JaiaawmC6VMDL6yAewA (1).png

ボットをコーディングする

開発者アカウントの作成が完了したら、個人用スクリプトと秘密鍵が送られてくるはずです。

Redditはこれらを使ってあなたのボットを認証し、あなたが悪さをしないことを確認します。

ボットを作る最も簡単な方法は、Python Reddit API Wrapper (PRAW)を使用することです。PRAWは、非常に洗練されたボットを簡単に構築するための機能をすべて備えています。新しい投稿やコメントをすべてスキャンし、投稿やコメントを行い、データを抽出するために使用することができます。

ボットをコーディングする。

新しいボット用のフォルダーを作成する、コマンドライン/ターミナルを開き、新しいプロジェクトフォルダーに移動します。

pipでPRAWをインストールする:

$ pip install praw

作業フォルダにmain.pyファイルを作成し、以下を追加してPRAWでReddit Botを検証します。

main.py
import praw

reddit = praw.Reddit(
	client_id="TfP3RokMNfUMX4ke9vjPzA", #clientIDはボットでの設定
	client_secret="xaxkj7HNh8kwg8e5t4m6KvSrbTI", #secretはボットでの設定
	password="impossible_to_guess_password", #自分のアカウントのパッスワード
	user_agent="A Random Blurb About Your Bot", #短い説明
	username="Your_Reddit_Account_Name", #自分のアカウントのユーサー名
)

このボットは、!quoteと入力した人にハリー・ポッターの引用文をコメントします。以下は、コードにコピー&ペーストできる引用文のリストです。また、引用文を選択するために、ランダムライブラリをインポートする必要があります。

main.py
import random

Harry_Potter_Quotes = [
  'It is impossible to manufacture or imitate love',
  'What do I care how he looks? I am good-looking enough for both of us. . .',
  'Family…Whatever yeh say, blood’s important. . .',
  'It matters not what someone is born, but what they grow to be.',
  'Every human life is worth the same, and worth saving.',
  'Fear of a name increases fear of the thing itself.'
]

最後に、冒頭で作成したredditの変数を使って、ユーザーのコメントの流れを取得し、!quoteと書いてあるものに反応することができます。

main.py
                                 #どこでものコミュニティー、"soccer"とかでも良い
for comment in reddit.subreddit("testingground4bots").stream.comments():
  
  #Use this line to see which accounts are commenting
  print(comment.parent().author)

  rand_index = random.randint(0, len(Harry_Potter_Quotes) -1)

  rand_quote = Harry_Potter_Quotes[rand_index]

  if "!quote" in comment.body:
    comment.reply(rand_quote)

コードを少し整理して、main関数でまとめると、最終的な出力は次のようになります。

main.py
import praw
import random


def main():

	reddit = praw.Reddit(
		client_id="TfP3RokMNfUMX4ke9vjPzA", #clientIDはボットでの設定
		client_secret="xaxkj7HNh8kwg8e5t4m6KvSrbTI", #secretはボットでの設定
		password="impossible_to_guess_password", #自分のアカウントのパッスワード
		user_agent="A Random Blurb About Your Bot", #短い説明
		username="Your_Reddit_Account_Name", #自分のアカウントのユーサー名
	)

	Harry_Potter_Quotes = [
	  'It is impossible to manufacture or imitate love',
	  'What do I care how he looks? I am good-looking enough for both of us. . .',
	  'Family…Whatever yeh say, blood’s important. . .',
	  'It matters not what someone is born, but what they grow to be.',
	  'Every human life is worth the same, and worth saving.',
	  'Fear of a name increases fear of the thing itself.'
	]

	for comment in reddit.subreddit("testingground4bots").stream.comments():
	  
	  #Use this line to see which accounts are commenting
	  print(comment.parent().author)

	  rand_index = random.randint(0, len(Harry_Potter_Quotes) -1)

	  rand_quote = Harry_Potter_Quotes[rand_index]

	  if "!quote" in comment.body:
	    comment.reply(rand_quote)

python3 main.py をコマンドラインに入力し、ボットを起動します。それから、あなたがデプロイしたコミュニティに行き、!quoteと入力してテストしてください。ボットが応答するまで、1、2分かかるかもしれません。なぜなら、ボットはトリガーとなるフレーズを探すために、新しいコメント一つ一つを解析しているからです。しかし、最終的にそれが生きているのを見れば、待った甲斐があったと思うはずです。

Herokuへのデプロイメント

Herokuはアプリケーションデプロイメントプラットフォームで、誰でも月に550時間のサーバー時間を無料で利用できる手厚い無料プランを備えています。この無料プランを利用して、botをデプロイすることになります。

Herokuにデプロイする前に、botのフォルダに2つの必要なファイルを追加する必要があります。

  • requirements.txt ファイル:アプリを動作させるために必要なライブラリや依存関係の概要が記述されています。第2部で仮想環境を適切に設定したと仮定して、コマンドラインで次のように入力すると、仮想環境を生成できます。
$ pip freeze > requirements.txt
  • procfile: これはHerokuにアプリの分類とデプロイ方法を指示します。Herokuは命名規則に厳しいです。Procfileは基本的なテキストファイルで、以下のようなコードを持っている必要があります。
procfile
worker: python main.py

ボットコードのセットアップは完了です。あとはそれを GitHub にプッシュするだけです。GitHub は Heroku にデプロイするための最もシンプルな方法です。

これで、アクティブなボットを使えるようになるまであと数ステップとなりました。

Heroku.comにアクセスします。
Sign up または SIGN UP FOR FREE をクリックします。
1_DstwRvDHAfkt3HojNGvvyw.png
一般的なサインアッププロセスに従うと、最終的に新しいアプリを作成するように要求されます。アプリの固有名と国名を入力し、Create app(アプリを作成)をクリックします。
1_grjpEyUm2YlGgqTInIRYFQ.png
それから「settings」をクリックして、buildpackを「add buildpack」にクリックして、pythonにする。
Screen Shot 2022-06-10 at 18.42.04.png

Screen Shot 2022-06-10 at 18.43.25.png

その設定終わったらAppのデプロイをします、deployにクリックして、それでgithubと連携します。

Screen Shot 2022-06-10 at 18.37.29.png

Gitリポジトリを選んで、ブランチを選んで、準備終了!

Screen Shot 2022-06-15 at 18.50.08.png

それでDeploy Branchをクリックして、デプロイのログもでます。

-----> Building on the Heroku-20 stack
-----> Using buildpack: heroku/python
-----> Python app detected
-----> No Python version was specified. Using the same version as the last build: python-3.10.4
      To use a different version, see: https://devcenter.heroku.com/articles/python-runtimes
!     Python has released a security update! Please consider upgrading to python-3.10.5
      Learn More: https://devcenter.heroku.com/articles/python-runtimes
-----> No change in requirements detected, installing from cache
-----> Using cached install of python-3.10.4
-----> Installing pip 22.1.2, setuptools 60.10.0 and wheel 0.37.1
-----> Installing SQLite3
-----> Installing requirements with pip
-----> Discovering process types
      Procfile declares types -> worker
-----> Compressing...
      Done: 62.7M
-----> Launching...
      Released v16
      https://XXXXXX.herokuapp.com/ deployed to Heroku

ログの中にrequirements.txtが読まれて、Procfileの設定が読まれて、無事にデプロイは出来ました!

最後は「resources」のタブでボットをOnにして終了です!それで
https://www.reddit.com/r/testingground4bots の!quoteすると:

Screen Shot 2022-06-15 at 18.55.47.png

以上。

8
1
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
8
1