LoginSignup
8
8

discord.py(2.0.0) 備忘録

Last updated at Posted at 2022-05-26

discord.pyであれこれしたい時のためのものと自分が探すのが時間かかったものとか。
今後も何かあったら更新します。

2.0.0での新機能

スラッシュコマンドを作る

import discord
from discord import app_commands
from discord.ext import tasks
guild=discord.Object(#サーバーid)
client=discord.Client(intents=discord.Intents.default())#intentsは確か必須になりました。
tree=app_commands.CommandTree(client)
@client.event
async def on_ready():
  await tree.sync(guild=guild)
  loop.start()
@tree.command(guild=guild)
async def test(i):
  await i.response.send_message("a")

discord.ext.commands.Bot()を使っている場合、
tree=client.treeとすれば良い。

text_input

import discord
from discord import app_commands
from discord.ui import Modal, View, text_input
from discord.ext import tasks

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

tree = app_commands.CommandTree(client)


TEST_GUILD = discord.Object(#here your guild_id)


@client.event
async def on_ready():
    print(f'Logged in as {client.user} (ID: {client.user.id})')
    print('------')
    loop.start()
    await tree.sync(guild=TEST_GUILD)

class M(Modal):
    a = text_input.TextInput(label='a', placeholder='a', max_length=20, required=True)
    b = text_input.TextInput(label='b', style=discord.TextStyle.paragraph, required=True)

    def __init__(self):
        super().__init__(title='Test')

    async def on_submit(self, interaction:discord.Interaction):
        await interaction.response.send_message(f'{interaction.user}\n{self.a.value}\n{self.b.value}')

@tree.command(guild=TEST_GUILD, description="test")
async def test(interaction: discord.Interaction):
    await interaction.response.send_modal(M())

既存のもの

コマンドのエラーを受け取る

@client.event
async def on_command_error(ctx,e):
  cmd=ctx.invoked_with#呼び出されたコマンド
  if isinstance(e,discord.ext.commands.CommandNotFound):
    await ctx.send("コマンドが見つかりませんでした")

メッセージの画像を取得

#…on_messageなど
    attachments=message.attachments
    for attachment in attachments:
      await attachment.save(f"{i}.{attachment.filename.split(".")[-1]}")

メッセージの返信先

discord.Message.referencediscord.ReferenceMessageを返すので注意。
discord.Messageは返しません。
ReferenceMessage.resolvedMessageに。

#…on_messageなど
ref=message.reference
message=ref.resolved
#……
8
8
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
8
8