4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Discordのbotを開発する Python版

Last updated at Posted at 2018-08-13

概要

discordのAPIラッパーdiscord.pyを使ってbotを作ってみた。ここにすでに記事があるのだが、画面キャプチャが古かったので最新版(2018年8月時点)を作ろうと思ったのがきっかけ。

本記事では触れないが似たようなラッパーでnode.js版もあるらしい。

環境

手順

Python環境の用意

何はともあれPython3系が必要。discor.py自体は3.4と3.5をサポートしていると書いてるのだが、そこに書いてある通り3.4だとQuick Exampleのコードを少し修正しないといけないので、3.5以降を使う。つもりだったのだが先に3.6.6で動作確認したので3.6.6を前提に説明します。

細かいPythonのバージョンを指定した環境構築にはpyenvとかを使うと良いと思うが、ここでは説明しない。以下の通り、何らかの手段でpython3.6の実行環境が整ったものとする。

$ python -V
Python 3.6.6

ちなみにPython3.7系では動かなかった。

botの登録

Discordのdevelopersサイトにアクセス。

Create an applicationを押下

スクリーンショット 2018-08-13 23.53.04.png

botの表示名(ここではDiscord Sample Bot)を入力して、画面右下のSave Changesを押下

screencapture-discordapp-developers-applications-478576764545925142-information-2018-08-13-23_59_40_2.png

左側のメニューからbotを選択し、右側のAdd Botを押下

screencapture-discordapp-developers-applications-478576764545925142-bots-2018-08-14-00_00_11.png

BOTを追加するか聞かれるので迷わずYes, do it!を押下

スクリーンショット 2018-08-13 23.58.44.png

Click to Reveal Tokenをクリックして、トークン情報を表示。このトークン情報はbotの実装時に認証情報として利用するので控えておく。もちろん後からも参照できる。

screencapture-discordapp-developers-applications-478576764545925142-bots-2018-08-14-00_00_31.png

左側のメニューからOAuth2を選択し、botにチェックを入れる。画面下部にbot認証用のURLが表示されるのでURLをコピーしてブラウザでアクセスする。

screencapture-discordapp-developers-applications-478576764545925142-oauth-2018-08-14-00_33_01.png

botを追加するサーバーを聞かれるので対象のサーバを選択する。自分が管理しているサーバでないと追加できないので注意。

スクリーンショット_2018-08-14_0_01_57.png

認証完了。

スクリーンショット 2018-08-14 0.02.15.png

自分のサーバにオフライン状態のbotが追加されている。

スクリーンショット_2018-08-14_0_02_56.png

botの実装

pipでdiscord.pyをインストール。

pip install -U discord.py

Quick Exampleのソースをそのまま貼り付けたbot.pyを作成。最終行のtokenはbot登録時に参照したトークン情報(文字列)に置き換えること。

DeveloperサイトのGeneral InformationのページにCLIENT IDとかCLIENT SECRETとかあるけど、それらの情報は全く必要なくて、必要なのはTOKENなので注意。

間違ってCLIENT SECRETを指定して認証通らずにハマった。

bot.py
import discord
import asyncio

client = discord.Client()

@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')

@client.event
async def on_message(message):
    if message.content.startswith('!test'):
        counter = 0
        tmp = await client.send_message(message.channel, 'Calculating messages...')
        async for log in client.logs_from(message.channel, limit=100):
            if log.author == message.author:
                counter += 1

        await client.edit_message(tmp, 'You have {} messages.'.format(counter))
    elif message.content.startswith('!sleep'):
        await asyncio.sleep(5)
        await client.send_message(message.channel, 'Done sleeping')

client.run('token')

動作確認

bot.pyを実行。on_ready()が実行される。

$ python bot.py 
Logged in as
Discord Sample Bot
123456789123456789
------

Discord上のbotがオンラインになっている。

スクリーンショット_2018-08-14_0_44_35.png

!testとチャットに打ち込むと、自分の投稿したメッセージ数を返してくれる。

スクリーンショット_2018-08-14_0_05_05.png

!sleepとチャットに打ち込むと、5秒後にDone sleepingと返してくれる。

スクリーンショット_2018-08-14_0_05_11.png

あとはbot.pyをカスタマイズしていけば好きなbotが作れる!!簡単!!

このやり方だとpythonを立ち上げておかないとbotが応答できない。常駐させるにはレンタルサーバとか立ち上げっぱなしのサーバーが必要。

4
3
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
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?