如何在 swift 的单个消息电报机器人中发送照片、标题和内联按钮?

How can I send photo, caption and inline button in a single message telegram bot with swift?

This is the result that I want

func getOffers(_ page: Int, _ i: Int) {
    getOfferProducts(category: [""], sort: -1, page: page) { (products) in

        let keyboard = [ "inline_keyboard" : [
                                [
                                    ["text" : "Amazon", "url" : products[i].detailedPageURL]
                                ]
                            ]
                        ]

        var url = "https://api.telegram.org/bot" + apiToken + "/sendPhoto?" +
            "chat_id=" + chatId +
            "&caption=" + products[i].title + "\n\n" +
            "Prezzo iniziale: " + String(products[i].startingPrice) + " €\n" +
            "Prezzo attuale: " + String(products[i].price) + " €\n" +
            "Risparmi il " + String(Double(products[i].percentOff!)) + "%\n\n" +
            "►" + String(products[i].detailedPageURL) +
            "&photo=" + String(products[i].largeImageURL!) +
            "&reply_markup=" + keyboard

        DispatchQueue.main.async {
            let url = URL(string: url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? "")
            let downloadTask = URLSession.shared.dataTask(with: url!) { (data : Data?, response : URLResponse?, error : Error?) in
                // Do what you want with data
            }
            downloadTask.resume()
        }

    }
}

如果我不包含参数 "reply_markup" 它会起作用(显然没有按钮)。相反,如果我尝试添加一个按钮,它 return 错误:

{"ok":false,"error_code":400,"description":"Bad Request: can't parse reply keyboard markup JSON object"}

根据this solutionreply_markup在发送到API之前需要转换为JSON编码对象。

那么,这将解决您的问题:

    let keyboard = [ "inline_keyboard" : [
                    [
                        ["text" : "Amazon", "url" : products[i].detailedPageURL]
                    ]
                   ]]

    guard let keyboardData = try? JSONSerialization.data(withJSONObject: keyboard, options: []) else {
        return
   }

    var url = "https://api.telegram.org/bot" + apiToken + "/sendPhoto?" +
        "chat_id=" + chatId +
        "&caption=" + products[i].title + "\n\n" +
        "Prezzo iniziale: " + String(products[i].startingPrice) + " €\n" +
        "Prezzo attuale: " + String(products[i].price) + " €\n" +
        "Risparmi il " + String(Double(products[i].percentOff!)) + "%\n\n" +
        "►" + String(products[i].detailedPageURL) +
        "&photo=" + String(products[i].largeImageURL!) +
        "&reply_markup=" + String(data: keyboardData, encoding: String.Encoding.utf8)!