简体中文 English 繁體中文 日本語 Русский
本文为静态镜像,内容以交互版为准 在交互式文档中心打开 →

Telegram Platform Features Documentation

TelegramAdapter is an adapter built on top of the Telegram Bot API, supporting various message types and event handling.


Documentation Information

Basic Information

Standard API Actions (API DSL)

Adapters map OB12 standard actions to the Telegram Bot API and standardize the data field:

OB12 Standard Action Telegram API data Field
get_self_info getMe user_id / user_name / user_displayname
get_user_info(user_id) getChat user_id / user_name / user_displayname
get_group_info(group_id) getChat group_id / group_name
get_group_member_info(group_id, user_id) getChatMember user_id / user_name / telegram_role
delete_message(message_id) deleteMessage chat_id is automatically completed via message registry
leave_group(group_id) leaveChat -

Extended actions: get_group_admin_list(group_id) (admin list), get_chat_member_count(chat_id) (member count).

from ErisPulse import sdk
telegram = sdk.adapter.get("telegram")

result = await telegram.Api.get_self_info()
result = await telegram.Api.get_group_info(group_id=-100123)
result = await telegram.Api.get_group_admin_list(-100123)
await telegram.Api.delete_message(message_id=55)   # chat_id is automatically completed
result = await telegram.Api.Using("main").get_self_info()

The Telegram Bot API does not provide an interface to retrieve friend/group lists; get_friend_list/get_group_list return errorcode=10002.


Request Operations (Request DSL)

Handle group join requests (chat_join_request event), based on approveChatJoinRequest / declineChatJoinRequest:

from ErisPulse.Core.Event import request

@request.on_request()
async def handle_join_request(event):
    if event.get("platform") != "telegram":
        return
    # event["request_id"] is a synthetic identifier (tjr_{chat_id}_{user_id}_{date})
    if event.get("user_nickname"):
        await event.approve()          # Approve
    # await event.reject()             # Reject

# Manual invocation (requires prior receipt of the corresponding request event to register context)
await telegram.Request(event["request_id"]).accept()
await telegram.Request(event["request_id"]).reject()
await telegram.Request(event["request_id"]).Using("main").accept()

Supported Message Sending Types

All sending methods are implemented using a fluent (chained) syntax, for example:

from ErisPulse.Core import adapter
telegram = adapter.get("telegram")

await telegram.Send.To("user", user_id).Text("Hello World!")

Basic Sending Methods

Method Description Parameters
.Text(text) Send plain text message text: str
.Face(emoji) Send emoji dice emoji: str (e.g., 🎲 🎯 🏀)
.Markdown(text, content_type) Send Markdown-formatted message content_type defaults to "MarkdownV2"
.HTML(text) Send HTML-formatted message text: str
.Sticker(file) Send sticker file: str (file_id/URL) | bytes
.Location(lat, lng) Send location latitude: float, longitude: float
.Venue(lat, lng, title, addr) Send venue Includes title and address
.Contact(phone, first, last) Send contact Includes phone number and name

Media Sending Methods

All media methods support both bytes (upload) and str (file_id / URL) input:

Method Description
.Image(file, caption, content_type) Send image
.Video(file, caption, content_type) Send video
.Voice(file, caption) Send voice
.Audio(file, caption, content_type) Send audio
.File(file, caption) Send file
.Document(file, caption, content_type) Alias for File

Message Management Methods

Method Description
.Edit(message_id, text, content_type) Edit an existing message
.Recall(message_id) Delete a specified message
.Forward(from_chat_id, message_id) Forward a message (retains source)
.CopyMessage(from_chat_id, message_id) Copy a message (without source)
.AnswerCallback(callback_query_id, text, show_alert) Answer a callback query

Raw Message Sending

Fluent Modifier Methods

Method Description
.At(user_id) @ a specified user (implemented via Telegram entities, can be called multiple times)
.AtAll() @ all members (sends @All text)
.Reply(message_id) Reply to a specified message
.Keyboard(inline_keyboard) Set inline keyboard (list[list[dict]])
.ProtectContent(protect) Protect content (prevents forwarding and saving)
.Silent(silent) Send silently (does not notify the user)

