LoginSignup
2
3

More than 1 year has passed since last update.

Discord.py ver2.0.0aでボタンの実装をしてみる

Posted at

Discord.pyがまさかの更新停止。
でもDannyは残してくれた。alpha版のDiscord.py、バージョン2.0.0aを―――――しかし。

Discord.py 2.0.0aの記事がどこにも載っていない!

すること

DiscordのUI機能?のボタンを作ってみる。

インストールするもの

Python 3.9以上
Discord.py 2.0.0a (alpha)
その他プログラムに必要なものがあればインストール

インストール手順

Pythonは割愛。

Discord.py 2.0.0aのインストール

pip install git+https://github.com/Rapptz/discord.py

でok。

ボタンを作ってみる

とりあえず表示だけ。

from discord.ext import commands
import discord

class ButtonBot(commands.Bot):
    def __init__(self):
        super().__init__(command_prefix="!")

class CreateButton(discord.ui.View):
    def __init__(self):
        super().__init__()
        self.add_item(discord.ui.Button(label="ボタンです"))

bot = ButtonBot()

@bot.command()
async def button(ctx: commands.Context):
    await ctx.send("下にボタンがあるはず", view=CreateButton())

bot.run('TOKEN')

こんな感じでできる。

ボタンを押しても何も無いのは寂しい(というか実用性がない)ので、メッセージを折り返し送ってみよう。

class CreateButton(discord.ui.View):
    def __init__(self):
        super().__init__()

    @discord.ui.button(label="ボタンです")
    async def return_message(self, button: discord.ui.Button, interaction: discord.Interaction):
        await interaction.response.send_message("折り返しのメッセージだよ")

こんな感じ。

interactionについては
https://discordpy.readthedocs.io/ja/latest/api.html#interaction
を見れば詳しく書いてあります。

ちなみに

await interaction.response.send_message("折り返しのメッセージだよ", ephemeral=True)

と、ephemeralパラメータをTrueにするとボタンを押した人だけに見えるメッセージが送られる。すごい。

他にもいろいろ機能があるので、ぜひDiscord.py 2.0.0aをインストールしてみてください!!!(懇願)
また、他の機能を試してみたいけどどうやってプログラミングするか分からないって方はコメントしていただければ反応できます。

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