Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions src/HuaJiBot.NET.Adapter.Telegram/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ This adapter allows HuaJiBot.NET to connect to Telegram using the official Teleg
- Set group chat titles
- Get user member permissions
- HTML formatting support for rich text
- **Automatic bot command registration** - Commands from plugins are automatically registered with Telegram Bot API

## Setup

Expand All @@ -38,6 +39,18 @@ await telegramAdapter.SetupServiceAsync();

The TelegramAdapter requires only a bot token to function. The bot token is obtained from [@BotFather](https://t.me/BotFather) when you create a new bot.

### Automatic Command Registration

When plugins are loaded, the adapter automatically collects all commands and registers them with the Telegram Bot API using the `setMyCommands` method. This makes commands visible to users in the Telegram UI.

**Command Requirements:**
- Command names must contain only lowercase letters (a-z), digits (0-9), and underscores (_)
- Maximum length: 32 characters
- Commands with Chinese or other non-ASCII characters in names will be skipped
- Command descriptions are limited to 256 characters

The adapter will log debug messages for any commands that are skipped due to invalid names.

## Message Types

- **TextMessage**: Sent as regular text with HTML formatting support
Expand Down
67 changes: 67 additions & 0 deletions src/HuaJiBot.NET.Adapter.Telegram/TelegramAdapter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using Telegram.Bot.Exceptions;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using BotCommand = Telegram.Bot.Types.BotCommand;

namespace HuaJiBot.NET.Adapter.Telegram;

Expand Down Expand Up @@ -61,6 +62,9 @@ public override async Task SetupServiceAsync()
return Task.CompletedTask;
};

// Subscribe to OnInitialized event to register commands after all plugins are loaded
Events.OnInitialized += RegisterBotCommandsAsync;

Log("Telegram bot is receiving messages...");
}
catch (Exception ex)
Expand Down Expand Up @@ -412,4 +416,67 @@ private async Task HandleUpdateAsync(Update update)
LogError("Error handling Telegram update", ex);
}
}

private async void RegisterBotCommandsAsync(object? sender, BotServiceBase service)
{
try
{
// Collect all commands from all loaded plugins
var commands = new List<BotCommand>();

foreach (var (entryPoint, plugin) in Internal.Plugins)
{
if (!plugin.Enabled)
continue;

foreach (var commandInfo in plugin.GetAllCommands())
{
// Telegram bot commands must be lowercase and can only contain letters, digits and underscores
// Maximum length is 32 characters
var commandName = commandInfo.Name.ToLowerInvariant();

// Check if command name contains only valid characters (letters, digits, underscores)
if (!System.Text.RegularExpressions.Regex.IsMatch(commandName, @"^[a-z0-9_]+$"))
{
LogDebug($"Skipping command '{commandInfo.Name}' - contains invalid characters for Telegram (only a-z, 0-9, _ allowed)");
continue;
}

if (commandName.Length > 32)
{
LogDebug($"Skipping command '{commandInfo.Name}' - name too long for Telegram (max 32 chars)");
continue;
}

// Telegram command description max length is 256 characters
var description = commandInfo.Description;
if (description.Length > 256)
{
description = description.Substring(0, 253) + "...";
}

commands.Add(new BotCommand
{
Command = commandName,
Description = description
});
}
}

if (commands.Count > 0)
{
// Register commands with Telegram Bot API
await _botClient.SetMyCommands(commands, cancellationToken: _cancellationTokenSource.Token);
Log($"Successfully registered {commands.Count} commands with Telegram Bot API");
}
else
{
Log("No commands to register with Telegram Bot API");
}
}
catch (Exception ex)
{
LogError("Failed to register bot commands with Telegram", ex);
}
}
}