discord bot pycode templ

discord.pyが開発終了になるのでpy-cordに乗り換える

テンプレート

pip

  • py-cord
  • python-dotenv
  • requests
  • main.py

    import dotenv
    import os
    # Pycordを読み込む
    import discord
    
    # アクセストークンを設定
    dotenv.load_dotenv()
    token = str(os.getenv("TOKEN"))
    
    # Botオブジェクト生成
    bot = discord.Bot(
            intents=discord.Intents.all(),  # 全てのインテンツ
            activity=discord.Game("Discord"),  # "~~をプレイ中",
    )
    
    
    # 起動時に動く
    @bot.event
    async def on_ready():
        # 起動確認。ターミナルに"Start"と表示される
        print("Start")
    
    
    # Botが見える場所でメッセージが見えた時に動く
    @bot.event
    async def on_message(message: discord.Message):
        # 送信者がBotだった場合は無視する
        if message.author.bot:
            return
    
        if message.content == 'hello':
            await message.reply("Hello!")
        
        if message.content == 'ez':
            await message.reply("ナイスゲーム!みんなこれからも頑張ってね!")
    
        if message.content == 'lol':
            await message.reply("うん、やっぱ楽しくプレイすることが何よりも大事だよね")
    
    
    # pingコマンドを実装
    @bot.command(name="ping", description="pingを返します")
    async def ping(ctx: discord.ApplicationContext):
        await ctx.respond(f"pong to {ctx.author.mention}")
    
    @bot.command(name="greeting", description="挨拶を行います")
    async def greeting(ctx: discord.ApplicationContext, user: discord.Option(discord.User, "対象のユーザー")):
        await ctx.respond(f"Hi, {user.mention}!")
    
    
    # Botを起動
    bot.run(token)

    .env

    TOKEN = "あなたのトークン"

    参考

    Discord Botを作ってみよう #01 - Hello, Pycord! #discord - Qiita

    ← Go home