LoginSignup
1
0

More than 1 year has passed since last update.

discord.py v2.0の自動変換を使ってみる

Last updated at Posted at 2022-09-09

久しぶりにdiscord botを作ってみたら面白い機能が追加されていたのでメモ書き。

discord.pyのVer2.0から追加された新機能の一部

  • app_commands.choices
  • app_commands.autocomplete

この2つはコマンドの引数を設定する際に特定の文字列の中からユーザーに入力して欲しい時に候補を表示することができて便利なのでよく使っています。

今回は候補にしたい配列がほとんどカタカナで構成されているという前提で、
ひらがな→カタカナ変換をして配列の中から部分一位した文字列を返すコードを載せています。

import discord  
from discord import app_commands  
from discord.ext import commands

intents = discord.Intents.default()  
intents.members = True  
bot = commands.Bot(command_prefix = '.',intents=intents, help_command=None)  
tree = bot.tree


special_list = [
'ウルトラショット', 'ウルトラハンコ', 'エナジースタンド', 'カニタンク', 
'キューインキ', 'グレートバリア', 'サメライド', 'ショクワンダー', 'ジェットパック', 
'トリプルトルネード', 'ナイスダマ', 'ホップソナー', 'マルチミサイル', 'メガホンレーザー5.1ch'
]

# ひらがな→カタカナ変換  
def hiraToKata(target):  
    return ''.join([chr(n + 96) if (12352 < n and n < 12439) or n == 12445 or n == 12446 else chr(n) for n in  
                    [ord(c) for c in target]])
                    
# 検索コマンド  
async def sp_autocomplete(  
    interaction: discord.Interaction,  
    current: str,  
) -> list[app_commands.Choice[str]]:  
    target_str = hiraToKata(current)  
    return [  
        app_commands.Choice(name=buki_name, value=buki_name)  
        for buki_name in special_list if target_str in buki_name  
    ]  
  
@tree.command(  
    name="find",  
    description="候補を表示します"  
)  
"""
選択肢が少ない時はchoicesの方が入力の必要がなく楽です
"""
# @app_commands.choices(  
#     category=[  
#         app_commands.Choice(name="サブウェポン",value="サブ"),  
#         app_commands.Choice(name="スペシャル",value="スペシャル"),  
#         app_commands.Choice(name="ブキカテゴリー",value="カテゴリー")  
#     ]  
# )  
@app_commands.autocomplete(name=sp_autocomplete)  
async def find(ctx, name: str):  
    await ctx.response.send_message(name)
    
  
bot.run(DISCORD_TOKEN)

いつの間にか起動時にインテントなるものが必要になっていて ちょっとつまづいた。

日本語だとカタカナ以外はコードで変換処置いれなくても部分一致で候補出しやすいかもしれないですね〜
漢字はユーザー側で変換までしてもらったほうが実装が楽そう...

参考

  • ひらがなからカタカナ変換

1
0
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
1
0