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

https://github.com/impworks/botrunner

Tiny framework for programming Telegram Bots
https://github.com/impworks/botrunner

telegram telegram-bot telegram-bot-framework

Last synced: 11 months ago
JSON representation

Tiny framework for programming Telegram Bots

Awesome Lists containing this project

README

          

# BotRunner
Tiny framework for programming Telegram Bots

### What is it?
This is a framework for scripting bot dialogs in Telegram based on Telegram.Bot library.
It is based on a state machine: the dialog consists of steps, which can be executed sequentially or in a custom order.
Each dialog with a user can have a custom "state" which stores data between steps.

### Usage
Pretty straightforward.

```csharp
namespace MyBot
{
// Step 1: define the state
public class MyState: StateBase
{
public string Name { get; set; }
}

// Step 2: define the dialog steps
public static class RunnerDefinition
{
public static Runner Create()
{
return new RunnerBuilder()
.Step(async s => { await s.Reply("Please enter your name"); })
.Step(async s =>
{
s.State.Name = s.Message.Text;
await s.Reply("Nice to meet you, " + s.State.Name);
})
.Build();
}
}

// Step 3: run the bot
class Program
{
private const string Token = "...";

static async Task Main(string[] args)
{
var runner = RunnerDefinition.Create();
var client = new TelegramBotClient(Token); // you may need to add a proxy

client.OnMessage += async (s, e) => await runner.HandleAsync(client, e.Message);
client.StartReceiving();

Thread.Sleep(int.MaxValue);
}
}
}
```

### API

When declaring a step, you need to provide the handler in a form of `Func, Task>`.

The `IExecutionContext` is defined as follows:

```csharp
public interface IExecutionContext where T: StateBase
{
///
/// Marks the specified step as next for execution.
///
void Goto(string stepId);

///
/// Bot client instance.
///
ITelegramBotClient Bot { get; }

///
/// User session.
///
T State { get; }

///
/// Current message from the user.
///
Message Message { get; }
}
```

All available Telegram.Bot APIs are available, but you can create shorthand extension methods to make code more conscise. A `Reply` helper is already provided:

```csharp
public static class ExecutionContextExtensions
{
///
/// Sends a text reply to the current message.
///
public static async Task Reply(this IExecutionContext ctx, string text)
where T: StateBase
{
await ctx.Bot.SendTextMessageAsync(ctx.Message.Chat.Id, text);
}
}
```