💻

0から1に!! Nextcord偏

に公開

はじめに

今回はDiscordBotを作るためのPythonライブラリのNextcordについての記事!!

最小コード

bot.py
import nextcord
from nextcord.ext import commands

intents = nextcord.Intents.default()
bot = commands.Bot(command_prefix="!", intents=intents)

@bot.event
async def on_ready():
    print(f"ログインしました: {bot.user}")

bot.run("YOUR_BOT_TOKEN")

このコードは"YOUR_BOT_TOKEN"のBOTを起動させ、起動したとき、コンソールに「ログインしました」とBOTのユーザー名を表示するコードです。

デコレータ関数

Nextcordで使用できるデコレータ関数一覧

@bot.event

イベントハンドラ関数です。
下記はボットが起動したときのイベント関数で、他にもon_ready, on_message, on_member_join などがある。

@bot.event
async def on_ready():
    print("Bot起動完了!")

@bot.command()

通常のテキストコマンド関数です。
下記は「!ping」で動くテキストコマンドで、commands.Botで設定したcommand_prefixの文字がコマンドの識別として動く。

@bot.command()
async def ping(ctx):
    await ctx.send("Pong!")

@bot.slash_command()

スラッシュコマンド関数
これは /hello みたいに、DiscordのGUI上で使えるコマンド。
自動補完, 引数付きの対話, 説明文つきで、とても使いやすくユーザーに分かりやすい!

@bot.slash_command(name="hello", description="挨拶するよ!")
async def hello(interaction: nextcord.Interaction):
    await interaction.response.send_message("こんにちは!")

@commands.Cog.listener(), @commands.Cog.command()

クラス(Cog)に上記したデコレータ関数をまとめるとき用
大規模BotではこのCogを使って、機能ごとに整理するのが便利。

class MyCog(commands.Cog):
    @commands.Cog.command()
    async def say(self, ctx, *, message):
        await ctx.send(message)

最後に

イベントの種類なども豊富で最近は記事も増えてきて扱いやすくなってきました。
discord.pyからの乗り換えおすすめです!
↓↓ 詳しくは公式Nextcord ↓↓
https://nextcord.dev/

Discussion