Sending Examples

# Basic text sending
await telegram.Send.To("user", user_id).Text("Hello World!")

# Message with inline keyboard
from ErisPulse import sdk
telegram = sdk.adapter.get("telegram")
keyboard = [
    [{"text": "Button 1", "callback_data": "btn1"}, {"text": "Button 2", "callback_data": "btn2"}],
    [{"text": "Visit Website", "url": "https://example.com"}],
]
await telegram.Send.To("group", group_id).Keyboard(keyboard).Text("Please select:")

# Media sending (using URL)
await telegram.Send.To("group", group_id).Image("https://example.com/image.jpg", caption="Image")

# @ user
await telegram.Send.To("group", group_id).At("6117725680").Text("Hello!")

# Reply + protected content
await telegram.Send.To("group", group_id).Reply("12345").ProtectContent().Text("Confidential message")

# Silent sending
await telegram.Send.To("group", group_id).Silent().Text("Silent notification")

# Answer callback query
await telegram.Send.AnswerCallback(callback_query_id, text="Processed", show_alert=False)

# OneBot12 composite message
ob12_message = [
    {"type": "text", "data": {"text": "Complex message:"}},
    {"type": "mention", "data": {"user_id": "6117725680", "user_name": "Username"}},
    {"type": "reply", "data": {"message_id": "12345"}},
    {"type": "image", "data": {"file": "https://http.cat/200"}}
]
await telegram.Send.To("group", group_id).Raw_ob12(ob12_message)

# Send sticker
await telegram.Send.To("user", user_id).Sticker("CAACAgIAAxkBAA...")  # file_id

# Send location
await telegram.Send.To("user", user_id).Location(39.9042, 116.4074)

Unique Event Types

Telegram event conversion follows the OneBot12 standard, while providing platform extensions through the telegram_ prefix.

Message Event detail_type Mapping

Telegram chat.type OneBot12 detail_type Target Type
private private user
group group group
supergroup group group
channel channel channel

Unique Event Types

detail_type Description
telegram_callback_query Callback query (inline keyboard button click)
telegram_inline_query Inline query
telegram_chosen_inline_result Chosen inline result
telegram_poll Poll event
telegram_poll_answer Poll answer
telegram_my_chat_member Bot member status change
telegram_chat_member Chat member change
telegram_chat_join_request Join chat request
telegram_shipping_query Shipping query
telegram_pre_checkout_query Pre-checkout query

Standard Message Segment Types

Converted message segments use the OneBot12 standard format:

Message Segment Type Description data Fields
text Plain text (without @username) text
mention @User (standard OB12) user_id, user_name
reply Reply reference message_id, user_id
image Image file_id, url
video Video file_id, url, duration, width, height
voice Voice file_id, url, duration
audio Audio file_id, url, duration, title, performer
file File file_id, url, file_name, file_size, mime_type
location Location latitude, longitude, optional title, address

Platform Extension Message Segments

Extension message segments identified by the telegram_ prefix:

Message Segment Type Description data Fields
telegram_sticker Sticker file_id, emoji, sticker_type, url
telegram_animation GIF animation file_id, url, duration, caption
telegram_contact Contact phone_number, first_name, last_name, user_id
telegram_inline_keyboard Inline keyboard inline_keyboard

Event Examples

Group Chat Message (with @mention)

{
  "type": "message",
  "detail_type": "group",
  "platform": "telegram",
  "user_id": "6117725680",
  "user_nickname": "WSu2059",
  "group_id": "-1002850921906",
  "message_id": "172",
  "message": [
    {"type": "text", "data": {"text": "/it.echo "}},
    {"type": "mention", "data": {"user_id": "", "user_name": "@nm123_91178"}}
  ],
  "alt_message": "/it.echo @nm123_91178",
  "telegram_chat": {
    "id": -1002850921906,
    "title": "ErisPulse",
    "username": "erispulse",
    "type": "supergroup"
  }
}

