WebSocket에 의존하지 않으므로 무국적 Webhook 환경에서 사용할 수있는 Discord Interaction API의 래퍼.
또한 명령 구조와 트리거 할 때 수신 된 데이터를 엄격하게 분리 할 수 있습니다.
파이썬 3.8+가 필요합니다
pip install discord-interactions.pypip install git+https://github.com/LiBa001/discord-interactions.py메모
GitHub에서 직접 설치하려면 컴퓨터에 GIT를 설치해야합니다.
python -m pip install ...py -m pip install ... 이 라이브러리는 플라스크 마이크로 프레임 워크와 완벽하게 작동하도록 특별히 설계되었습니다.
플라스크 확장 기능이있는 가장 API와 같은 예는 다음과 같습니다.
from discord_interactions . flask_ext import Interactions
from discord_interactions import (
ApplicationCommand ,
ApplicationCommandOption ,
ApplicationCommandOptionType ,
Interaction ,
InteractionResponse ,
InteractionResponseType ,
InteractionApplicationCommandCallbackData ,
)
from flask import Flask
import os
app = Flask ( __name__ )
interactions = Interactions ( app , os . getenv ( "CLIENT_PUBLIC_KEY" ))
echo_cmd = ApplicationCommand ( "echo" , "what goes around comes around" )
echo_cmd . add_option (
ApplicationCommandOption (
type = ApplicationCommandOptionType . STRING ,
name = "message" ,
description = "This will be echoed." ,
required = True ,
)
)
@ interactions . command ( echo_cmd )
def _echo ( interaction : Interaction ):
msg = interaction . data . options [ 0 ]. value # "message" option content
return InteractionResponse (
type = InteractionResponseType . CHANNEL_MESSAGE_WITH_SOURCE ,
data = InteractionApplicationCommandCallbackData ( content = msg ),
) 여기서 우리는 기본적으로 원래 API 모델의 정확한 구조에 해당하는 기초 ApplicationCommand , Interaction 및 InteractionResponse 클래스를 사용합니다.
좀 더 간단하게하자 :
@ interactions . command ( echo_cmd )
def _echo ( interaction : Interaction ):
# different way of getting an option
msg = interaction . data . get_option ( "message" ). value
return msg 이제 우리는 더 이상 InteractionResponse 다룰 필요가 없지만 대신 응답 내용을 문자열로 반환합니다. 응답 유형은 기본적으로 InteractionResponseType.CHANNEL_MESSAGE_WITH_SOURCE 로 기본적으로 표시됩니다. 응답을 보내고 싶지 않으면 아무것도 반환 할 수 있습니다. 부울을 두 번째 값으로 간단히 반환 할 수 있으며, 명령 호출이 불일치에 표시되어야하는지 여부를 나타냅니다 (예 : 응답 유형의 _WITH_SOURCE 부분). 또한 get_option 도우미 방법을 통해 옵션을 얻습니다.
그러나이 라이브러리는 또 다른 추상화 계층을 제공합니다. 데이터베이스 ORM의 개념에서 영감을 얻은이 제품은 각 명령에 대한 클래스를 정의 할 수있는 객체 커뮤니케이션 맵퍼 (OCM)가있어 명령에 대한 일반적인 구조적 설명 ( ApplicationCommand 와 같은) 과 명령이 호출 될 때 수신 된 실제 데이터에 대한 Interaction 를 모두 사용합니다.
따라서 가능한 가장 간단한 예는 다음과 같습니다.
from discord_interactions . flask_ext import Interactions
from discord_interactions . ocm import Command , Option
from flask import Flask
import os
app = Flask ( __name__ )
interactions = Interactions ( app , os . getenv ( "CLIENT_PUBLIC_KEY" ))
class _Echo ( Command ):
""" what goes around comes around """
message : str = Option ( "This will be echoed." , required = True )
@ interactions . command
def _echo ( cmd : _Echo ):
return cmd . message 초기 응답 후 메시지를 보내려면 후속 메시지를 만들어야합니다. 이 목적을 위해 실제 명령 함수가 반환 된 후 호출 할 함수를 등록하는 after_command 데코레이터를 사용할 수 있습니다. 이 함수는 Interaction 및 초기 InteractionResponse 같은 여러 가지를 포함하는 AfterCommandContext 의 정확히 하나의 매개 변수를 가져와야합니다.
interactions = Interactions ( app , PUBLIC_KEY )
@ interactions . command ( "delay" )
def delay ( _ : Interaction ):
return "starting countdown" , True # this message is ephemeral
@ delay . after_command
def after_delay ( ctx : AfterCommandContext ):
delay_time = ctx . interaction . data . options [ 0 ]. value
time . sleep ( delay_time )
ctx . send ( f" { delay_time } seconds have passed" ) 버튼과 같은 메시지 구성 요소에 대한 콜백을 등록 할 수도 있습니다. 구성 요소는 custom_id 로 등록 및 식별됩니다.
@ interactions . component ( "my_button" )
def my_button_handler ( ctx : ComponentContext ):
return f" { ctx . interaction . user . username } clicked the button" 다른 기능의 더 많은 예를 보려면 예제를 살펴보십시오.
Discord 봇이 슬래시 명령으로 작동하는 방법과 모든 것을 설정하는 방법을 알고 싶다면이 예제 프로젝트를 살펴보십시오. Google Cloud Run을 통해 서버리스 환경에서 프로그램을 호스팅하고 데모 봇도 제공하므로 Discord 서버에서 슬래시 명령을 시도 할 수 있습니다. 자세히 알아 보려면 확인하십시오!