Skip to content

New Bot

Andrey Fidrya edited this page Jun 7, 2016 · 6 revisions

Creating a new bot

Create the project

Create a directory for the project, we'll call the bot todo-bot:

mkdir todo-bot
cd todo-bot
swift build --init

We now have the following project structure:

├── Package.swift
├── Sources
│   └── main.swift
└── Tests

Edit Package.swift to look like this:

import PackageDescription

let package = Package(
    name: "todo-bot",
    dependencies: [
        .Package(url: "https://github.com/zmeyc/telegram-bot-swift.git", majorVersion: 0)
    ]
)

Run swift build:

Cloning https://github.com/zmeyc/telegram-bot-swift.git
Resolved version: 0.2.1
Cloning https://github.com/IBM-Swift/SwiftyJSON.git
Resolved version: 6.0.0
Compiling Swift Module 'SwiftyJSON' (3 sources)
Compiling Swift Module 'TelegramBot' (46 sources)
Compiling Swift Module 'todobot' (1 sources)
Linking .build/debug/todo-bot

Try running .build/debug/todo-bot:

Hello, world!

Create Xcode project

Working from command-line without autocomplete is not very convenient. To create Xcode project, run:

swift build -X

This will produce todo-bot.xcodeproj. Open it in Xcode and switch scheme to the bottom one:

Build the project and run it.

Create a simple bot

Edit Sources/main.swift to look like this:

import TelegramBot

let bot = TelegramBot(token: "TOKEN")

while let update = bot.nextUpdateSync() {
	if let message = update.message, let text = message.text {
		bot.sendMessageAsync(chat_id: message.from.id,
		                     text: "Hi \(message.from.first_name)! You said: \(text).\n")
	}
}

fatalError("Server stopped due to error: \(bot.lastError)")

Replace TOKEN with the token obtained from BotFather.

Run swift build. If there are no compilation errors, run .build/debug/todo-bot.

If you get fatal error: Unable to fetch bot information, verify that the token is correct. Otherwise, the bot is ready to accept commands.

Find your bot in Telegram and send him something.

Congratulations, you've just created a simple bot!

Next: API Introduction

Clone this wiki locally