Callback Query Event

{
  "type": "notice",
  "detail_type": "telegram_callback_query",
  "user_id": "123456",
  "user_nickname": "YingXinche",
  "telegram_callback_id": "cb_123",
  "telegram_callback_data": "callback_data",
  "message_id": "msg_456"
}

Inline Query Event

{
  "type": "request",
  "detail_type": "telegram_inline_query",
  "user_id": "789012",
  "user_nickname": "YingXinche",
  "telegram_query_id": "iq_789",
  "telegram_query_text": "search_text",
  "telegram_query_offset": "0"
}

Message with Inline Keyboard

{
  "type": "message",
  "detail_type": "group",
  "message": [
    {"type": "text", "data": {"text": "请选择:"}},
    {
      "type": "telegram_inline_keyboard",
      "data": {
        "inline_keyboard": [
          [{"text": "按钮1", "callback_data": "btn1"}],
          [{"text": "访问", "url": "https://example.com"}]
        ]
      }
    }
  ]
}

Event Mixin Extension Methods

The adapter registers the following platform-specific methods, available only when platform == "telegram":

Method Return Type Description
is_bot_message() bool Check if the message is from a bot
is_edited_message() bool Check if the message has been edited
is_topic_message() bool Check if the message is a topic/Topic message
get_update_id() int Get the Telegram update ID
get_chat_title() str Get the chat title
get_chat_username() str Get the chat username
get_forward_from() dict Get the forwarding source information
get_topic_id() str Get the topic ID
Method Return Type Description
get_callback_data() str Get the callback_data of the callback query
get_callback_id() str Get the callback query ID (used for responding)

Message Segment Data Extraction

Method Return Type Description
get_inline_keyboard() list Get the inline keyboard from the message
get_sticker_info() dict Get the sticker information
get_contact_info() dict Get the contact information
get_location() dict Get the location information

Usage Example

from ErisPulse.Core.Event import message, notice

@message.on_message()
async def handle_message(event):
    if event.get("platform") != "telegram":
        return

    # Message properties
    if event.is_bot_message():
        return  # Ignore bot messages

    if event.is_edited_message():
        print("This is an edited message")

    # Chat information
    title = event.get_chat_title()
    username = event.get_chat_username()

    # Forwarding source
    forward = event.get_forward_from()

    # Message segment data
    sticker = event.get_sticker_info()
    contact = event.get_contact_info()
    location = event.get_location()
    keyboard = event.get_inline_keyboard()

    # Topic
    if event.is_topic_message():
        topic_id = event.get_topic_id()

@notice.on_notice()
async def handle_notice(event):
    if event.get("platform") != "telegram":
        return

    if event.get("detail_type") == "telegram_callback_query":
        callback_data = event.get_callback_data()
        callback_id = event.get_callback_id()

        # Respond to the callback query
        telegram = sdk.adapter.get("telegram")
        await telegram.Send.AnswerCallback(callback_id, text="Clicked")

        # Reply to the message
        await event.reply(f"You clicked: {callback_data}")

Extension Field Description

Configuration Options

The Telegram adapter supports multi-account configuration:

Configuration Example

[Telegram_Adapter.accounts.default]
token = "YOUR_BOT_TOKEN"
enabled = true

[Telegram_Adapter.accounts.bot2]
token = "ANOTHER_BOT_TOKEN"
enabled = true

Running Mode

The Telegram adapter only supports Polling (polling) mode; the Webhook mode has been removed.

Proxy Configuration

If you need to connect to the Telegram API through a proxy, use a system-level proxy (environment variables ALL_PROXY / HTTPS_PROXY).

Migration from Old Configuration

The old single-token configuration is automatically compatible:

# Old format (still usable, but migration is recommended)
[Telegram_Adapter]
token = "YOUR_BOT_TOKEN"

It is recommended to migrate to the new format:

[Telegram_Adapter.accounts.default]
token = "YOUR_BOT_TOKEN"
enabled = true