環境
- 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」
名前を入れて「Create」します。それに伴いAPPLICATION ID と PUBLIC KEY が発行されますが、特に使いませんでした。
Bot - TOKEN を一度Reset してから Copy し、後ほど使うのでメモなどに残しておきましょう。
intent 設定を変更します。
最初は SERVER MEMBERS INTENT のみONにしたらうまくいかなかったので全部ONにしてみました。
変更したら save しておきます。
OAuth2 で、「bot」 と「Send Messages」をクリックして出てきたURLを開きます。
対象のサーバを選び、ユーザを追加します。
サーバに追加されます。
今回は特定のチャンネルにメッセージを流すようにするので、チャンネルIDを取得します。
Discord アプリ画面でユーザー設定を開き、
開発者モードをONにします。
チャンネルを右クリックして「チャンネルIDをコピー」します。
環境変数を設定
まずプログラムの場所を作り、.env ファイルをまず作成します。
$ mkdir botexample
$ cd botexample
$ vim .env
トークンとチャンネルを記述します。
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')