gpt4 book ai didi

haskell - 在 Servant 的 API 端点内发出请求

转载 作者:行者123 更新时间:2023-12-02 14:21:05 27 4
gpt4 key购买 nike

我正在尝试使用 telegram-api 构建一个 Telegram 机器人。到目前为止,我还没有遇到任何问题,因为我可以阅读测试来了解事情是如何工作的,但在使用 Servant 构建 webhook 端点时遇到了很多麻烦。 。总体思路是,当我从 webhook 收到 Update 时,我会发回回复。

问题与我的 postWebhook 代码有关,它期望收到 Message,但却收到 IO Message。我认为这是因为 Servant 不希望我在该函数内发出请求,因为我的类型为 EitherT ServantError IO (IO Message) (部分由 BotHandler 应用)实际上它应该是 EitherT ServantError IO Message

我仍在学习 Haskell,但我知道我必须以某种方式从 IO monad 中获取消息?更新 BotAPI 以返回 Post '[JSON](IO 消息) 给我这个:没有因使用“serve”而产生的(可折叠 IO)实例,这超出了我的初学者知识范围,我可以看到摆弄类型只会将相同的问题转移到代码的不同部分。我只是不知道如何解决这个问题。

以下是删除敏感字符串的代码:

{-# LANGUAGE DataKinds         #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeOperators #-}

module Main where

import Control.Monad
import Control.Monad.Trans.Either
import Data.Proxy
import Data.Text (Text, pack)
import Network.Wai.Handler.Warp
import Servant
import Web.Telegram.API.Bot

reply :: Token -> Message -> Text -> IO Message
reply token msg response = do
Right MessageResponse { message_result = m } <-
sendMessage token $ SendMessageRequest chatId response (Just Markdown) Nothing Nothing Nothing
return m
where chatId = pack . show $ chat_id (chat msg)

type BotAPI = "webhook" :> ReqBody '[JSON] Update :> Post '[JSON] Message
type BotHandler a = EitherT ServantErr IO a

botApi :: Proxy BotAPI
botApi = Proxy

initWebhook :: Token -> IO Bool
initWebhook token = do
Right SetWebhookResponse { webhook_result = w } <-
setWebhook token $ Just "https://example.com/webhook"
return w

postWebhook :: Token -> Update -> BotHandler (IO Message)
postWebhook token update = case message update of
Just msg -> return $ reply token msg "Testing!"
Nothing -> left err400

server :: Token -> Server BotAPI
server = postWebhook

main :: IO ()
main = do
initWebhook token
run port $ serve botApi (server token)
where token = Token "<token>"
port = 8080

对可能不是理想的 Haskell 代码表示歉意。预先感谢您:)

最佳答案

您的错误位于

Just msg → return $ reply token msg "Testing!"

你正在

EitherT ServantErr IO Message

monad 但 reply 有类型

reply :: Token → Message → Text → IO Message

然后只需将 IO 操作提升到您的 monad 中,它就可以工作

postWebhook :: Token → Update → BotHandler Message
postWebhook token update = case message update of
Just msg → lift $ reply token msg "Testing!"
Nothing → left err400

(对我来说解释这里涉及的所有事情并不容易)我认为你应该在这些复杂的例子之前多练习一下 monad、transformers...但是你很勇敢! :)

关于haskell - 在 Servant 的 API 端点内发出请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35340857/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com