2
0

More than 1 year has passed since last update.

Discord.pyで新規スレッドを作成する方法

Last updated at Posted at 2023-02-19

Discord.py(2.1.0)でスレッドを作成する方法について紹介します。

$ python3 --version
Python 3.9.2

$ pip show discord
Version: 2.1.0 

スレッドとは

スレッドとは、一般のチャンネルの中に作られる一時的な子チャンネルのようなものです。
画面右上付近のシャープマークから確認でき、親のチャンネルとは内容は分離されるため、特定のテーマについて会話したり共有したりといった目的に向いています。
作成されてから一定期間(設定可能)が経過すると自動的に非表示&書き込み不可になるため、使い所には注意が必要です。
Discord.py(qiita).png

実装

当方、初心者で苦戦した結果、@bot.tree.command というデコレータを使用しています。
お使いの環境で動作するとは保証できないことご了承ください。
また記事の構成も分かりづらく申し訳ないです。

基本コード

import discord
from discord.ext import commands

intents = discord.Intesnts.default()
bot = commands.Bot(command_prefix='/',intents=intents)
 
@bot.tree.command(name="chat", description="新しいスレッドを作成します。")
async def chat(ctx):
    channel = ctx.channel
    thread = await channel.create_thread(name="ぼっち・ざ・ろっくを語りたい",reason="雷鳴を轟かせたいから")
    link = thread.mention
    await thread.send("調整中です")
    await ctx.response.send_message(f"{link} こちらで会話してください")

bot.run("your token")

スレッド作成のため、まずスレッドを作成したいチャンネルのIDを取得します。

channel = ctx.channel

次にchannel.create_thread()でスレッドを作成。
nameには作成したいスレッドの名前、reasonにはサーバの監査ログに表示したい作成の理由を入力してください(任意)。

thread = await channel.create_thread(name="ぼっち・ざ・ろっくを語りたい",reason="3周目だから")

Discord上からユーザの任意の名前でスレッドを作成したい場合はこのような感じでしょうか

@bot.tree.command(name="chat", description="新しいスレッドを作成します。")
async def chat(ctx,title:str):
    channel = ctx.channel
    thread = await channel.create_thread(name=title)

その他引数の一部

|auto_archive_duration #スレッドがアーカイブされるまでの時間(分)を60/1440/4320/10080から選択する。
|type #作成するスレッドの形式を選択する。デフォルトはNoneでプライベートスレッドになる。((discord.)ChannelType.private_tread/public_threadを動作確認済み)
|slowmode_delay #スレッドの低速モードを26100秒まで設定可能。

スレッドとの連携

スレッドへのメンションを取得したりスレッドへデフォルトの書き込みを投稿したりできます

link = thread.mention #押したらスレッドへ移動できるリンクを取得
await ctx.response.send_message(link)
await thread.send("Hello World!") #スレッドへ予め投稿できる

Forbiddenが返された場合、Botの権限が不足している可能性があります。
今一度スレッドを作成する権限があるか確認してみてください。

ここまでお読みいただきありがとうございました。
もしお疲れでしたら下記がおすすめです。

こちら

参考

公式リファレンス(それぞれ異なる内容です)

2
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
2
0