メインコンテンツへスキップ
見出し画像

【Splatoon×Discord】お手軽ブキチ杯について。

     ボタンぽちぽちによる、ブキのランダム選出機能について、備忘録です。

    Step0.Discord Bot

     まずは、 Discord Developer Portal にて Bot を登録しましょう。トークン発行・招待URL取得など、色々ありますが省はぶきます。また、 VScode でのプログラミングをオススメします。

    Step1.ボタン機構

     はじめのボタンは[🎲ブキ抽選]として、抽選結果には[🎲再抽選]を用意します。どちらのボタンも識別子は "dice" とします:

    // import 云々略。
    
    const DICE_BUTTON = new ButtonBuilder()
      .setCustomId("dice")
      .setLabel("🎲ブキ抽選")
      .setStyle(ButtonStyle.Secondary);
    
    const REDICE_BUTTON =
      new ButtonBuilder(DICE_BUTTON.data)
        .setLabel("🎲再抽選")

    ⠀※Node.js用ライブラリ: discord.js によるコード例です。

    Step2.イベント発火

     ボタン押下を引き金に、イベント(処理)が発火するようにします。if 文により巧く分岐させて、dice 処理部分をあらわにします:

    // ボタン由来 かつ 識別子一致。
    const isFromDiceBtn = (__interaction) => (
      __interaction.isButton()
      && __interaction.customId === DICE_BUTTON.data.custom_id
    )
    
    // ボタン押下で interaction 生成&発火。
    client.on("interactionCreate", async interaction => {
      if (isFromDiceBtn(interaction)) {
        /* dice 処理 */
      }
    
      /* ※ボタン以外の要因でも発火する */
    }

    ⠀※以下略

    Step3.ブキ抽選処理

     dice 処理にあたり、すでに

    • ブキの名前【必須】

    • ブキの画像

    • サブ/スぺ

    がまとめられた配列 Weapons があるものと仮定します。作り方は後述。

     機能美にこだわらなければ、本質的には下記のプログラムで解決します:

        const weapon = weapons[Math.floor(Math.random() * weapons.length)]
        await interaction.reply(weapon.name)

     もしローカル画像を使用する場合、添付ファイルとして渡してあげましょう:

        const embed = new EmbedBuilder().setColor(color) // 色はお好みで。
        const weapon = weapons[Math.floor(Math.random() * weapons.length)]
        const imgFile = new AttachmentBuilder(
          weapon.imgPath,
          { name: `${weapon.imgName}.png` }
        )
    
        embed.setTitle(weapon.name)
          .setURL(DEFAULT_URL)
          .setDescription(`\`${weapon.sub}, ${weapon.spe}\``)
          .setThumbnail(`attachment://${weapon.imgName}.png`)
    
        const components = [new ActionRowBuilder().addComponents(REDICE_BUTTON)]
        await interaction.reply({
          embeds: [embed],
          files: [imgFile],
          components,
          flag: 64, // 実行者のみ表示。
        })

     一方で画像をURL管理している場合、添付ファイルは不要でURLべた書きとします:

        const embed = new EmbedBuilder().setColor(color) // 色はお好みで。
        const weapon = weapons[Math.floor(Math.random() * weapons.length)]
    
        embed.setTitle(weapon.name)
          .setURL(DEFAULT_URL)
          .setDescription(`\`${weapon.sub}, ${weapon.spe}\``)
          .setThumbnail(weapon.imgURL)
    
        const components = [new ActionRowBuilder().addComponents(REDICE_BUTTON)]
        await interaction.reply({
          embeds: [embed],
          components,
          flag: 64, // 実行者のみ表示。
        })

    完成。

     あとは[🎲ブキ抽選]ボタンを配備して完成です。おつかれさまでした。

    画像
    実装例1
    画像
    実装例2

    オマケ.ブキ一覧作成

     173種のブキ情報を人力で、収集・管理するのは現実的ではありません。そこで、 Splatoon Database の JSONファイル を借用して Weapons を作成します。

    ※ 内部データへのアクセスはグレー行為。もちろん大量アクセスは厳禁であり、個人運用かつローカルへの保存に限るのが最低限のマナーでしょう。

     Web上でF12を押して開発者ツールを開き、どこをどうアクセスして画像やサブスぺを表示しているか読み取ります。すると、WeaponInfoMain.json が見つかるので拝借します:

    const WeaponInfoURL =
      "https://leanny.github.io/splat3/data/mush/1110/WeaponInfoMain.json"
    
    const json = await fetch(WeaponInfoURL).then(res => res.json())

     得られた json はすでに配列なので、不要な情報を除いて取り回しやすくすればOK。特に、各要素 x に対して、

    • ブキ名:x.Label

    • サブ名:x.SubWeaponの部分列

    • スぺ名:x.SpecialWeaponの部分列

    • 画像URL:`https://leanny.github.io/splat3/images/weapon_flat/Path_Wst_${x.__RowId}.png`

    と抽出できます。必要に応じて変換していきましょう。

     また、スプラの内部データ由来なのか未実装ブキも紛れます。なので、識別番号10000未満に限るようフィルターを掛けましょう:

    const weapons = json.filter(x => x.Id < 10000).map(normalize)

     あとはローカルに保存していきます。実装例です:

    import weapons from "./weapons.js"
    import fs from "node:fs/promises"
    
    await fs.writeFile("./_weapons-v11.json", JSON.stringify(weapons))
    
    weapons.forEach(async (weapon) => {
      const imgURL = weapon.imgURL
      const imgBuf = Buffer.from(
        await fetch(imgURL).then(res => res.arrayBuffer())
      )
    
      const dirName = `./_imgs/${weapon.type}`
      await fs.mkdir(dirName, { recursive: true, })
    
      const fileName = (weapon.name)
        .replace(/^\./, "_") // .52  .96 -> _52  _96
        .replace(/\//g, "_") // R-PEN/5H -> R-PEN_5H
      fs.writeFile(`${dirName}/${fileName}.png`, imgBuf);
    });


    お わ り


     何かの参考に成れば幸いです。よければチャンネル登録・高評価をお願い致します。最後まで読んでくれた、優しきアナタに幸あれ。

    あなたへのおすすめ