An open API service indexing awesome lists of open source software.

https://github.com/Nyarum/zigtgshka

🤖 Memory-safe, high-performance Telegram Bot API library for Zig with zero-cost abstractions and comprehensive examples
https://github.com/Nyarum/zigtgshka

Last synced: 8 months ago
JSON representation

🤖 Memory-safe, high-performance Telegram Bot API library for Zig with zero-cost abstractions and comprehensive examples

Awesome Lists containing this project

README

          

# 🤖 Telegram Bot API for Zig

[![Zig](https://img.shields.io/badge/Zig-0.14.0+-F7A41D?style=for-the-badge&logo=zig&logoColor=white)](https://ziglang.org/)
[![Telegram Bot API](https://img.shields.io/badge/Bot%20API-7.0+-2AABEE?style=for-the-badge&logo=telegram&logoColor=white)](https://core.telegram.org/bots/api)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg?style=for-the-badge)](https://opensource.org/licenses/MIT)

**A memory-safe, high-performance Telegram Bot API implementation in Zig**

*Build powerful bots with zero allocations in hot paths and compile-time guarantees*

[![API Coverage](https://img.shields.io/badge/API%20Coverage-85%25-brightgreen?style=for-the-badge)](API_METHODS_IMPLEMENTED.md)

[🚀 Quick Start](#-quick-start) • [📚 Examples](#-examples) • [🎯 Features](#-features) • [📖 DeepWiki](https://deepwiki.com/Nyarum/zigtgshka/1-overview)

🤖 **Complete Bot API Support**
- 📨 **Message Handling**: Send, receive, edit, and delete messages
- 📁 **File Operations**: Upload and download files with streaming support
- 🎯 **Inline Queries**: Full inline mode support
- 🔗 **Webhooks**: Secure webhook management
- 🎮 **Interactive Elements**: Keyboards, buttons, and callbacks
- 📊 **Rich Media**: Photos, videos, documents, and more

## 🚀 Quick Start

### Prerequisites
- **Zig 0.14.0+** ([Download here](https://ziglang.org/download/))
- **Telegram Bot Token** ([Get from @BotFather](https://t.me/botfather))

### 📦 Installation

**Option 1: Using Zig Package Manager (Recommended)**
```bash
# Add to your build.zig.zon
zig fetch --save git+https://github.com/Nyarum/zigtgshka.git
```

**Your build.zig.zon should look like:**
```zig
.{
.name = "my_bot",
.version = "0.0.0",
.minimum_zig_version = "0.14.0",
.dependencies = .{
.zigtgshka = .{
.url = "git+https://github.com/Nyarum/zigtgshka.git",
.hash = "1220...", // This will be auto-generated by zig fetch
},
},
.paths = .{
"build.zig",
"build.zig.zon",
"src",
},
}
```

**Complete build.zig example:**
```zig
const std = @import("std");

pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});

// Add zigtgshka dependency
const telegram_dependency = b.dependency("zigtgshka", .{
.target = target,
.optimize = optimize,
});

// Create your executable
const exe = b.addExecutable(.{
.name = "my_bot",
.root_source_file = b.path("src/main.zig"),
.target = target,
.optimize = optimize,
});

// Import the telegram module
exe.root_module.addImport("telegram", telegram_dependency.module("telegram"));
exe.linkLibC(); // Required for HTTP client

b.installArtifact(exe);

// Run step
const run_cmd = b.addRunArtifact(exe);
run_cmd.step.dependOn(b.getInstallStep());

if (b.args) |args| {
run_cmd.addArgs(args);
}

const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step);
}
```

**Option 2: Git Submodule**
```bash
git submodule add https://github.com/Nyarum/zigtgshka.git libs/telegram

const telegram_mod = b.addModule("telegram", .{
.root_source_file = b.path("libs/telegram/src/telegram.zig"),
.target = target,
.optimize = optimize,
});
exe.root_module.addImport("telegram", telegram_mod);
exe.linkLibC(); // Required for HTTP client
```

**Option 3: Direct Download**
```bash
git clone https://github.com/Nyarum/zigtgshka.git
cd zigtgshka
```

### ⚡ Your First Bot (60 seconds)

Create `src/main.zig`:

```zig
const std = @import("std");
const telegram = @import("telegram");

pub fn main() !void {
// 🏗️ Setup with explicit allocator (Zig best practice)
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();

// 🌐 Initialize HTTP client
var client = try telegram.HTTPClient.init(allocator);
defer client.deinit();

// 🤖 Create your bot
var bot = try telegram.Bot.init(allocator, "YOUR_BOT_TOKEN", &client);
defer bot.deinit();

// 🎉 Get bot info and start polling
const me = try telegram.methods.getMe(&bot);
defer me.deinit(allocator);

std.debug.print("🚀 Bot @{s} is online!\n", .{me.username orelse me.first_name});

// 🔄 Simple polling loop
var offset: i32 = 0;
while (true) {
const updates = try telegram.methods.getUpdates(&bot, offset, 100, 30);
defer {
for (updates) |*update| update.deinit(allocator);
allocator.free(updates);
}

for (updates) |update| {
offset = update.update_id + 1;

if (update.message) |message| {
if (message.text) |text| {
// 💬 Echo messages back
const reply = try telegram.methods.sendMessage(&bot, message.chat.id, text);
defer reply.deinit(allocator);

std.debug.print("📨 Echoed: {s}\n", .{text});
}
}
}
}
}
```

**Run it:**
```bash
# Using zig build (recommended)
zig build run

# Or build and run manually
zig build
./zig-out/bin/my_bot
```

## 📚 Examples

We provide comprehensive examples from beginner to advanced use cases:

> 📖 **For detailed documentation of all examples, see [examples/README.md](examples/README.md)**

### 🎯 Available Examples

| Example | Description | Complexity | Key Features |
|---------|-------------|------------|--------------|
| [**echo_bot**](examples/echo_bot.zig) | Simple echo bot | 🟢 Beginner | Basic message handling |
| [**bot_info**](examples/bot_info.zig) | Get bot information | 🟢 Beginner | API calls, error handling |
| [**simple_sender**](examples/simple_sender.zig) | Send targeted messages | 🟡 Intermediate | Direct messaging |
| [**polling_bot**](examples/polling_bot.zig) | Command-based bot | 🟡 Intermediate | Command parsing, help system |
| [**advanced_bot**](examples/advanced_bot.zig) | Full-featured bot | 🔴 Advanced | State management, analytics |
| [**webhook_manager**](examples/webhook_manager.zig) | Webhook setup | 🟡 Intermediate | Webhook configuration |

## 🤝 Contributing

We welcome contributions! Here's how to get started:

### 🔧 Development Setup
```bash
# Clone the repository
git clone https://github.com/Nyarum/zigtgshka.git
cd zigtgshka

# Run tests to verify setup
zig build test

# Run examples to test functionality
make run-info API_KEY=your_test_token
```

### 📝 Contribution Guidelines
- **Code Style**: Follow Zig's standard formatting (`zig fmt`)
- **Memory Safety**: Always pair `init()` with `deinit()`
- **Error Handling**: Use explicit error types and handling
- **Documentation**: Update docs for any API changes
- **Tests**: Add tests for new functionality

### 🐛 Reporting Issues
- Use the issue template
- Include Zig version (`zig version`)
- Provide minimal reproduction code
- Include relevant log output

## 📊 Performance

### 🚀 Benchmarks
- **Memory Usage**: < 10MB for typical bots
- **Latency**: < 50ms average response time
- **Throughput**: 1000+ messages/second
- **Binary Size**: < 2MB (release builds)

### 📈 Optimization Features
- Zero-allocation hot paths
- Compile-time parameter validation
- Efficient JSON parsing with `std.json`
- Connection pooling for HTTP requests

## 🔗 Resources

### 📚 Learning Zig
- [Official Zig Documentation](https://ziglang.org/documentation/master/)
- [Zig Learn](https://ziglearn.org/)
- [Zig News](https://zig.news/)

### 🤖 Telegram Bot API
- [Official Bot API Documentation](https://core.telegram.org/bots/api)
- [BotFather](https://t.me/botfather) - Create and manage bots
- [Telegram Bot Examples](https://core.telegram.org/bots/samples)

## 📜 License

This project is licensed under the **MIT License** - see the [LICENSE](LICENSE) file for details.

---

**Made with ❤️ and Zig**

*Star ⭐ this repo if you find it useful!*

[🐛 Report Bug](https://github.com/Nyarum/zigtgshka/issues) • [✨ Request Feature](https://github.com/Nyarum/zigtgshka/issues) • [💬 Discussions](https://github.com/Nyarum/zigtgshka/discussions)