text
stringlengths 1
93.6k
|
|---|
# "ack"nowledge the ping from Discord
|
return {"type": DiscordResponseType.PONG.value}
|
if data.get("type") == DiscordInteractionType.APPLICATION_COMMAND.value:
|
# this is a command interaction
|
app_id = data["application_id"]
|
interaction_token = data["token"]
|
user_id = data["member"]["user"]["id"]
|
question = data["data"]["options"][0]["value"]
|
pretty_log(question)
|
# kick off our actual response in the background
|
respond.spawn(
|
question,
|
app_id,
|
interaction_token,
|
user_id,
|
)
|
# and respond immediately to let Discord know we're on the case
|
return {
|
"type": DiscordResponseType.DEFERRED_CHANNEL_MESSAGE_WITH_SOURCE.value
|
}
|
raise HTTPException(status_code=400, detail="Bad request")
|
return app
|
@stub.function()
|
async def respond(
|
question: str,
|
application_id: str,
|
interaction_token: str,
|
user_id: str,
|
):
|
"""Respond to a user's question by passing it to the language model."""
|
import modal
|
try:
|
raw_response = await modal.Function.lookup(
|
"askfsdl-backend", "qanda"
|
).remote.aio(question, request_id=interaction_token, with_logging=True)
|
pretty_log(raw_response)
|
response = construct_response(raw_response, user_id, question)
|
except Exception as e:
|
pretty_log("Error", e)
|
response = construct_error_message(user_id)
|
await send_response(response, application_id, interaction_token)
|
async def send_response(
|
response: str,
|
application_id: str,
|
interaction_token: str,
|
):
|
"""Send a response to the user interaction."""
|
interaction_url = (
|
f"https://discord.com/api/v10/webhooks/{application_id}/{interaction_token}"
|
)
|
json_payload = {"content": f"{response}"}
|
payload = aiohttp.FormData()
|
payload.add_field(
|
"payload_json", json.dumps(json_payload), content_type="application/json"
|
)
|
async with aiohttp.ClientSession() as session:
|
async with session.post(interaction_url, data=payload) as resp:
|
await resp.text()
|
async def verify(request: Request):
|
"""Verify that the request is from Discord."""
|
from nacl.signing import VerifyKey
|
from nacl.exceptions import BadSignatureError
|
public_key = os.getenv("DISCORD_PUBLIC_KEY")
|
verify_key = VerifyKey(bytes.fromhex(public_key))
|
signature = request.headers.get("X-Signature-Ed25519")
|
timestamp = request.headers.get("X-Signature-Timestamp")
|
body = await request.body()
|
message = timestamp.encode() + body
|
try:
|
verify_key.verify(message, bytes.fromhex(signature))
|
except BadSignatureError:
|
# IMPORTANT: if you let bad signatures through,
|
# Discord will refuse to talk to you
|
raise HTTPException(status_code=401, detail="Invalid request") from None
|
return body
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.