LoginSignup
1
0

Discord ボットを作ってみる

Posted at

環境

  • Ubuntu 22.04 LTS
  • Python 3.10.12
  • pip 22.0.2
  • discord.py 2.3.2

Discrod 側の準備

https://discord.com/developers/applications/
こちらから「New Applicaton」
image.png
名前を入れて「Create」します。それに伴いAPPLICATION ID と PUBLIC KEY が発行されますが、特に使いませんでした。
image.png
Bot - TOKEN を一度Reset してから Copy し、後ほど使うのでメモなどに残しておきましょう。
image.png
intent 設定を変更します。

image.png
最初は SERVER MEMBERS INTENT のみONにしたらうまくいかなかったので全部ONにしてみました。
変更したら save しておきます。
image.png

OAuth2 で、「bot」 と「Send Messages」をクリックして出てきたURLを開きます。
image.png

image.png

image.png

対象のサーバを選び、ユーザを追加します。

image.png

サーバに追加されます。

image.png

今回は特定のチャンネルにメッセージを流すようにするので、チャンネルIDを取得します。

Discord アプリ画面でユーザー設定を開き、
image.png
開発者モードをONにします。
チャンネルを右クリックして「チャンネルIDをコピー」します。
image.png

環境変数を設定

まずプログラムの場所を作り、.env ファイルをまず作成します。


$ mkdir botexample
$ cd botexample
$ vim .env

トークンとチャンネルを記述します。

image.png

python ライブラリをインストール

$ sudo pip3 install discord

コード

import discord
import os
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
CHANNEL_ID = int(os.getenv('CHANNEL_ID'))

intents = discord.Intents.all()
client = discord.Client(intents=intents)

@client.event
async def on_ready():
    print('ready on')
    channel = client.get_channel(CHANNEL_ID)
    await channel.send('進捗どうですか')

client.run(TOKEN)

トラブルシューティング

  File "/usr/local/lib/python3.10/dist-packages/discord/client.py", line 704, in connect
    raise PrivilegedIntentsRequired(exc.shard_id) from None
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.

intent が足りませんでした。

NameError: name 'channel' is not defined

ミスタイプしてました

AttributeError: 'NoneType' object has no attribute 'send'

最初以下のようにしていたらエラーが出ました。

CHANNEL_ID = int(os.getenv('CHANNEL_ID'))

以下のように変更しました。

CHANNEL_ID = os.getenv('CHANNEL_ID')
1
0
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
1
0