Creating a Chat Bot in Swift: From Idea to First Conversation

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Why Swift is an Excellent Choice for a Chat Bot?

\n

When it comes to creating chat bots, many immediately think of Python or JavaScript. And that's logical: there are tons of ready-made libraries and examples. But what if your stack is the Apple ecosystem? Or you want to make a bot that will run directly on a Vapor server? Or maybe you're just interested in trying Swift outside of iOS development?

\n

Swift is not only beautiful syntax and type safety. It also offers lightning-fast speed, excellent networking capabilities, and powerful tools for data parsing. In this article, we won't write yet another "hello world" bot. We will step by step build a full-fledged Telegram bot in Swift that can respond to commands, process text messages, and parse JSON. Let's go!

\n\n

What Do We Need?

\n

Before diving into the code, let's figure out the toolkit. For our project, we will use:

\n
    \n
  • Swift 5.9+ — the latest stable version.
  • \n
  • Foundation — the built-in library for working with networking and JSON.
  • \n
  • Telegram Bot API — the REST API we need to interact with.
  • \n
  • SwiftBot Library — a lightweight wrapper for working with Telegram (or we'll write our own minimal client).
  • \n
\n

If you want to go the route of maximum control, we will use only standard Foundation tools. No third-party dependencies — just pure Swift.

\n\n

Step 1: Register the Bot with BotFather

\n

This is the simplest step. Open Telegram, find BotFather, type /newbot and follow the instructions. You will receive a token — a long string like 123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11. Save it to an environment variable or config file. Never hardcode the token directly into the code if you plan to upload the project to GitHub.

\n

The token is the access key to your bot. Through it, we will send requests to the Telegram API.

\n\n

Step 2: Create a Structure for Working with the API

\n

First, we need to write a simple HTTP client. The Telegram API works via GET and POST requests. We will use URLSession — the standard Swift tool for networking.

\n\n

Create a Base BotClient Class

\n
import Foundation\n\nclass BotClient {\n    private let token: String\n    private let baseURL = "https://api.telegram.org/bot"\n    \n    init(token: String) {\n        self.token = token\n    }\n    \n    // Method for sending requests\n    private func sendRequest(method: String, parameters: [String: Any] = [:], completion: @escaping (Data?, Error?) -> Void) {\n        let urlString = "\\(baseURL)\\(token)/\\(method)"\n        guard let url = URL(string: urlString) else {\n            completion(nil, NSError(domain: "Invalid URL", code: -1))\n            return\n        }\n        \n        var request = URLRequest(url: url)\n        request.httpMethod = "POST"\n        request.setValue("application/json", forHTTPHeaderField: "Content-Type")\n        \n        if !parameters.isEmpty {\n            request.httpBody = try? JSONSerialization.data(withJSONObject: parameters)\n        }\n        \n        let task = URLSession.shared.dataTask(with: request) { data, response, error in\n            completion(data, error)\n        }\n        task.resume()\n    }\n    \n    // Get updates (new messages)\n    func getUpdates(offset: Int? = nil, completion: @escaping ([Update]?) -> Void) {\n        var params: [String: Any] = [:]\n        if let offset = offset {\n            params["offset"] = offset\n        }\n        \n        sendRequest(method: "getUpdates", parameters: params) { data, error in\n            guard let data = data else {\n                completion(nil)\n                return\n            }\n            \n            do {\n                let response = try JSONDecoder().decode(TelegramRespons                

Blogs

Book Recommendations