From f7fdb02fe6bc8d2523f5c22d9584b66ac498f4d9 Mon Sep 17 00:00:00 2001 From: fwcd Date: Tue, 5 Nov 2024 15:00:59 +0000 Subject: [PATCH] Add dad joke command --- Sources/D2Commands/Fun/DadJokeCommand.swift | 20 ++++++++++++++++++++ Sources/D2Handlers/D2Receiver.swift | 1 + Sources/D2NetAPIs/DadJoke/DadJoke.swift | 4 ++++ Sources/D2NetAPIs/DadJoke/DadJokeQuery.swift | 16 ++++++++++++++++ 4 files changed, 41 insertions(+) create mode 100644 Sources/D2Commands/Fun/DadJokeCommand.swift create mode 100644 Sources/D2NetAPIs/DadJoke/DadJoke.swift create mode 100644 Sources/D2NetAPIs/DadJoke/DadJokeQuery.swift diff --git a/Sources/D2Commands/Fun/DadJokeCommand.swift b/Sources/D2Commands/Fun/DadJokeCommand.swift new file mode 100644 index 00000000..2f3d3b49 --- /dev/null +++ b/Sources/D2Commands/Fun/DadJokeCommand.swift @@ -0,0 +1,20 @@ +import D2NetAPIs + +public class DadJokeCommand: VoidCommand { + public let info = CommandInfo( + category: .fun, + shortDescription: "Fetches a random dad joke", + requiredPermissionLevel: .basic + ) + + public init() {} + + public func invoke(output: any CommandOutput, context: CommandContext) async { + do { + let joke = try await DadJokeQuery().perform() + await output.append(joke.joke) + } catch { + await output.append(error, errorText: "Could not fetch dad joke") + } + } +} diff --git a/Sources/D2Handlers/D2Receiver.swift b/Sources/D2Handlers/D2Receiver.swift index fcead3ba..9227ad15 100644 --- a/Sources/D2Handlers/D2Receiver.swift +++ b/Sources/D2Handlers/D2Receiver.swift @@ -329,6 +329,7 @@ public class D2Receiver: Receiver { registry["pickupline", aka: ["pickup"]] = PickupLineCommand() registry["chucknorrisjoke", aka: ["cnj"]] = ChuckNorrisJokeCommand() registry["joke"] = JokeCommand() + registry["dadjoke"] = DadJokeCommand() registry["pat"] = PatCommand(inventoryManager: inventoryManager) registry["hug"] = HugCommand(inventoryManager: inventoryManager) registry["wouldyourather", aka: ["wyr"]] = WouldYouRatherCommand(partyGameDB: partyGameDB) diff --git a/Sources/D2NetAPIs/DadJoke/DadJoke.swift b/Sources/D2NetAPIs/DadJoke/DadJoke.swift new file mode 100644 index 00000000..dd409df4 --- /dev/null +++ b/Sources/D2NetAPIs/DadJoke/DadJoke.swift @@ -0,0 +1,4 @@ +public struct DadJoke: Codable, Identifiable, Sendable { + public let id: String + public let joke: String +} diff --git a/Sources/D2NetAPIs/DadJoke/DadJokeQuery.swift b/Sources/D2NetAPIs/DadJoke/DadJokeQuery.swift new file mode 100644 index 00000000..5d8b5ee8 --- /dev/null +++ b/Sources/D2NetAPIs/DadJoke/DadJokeQuery.swift @@ -0,0 +1,16 @@ +import Utils + +public struct DadJokeQuery: Sendable { + public init() {} + + public func perform() async throws -> DadJoke { + try await HTTPRequest( + host: "icanhazdadjoke.com", + path: "/", + headers: [ + "Accept": "application/json", + "User-Agent": "D2 (https://github.com/fwcd/d2)" + ] + ).fetchJSON(as: DadJoke.self) + } +}