fix(docs):多份文档汉译英并整理 (#8001)

* docs(en): translate plugin-platform-adapter.md from Chinese to English

* docs(en): translate plugin-platform-adapter.md from Chinese to English

* Update ppio.md

* Update provider-lmstudio.md

* Update function-calling.md

* Update skills.md

* Update ai.md

* Update simple.md

* Update mcp.md

* Update config.mjs kook

* fix(docs): fix MessageSesion import path in platform adapter example

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>

---------

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
This commit is contained in:
lingyun14
2026-05-09 22:17:47 +08:00
committed by GitHub
parent 4bcaaab44f
commit bd9aade842
10 changed files with 102 additions and 120 deletions

View File

@@ -2,23 +2,23 @@
outline: deep
---
# 开发一个平台适配器
# Developing a Platform Adapter
AstrBot 支持以插件的形式接入平台适配器,你可以自行接入 AstrBot 没有的平台。如飞书、钉钉甚至是哔哩哔哩私信、Minecraft
AstrBot supports integrating platform adapters in plugin form, allowing you to connect platforms that AstrBot does not natively support — such as Lark, DingTalk, Bilibili private messages, or even Minecraft.
我们以一个平台 `FakePlatform` 为例展开讲解。
We will use a platform called `FakePlatform` as an example.
首先,在插件目录下新增 `fake_platform_adapter.py` `fake_platform_event.py` 文件。前者主要是平台适配器的实现,后者是平台事件的定义。
First, add `fake_platform_adapter.py` and `fake_platform_event.py` to your plugin directory. The former handles the platform adapter implementation, while the latter defines the platform event.
## 平台适配器
## Platform Adapter
假设 FakePlatform 的客户端 SDK 是这样:
Assume FakePlatform's client SDK looks like this:
```py
import asyncio
class FakeClient():
'''模拟一个消息平台,这里 5 秒钟下发一个消息'''
'''Simulates a messaging platform that sends a message every 5 seconds'''
def __init__(self, token: str, username: str):
self.token = token
self.username = username
@@ -29,7 +29,7 @@ class FakeClient():
await asyncio.sleep(5)
await getattr(self, 'on_message_received')({
'bot_id': '123',
'content': '新消息',
'content': 'new message',
'username': 'zhangsan',
'userid': '123',
'message_id': 'asdhoashd',
@@ -37,28 +37,28 @@ class FakeClient():
})
async def send_text(self, to: str, message: str):
print('发了消息:', to, message)
print('Message sent:', to, message)
async def send_image(self, to: str, image_path: str):
print('发了消息:', to, image_path)
print('Image sent:', to, image_path)
```
我们创建 `fake_platform_adapter.py`
Now create `fake_platform_adapter.py`:
```py
import asyncio
from astrbot.api.platform import Platform, AstrBotMessage, MessageMember, PlatformMetadata, MessageType
from astrbot.api.event import MessageChain
from astrbot.api.message_components import Plain, Image, Record # 消息链中的组件,可以根据需要导入
from astrbot.core.platform.astr_message_event import MessageSesion
from astrbot.api.message_components import Plain, Image, Record # Message chain components, import as needed
from astrbot.core.platform.message_session import MessageSesion
from astrbot.api.platform import register_platform_adapter
from astrbot import logger
from .client import FakeClient
from .fake_platform_event import FakePlatformEvent
# 注册平台适配器。第一个参数为平台名,第二个为描述。第三个为默认配置。
@register_platform_adapter("fake", "fake 适配器", default_config_tmpl={
# Register the platform adapter. First param: platform name, second: description, third: default config.
@register_platform_adapter("fake", "fake adapter", default_config_tmpl={
"token": "your_token",
"username": "bot_username"
})
@@ -66,52 +66,53 @@ class FakePlatformAdapter(Platform):
def __init__(self, platform_config: dict, platform_settings: dict, event_queue: asyncio.Queue) -> None:
super().__init__(event_queue)
self.config = platform_config # 上面的默认配置,用户填写后会传到这里
self.settings = platform_settings # platform_settings 平台设置。
self.config = platform_config # The default config above; filled in by the user and passed here
self.settings = platform_settings # platform_settings: platform settings
async def send_by_session(self, session: MessageSesion, message_chain: MessageChain):
# 必须实现
# Must be implemented
await super().send_by_session(session, message_chain)
def meta(self) -> PlatformMetadata:
# 必须实现,直接像下面一样返回即可。
# Must be implemented. Simply return as shown below.
return PlatformMetadata(
"fake",
"fake 适配器",
"fake adapter",
)
async def run(self):
# 必须实现,这里是主要逻辑。
# Must be implemented. This is the main logic.
# FakeClient 是我们自己定义的,这里只是示例。这个是其回调函数
# FakeClient is defined by us — this is just an example. This is its callback function.
async def on_received(data):
logger.info(data)
abm = await self.convert_message(data=data) # 转换成 AstrBotMessage
abm = await self.convert_message(data=data) # Convert to AstrBotMessage
await self.handle_msg(abm)
# 初始化 FakeClient
# Initialize FakeClient
self.client = FakeClient(self.config['token'], self.config['username'])
self.client.on_message_received = on_received
await self.client.start_polling() # 持续监听消息,这是个堵塞方法。
await self.client.start_polling() # Continuously listens for messages; this is a blocking call.
async def convert_message(self, data: dict) -> AstrBotMessage:
# 将平台消息转换成 AstrBotMessage
# 这里就体现了适配程度,不同平台的消息结构不一样,这里需要根据实际情况进行转换。
# Convert the platform message to AstrBotMessage.
# The degree of adaptation is reflected here. Different platforms have different message
# structures; convert accordingly.
abm = AstrBotMessage()
abm.type = MessageType.GROUP_MESSAGE # 还有 friend_message,对应私聊。具体平台具体分析。重要!
abm.group_id = data['group_id'] # 如果是私聊,这里可以不填
abm.message_str = data['content'] # 纯文本消息。重要!
abm.sender = MessageMember(user_id=data['userid'], nickname=data['username']) # 发送者。重要!
abm.message = [Plain(text=data['content'])] # 消息链。如果有其他类型的消息,直接 append 即可。重要!
abm.raw_message = data # 原始消息。
abm.type = MessageType.GROUP_MESSAGE # Also friend_message for private chats. Analyze per platform. Important!
abm.group_id = data['group_id'] # Can be omitted for private chats
abm.message_str = data['content'] # Plain text message. Important!
abm.sender = MessageMember(user_id=data['userid'], nickname=data['username']) # Sender. Important!
abm.message = [Plain(text=data['content'])] # Message chain. Append other message types as needed. Important!
abm.raw_message = data # Raw message.
abm.self_id = data['bot_id']
abm.session_id = data['userid'] # 会话 ID。重要
abm.message_id = data['message_id'] # 消息 ID
abm.session_id = data['userid'] # Session ID. Important!
abm.message_id = data['message_id'] # Message ID.
return abm
async def handle_msg(self, message: AstrBotMessage):
# 处理消息
# Handle the message
message_event = FakePlatformEvent(
message_str=message.message_str,
message_obj=message,
@@ -119,11 +120,11 @@ class FakePlatformAdapter(Platform):
session_id=message.session_id,
client=self.client
)
self.commit_event(message_event) # 提交事件到事件队列。不要忘记!
self.commit_event(message_event) # Submit the event to the event queue. Don't forget this!
```
`fake_platform_event.py`
`fake_platform_event.py`:
```py
from astrbot.api.event import AstrMessageEvent, MessageChain
@@ -138,13 +139,13 @@ class FakePlatformEvent(AstrMessageEvent):
self.client = client
async def send(self, message: MessageChain):
for i in message.chain: # 遍历消息链
if isinstance(i, Plain): # 如果是文字类型的
for i in message.chain: # Iterate over the message chain
if isinstance(i, Plain): # If it's a text message
await self.client.send_text(to=self.get_sender_id(), message=i.text)
elif isinstance(i, Image): # 如果是图片类型的
elif isinstance(i, Image): # If it's an image
img_url = i.file
img_path = ""
# 下面的三个条件可以直接参考一下。
# The three conditions below can be used as a reference.
if img_url.startswith("file:///"):
img_path = img_url[8:]
elif i.file and i.file.startswith("http"):
@@ -152,14 +153,14 @@ class FakePlatformEvent(AstrMessageEvent):
else:
img_path = img_url
# 请善于 Debug
# Make good use of debugging!
await self.client.send_image(to=self.get_sender_id(), image_path=img_path)
await super().send(message) # 需要最后加上这一段,执行父类的 send 方法。
await super().send(message) # Must be called at the end to invoke the parent class's send method.
```
最后main.py 只需这样,在初始化的时候导入 fake_platform_adapter 模块。装饰器会自动注册。
Finally, in `main.py`, simply import the `fake_platform_adapter` module during initialization. The decorator will handle registration automatically.
```py
from astrbot.api.star import Context, Star
@@ -169,17 +170,17 @@ class MyPlugin(Star):
from .fake_platform_adapter import FakePlatformAdapter # noqa
```
搞好后,运行 AstrBot
Once set up, run AstrBot:
![image](https://files.astrbot.app/docs/source/images/plugin-platform-adapter/QQ_1738155926221.png)
这里出现了我们创建的 fake。
The `fake` adapter we created now appears here.
![image](https://files.astrbot.app/docs/source/images/plugin-platform-adapter/QQ_1738155982211.png)
启动后,可以看到正常工作:
After starting, you can see it working correctly:
![image](https://files.astrbot.app/docs/source/images/plugin-platform-adapter/QQ_1738156166893.png)
有任何疑问欢迎加群询问~
If you have any questions, feel free to join the community group and ask~