mirror of
https://github.com/langbot-app/LangBot.git
synced 2026-10-30 20:35:22 +08:00
Add English documentation
Co-Authored-By: Junyan Qin <Chin> <[email protected]>
This commit is contained in:
co-authored by
Junyan Qin <Chin>
parent
cca2067b88
commit
dd93920369
+186
-215
@@ -210,225 +210,196 @@ export default defineConfig({
|
||||
],
|
||||
},
|
||||
},
|
||||
// en: {
|
||||
// label: "English",
|
||||
// lang: "en",
|
||||
// link: "/en/",
|
||||
// themeConfig: {
|
||||
// // https://vitepress.dev/reference/default-theme-config
|
||||
en: {
|
||||
label: "English",
|
||||
lang: "en",
|
||||
link: "/en/",
|
||||
themeConfig: {
|
||||
// https://vitepress.dev/reference/default-theme-config
|
||||
|
||||
// nav: [
|
||||
// { text: "Home", link: "/en/" },
|
||||
// { text: "Insight", link: "/en/insight/guide" },
|
||||
// { text: "Deploy", link: "/en/deploy/langbot/manual" },
|
||||
// { text: "Plugin", link: "/en/plugin/plugin-intro" },
|
||||
// ],
|
||||
nav: [
|
||||
{ text: "Home", link: "https://langbot.app" },
|
||||
{ text: "Roadmap", link: "https://langbot.featurebase.app/roadmap" },
|
||||
],
|
||||
|
||||
// sidebar: [
|
||||
// {
|
||||
// text: "Insight",
|
||||
// items: [
|
||||
// { text: "Getting Started", link: "/en/insight/guide" },
|
||||
// { text: "Introduction", link: "/en/insight/intro" },
|
||||
// { text: "Community Resources", link: "/en/insight/community" },
|
||||
// ],
|
||||
// },
|
||||
// {
|
||||
// text: "Deploy",
|
||||
// items: [
|
||||
// {
|
||||
// text: "Deploy LangBot",
|
||||
// collapsed: true,
|
||||
// items: [
|
||||
// {
|
||||
// text: "Deploy with Baota Panel",
|
||||
// link: "/en/deploy/langbot/one-click/bt",
|
||||
// },
|
||||
// {
|
||||
// text: "Deploy with Docker",
|
||||
// link: "/en/deploy/langbot/docker",
|
||||
// },
|
||||
// {
|
||||
// text: "Manual Deployment",
|
||||
// link: "/en/deploy/langbot/manual",
|
||||
// },
|
||||
// ],
|
||||
// },
|
||||
// {
|
||||
// text: "Deploy Message Platforms",
|
||||
// collapsed: true,
|
||||
// items: [
|
||||
// {
|
||||
// text: "aiocqhttp",
|
||||
// collapsed: true,
|
||||
// items: [
|
||||
// {
|
||||
// text: "NapCat",
|
||||
// link: "/en/deploy/platforms/aiocqhttp/napcat",
|
||||
// },
|
||||
// {
|
||||
// text: "Lagrange",
|
||||
// link: "/en/deploy/platforms/aiocqhttp/lagrange",
|
||||
// },
|
||||
// {
|
||||
// text: "llonebot",
|
||||
// link: "/en/deploy/platforms/aiocqhttp/llonebot",
|
||||
// },
|
||||
// {
|
||||
// text: "shamrock",
|
||||
// link: "/en/deploy/platforms/aiocqhttp/shamrock",
|
||||
// },
|
||||
// ],
|
||||
// },
|
||||
// {
|
||||
// text: "go-cqhttp",
|
||||
// link: "/en/deploy/platforms/gocq",
|
||||
// },
|
||||
// {
|
||||
// text: "QQ Official",
|
||||
// link: "/en/deploy/platforms/official",
|
||||
// },
|
||||
// ],
|
||||
// },
|
||||
// {
|
||||
// text: "Fill in the Configuration",
|
||||
// link: "/en/deploy/quick-config/config",
|
||||
// },
|
||||
// {
|
||||
// text: "Network Configuration",
|
||||
// link: "/en/deploy/network-details",
|
||||
// },
|
||||
// {
|
||||
// text: "Update LangBot",
|
||||
// link: "/en/deploy/update",
|
||||
// },
|
||||
// ],
|
||||
// },
|
||||
sidebar: [
|
||||
{
|
||||
text: "Overview",
|
||||
items: [
|
||||
{ text: "Getting Started (Must Read)", link: "/en/insight/guide" },
|
||||
{ text: "Community Resources", link: "/en/insight/community" },
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "Deployment and Usage",
|
||||
items: [
|
||||
{
|
||||
text: "Deploy LangBot",
|
||||
collapsed: true,
|
||||
items: [
|
||||
{ text: "Docker Deployment", link: "/en/deploy/langbot/docker" },
|
||||
{
|
||||
text: "Baota Panel Deployment",
|
||||
link: "/en/deploy/langbot/one-click/bt",
|
||||
},
|
||||
{ text: "Manual Deployment", link: "/en/deploy/langbot/manual" },
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "Configure Bots",
|
||||
collapsed: true,
|
||||
link: "/en/deploy/platforms/readme",
|
||||
items: [
|
||||
{
|
||||
text: "OneBot v11",
|
||||
collapsed: true,
|
||||
items: [
|
||||
{
|
||||
text: "NapCat",
|
||||
link: "/en/deploy/platforms/qq/aiocqhttp/napcat",
|
||||
},
|
||||
{
|
||||
text: "Lagrange",
|
||||
link: "/en/deploy/platforms/qq/aiocqhttp/lagrange",
|
||||
},
|
||||
{
|
||||
text: "llonebot",
|
||||
link: "/en/deploy/platforms/qq/aiocqhttp/llonebot",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "QQ Official Bot",
|
||||
collapsed: true,
|
||||
items: [
|
||||
{
|
||||
text: "Webhook Method",
|
||||
link: "/en/deploy/platforms/qq/official_webhook",
|
||||
},
|
||||
{
|
||||
text: "WebSocket Method",
|
||||
link: "/en/deploy/platforms/qq/official",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "Personal WeChat",
|
||||
collapsed: true,
|
||||
items: [
|
||||
{
|
||||
text: "Gewechat",
|
||||
link: "/en/deploy/platforms/wechat/gewechat",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "WeCom (Enterprise WeChat)",
|
||||
collapsed: true,
|
||||
items: [
|
||||
{
|
||||
text: "Internal Application",
|
||||
link: "/en/deploy/platforms/wecom/wecom",
|
||||
},
|
||||
{
|
||||
text: "External Customer Service",
|
||||
link: "/en/deploy/platforms/wecom/wecomcs",
|
||||
},
|
||||
],
|
||||
},
|
||||
{ text: "WeChat Official Account", link: "/en/deploy/platforms/wxoa" },
|
||||
{ text: "Feishu (Lark)", link: "/en/deploy/platforms/lark" },
|
||||
{ text: "DingTalk", link: "/en/deploy/platforms/dingtalk" },
|
||||
{ text: "Discord", link: "/en/deploy/platforms/discord" },
|
||||
{ text: "Telegram", link: "/en/deploy/platforms/telegram" },
|
||||
{ text: "Slack", link: "/en/deploy/platforms/slack" },
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "Configure Dialogue Models",
|
||||
link: "/en/deploy/models/readme",
|
||||
},
|
||||
{
|
||||
text: "Modify Dialogue Pipeline",
|
||||
link: "/en/deploy/pipelines/readme",
|
||||
},
|
||||
{
|
||||
text: "System Environment Settings",
|
||||
link: "/en/deploy/settings",
|
||||
},
|
||||
{
|
||||
text: "Dialogue Commands",
|
||||
link: "/en/deploy/command",
|
||||
},
|
||||
{
|
||||
text: "Update LangBot",
|
||||
link: "/en/deploy/update",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "Plugins",
|
||||
items: [
|
||||
{ text: "Plugin Introduction", link: "/en/plugin/plugin-intro" },
|
||||
{
|
||||
text: "Plugin Development",
|
||||
collapsed: true,
|
||||
items: [
|
||||
{ text: "Basic Tutorial", link: "/en/plugin/dev/tutor" },
|
||||
{ text: "Message Platform Entities", link: "/en/plugin/dev/messages" },
|
||||
{ text: "API Reference", link: "/en/plugin/dev/api-ref" },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "Workshops",
|
||||
items: [
|
||||
{
|
||||
text: "How to Integrate with Dify?",
|
||||
link: "/en/workshop/dify-service-api",
|
||||
},
|
||||
{
|
||||
text: "How to Implement a Message Platform Adapter?",
|
||||
link: "/en/workshop/impl-platform-adapter",
|
||||
},
|
||||
{
|
||||
text: "Integrating Complete MCP Ecosystem in LangBot",
|
||||
link: "/en/workshop/mcp-details"
|
||||
},
|
||||
{
|
||||
text: "Container Network Configuration Details",
|
||||
link: "/en/workshop/network-details",
|
||||
},
|
||||
{
|
||||
text: "Integrating PPIO API",
|
||||
link: "/en/workshop/ppio-integration"
|
||||
}
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "Development",
|
||||
items: [
|
||||
{ text: "Development Configuration", link: "/en/develop/dev-config" },
|
||||
{ text: "Component Architecture", link: "/en/develop/comp-arch" },
|
||||
],
|
||||
},
|
||||
],
|
||||
|
||||
// {
|
||||
// text: "Usage",
|
||||
// items: [
|
||||
// { text: "Command Usage", link: "/en/usage/command" },
|
||||
// { text: "FAQ", link: "/en/usage/faq" },
|
||||
// ],
|
||||
// },
|
||||
// {
|
||||
// text: "Config",
|
||||
// items: [
|
||||
// {
|
||||
// text: "Function Configuration",
|
||||
// collapsed: true,
|
||||
// items: [
|
||||
// {
|
||||
// text: "platform.json",
|
||||
// link: "/en/config/function/platform",
|
||||
// },
|
||||
// {
|
||||
// text: "pipeline.json",
|
||||
// link: "/en/config/function/pipeline",
|
||||
// },
|
||||
// {
|
||||
// text: "provider.json",
|
||||
// link: "/en/config/function/provider",
|
||||
// },
|
||||
// { text: "command.json", link: "/en/config/function/command" },
|
||||
// { text: "system.json", link: "/en/config/function/system" },
|
||||
// ],
|
||||
// },
|
||||
// {
|
||||
// text: "Metadata Configuration",
|
||||
// collapsed: true,
|
||||
// items: [
|
||||
// {
|
||||
// text: "sensitive-words.json",
|
||||
// link: "/en/config/metadata/sensitive-words",
|
||||
// },
|
||||
// {
|
||||
// text: "llm-models.json",
|
||||
// link: "/en/config/metadata/llm-models",
|
||||
// },
|
||||
// {
|
||||
// text: "adapter-qq-botpy.json",
|
||||
// link: "/en/config/metadata/adapter-qq-botpy",
|
||||
// },
|
||||
// ],
|
||||
// },
|
||||
// ],
|
||||
// },
|
||||
// {
|
||||
// text: "Plugin",
|
||||
// items: [
|
||||
// { text: "Plugin Introduction", link: "/en/plugin/plugin-intro" },
|
||||
// {
|
||||
// text: "Plugin Development",
|
||||
// collapsed: true,
|
||||
// items: [
|
||||
// { text: "Basic Tutorial", link: "/en/plugin/dev/tutor" },
|
||||
// {
|
||||
// text: "Message Platform Entity",
|
||||
// link: "/en/plugin/dev/messages",
|
||||
// },
|
||||
// { text: "API Reference", link: "/en/plugin/dev/api-ref" },
|
||||
// {
|
||||
// text: "Component Extension",
|
||||
// link: "/en/plugin/dev/extension",
|
||||
// },
|
||||
// ],
|
||||
// },
|
||||
// ],
|
||||
// },
|
||||
// {
|
||||
// text: "WebUI (Beta)",
|
||||
// items: [
|
||||
// { text: "Introduction & Usage", link: "/en/webui/intro" },
|
||||
// { text: "System Operation", link: "/en/webui/system" },
|
||||
// { text: "Settings Management", link: "/en/webui/settings" },
|
||||
// ],
|
||||
// },
|
||||
// {
|
||||
// text: "Workshop",
|
||||
// items: [
|
||||
// {
|
||||
// text: "How to Access Dify Service API?",
|
||||
// link: "/en/workshop/dify-service-api",
|
||||
// },
|
||||
// {
|
||||
// text: "How to Access Dify Service API? - NewAPI Intermediate Solution",
|
||||
// link: "/en/workshop/dify-integration",
|
||||
// },
|
||||
// {
|
||||
// text: "How to Access Third-party OpenAI Format APIs like OneAPI, LinkAI?",
|
||||
// link: "/en/workshop/one-api",
|
||||
// },
|
||||
// {
|
||||
// text: "How to Implement a Message Platform Adapter?",
|
||||
// link: "/en/workshop/impl-platform-adapter",
|
||||
// },
|
||||
// ],
|
||||
// },
|
||||
// {
|
||||
// text: "Develop",
|
||||
// items: [
|
||||
// { text: "Component Architecture", link: "/en/develop/comp-arch" },
|
||||
// ],
|
||||
// },
|
||||
// ],
|
||||
// edit link
|
||||
editLink: {
|
||||
pattern:
|
||||
"https://github.com/the-lazy-me/Langbot-Wiki/edit/main/docs/:path",
|
||||
},
|
||||
|
||||
// // edit link
|
||||
// editLink: {
|
||||
// pattern:
|
||||
// "https://github.com/the-lazy-me/Langbot-Wiki/edit/main/docs/:path",
|
||||
// },
|
||||
|
||||
// // social links in the navbar
|
||||
// socialLinks: [
|
||||
// {
|
||||
// icon: "github",
|
||||
// link: "https://github.com/the-lazy-me/QChatGPT-Wiki",
|
||||
// },
|
||||
// ],
|
||||
// },
|
||||
// },
|
||||
// social links in the navbar
|
||||
socialLinks: [
|
||||
{
|
||||
icon: "github",
|
||||
link: "https://github.com/RockChinQ/LangBot",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
// 最后更新时间
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
# Dialogue Commands
|
||||
|
||||
LangBot provides various commands that can be used during conversations to control the bot's behavior.
|
||||
|
||||
## Command Prefix
|
||||
|
||||
Commands start with a prefix, which by default is `!` or `!`. You can configure the command prefixes in the `data/config.yaml` file:
|
||||
|
||||
```yaml
|
||||
trigger:
|
||||
command_prefixes:
|
||||
- "!"
|
||||
- "!"
|
||||
```
|
||||
|
||||
## Available Commands
|
||||
|
||||
### Help Command
|
||||
|
||||
```
|
||||
!help
|
||||
```
|
||||
|
||||
Displays a list of available commands.
|
||||
|
||||
### Model Commands
|
||||
|
||||
```
|
||||
!model list
|
||||
```
|
||||
|
||||
Lists all available models.
|
||||
|
||||
```
|
||||
!model use <model_name>
|
||||
```
|
||||
|
||||
Switches to the specified model.
|
||||
|
||||
```
|
||||
!model info
|
||||
```
|
||||
|
||||
Displays information about the current model.
|
||||
|
||||
### Context Commands
|
||||
|
||||
```
|
||||
!context clear
|
||||
```
|
||||
|
||||
Clears the current conversation context.
|
||||
|
||||
```
|
||||
!context show
|
||||
```
|
||||
|
||||
Displays the current conversation context.
|
||||
|
||||
```
|
||||
!context length
|
||||
```
|
||||
|
||||
Shows the length of the current context in tokens.
|
||||
|
||||
### Pipeline Commands
|
||||
|
||||
```
|
||||
!pipeline list
|
||||
```
|
||||
|
||||
Lists all available pipelines.
|
||||
|
||||
```
|
||||
!pipeline use <pipeline_id>
|
||||
```
|
||||
|
||||
Switches to the specified pipeline.
|
||||
|
||||
```
|
||||
!pipeline info
|
||||
```
|
||||
|
||||
Displays information about the current pipeline.
|
||||
|
||||
### System Commands
|
||||
|
||||
```
|
||||
!system info
|
||||
```
|
||||
|
||||
Displays system information, including version, uptime, and memory usage.
|
||||
|
||||
```
|
||||
!system reload
|
||||
```
|
||||
|
||||
Reloads the system configuration.
|
||||
|
||||
### Plugin Commands
|
||||
|
||||
```
|
||||
!plugin list
|
||||
```
|
||||
|
||||
Lists all installed plugins.
|
||||
|
||||
```
|
||||
!plugin enable <plugin_id>
|
||||
```
|
||||
|
||||
Enables the specified plugin.
|
||||
|
||||
```
|
||||
!plugin disable <plugin_id>
|
||||
```
|
||||
|
||||
Disables the specified plugin.
|
||||
|
||||
```
|
||||
!plugin info <plugin_id>
|
||||
```
|
||||
|
||||
Displays information about the specified plugin.
|
||||
|
||||
### Preset Commands
|
||||
|
||||
```
|
||||
!preset list
|
||||
```
|
||||
|
||||
Lists all available presets.
|
||||
|
||||
```
|
||||
!preset use <preset_id>
|
||||
```
|
||||
|
||||
Switches to the specified preset.
|
||||
|
||||
```
|
||||
!preset info
|
||||
```
|
||||
|
||||
Displays information about the current preset.
|
||||
|
||||
## Command Permissions
|
||||
|
||||
You can configure command permissions in the `data/config.yaml` file:
|
||||
|
||||
```yaml
|
||||
command:
|
||||
permissions:
|
||||
- command: "system reload"
|
||||
roles:
|
||||
- admin
|
||||
- command: "plugin *"
|
||||
roles:
|
||||
- admin
|
||||
```
|
||||
|
||||
## Custom Commands
|
||||
|
||||
Plugins can register custom commands. Check the plugin documentation for available commands.
|
||||
@@ -0,0 +1,113 @@
|
||||
# Configure Dialogue Models
|
||||
|
||||
LangBot supports multiple model providers, including OpenAI, Anthropic, Moonshot, Baichuan, and more.
|
||||
|
||||
## Configuration Methods
|
||||
|
||||
### Method 1: Configure via WebUI
|
||||
|
||||
After deploying LangBot, access the WebUI at `http://your-server-ip:5300` and configure the models in the "Models" section.
|
||||
|
||||
### Method 2: Configure via Configuration File
|
||||
|
||||
Edit the `data/config.yaml` file and add your model configuration under the `providers` section:
|
||||
|
||||
```yaml
|
||||
providers:
|
||||
- id: openai
|
||||
type: openai
|
||||
config:
|
||||
api_key: "your-api-key"
|
||||
base_url: "https://api.openai.com/v1"
|
||||
models:
|
||||
- gpt-3.5-turbo
|
||||
- gpt-4
|
||||
- gpt-4-turbo
|
||||
```
|
||||
|
||||
## Supported Providers
|
||||
|
||||
### OpenAI
|
||||
|
||||
```yaml
|
||||
providers:
|
||||
- id: openai
|
||||
type: openai
|
||||
config:
|
||||
api_key: "your-api-key"
|
||||
base_url: "https://api.openai.com/v1"
|
||||
models:
|
||||
- gpt-3.5-turbo
|
||||
- gpt-4
|
||||
- gpt-4-turbo
|
||||
```
|
||||
|
||||
### Anthropic
|
||||
|
||||
```yaml
|
||||
providers:
|
||||
- id: anthropic
|
||||
type: anthropic
|
||||
config:
|
||||
api_key: "your-api-key"
|
||||
models:
|
||||
- claude-3-opus-20240229
|
||||
- claude-3-sonnet-20240229
|
||||
- claude-3-haiku-20240307
|
||||
```
|
||||
|
||||
### Moonshot
|
||||
|
||||
```yaml
|
||||
providers:
|
||||
- id: moonshot
|
||||
type: openai
|
||||
config:
|
||||
api_key: "your-api-key"
|
||||
base_url: "https://api.moonshot.cn/v1"
|
||||
models:
|
||||
- moonshot-v1-8k
|
||||
- moonshot-v1-32k
|
||||
- moonshot-v1-128k
|
||||
```
|
||||
|
||||
### OneAPI
|
||||
|
||||
```yaml
|
||||
providers:
|
||||
- id: oneapi
|
||||
type: openai
|
||||
config:
|
||||
api_key: "your-api-key"
|
||||
base_url: "https://your-oneapi-url/v1"
|
||||
models:
|
||||
- gpt-3.5-turbo
|
||||
- gpt-4
|
||||
- claude-3-opus-20240229
|
||||
```
|
||||
|
||||
## Default Model Configuration
|
||||
|
||||
You can set the default model in the `data/config.yaml` file:
|
||||
|
||||
```yaml
|
||||
system:
|
||||
default_provider: openai
|
||||
default_model: gpt-3.5-turbo
|
||||
```
|
||||
|
||||
## Testing Your Configuration
|
||||
|
||||
After configuring your models, you can test them by sending a message to your bot:
|
||||
|
||||
```
|
||||
!model list
|
||||
```
|
||||
|
||||
This command will list all available models.
|
||||
|
||||
To switch to a specific model:
|
||||
|
||||
```
|
||||
!model use gpt-4
|
||||
```
|
||||
@@ -0,0 +1,148 @@
|
||||
# Modify Dialogue Pipeline
|
||||
|
||||
The dialogue pipeline is the core processing flow of LangBot, which handles user messages and generates responses.
|
||||
|
||||
## Pipeline Structure
|
||||
|
||||

|
||||
|
||||
The pipeline consists of the following components:
|
||||
|
||||
1. **Trigger**: Determines whether to process a message
|
||||
2. **Moderation**: Filters and processes messages before sending to the model
|
||||
3. **AI**: Sends the message to the LLM and receives a response
|
||||
4. **Output**: Processes the model's response before sending it back to the user
|
||||
|
||||
## Configuration Methods
|
||||
|
||||
### Method 1: Configure via WebUI
|
||||
|
||||
After deploying LangBot, access the WebUI at `http://your-server-ip:5300` and configure the pipeline in the "Pipeline" section.
|
||||
|
||||
### Method 2: Configure via Configuration File
|
||||
|
||||
Edit the `data/config.yaml` file and modify the `pipelines` section:
|
||||
|
||||
```yaml
|
||||
pipelines:
|
||||
- id: default
|
||||
components:
|
||||
- id: trigger
|
||||
type: trigger
|
||||
config:
|
||||
# Trigger configuration
|
||||
- id: moderation
|
||||
type: moderation
|
||||
config:
|
||||
# Moderation configuration
|
||||
- id: ai
|
||||
type: ai
|
||||
config:
|
||||
# AI configuration
|
||||
- id: output
|
||||
type: output
|
||||
config:
|
||||
# Output configuration
|
||||
```
|
||||
|
||||
## Component Configuration
|
||||
|
||||
### Trigger Component
|
||||
|
||||
The trigger component determines whether a message should be processed by the pipeline.
|
||||
|
||||
```yaml
|
||||
- id: trigger
|
||||
type: trigger
|
||||
config:
|
||||
# Whether to respond to messages that start with a command prefix
|
||||
command_prefix: true
|
||||
# Command prefixes (characters that trigger the bot)
|
||||
command_prefixes:
|
||||
- "!"
|
||||
- "!"
|
||||
# Whether to respond to messages that mention the bot
|
||||
at: true
|
||||
# Whether to respond to private messages
|
||||
private: true
|
||||
# Whether to respond to group messages without being triggered by command prefix or mention
|
||||
group_chat: false
|
||||
```
|
||||
|
||||
### Moderation Component
|
||||
|
||||
The moderation component filters and processes messages before sending them to the model.
|
||||
|
||||
```yaml
|
||||
- id: moderation
|
||||
type: moderation
|
||||
config:
|
||||
# Whether to enable sensitive word filtering
|
||||
sensitive_word_filter: true
|
||||
# Whether to enable rate limiting
|
||||
rate_limit: true
|
||||
# Rate limit configuration
|
||||
rate_limit_config:
|
||||
# Number of messages allowed per time period
|
||||
count: 10
|
||||
# Time period in seconds
|
||||
period: 60
|
||||
# Whether to enable context management
|
||||
context: true
|
||||
# Context configuration
|
||||
context_config:
|
||||
# Maximum number of messages to include in the context
|
||||
max_count: 10
|
||||
# Maximum context length in tokens
|
||||
max_tokens: 4000
|
||||
```
|
||||
|
||||
### AI Component
|
||||
|
||||
The AI component sends the message to the LLM and receives a response.
|
||||
|
||||
```yaml
|
||||
- id: ai
|
||||
type: ai
|
||||
config:
|
||||
# System prompt
|
||||
system_prompt: "You are LangBot, a helpful assistant."
|
||||
# Whether to enable function calling
|
||||
function_call: true
|
||||
# Whether to enable streaming responses
|
||||
stream: true
|
||||
```
|
||||
|
||||
### Output Component
|
||||
|
||||
The output component processes the model's response before sending it back to the user.
|
||||
|
||||
```yaml
|
||||
- id: output
|
||||
type: output
|
||||
config:
|
||||
# Whether to enable message splitting for long responses
|
||||
split: true
|
||||
# Maximum length of a single message
|
||||
max_length: 1000
|
||||
```
|
||||
|
||||
## Multiple Pipelines
|
||||
|
||||
You can configure multiple pipelines for different scenarios:
|
||||
|
||||
```yaml
|
||||
pipelines:
|
||||
- id: default
|
||||
# Default pipeline configuration
|
||||
- id: image-generation
|
||||
# Pipeline for image generation
|
||||
- id: code-assistant
|
||||
# Pipeline for code assistance
|
||||
```
|
||||
|
||||
To switch between pipelines, use the following command:
|
||||
|
||||
```
|
||||
!pipeline use image-generation
|
||||
```
|
||||
@@ -0,0 +1,20 @@
|
||||
# Configure Bots
|
||||
|
||||
Bots are used to receive message events from messaging platforms and call pipelines to process messages.
|
||||
|
||||

|
||||
|
||||
|
||||
| Platform | Status | Notes | Tutorial |
|
||||
| ------ | ---- | ---- | ---- |
|
||||
| OneBot v11 | ✅ | Uses a regular QQ account as a bot, requires an independent protocol client, supports OneBot v11 | [NapCat](/en/deploy/platforms/qq/aiocqhttp/napcat) <br> [Lagrange](/en/deploy/platforms/qq/aiocqhttp/lagrange) <br> [LiteLoaderQQNT](/en/deploy/platforms/qq/aiocqhttp/llonebot) |
|
||||
| QQ Official Bot | ✅ | Connects to the QQ Open Platform bot API | [Tutorial](/en/deploy/platforms/qq/official_webhook) |
|
||||
| WeCom (Enterprise WeChat) | ✅ | Enterprise internal bot | [Tutorial](/en/deploy/platforms/wecom/wecom) |
|
||||
| WeCom Customer Service | ✅ | Enterprise external bot | [Tutorial](/en/deploy/platforms/wecom/wecomcs) |
|
||||
| WeChat Official Account | ✅ | WeChat public platform bot | [Tutorial](/en/deploy/platforms/wxoa) |
|
||||
| Personal WeChat | ✅ | Personal WeChat bot | [Gewechat](/en/deploy/platforms/wechat/gewechat) |
|
||||
| Feishu (Lark) | ✅ | | [Tutorial](/en/deploy/platforms/lark) |
|
||||
| DingTalk | ✅ | | [Tutorial](/en/deploy/platforms/dingtalk) |
|
||||
| Discord | ✅ | | [Tutorial](/en/deploy/platforms/discord) |
|
||||
| Telegram | ✅ | | [Tutorial](/en/deploy/platforms/telegram) |
|
||||
| Slack | ✅ | | [Tutorial](/en/deploy/platforms/slack) |
|
||||
@@ -0,0 +1,93 @@
|
||||
# Update LangBot
|
||||
|
||||
This guide explains how to update your LangBot installation to the latest version.
|
||||
|
||||
## Docker Deployment
|
||||
|
||||
If you deployed LangBot using Docker, follow these steps to update:
|
||||
|
||||
1. Pull the latest image:
|
||||
|
||||
```bash
|
||||
docker pull rockchin/langbot:latest
|
||||
```
|
||||
|
||||
2. Stop and remove the current container:
|
||||
|
||||
```bash
|
||||
docker stop langbot
|
||||
docker rm langbot
|
||||
```
|
||||
|
||||
3. Start a new container with the latest image:
|
||||
|
||||
```bash
|
||||
docker run -d --name langbot \
|
||||
-p 5300:5300 \
|
||||
-v /path/to/data:/app/data \
|
||||
rockchin/langbot:latest
|
||||
```
|
||||
|
||||
Replace `/path/to/data` with the path to your data directory.
|
||||
|
||||
## Manual Deployment
|
||||
|
||||
If you deployed LangBot manually, follow these steps to update:
|
||||
|
||||
1. Navigate to your LangBot directory:
|
||||
|
||||
```bash
|
||||
cd /path/to/langbot
|
||||
```
|
||||
|
||||
2. Pull the latest changes:
|
||||
|
||||
```bash
|
||||
git pull
|
||||
```
|
||||
|
||||
3. Update dependencies:
|
||||
|
||||
```bash
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
4. Restart LangBot:
|
||||
|
||||
```bash
|
||||
python main.py
|
||||
```
|
||||
|
||||
## Baota Panel Deployment
|
||||
|
||||
If you deployed LangBot using the Baota Panel, follow these steps to update:
|
||||
|
||||
1. Log in to your Baota Panel
|
||||
2. Navigate to the LangBot website
|
||||
3. Click on "Site Settings"
|
||||
4. Click on "Update from Git"
|
||||
5. Click "Update" to pull the latest changes
|
||||
6. Restart the website
|
||||
|
||||
## Configuration Changes
|
||||
|
||||
After updating, check the [release notes](https://github.com/RockChinQ/LangBot/releases) for any configuration changes. You may need to update your `data/config.yaml` file to accommodate new features or changes.
|
||||
|
||||
## Database Migration
|
||||
|
||||
LangBot automatically handles database migrations during updates. However, it's always a good idea to back up your data directory before updating.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
If you encounter issues after updating, check the following:
|
||||
|
||||
1. Make sure your configuration file is compatible with the new version
|
||||
2. Check the logs for any error messages
|
||||
3. Ensure all dependencies are installed correctly
|
||||
4. Verify that your model providers are still configured correctly
|
||||
|
||||
If problems persist, you can:
|
||||
|
||||
1. Join the [community chat](https://qm.qq.com/q/Nnz7Vbj8OU) for help
|
||||
2. Open an issue on [GitHub](https://github.com/RockChinQ/LangBot/issues)
|
||||
3. Revert to a previous version if necessary
|
||||
@@ -0,0 +1,96 @@
|
||||
# Component Architecture
|
||||
|
||||
This document describes the component architecture of LangBot, which is designed to be modular and extensible.
|
||||
|
||||
## Overview
|
||||
|
||||
LangBot is built around a component-based architecture that allows for easy extension and customization. The main components are:
|
||||
|
||||
1. **Bots**: Interface with messaging platforms
|
||||
2. **Pipelines**: Process messages and generate responses
|
||||
3. **Models**: Connect to LLM providers
|
||||
4. **Plugins**: Extend functionality
|
||||
|
||||

|
||||
|
||||
## Bots
|
||||
|
||||
Bots are responsible for connecting to messaging platforms and handling message events. Each bot implements a specific platform adapter that translates between the platform's API and LangBot's internal event system.
|
||||
|
||||
Key classes:
|
||||
- `MessageSourceAdapter`: Base class for all platform adapters
|
||||
- `EventConverter`: Converts platform-specific events to LangBot events
|
||||
- `MessageConverter`: Converts platform-specific messages to LangBot messages
|
||||
|
||||
## Pipelines
|
||||
|
||||
Pipelines process messages through a series of components:
|
||||
|
||||
1. **Trigger**: Determines whether to process a message
|
||||
2. **Moderation**: Filters and processes messages before sending to the model
|
||||
3. **AI**: Sends the message to the LLM and receives a response
|
||||
4. **Output**: Processes the model's response before sending it back to the user
|
||||
|
||||
Each component in the pipeline can be configured and customized.
|
||||
|
||||
## Models
|
||||
|
||||
The Models component manages connections to various LLM providers, such as OpenAI, Anthropic, and others. It provides a unified interface for sending requests to these providers and handling their responses.
|
||||
|
||||
Key classes:
|
||||
- `ModelProvider`: Base class for all model providers
|
||||
- `ModelRequest`: Represents a request to a model
|
||||
- `ModelResponse`: Represents a response from a model
|
||||
|
||||
## Plugins
|
||||
|
||||
The plugin system allows for extending LangBot's functionality without modifying the core code. Plugins can:
|
||||
|
||||
- Register event handlers
|
||||
- Add new commands
|
||||
- Provide functions that can be called by the LLM
|
||||
- Extend core components
|
||||
|
||||
Key concepts:
|
||||
- `@handler`: Decorator for registering event handlers
|
||||
- `@llm_func`: Decorator for registering functions that can be called by the LLM
|
||||
- `APIHost`: Provides access to LangBot's API from plugins
|
||||
- `manifest.yaml`: Configuration file for plugins
|
||||
|
||||
## Event System
|
||||
|
||||
LangBot uses an event-driven architecture where different components communicate through events. Events include:
|
||||
|
||||
- Message events (received, sent)
|
||||
- Group events (joined, left, invited)
|
||||
- System events (startup, shutdown)
|
||||
- Custom events defined by plugins
|
||||
|
||||
## Configuration System
|
||||
|
||||
The configuration system uses a YAML-based approach with the main configuration file at `data/config.yaml`. The configuration is structured around the component architecture:
|
||||
|
||||
```yaml
|
||||
bots:
|
||||
# Bot configurations
|
||||
pipelines:
|
||||
# Pipeline configurations
|
||||
providers:
|
||||
# Model provider configurations
|
||||
plugins:
|
||||
# Plugin configurations
|
||||
system:
|
||||
# System configurations
|
||||
```
|
||||
|
||||
## Development Workflow
|
||||
|
||||
When developing for LangBot, follow these steps:
|
||||
|
||||
1. Understand the component you want to modify or extend
|
||||
2. Create a plugin if you're adding new functionality
|
||||
3. Implement the necessary classes and methods
|
||||
4. Test your changes
|
||||
5. Submit a pull request
|
||||
|
||||
For more detailed information on development, see the [Development Configuration](/en/develop/dev-config) page.
|
||||
@@ -0,0 +1,160 @@
|
||||
# Development Configuration
|
||||
|
||||
This guide explains how to set up a development environment for LangBot and contribute to the project.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Before you start, make sure you have the following installed:
|
||||
|
||||
- Python 3.10 or higher
|
||||
- Git
|
||||
- Node.js 16 or higher (for WebUI development)
|
||||
- A code editor (VS Code recommended)
|
||||
|
||||
## Setting Up the Development Environment
|
||||
|
||||
1. Fork the LangBot repository on GitHub
|
||||
2. Clone your fork:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/your-username/LangBot.git
|
||||
cd LangBot
|
||||
```
|
||||
|
||||
3. Create a virtual environment:
|
||||
|
||||
```bash
|
||||
python -m venv venv
|
||||
source venv/bin/activate # On Windows: venv\Scripts\activate
|
||||
```
|
||||
|
||||
4. Install dependencies:
|
||||
|
||||
```bash
|
||||
pip install -r requirements.txt
|
||||
pip install -r requirements-dev.txt
|
||||
```
|
||||
|
||||
5. Set up pre-commit hooks:
|
||||
|
||||
```bash
|
||||
pre-commit install
|
||||
```
|
||||
|
||||
## Project Structure
|
||||
|
||||
The LangBot project is organized as follows:
|
||||
|
||||
```
|
||||
LangBot/
|
||||
├── data/ # Data directory (configs, plugins, etc.)
|
||||
├── langbot/ # Core package
|
||||
│ ├── bot/ # Bot implementations
|
||||
│ ├── pipeline/ # Pipeline components
|
||||
│ ├── model/ # Model providers
|
||||
│ ├── plugin/ # Plugin system
|
||||
│ ├── webui/ # WebUI backend
|
||||
│ └── utils/ # Utility functions
|
||||
├── tests/ # Test cases
|
||||
├── web/ # WebUI frontend
|
||||
├── main.py # Entry point
|
||||
└── requirements.txt # Dependencies
|
||||
```
|
||||
|
||||
## Running LangBot in Development Mode
|
||||
|
||||
To run LangBot in development mode:
|
||||
|
||||
```bash
|
||||
python main.py --debug
|
||||
```
|
||||
|
||||
This will start LangBot with debug logging enabled.
|
||||
|
||||
## WebUI Development
|
||||
|
||||
To develop the WebUI:
|
||||
|
||||
1. Navigate to the web directory:
|
||||
|
||||
```bash
|
||||
cd web
|
||||
```
|
||||
|
||||
2. Install dependencies:
|
||||
|
||||
```bash
|
||||
npm install
|
||||
```
|
||||
|
||||
3. Start the development server:
|
||||
|
||||
```bash
|
||||
npm run dev
|
||||
```
|
||||
|
||||
4. In another terminal, start LangBot with the WebUI enabled:
|
||||
|
||||
```bash
|
||||
python main.py --webui
|
||||
```
|
||||
|
||||
## Testing
|
||||
|
||||
LangBot uses pytest for testing. To run the tests:
|
||||
|
||||
```bash
|
||||
pytest
|
||||
```
|
||||
|
||||
To run a specific test:
|
||||
|
||||
```bash
|
||||
pytest tests/test_file.py::test_function
|
||||
```
|
||||
|
||||
## Code Style
|
||||
|
||||
LangBot follows the PEP 8 style guide with some modifications. We use black for code formatting and isort for import sorting.
|
||||
|
||||
To format your code:
|
||||
|
||||
```bash
|
||||
black langbot tests
|
||||
isort langbot tests
|
||||
```
|
||||
|
||||
## Creating a Pull Request
|
||||
|
||||
1. Create a new branch for your feature or bugfix:
|
||||
|
||||
```bash
|
||||
git checkout -b feature/your-feature-name
|
||||
```
|
||||
|
||||
2. Make your changes and commit them:
|
||||
|
||||
```bash
|
||||
git add .
|
||||
git commit -m "Add your feature or fix"
|
||||
```
|
||||
|
||||
3. Push your branch to GitHub:
|
||||
|
||||
```bash
|
||||
git push origin feature/your-feature-name
|
||||
```
|
||||
|
||||
4. Create a pull request on GitHub
|
||||
|
||||
## Documentation
|
||||
|
||||
When adding new features, make sure to update the documentation. The documentation is written in Markdown and is located in the [QChatGPT-Wiki](https://github.com/RockChinQ/QChatGPT-Wiki) repository.
|
||||
|
||||
## Getting Help
|
||||
|
||||
If you need help with development, you can:
|
||||
|
||||
- Join the [community chat](https://qm.qq.com/q/Nnz7Vbj8OU)
|
||||
- Open an issue on [GitHub](https://github.com/RockChinQ/LangBot/issues)
|
||||
- Check the existing documentation and code for examples
|
||||
@@ -0,0 +1,3 @@
|
||||
<script setup>
|
||||
window.location.href = '/en/insight/guide'
|
||||
</script>
|
||||
@@ -0,0 +1,24 @@
|
||||
# Community Resources
|
||||
|
||||
## Official Resources
|
||||
|
||||
- [GitHub Repository](https://github.com/RockChinQ/LangBot)
|
||||
- [Documentation](https://docs.langbot.app)
|
||||
- [Plugin Market](https://plugins.langbot.app)
|
||||
|
||||
## Community Resources
|
||||
|
||||
### Deployment Tutorials
|
||||
|
||||
- [Simplified Deployment Tutorial](https://www.bilibili.com/video/BV1Uj421y7Gu)
|
||||
- [Simplified Deployment Tutorial (Text Version)](https://www.bilibili.com/read/cv31018000)
|
||||
|
||||
### Community Discussions
|
||||
|
||||
- [QQ Group: 1141946368](https://qm.qq.com/q/Nnz7Vbj8OU)
|
||||
- [Telegram Group](https://t.me/+Ij8xM9pPToxmNDQ1)
|
||||
- [Discord Server](https://discord.gg/Nnz7Vbj8OU)
|
||||
|
||||
## Contribution
|
||||
|
||||
If you want to contribute to LangBot, please read the [Development Configuration](/en/develop/dev-config) and [Component Architecture](/en/develop/comp-arch) sections.
|
||||
@@ -0,0 +1,49 @@
|
||||
# Welcome to LangBot Documentation Center
|
||||
|
||||
LangBot is an open-source Large Language Model (LLM) native instant messaging robot platform that supports multiple messaging platforms and model providers. It provides support for LLMOps platforms such as Dify and Alibaba Cloud Bailian. It also offers a WebUI for users to quickly deploy and use.
|
||||
|
||||
:::info
|
||||
This is the documentation for LangBot 4.0. For 3.0 documentation, please [visit here](https://v3.docs.langbot.app).
|
||||
:::
|
||||
|
||||
## Documentation Structure
|
||||
|
||||
The documentation is divided into the following sections:
|
||||
|
||||
- Deployment and Usage (Must Read): Detailed steps for deploying and using LangBot
|
||||
- Plugins: Information related to plugin usage and development
|
||||
- Workshops: Many excellent use cases for LangBot
|
||||
- Development: Information related to participating in LangBot development
|
||||
|
||||
## Usage Examples
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
## Quick Start Guide
|
||||
|
||||
> Two ways to get started quickly:
|
||||
>
|
||||
> - Use the simplified tutorial from community resources (see left sidebar)
|
||||
> - Read the documentation to deploy it yourself (method described below)
|
||||
|
||||
### 1. Deploy LangBot
|
||||
|
||||
Read the **Deploy LangBot** section on the left and choose a method to deploy LangBot
|
||||
|
||||
After deployment, open `http://127.0.0.1:5300` or `http://your-server-public-ip:5300`
|
||||
|
||||
Complete the initialization by entering an email and password, and make sure to save them
|
||||
|
||||
### 2. Configure Bots
|
||||
|
||||
Check [Configure Bots](/en/deploy/platforms/readme) in the left sidebar
|
||||
|
||||
### 3. Configure Models
|
||||
|
||||
Check [Configure Dialogue Models](/en/deploy/models/readme) in the left sidebar
|
||||
|
||||
<br>
|
||||
|
||||
After completing the above two steps, you can start using LangBot. If you need to configure more features, you can set them in the [Pipeline](/en/deploy/pipelines/readme) section
|
||||
@@ -0,0 +1,612 @@
|
||||
# API Reference
|
||||
|
||||
This document provides a reference for the LangBot API that is available to plugins.
|
||||
|
||||
## APIHost
|
||||
|
||||
The `APIHost` class provides access to LangBot's API from plugins. It is passed to the plugin's constructor.
|
||||
|
||||
```python
|
||||
from langbot.api import APIHost
|
||||
|
||||
class MyPlugin(Plugin):
|
||||
def __init__(self, api_host: APIHost):
|
||||
super().__init__(api_host)
|
||||
self.api = api_host
|
||||
```
|
||||
|
||||
## Message API
|
||||
|
||||
### send_message
|
||||
|
||||
Sends a message to a specific destination.
|
||||
|
||||
```python
|
||||
def send_message(self, source, content, **kwargs) -> str:
|
||||
"""
|
||||
Send a message to a specific destination.
|
||||
|
||||
Args:
|
||||
source: The destination to send the message to
|
||||
content: The content of the message
|
||||
**kwargs: Additional arguments
|
||||
|
||||
Returns:
|
||||
The message ID
|
||||
"""
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
```python
|
||||
message_id = self.api.send_message(
|
||||
ctx.event.message.source,
|
||||
"Hello, World!"
|
||||
)
|
||||
```
|
||||
|
||||
### reply_message
|
||||
|
||||
Replies to a specific message.
|
||||
|
||||
```python
|
||||
def reply_message(self, message, content, **kwargs) -> str:
|
||||
"""
|
||||
Reply to a specific message.
|
||||
|
||||
Args:
|
||||
message: The message to reply to
|
||||
content: The content of the reply
|
||||
**kwargs: Additional arguments
|
||||
|
||||
Returns:
|
||||
The message ID
|
||||
"""
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
```python
|
||||
message_id = self.api.reply_message(
|
||||
ctx.event.message,
|
||||
"This is a reply"
|
||||
)
|
||||
```
|
||||
|
||||
### delete_message
|
||||
|
||||
Deletes a specific message.
|
||||
|
||||
```python
|
||||
def delete_message(self, message_id, **kwargs) -> bool:
|
||||
"""
|
||||
Delete a specific message.
|
||||
|
||||
Args:
|
||||
message_id: The ID of the message to delete
|
||||
**kwargs: Additional arguments
|
||||
|
||||
Returns:
|
||||
True if successful, False otherwise
|
||||
"""
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
```python
|
||||
success = self.api.delete_message(message_id)
|
||||
```
|
||||
|
||||
## User API
|
||||
|
||||
### get_user_info
|
||||
|
||||
Gets information about a user.
|
||||
|
||||
```python
|
||||
def get_user_info(self, user_id, **kwargs) -> dict:
|
||||
"""
|
||||
Get information about a user.
|
||||
|
||||
Args:
|
||||
user_id: The ID of the user
|
||||
**kwargs: Additional arguments
|
||||
|
||||
Returns:
|
||||
A dictionary containing user information
|
||||
"""
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
```python
|
||||
user_info = self.api.get_user_info("12345678")
|
||||
print(user_info["nickname"])
|
||||
```
|
||||
|
||||
### get_friend_list
|
||||
|
||||
Gets a list of the bot's friends.
|
||||
|
||||
```python
|
||||
def get_friend_list(self, **kwargs) -> list:
|
||||
"""
|
||||
Get a list of the bot's friends.
|
||||
|
||||
Args:
|
||||
**kwargs: Additional arguments
|
||||
|
||||
Returns:
|
||||
A list of friend information
|
||||
"""
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
```python
|
||||
friends = self.api.get_friend_list()
|
||||
for friend in friends:
|
||||
print(friend["nickname"])
|
||||
```
|
||||
|
||||
## Group API
|
||||
|
||||
### get_group_info
|
||||
|
||||
Gets information about a group.
|
||||
|
||||
```python
|
||||
def get_group_info(self, group_id, **kwargs) -> dict:
|
||||
"""
|
||||
Get information about a group.
|
||||
|
||||
Args:
|
||||
group_id: The ID of the group
|
||||
**kwargs: Additional arguments
|
||||
|
||||
Returns:
|
||||
A dictionary containing group information
|
||||
"""
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
```python
|
||||
group_info = self.api.get_group_info("12345678")
|
||||
print(group_info["name"])
|
||||
```
|
||||
|
||||
### get_group_member_list
|
||||
|
||||
Gets a list of members in a group.
|
||||
|
||||
```python
|
||||
def get_group_member_list(self, group_id, **kwargs) -> list:
|
||||
"""
|
||||
Get a list of members in a group.
|
||||
|
||||
Args:
|
||||
group_id: The ID of the group
|
||||
**kwargs: Additional arguments
|
||||
|
||||
Returns:
|
||||
A list of member information
|
||||
"""
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
```python
|
||||
members = self.api.get_group_member_list("12345678")
|
||||
for member in members:
|
||||
print(member["nickname"])
|
||||
```
|
||||
|
||||
### get_group_list
|
||||
|
||||
Gets a list of groups the bot is in.
|
||||
|
||||
```python
|
||||
def get_group_list(self, **kwargs) -> list:
|
||||
"""
|
||||
Get a list of groups the bot is in.
|
||||
|
||||
Args:
|
||||
**kwargs: Additional arguments
|
||||
|
||||
Returns:
|
||||
A list of group information
|
||||
"""
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
```python
|
||||
groups = self.api.get_group_list()
|
||||
for group in groups:
|
||||
print(group["name"])
|
||||
```
|
||||
|
||||
## LLM API
|
||||
|
||||
### call_llm
|
||||
|
||||
Calls the LLM with a specific prompt.
|
||||
|
||||
```python
|
||||
def call_llm(self, prompt, model=None, **kwargs) -> str:
|
||||
"""
|
||||
Call the LLM with a specific prompt.
|
||||
|
||||
Args:
|
||||
prompt: The prompt to send to the LLM
|
||||
model: The model to use (defaults to the system default)
|
||||
**kwargs: Additional arguments
|
||||
|
||||
Returns:
|
||||
The LLM's response
|
||||
"""
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
```python
|
||||
response = self.api.call_llm(
|
||||
"What is the capital of France?",
|
||||
model="gpt-3.5-turbo"
|
||||
)
|
||||
print(response)
|
||||
```
|
||||
|
||||
### call_llm_with_functions
|
||||
|
||||
Calls the LLM with a specific prompt and available functions.
|
||||
|
||||
```python
|
||||
def call_llm_with_functions(self, prompt, functions, model=None, **kwargs) -> dict:
|
||||
"""
|
||||
Call the LLM with a specific prompt and available functions.
|
||||
|
||||
Args:
|
||||
prompt: The prompt to send to the LLM
|
||||
functions: A list of function definitions
|
||||
model: The model to use (defaults to the system default)
|
||||
**kwargs: Additional arguments
|
||||
|
||||
Returns:
|
||||
A dictionary containing the LLM's response and any function calls
|
||||
"""
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
```python
|
||||
functions = [
|
||||
{
|
||||
"name": "get_weather",
|
||||
"description": "Get the weather for a location",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"location": {
|
||||
"type": "string",
|
||||
"description": "The location to get weather for"
|
||||
}
|
||||
},
|
||||
"required": ["location"]
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
response = self.api.call_llm_with_functions(
|
||||
"What's the weather in Paris?",
|
||||
functions,
|
||||
model="gpt-3.5-turbo"
|
||||
)
|
||||
|
||||
if "function_call" in response:
|
||||
function_name = response["function_call"]["name"]
|
||||
function_args = response["function_call"]["arguments"]
|
||||
# Handle the function call
|
||||
```
|
||||
|
||||
## Storage API
|
||||
|
||||
### storage.set
|
||||
|
||||
Stores a value with a specific key.
|
||||
|
||||
```python
|
||||
def set(self, key, value) -> None:
|
||||
"""
|
||||
Store a value with a specific key.
|
||||
|
||||
Args:
|
||||
key: The key to store the value under
|
||||
value: The value to store
|
||||
"""
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
```python
|
||||
self.api.storage.set("my_plugin:counter", 42)
|
||||
```
|
||||
|
||||
### storage.get
|
||||
|
||||
Gets a value with a specific key.
|
||||
|
||||
```python
|
||||
def get(self, key, default=None):
|
||||
"""
|
||||
Get a value with a specific key.
|
||||
|
||||
Args:
|
||||
key: The key to get the value for
|
||||
default: The default value to return if the key doesn't exist
|
||||
|
||||
Returns:
|
||||
The stored value or the default value
|
||||
"""
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
```python
|
||||
counter = self.api.storage.get("my_plugin:counter", 0)
|
||||
```
|
||||
|
||||
### storage.has
|
||||
|
||||
Checks if a key exists.
|
||||
|
||||
```python
|
||||
def has(self, key) -> bool:
|
||||
"""
|
||||
Check if a key exists.
|
||||
|
||||
Args:
|
||||
key: The key to check
|
||||
|
||||
Returns:
|
||||
True if the key exists, False otherwise
|
||||
"""
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
```python
|
||||
if self.api.storage.has("my_plugin:counter"):
|
||||
# Key exists
|
||||
```
|
||||
|
||||
### storage.delete
|
||||
|
||||
Deletes a key.
|
||||
|
||||
```python
|
||||
def delete(self, key) -> None:
|
||||
"""
|
||||
Delete a key.
|
||||
|
||||
Args:
|
||||
key: The key to delete
|
||||
"""
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
```python
|
||||
self.api.storage.delete("my_plugin:counter")
|
||||
```
|
||||
|
||||
## Config API
|
||||
|
||||
### config.get
|
||||
|
||||
Gets a configuration value.
|
||||
|
||||
```python
|
||||
def get(self, key, default=None):
|
||||
"""
|
||||
Get a configuration value.
|
||||
|
||||
Args:
|
||||
key: The key to get the value for
|
||||
default: The default value to return if the key doesn't exist
|
||||
|
||||
Returns:
|
||||
The configuration value or the default value
|
||||
"""
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
```python
|
||||
api_key = self.api.config.get("my_plugin:api_key")
|
||||
```
|
||||
|
||||
### config.set
|
||||
|
||||
Sets a configuration value.
|
||||
|
||||
```python
|
||||
def set(self, key, value) -> None:
|
||||
"""
|
||||
Set a configuration value.
|
||||
|
||||
Args:
|
||||
key: The key to set the value for
|
||||
value: The value to set
|
||||
"""
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
```python
|
||||
self.api.config.set("my_plugin:api_key", "my-api-key")
|
||||
```
|
||||
|
||||
## Event API
|
||||
|
||||
### register_event_handler
|
||||
|
||||
Registers a handler for a specific event.
|
||||
|
||||
```python
|
||||
def register_event_handler(self, event_type, handler) -> None:
|
||||
"""
|
||||
Register a handler for a specific event.
|
||||
|
||||
Args:
|
||||
event_type: The type of event to handle
|
||||
handler: The handler function
|
||||
"""
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
```python
|
||||
def my_handler(ctx):
|
||||
# Handle the event
|
||||
pass
|
||||
|
||||
self.api.register_event_handler(PersonNormalMessageReceived, my_handler)
|
||||
```
|
||||
|
||||
### unregister_event_handler
|
||||
|
||||
Unregisters a handler for a specific event.
|
||||
|
||||
```python
|
||||
def unregister_event_handler(self, event_type, handler) -> None:
|
||||
"""
|
||||
Unregister a handler for a specific event.
|
||||
|
||||
Args:
|
||||
event_type: The type of event
|
||||
handler: The handler function
|
||||
"""
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
```python
|
||||
self.api.unregister_event_handler(PersonNormalMessageReceived, my_handler)
|
||||
```
|
||||
|
||||
## Command API
|
||||
|
||||
### register_command
|
||||
|
||||
Registers a command.
|
||||
|
||||
```python
|
||||
def register_command(self, name, handler, description=None) -> None:
|
||||
"""
|
||||
Register a command.
|
||||
|
||||
Args:
|
||||
name: The name of the command
|
||||
handler: The handler function
|
||||
description: The description of the command
|
||||
"""
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
```python
|
||||
def echo_handler(args):
|
||||
return args
|
||||
|
||||
self.api.register_command("echo", echo_handler, "Echo a message")
|
||||
```
|
||||
|
||||
### unregister_command
|
||||
|
||||
Unregisters a command.
|
||||
|
||||
```python
|
||||
def unregister_command(self, name) -> None:
|
||||
"""
|
||||
Unregister a command.
|
||||
|
||||
Args:
|
||||
name: The name of the command
|
||||
"""
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
```python
|
||||
self.api.unregister_command("echo")
|
||||
```
|
||||
|
||||
## Utility API
|
||||
|
||||
### logger
|
||||
|
||||
Provides access to the logger.
|
||||
|
||||
```python
|
||||
self.api.logger.debug("Debug message")
|
||||
self.api.logger.info("Info message")
|
||||
self.api.logger.warning("Warning message")
|
||||
self.api.logger.error("Error message")
|
||||
```
|
||||
|
||||
### schedule
|
||||
|
||||
Schedules a function to be called at a specific time.
|
||||
|
||||
```python
|
||||
def schedule(self, func, when, *args, **kwargs) -> str:
|
||||
"""
|
||||
Schedule a function to be called at a specific time.
|
||||
|
||||
Args:
|
||||
func: The function to call
|
||||
when: When to call the function (datetime or timedelta)
|
||||
*args: Arguments to pass to the function
|
||||
**kwargs: Keyword arguments to pass to the function
|
||||
|
||||
Returns:
|
||||
The schedule ID
|
||||
"""
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
```python
|
||||
from datetime import timedelta
|
||||
|
||||
def my_function():
|
||||
# Do something
|
||||
pass
|
||||
|
||||
schedule_id = self.api.schedule(my_function, timedelta(hours=1))
|
||||
```
|
||||
|
||||
### cancel_schedule
|
||||
|
||||
Cancels a scheduled function.
|
||||
|
||||
```python
|
||||
def cancel_schedule(self, schedule_id) -> bool:
|
||||
"""
|
||||
Cancel a scheduled function.
|
||||
|
||||
Args:
|
||||
schedule_id: The ID of the schedule
|
||||
|
||||
Returns:
|
||||
True if successful, False otherwise
|
||||
"""
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
```python
|
||||
success = self.api.cancel_schedule(schedule_id)
|
||||
```
|
||||
@@ -0,0 +1,338 @@
|
||||
# Message Platform Entities
|
||||
|
||||
This document describes the message platform entities used in LangBot, which are important for plugin development.
|
||||
|
||||
## Message
|
||||
|
||||
The `Message` class represents a message in LangBot.
|
||||
|
||||
```python
|
||||
class Message:
|
||||
"""
|
||||
Represents a message in LangBot.
|
||||
"""
|
||||
|
||||
def __init__(self, source, content, message_id=None, sender=None, time=None, **kwargs):
|
||||
"""
|
||||
Initialize a message.
|
||||
|
||||
Args:
|
||||
source: The source of the message
|
||||
content: The content of the message
|
||||
message_id: The ID of the message
|
||||
sender: The sender of the message
|
||||
time: The time the message was sent
|
||||
**kwargs: Additional arguments
|
||||
"""
|
||||
self.source = source
|
||||
self.content = content
|
||||
self.message_id = message_id
|
||||
self.sender = sender
|
||||
self.time = time
|
||||
self.kwargs = kwargs
|
||||
```
|
||||
|
||||
### Properties
|
||||
|
||||
- `source`: The source of the message (where it was sent from)
|
||||
- `content`: The content of the message
|
||||
- `message_id`: The ID of the message
|
||||
- `sender`: The sender of the message
|
||||
- `time`: The time the message was sent
|
||||
- `kwargs`: Additional arguments
|
||||
|
||||
## Source
|
||||
|
||||
The `Source` class represents the source of a message.
|
||||
|
||||
```python
|
||||
class Source:
|
||||
"""
|
||||
Represents the source of a message.
|
||||
"""
|
||||
|
||||
def __init__(self, platform, identity, **kwargs):
|
||||
"""
|
||||
Initialize a source.
|
||||
|
||||
Args:
|
||||
platform: The platform of the source
|
||||
identity: The identity of the source
|
||||
**kwargs: Additional arguments
|
||||
"""
|
||||
self.platform = platform
|
||||
self.identity = identity
|
||||
self.kwargs = kwargs
|
||||
```
|
||||
|
||||
### Properties
|
||||
|
||||
- `platform`: The platform of the source (e.g., "qq", "wechat", "discord")
|
||||
- `identity`: The identity of the source (e.g., user ID, group ID)
|
||||
- `kwargs`: Additional arguments
|
||||
|
||||
### Types of Sources
|
||||
|
||||
#### Person Source
|
||||
|
||||
Represents a direct message from a person.
|
||||
|
||||
```python
|
||||
class PersonSource(Source):
|
||||
"""
|
||||
Represents a direct message from a person.
|
||||
"""
|
||||
|
||||
def __init__(self, platform, identity, **kwargs):
|
||||
"""
|
||||
Initialize a person source.
|
||||
|
||||
Args:
|
||||
platform: The platform of the source
|
||||
identity: The identity of the person
|
||||
**kwargs: Additional arguments
|
||||
"""
|
||||
super().__init__(platform, identity, **kwargs)
|
||||
```
|
||||
|
||||
#### Group Source
|
||||
|
||||
Represents a message from a group.
|
||||
|
||||
```python
|
||||
class GroupSource(Source):
|
||||
"""
|
||||
Represents a message from a group.
|
||||
"""
|
||||
|
||||
def __init__(self, platform, identity, **kwargs):
|
||||
"""
|
||||
Initialize a group source.
|
||||
|
||||
Args:
|
||||
platform: The platform of the source
|
||||
identity: The identity of the group
|
||||
**kwargs: Additional arguments
|
||||
"""
|
||||
super().__init__(platform, identity, **kwargs)
|
||||
```
|
||||
|
||||
## Sender
|
||||
|
||||
The `Sender` class represents the sender of a message.
|
||||
|
||||
```python
|
||||
class Sender:
|
||||
"""
|
||||
Represents the sender of a message.
|
||||
"""
|
||||
|
||||
def __init__(self, identity, name=None, **kwargs):
|
||||
"""
|
||||
Initialize a sender.
|
||||
|
||||
Args:
|
||||
identity: The identity of the sender
|
||||
name: The name of the sender
|
||||
**kwargs: Additional arguments
|
||||
"""
|
||||
self.identity = identity
|
||||
self.name = name
|
||||
self.kwargs = kwargs
|
||||
```
|
||||
|
||||
### Properties
|
||||
|
||||
- `identity`: The identity of the sender (e.g., user ID)
|
||||
- `name`: The name of the sender
|
||||
- `kwargs`: Additional arguments
|
||||
|
||||
## Events
|
||||
|
||||
LangBot uses events to represent various actions in the system. Here are some common events related to messages:
|
||||
|
||||
### PersonNormalMessageReceived
|
||||
|
||||
Triggered when a normal message is received from a person.
|
||||
|
||||
```python
|
||||
class PersonNormalMessageReceived(Event):
|
||||
"""
|
||||
Triggered when a normal message is received from a person.
|
||||
"""
|
||||
|
||||
def __init__(self, message):
|
||||
"""
|
||||
Initialize the event.
|
||||
|
||||
Args:
|
||||
message: The received message
|
||||
"""
|
||||
super().__init__()
|
||||
self.message = message
|
||||
```
|
||||
|
||||
### GroupNormalMessageReceived
|
||||
|
||||
Triggered when a normal message is received in a group.
|
||||
|
||||
```python
|
||||
class GroupNormalMessageReceived(Event):
|
||||
"""
|
||||
Triggered when a normal message is received in a group.
|
||||
"""
|
||||
|
||||
def __init__(self, message):
|
||||
"""
|
||||
Initialize the event.
|
||||
|
||||
Args:
|
||||
message: The received message
|
||||
"""
|
||||
super().__init__()
|
||||
self.message = message
|
||||
```
|
||||
|
||||
### MessageSent
|
||||
|
||||
Triggered when a message is sent.
|
||||
|
||||
```python
|
||||
class MessageSent(Event):
|
||||
"""
|
||||
Triggered when a message is sent.
|
||||
"""
|
||||
|
||||
def __init__(self, message):
|
||||
"""
|
||||
Initialize the event.
|
||||
|
||||
Args:
|
||||
message: The sent message
|
||||
"""
|
||||
super().__init__()
|
||||
self.message = message
|
||||
```
|
||||
|
||||
## Working with Messages in Plugins
|
||||
|
||||
### Handling Messages
|
||||
|
||||
```python
|
||||
from langbot.plugin import Plugin, handler
|
||||
from langbot.event import PersonNormalMessageReceived, GroupNormalMessageReceived
|
||||
from langbot.api import APIHost
|
||||
|
||||
class MessageHandlerPlugin(Plugin):
|
||||
def __init__(self, api_host: APIHost):
|
||||
super().__init__(api_host)
|
||||
self.api = api_host
|
||||
|
||||
@handler(PersonNormalMessageReceived)
|
||||
def on_person_message(self, ctx):
|
||||
# Get the message
|
||||
message = ctx.event.message
|
||||
|
||||
# Get the content
|
||||
content = message.content
|
||||
|
||||
# Get the sender
|
||||
sender = message.sender
|
||||
|
||||
# Get the source
|
||||
source = message.source
|
||||
|
||||
# Do something with the message
|
||||
if content == "!hello":
|
||||
self.api.send_message(source, f"Hello, {sender.name}!")
|
||||
|
||||
@handler(GroupNormalMessageReceived)
|
||||
def on_group_message(self, ctx):
|
||||
# Get the message
|
||||
message = ctx.event.message
|
||||
|
||||
# Get the content
|
||||
content = message.content
|
||||
|
||||
# Get the sender
|
||||
sender = message.sender
|
||||
|
||||
# Get the source
|
||||
source = message.source
|
||||
|
||||
# Do something with the message
|
||||
if content == "!hello":
|
||||
self.api.send_message(source, f"Hello, {sender.name}!")
|
||||
```
|
||||
|
||||
### Sending Messages
|
||||
|
||||
```python
|
||||
# Send a message to a person
|
||||
person_source = PersonSource("qq", "12345678")
|
||||
self.api.send_message(person_source, "Hello!")
|
||||
|
||||
# Send a message to a group
|
||||
group_source = GroupSource("qq", "87654321")
|
||||
self.api.send_message(group_source, "Hello, everyone!")
|
||||
|
||||
# Reply to a message
|
||||
self.api.reply_message(message, "This is a reply")
|
||||
```
|
||||
|
||||
### Creating Messages
|
||||
|
||||
```python
|
||||
from langbot.message import Message, PersonSource, Sender
|
||||
|
||||
# Create a person source
|
||||
source = PersonSource("qq", "12345678")
|
||||
|
||||
# Create a sender
|
||||
sender = Sender("87654321", "John Doe")
|
||||
|
||||
# Create a message
|
||||
message = Message(
|
||||
source=source,
|
||||
content="Hello, World!",
|
||||
message_id="msg123",
|
||||
sender=sender,
|
||||
time=1234567890
|
||||
)
|
||||
```
|
||||
|
||||
## Platform-Specific Considerations
|
||||
|
||||
Different messaging platforms may have different capabilities and limitations. Here are some platform-specific considerations:
|
||||
|
||||
### QQ
|
||||
|
||||
- Supports text, images, and rich media
|
||||
- Group messages can mention specific users
|
||||
- Message IDs are platform-specific
|
||||
|
||||
### WeChat
|
||||
|
||||
- Supports text, images, and rich media
|
||||
- Limited API for personal accounts
|
||||
- More features available for official accounts
|
||||
|
||||
### Discord
|
||||
|
||||
- Supports text, images, embeds, and rich formatting
|
||||
- Has a robust API with many features
|
||||
- Supports slash commands
|
||||
|
||||
### Telegram
|
||||
|
||||
- Supports text, images, and rich formatting
|
||||
- Has a comprehensive API
|
||||
- Supports inline bots and commands
|
||||
|
||||
## Best Practices
|
||||
|
||||
- Always check the platform before using platform-specific features
|
||||
- Handle message content carefully, as it may contain special formatting
|
||||
- Use the appropriate source type (PersonSource or GroupSource) when sending messages
|
||||
- Consider rate limits and message size limits when sending messages
|
||||
- Handle errors gracefully, as message sending may fail for various reasons
|
||||
@@ -0,0 +1,298 @@
|
||||
# Plugin Development Tutorial
|
||||
|
||||
This tutorial will guide you through the process of developing a plugin for LangBot.
|
||||
|
||||
## Plugin Structure
|
||||
|
||||
A LangBot plugin consists of the following components:
|
||||
|
||||
1. A main Python file that contains the plugin logic
|
||||
2. A `manifest.yaml` file that describes the plugin
|
||||
3. Optional additional files for resources, templates, etc.
|
||||
|
||||
## Creating a Basic Plugin
|
||||
|
||||
Let's create a simple "Hello World" plugin that responds to a specific command.
|
||||
|
||||
### Step 1: Create the Plugin Directory
|
||||
|
||||
Create a directory for your plugin in the `data/plugins` directory:
|
||||
|
||||
```bash
|
||||
mkdir -p data/plugins/hello-plugin
|
||||
```
|
||||
|
||||
### Step 2: Create the Manifest File
|
||||
|
||||
Create a `manifest.yaml` file in your plugin directory:
|
||||
|
||||
```yaml
|
||||
name: HelloPlugin
|
||||
version: 1.0.0
|
||||
description: A simple hello world plugin
|
||||
author: Your Name
|
||||
entry: hello.py
|
||||
requirements:
|
||||
- requests>=2.28.0
|
||||
```
|
||||
|
||||
### Step 3: Create the Plugin Code
|
||||
|
||||
Create a `hello.py` file in your plugin directory:
|
||||
|
||||
```python
|
||||
from langbot.plugin import Plugin, handler
|
||||
from langbot.event import PersonNormalMessageReceived
|
||||
from langbot.api import APIHost
|
||||
|
||||
class HelloPlugin(Plugin):
|
||||
def __init__(self, api_host: APIHost):
|
||||
super().__init__(api_host)
|
||||
self.api = api_host
|
||||
|
||||
@handler(PersonNormalMessageReceived)
|
||||
def on_person_message(self, ctx):
|
||||
# Get the message content
|
||||
message = ctx.event.message.content
|
||||
|
||||
# Check if the message is the command we want to handle
|
||||
if message == "!hello":
|
||||
# Prevent the default handling (don't send to LLM)
|
||||
ctx.prevent_default()
|
||||
|
||||
# Send a response
|
||||
self.api.send_message(
|
||||
ctx.event.message.source,
|
||||
"Hello, World! This is my first LangBot plugin."
|
||||
)
|
||||
```
|
||||
|
||||
### Step 4: Install and Test the Plugin
|
||||
|
||||
1. Restart LangBot or use the `!plugin reload` command
|
||||
2. Send the `!hello` command to your bot
|
||||
3. The bot should respond with "Hello, World! This is my first LangBot plugin."
|
||||
|
||||
## Event Handling
|
||||
|
||||
LangBot uses an event-driven architecture. Plugins can register handlers for various events:
|
||||
|
||||
```python
|
||||
@handler(PersonNormalMessageReceived)
|
||||
def on_person_message(self, ctx):
|
||||
# Handle the event
|
||||
pass
|
||||
```
|
||||
|
||||
Common events include:
|
||||
|
||||
- `PersonNormalMessageReceived`: Received a message from a person
|
||||
- `GroupNormalMessageReceived`: Received a message in a group
|
||||
- `GroupInvitationReceived`: Received an invitation to join a group
|
||||
- `FriendRequestReceived`: Received a friend request
|
||||
|
||||
The `ctx` parameter provides access to:
|
||||
|
||||
- `ctx.event`: The event that triggered the handler
|
||||
- `ctx.prevent_default()`: Prevents the default handling of the event
|
||||
- `ctx.add_return(key, value)`: Adds a return value to the event
|
||||
|
||||
## API Access
|
||||
|
||||
The `APIHost` provides access to LangBot's API:
|
||||
|
||||
```python
|
||||
# Send a message
|
||||
self.api.send_message(source, content)
|
||||
|
||||
# Get user information
|
||||
user_info = self.api.get_user_info(user_id)
|
||||
|
||||
# Get group information
|
||||
group_info = self.api.get_group_info(group_id)
|
||||
|
||||
# Call the LLM
|
||||
response = self.api.call_llm(prompt, model="gpt-3.5-turbo")
|
||||
```
|
||||
|
||||
## LLM Function Registration
|
||||
|
||||
Plugins can register functions that can be called by the LLM during conversations:
|
||||
|
||||
```python
|
||||
import requests
|
||||
from langbot.plugin import Plugin, llm_func
|
||||
from langbot.api import APIHost
|
||||
|
||||
class WebSearchPlugin(Plugin):
|
||||
def __init__(self, api_host: APIHost):
|
||||
super().__init__(api_host)
|
||||
self.api = api_host
|
||||
|
||||
@llm_func(name="search_the_web")
|
||||
def search_web(self, query: str) -> str:
|
||||
"""
|
||||
Search the web for information.
|
||||
|
||||
Args:
|
||||
query: The search query
|
||||
|
||||
Returns:
|
||||
The search results
|
||||
"""
|
||||
# Implement web search logic
|
||||
response = requests.get(
|
||||
"https://api.search.com/search",
|
||||
params={"q": query}
|
||||
)
|
||||
return response.json()["results"]
|
||||
```
|
||||
|
||||
The LLM can then call this function during conversations:
|
||||
|
||||
```
|
||||
User: What's the weather in New York?
|
||||
Bot: Let me check that for you.
|
||||
[Function call: search_the_web("weather in New York")]
|
||||
The current weather in New York is 72°F and sunny.
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
Plugins can have configuration options that users can set:
|
||||
|
||||
```python
|
||||
from langbot.plugin import Plugin, config_field
|
||||
from langbot.api import APIHost
|
||||
|
||||
class WeatherPlugin(Plugin):
|
||||
def __init__(self, api_host: APIHost):
|
||||
super().__init__(api_host)
|
||||
self.api = api_host
|
||||
|
||||
@config_field(name="api_key", description="API key for the weather service")
|
||||
def set_api_key(self, api_key: str):
|
||||
self.api_key = api_key
|
||||
```
|
||||
|
||||
Users can set these options using the WebUI or the `!plugin config` command:
|
||||
|
||||
```
|
||||
!plugin config WeatherPlugin api_key=your-api-key
|
||||
```
|
||||
|
||||
## Persistent Storage
|
||||
|
||||
Plugins can store data persistently:
|
||||
|
||||
```python
|
||||
# Store data
|
||||
self.api.storage.set("key", "value")
|
||||
|
||||
# Retrieve data
|
||||
value = self.api.storage.get("key")
|
||||
|
||||
# Check if a key exists
|
||||
exists = self.api.storage.has("key")
|
||||
|
||||
# Delete a key
|
||||
self.api.storage.delete("key")
|
||||
```
|
||||
|
||||
## Advanced Features
|
||||
|
||||
### Command Registration
|
||||
|
||||
Plugins can register commands that users can use:
|
||||
|
||||
```python
|
||||
from langbot.plugin import Plugin, command
|
||||
from langbot.api import APIHost
|
||||
|
||||
class EchoPlugin(Plugin):
|
||||
def __init__(self, api_host: APIHost):
|
||||
super().__init__(api_host)
|
||||
self.api = api_host
|
||||
|
||||
@command(name="echo", description="Echo a message")
|
||||
def echo_command(self, args: str) -> str:
|
||||
"""
|
||||
Echo the provided message.
|
||||
|
||||
Usage: !echo <message>
|
||||
"""
|
||||
return args
|
||||
```
|
||||
|
||||
Users can then use the command:
|
||||
|
||||
```
|
||||
!echo Hello, World!
|
||||
```
|
||||
|
||||
### Event Return Values
|
||||
|
||||
Handlers can add return values to events:
|
||||
|
||||
```python
|
||||
@handler(PersonNormalMessageReceived)
|
||||
def on_person_message(self, ctx):
|
||||
# Add a return value
|
||||
ctx.add_return("reply", ["This is a reply"])
|
||||
```
|
||||
|
||||
### Component Extension
|
||||
|
||||
Plugins can extend LangBot's core components:
|
||||
|
||||
```python
|
||||
from langbot.plugin import Plugin, component_extension
|
||||
from langbot.api import APIHost
|
||||
|
||||
class CustomTriggerPlugin(Plugin):
|
||||
def __init__(self, api_host: APIHost):
|
||||
super().__init__(api_host)
|
||||
self.api = api_host
|
||||
|
||||
@component_extension("trigger")
|
||||
def custom_trigger(self, component, message):
|
||||
# Implement custom trigger logic
|
||||
if message.content.startswith("custom:"):
|
||||
return True
|
||||
return None # Let the default trigger handle it
|
||||
```
|
||||
|
||||
## Publishing Your Plugin
|
||||
|
||||
To publish your plugin:
|
||||
|
||||
1. Create a GitHub repository for your plugin
|
||||
2. Add a README.md file with installation and usage instructions
|
||||
3. Add your plugin to the [LangBot Plugin Market](https://plugins.langbot.app)
|
||||
|
||||
## Best Practices
|
||||
|
||||
- Keep your plugin focused on a specific functionality
|
||||
- Handle errors gracefully
|
||||
- Provide clear documentation
|
||||
- Follow Python best practices
|
||||
- Test your plugin thoroughly
|
||||
- Keep dependencies minimal
|
||||
|
||||
## Example Plugins
|
||||
|
||||
Check out these example plugins for inspiration:
|
||||
|
||||
- [WebSearch](https://github.com/RockChinQ/WebSearch): Search the web for information
|
||||
- [ImageGen](https://github.com/RockChinQ/ImageGen): Generate images using AI
|
||||
- [Schedule](https://github.com/RockChinQ/Schedule): Schedule messages to be sent at specific times
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
If you encounter issues with your plugin:
|
||||
|
||||
1. Check the logs for error messages
|
||||
2. Verify that your plugin is correctly installed
|
||||
3. Make sure your plugin's dependencies are installed
|
||||
4. Test your plugin with simple functionality first
|
||||
5. Ask for help in the [community chat](https://qm.qq.com/q/Nnz7Vbj8OU)
|
||||
@@ -0,0 +1,84 @@
|
||||
# Plugin Introduction
|
||||
|
||||
LangBot supports a powerful plugin system that allows you to extend its functionality. Plugins can add new commands, event handlers, and even integrate with external services.
|
||||
|
||||
## What Can Plugins Do?
|
||||
|
||||
Plugins can:
|
||||
|
||||
- Add new commands to the bot
|
||||
- Handle and respond to various events (messages, group invitations, etc.)
|
||||
- Integrate with external services and APIs
|
||||
- Modify the behavior of the bot
|
||||
- Add new functions that can be called by the LLM during conversations
|
||||
- Extend the core components of LangBot
|
||||
|
||||
## Plugin Market
|
||||
|
||||
You can find and install plugins from the [LangBot Plugin Market](https://plugins.langbot.app).
|
||||
|
||||
## Installing Plugins
|
||||
|
||||
### Method 1: Install via WebUI
|
||||
|
||||
1. Access the WebUI at `http://your-server-ip:5300`
|
||||
2. Navigate to the "Plugins" section
|
||||
3. Click "Install Plugin"
|
||||
4. Enter the plugin's GitHub repository URL or select from the featured plugins
|
||||
5. Click "Install"
|
||||
|
||||
### Method 2: Manual Installation
|
||||
|
||||
1. Download or clone the plugin repository
|
||||
2. Place the plugin files in the `data/plugins` directory
|
||||
3. Restart LangBot or use the `!plugin reload` command
|
||||
|
||||
## Managing Plugins
|
||||
|
||||
You can manage plugins using the following commands:
|
||||
|
||||
```
|
||||
!plugin list
|
||||
```
|
||||
|
||||
Lists all installed plugins.
|
||||
|
||||
```
|
||||
!plugin enable <plugin_id>
|
||||
```
|
||||
|
||||
Enables the specified plugin.
|
||||
|
||||
```
|
||||
!plugin disable <plugin_id>
|
||||
```
|
||||
|
||||
Disables the specified plugin.
|
||||
|
||||
```
|
||||
!plugin info <plugin_id>
|
||||
```
|
||||
|
||||
Displays information about the specified plugin.
|
||||
|
||||
```
|
||||
!plugin reload
|
||||
```
|
||||
|
||||
Reloads all plugins.
|
||||
|
||||
## Popular Plugins
|
||||
|
||||
Here are some popular plugins for LangBot:
|
||||
|
||||
- **WebSearch**: Allows the bot to search the web and provide information
|
||||
- **ImageGen**: Generates images using AI models like DALL-E or Stable Diffusion
|
||||
- **Weather**: Provides weather information for specified locations
|
||||
- **Translator**: Translates text between languages
|
||||
- **Calculator**: Performs mathematical calculations
|
||||
- **Schedule**: Schedules messages to be sent at specific times
|
||||
- **GroupManager**: Provides group management features like welcome messages and anti-spam
|
||||
|
||||
## Developing Plugins
|
||||
|
||||
If you want to develop your own plugins, check out the [Plugin Development Tutorial](/en/plugin/dev/tutor).
|
||||
@@ -0,0 +1,176 @@
|
||||
# How to Integrate with Dify?
|
||||
|
||||
This guide explains how to integrate LangBot with Dify, a powerful LLMOps platform that allows you to create and deploy AI applications.
|
||||
|
||||
## What is Dify?
|
||||
|
||||
[Dify](https://dify.ai) is an open-source LLMOps platform that helps you build, deploy, and monitor AI applications. It provides a user-friendly interface for creating AI applications without writing code, as well as APIs for integrating with other systems.
|
||||
|
||||
## Integration Methods
|
||||
|
||||
There are two ways to integrate LangBot with Dify:
|
||||
|
||||
1. **Service API**: Use Dify's Service API to access applications created in Dify
|
||||
2. **Completion API**: Use Dify's Completion API as a model provider in LangBot
|
||||
|
||||
This guide focuses on the Service API integration, which is the recommended approach for most use cases.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Before you begin, you need:
|
||||
|
||||
1. A Dify account and a deployed application
|
||||
2. The API key for your Dify application
|
||||
3. LangBot version 4.0 or higher
|
||||
|
||||
## Step 1: Create a Dify Application
|
||||
|
||||
1. Sign up or log in to [Dify](https://dify.ai)
|
||||
2. Create a new application or use an existing one
|
||||
3. Configure your application with the desired model, prompt, and other settings
|
||||
4. Deploy your application
|
||||
5. Go to the API Reference section and copy your API key
|
||||
|
||||
## Step 2: Configure LangBot
|
||||
|
||||
### Method 1: Configure via WebUI
|
||||
|
||||
1. Access the LangBot WebUI at `http://your-server-ip:5300`
|
||||
2. Navigate to the "Models" section
|
||||
3. Click "Add Provider"
|
||||
4. Select "Dify" as the provider type
|
||||
5. Enter your Dify API key and application ID
|
||||
6. Save the configuration
|
||||
|
||||
### Method 2: Configure via Configuration File
|
||||
|
||||
Edit the `data/config.yaml` file and add the Dify provider:
|
||||
|
||||
```yaml
|
||||
providers:
|
||||
- id: dify
|
||||
type: dify
|
||||
config:
|
||||
api_key: "your-dify-api-key"
|
||||
application_id: "your-dify-application-id"
|
||||
base_url: "https://api.dify.ai/v1" # Optional, defaults to Dify's official API endpoint
|
||||
```
|
||||
|
||||
## Step 3: Test the Integration
|
||||
|
||||
Send a test message to your bot:
|
||||
|
||||
```
|
||||
!model use dify
|
||||
Hello, how are you?
|
||||
```
|
||||
|
||||
The bot should respond using your Dify application.
|
||||
|
||||
## Advanced Configuration
|
||||
|
||||
### Using Multiple Dify Applications
|
||||
|
||||
You can configure multiple Dify applications in LangBot:
|
||||
|
||||
```yaml
|
||||
providers:
|
||||
- id: dify-general
|
||||
type: dify
|
||||
config:
|
||||
api_key: "your-dify-api-key-1"
|
||||
application_id: "your-dify-application-id-1"
|
||||
|
||||
- id: dify-specialized
|
||||
type: dify
|
||||
config:
|
||||
api_key: "your-dify-api-key-2"
|
||||
application_id: "your-dify-application-id-2"
|
||||
```
|
||||
|
||||
### Configuring Input Variables
|
||||
|
||||
If your Dify application uses input variables, you can configure them in LangBot:
|
||||
|
||||
```yaml
|
||||
providers:
|
||||
- id: dify
|
||||
type: dify
|
||||
config:
|
||||
api_key: "your-dify-api-key"
|
||||
application_id: "your-dify-application-id"
|
||||
input_variables:
|
||||
- name: "user_name"
|
||||
value: "{sender.name}"
|
||||
- name: "group_name"
|
||||
value: "{group.name}"
|
||||
```
|
||||
|
||||
### Using Dify's File Capabilities
|
||||
|
||||
If your Dify application supports file inputs, you can configure LangBot to handle them:
|
||||
|
||||
```yaml
|
||||
providers:
|
||||
- id: dify
|
||||
type: dify
|
||||
config:
|
||||
api_key: "your-dify-api-key"
|
||||
application_id: "your-dify-application-id"
|
||||
file_enabled: true
|
||||
```
|
||||
|
||||
When file support is enabled, users can send files to the bot, and they will be forwarded to Dify:
|
||||
|
||||
```
|
||||
!model use dify
|
||||
[Attach a file]
|
||||
Can you analyze this document?
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Connection Issues
|
||||
|
||||
If you're having trouble connecting to Dify, check:
|
||||
|
||||
1. Your API key is correct
|
||||
2. Your application ID is correct
|
||||
3. Your Dify application is deployed and active
|
||||
4. Your server can access the Dify API endpoint
|
||||
|
||||
### Response Format Issues
|
||||
|
||||
If the responses from Dify don't look right:
|
||||
|
||||
1. Check your Dify application's prompt configuration
|
||||
2. Make sure your application is using the correct model
|
||||
3. Verify that your application is configured for chat completion (not text completion)
|
||||
|
||||
### Rate Limiting
|
||||
|
||||
If you're hitting rate limits:
|
||||
|
||||
1. Check your Dify plan's rate limits
|
||||
2. Consider implementing rate limiting in LangBot
|
||||
3. Upgrade your Dify plan if necessary
|
||||
|
||||
## Example Use Cases
|
||||
|
||||
### Customer Support Bot
|
||||
|
||||
Create a Dify application for customer support, with knowledge of your products and services, and integrate it with LangBot to provide automated customer support in your messaging channels.
|
||||
|
||||
### Content Creation Assistant
|
||||
|
||||
Create a Dify application for content creation, with templates and guidelines for your brand, and integrate it with LangBot to help your team create content more efficiently.
|
||||
|
||||
### Data Analysis Bot
|
||||
|
||||
Create a Dify application for data analysis, with the ability to interpret and visualize data, and integrate it with LangBot to provide data insights on demand.
|
||||
|
||||
## Conclusion
|
||||
|
||||
Integrating LangBot with Dify allows you to leverage Dify's powerful LLMOps capabilities while using LangBot's messaging platform integrations. This combination provides a flexible and powerful solution for deploying AI applications across multiple messaging platforms.
|
||||
|
||||
For more information, check out the [Dify documentation](https://docs.dify.ai) and the [LangBot documentation](https://docs.langbot.app).
|
||||
@@ -0,0 +1,389 @@
|
||||
# How to Implement a Message Platform Adapter?
|
||||
|
||||
This guide explains how to implement a custom message platform adapter for LangBot, allowing you to connect the bot to new messaging platforms.
|
||||
|
||||
## Overview
|
||||
|
||||
LangBot uses a modular architecture that allows for easy integration with various messaging platforms. The core component for platform integration is the `MessageSourceAdapter`, which handles the communication between LangBot and the messaging platform.
|
||||
|
||||

|
||||
|
||||
## Prerequisites
|
||||
|
||||
Before implementing a platform adapter, you should:
|
||||
|
||||
1. Understand the API of the messaging platform you want to integrate with
|
||||
2. Have basic knowledge of Python and asynchronous programming
|
||||
3. Be familiar with LangBot's architecture and event system
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
### Step 1: Create a New Adapter Class
|
||||
|
||||
Create a new Python file in the `langbot/bot/adapters` directory:
|
||||
|
||||
```python
|
||||
from langbot.bot import MessageSourceAdapter
|
||||
from langbot.message import Message, PersonSource, GroupSource, Sender
|
||||
from langbot.event import PersonNormalMessageReceived, GroupNormalMessageReceived
|
||||
|
||||
class MyPlatformAdapter(MessageSourceAdapter):
|
||||
"""
|
||||
Adapter for MyPlatform.
|
||||
"""
|
||||
|
||||
def __init__(self, config):
|
||||
"""
|
||||
Initialize the adapter.
|
||||
|
||||
Args:
|
||||
config: The adapter configuration
|
||||
"""
|
||||
super().__init__(config)
|
||||
self.config = config
|
||||
# Initialize platform-specific client
|
||||
self.client = None
|
||||
```
|
||||
|
||||
### Step 2: Implement the Required Methods
|
||||
|
||||
Implement the required methods for the adapter:
|
||||
|
||||
```python
|
||||
async def start(self):
|
||||
"""
|
||||
Start the adapter.
|
||||
"""
|
||||
# Initialize and start the platform client
|
||||
self.client = MyPlatformClient(
|
||||
api_key=self.config.get("api_key"),
|
||||
# Other platform-specific configuration
|
||||
)
|
||||
|
||||
# Register event handlers
|
||||
self.client.on_message(self.on_message)
|
||||
|
||||
# Start the client
|
||||
await self.client.start()
|
||||
|
||||
async def stop(self):
|
||||
"""
|
||||
Stop the adapter.
|
||||
"""
|
||||
# Stop the platform client
|
||||
if self.client:
|
||||
await self.client.stop()
|
||||
|
||||
async def send_message(self, source, content, **kwargs):
|
||||
"""
|
||||
Send a message to a specific destination.
|
||||
|
||||
Args:
|
||||
source: The destination to send the message to
|
||||
content: The content of the message
|
||||
**kwargs: Additional arguments
|
||||
|
||||
Returns:
|
||||
The message ID
|
||||
"""
|
||||
# Send the message using the platform client
|
||||
if isinstance(source, PersonSource):
|
||||
# Send a direct message
|
||||
message_id = await self.client.send_direct_message(
|
||||
source.identity,
|
||||
content,
|
||||
**kwargs
|
||||
)
|
||||
elif isinstance(source, GroupSource):
|
||||
# Send a group message
|
||||
message_id = await self.client.send_group_message(
|
||||
source.identity,
|
||||
content,
|
||||
**kwargs
|
||||
)
|
||||
else:
|
||||
raise ValueError(f"Unsupported source type: {type(source)}")
|
||||
|
||||
return message_id
|
||||
```
|
||||
|
||||
### Step 3: Implement Event Handlers
|
||||
|
||||
Implement event handlers to convert platform-specific events to LangBot events:
|
||||
|
||||
```python
|
||||
async def on_message(self, platform_message):
|
||||
"""
|
||||
Handle a message from the platform.
|
||||
|
||||
Args:
|
||||
platform_message: The platform-specific message
|
||||
"""
|
||||
# Convert the platform message to a LangBot message
|
||||
message = self.convert_message(platform_message)
|
||||
|
||||
# Determine the type of message and emit the appropriate event
|
||||
if isinstance(message.source, PersonSource):
|
||||
# Emit a person message event
|
||||
await self.emit(PersonNormalMessageReceived(message))
|
||||
elif isinstance(message.source, GroupSource):
|
||||
# Emit a group message event
|
||||
await self.emit(GroupNormalMessageReceived(message))
|
||||
|
||||
def convert_message(self, platform_message):
|
||||
"""
|
||||
Convert a platform-specific message to a LangBot message.
|
||||
|
||||
Args:
|
||||
platform_message: The platform-specific message
|
||||
|
||||
Returns:
|
||||
A LangBot message
|
||||
"""
|
||||
# Extract message information
|
||||
message_id = platform_message.get("id")
|
||||
content = platform_message.get("content")
|
||||
time = platform_message.get("timestamp")
|
||||
|
||||
# Extract sender information
|
||||
sender_id = platform_message.get("sender_id")
|
||||
sender_name = platform_message.get("sender_name")
|
||||
sender = Sender(sender_id, sender_name)
|
||||
|
||||
# Determine the source type
|
||||
if platform_message.get("is_group"):
|
||||
# Group message
|
||||
group_id = platform_message.get("group_id")
|
||||
source = GroupSource("my_platform", group_id)
|
||||
else:
|
||||
# Direct message
|
||||
source = PersonSource("my_platform", sender_id)
|
||||
|
||||
# Create and return the message
|
||||
return Message(
|
||||
source=source,
|
||||
content=content,
|
||||
message_id=message_id,
|
||||
sender=sender,
|
||||
time=time
|
||||
)
|
||||
```
|
||||
|
||||
### Step 4: Register the Adapter
|
||||
|
||||
Register the adapter in the `langbot/bot/adapters/__init__.py` file:
|
||||
|
||||
```python
|
||||
from .my_platform import MyPlatformAdapter
|
||||
|
||||
__all__ = [
|
||||
# Other adapters
|
||||
"MyPlatformAdapter",
|
||||
]
|
||||
```
|
||||
|
||||
### Step 5: Add Configuration Schema
|
||||
|
||||
Add the configuration schema for your adapter in the `langbot/schema/bot.py` file:
|
||||
|
||||
```python
|
||||
MY_PLATFORM_SCHEMA = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"type": {"type": "string", "enum": ["my_platform"]},
|
||||
"api_key": {"type": "string"},
|
||||
# Other platform-specific configuration
|
||||
},
|
||||
"required": ["type", "api_key"],
|
||||
}
|
||||
|
||||
# Add to the BOT_SCHEMA
|
||||
BOT_SCHEMA = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"bots": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"oneOf": [
|
||||
# Other adapter schemas
|
||||
MY_PLATFORM_SCHEMA,
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
## Example: Implementing a Discord Adapter
|
||||
|
||||
Here's a simplified example of implementing a Discord adapter:
|
||||
|
||||
```python
|
||||
import discord
|
||||
from langbot.bot import MessageSourceAdapter
|
||||
from langbot.message import Message, PersonSource, GroupSource, Sender
|
||||
from langbot.event import PersonNormalMessageReceived, GroupNormalMessageReceived
|
||||
|
||||
class DiscordAdapter(MessageSourceAdapter):
|
||||
"""
|
||||
Adapter for Discord.
|
||||
"""
|
||||
|
||||
def __init__(self, config):
|
||||
"""
|
||||
Initialize the adapter.
|
||||
|
||||
Args:
|
||||
config: The adapter configuration
|
||||
"""
|
||||
super().__init__(config)
|
||||
self.config = config
|
||||
self.client = discord.Client(intents=discord.Intents.all())
|
||||
|
||||
# Register event handlers
|
||||
@self.client.event
|
||||
async def on_ready():
|
||||
print(f"Logged in as {self.client.user}")
|
||||
|
||||
@self.client.event
|
||||
async def on_message(message):
|
||||
# Ignore messages from the bot itself
|
||||
if message.author == self.client.user:
|
||||
return
|
||||
|
||||
# Convert and emit the message
|
||||
await self.on_message(message)
|
||||
|
||||
async def start(self):
|
||||
"""
|
||||
Start the adapter.
|
||||
"""
|
||||
# Start the Discord client
|
||||
await self.client.start(self.config.get("token"))
|
||||
|
||||
async def stop(self):
|
||||
"""
|
||||
Stop the adapter.
|
||||
"""
|
||||
# Stop the Discord client
|
||||
if self.client:
|
||||
await self.client.close()
|
||||
|
||||
async def send_message(self, source, content, **kwargs):
|
||||
"""
|
||||
Send a message to a specific destination.
|
||||
|
||||
Args:
|
||||
source: The destination to send the message to
|
||||
content: The content of the message
|
||||
**kwargs: Additional arguments
|
||||
|
||||
Returns:
|
||||
The message ID
|
||||
"""
|
||||
# Send the message using the Discord client
|
||||
if isinstance(source, PersonSource):
|
||||
# Send a direct message
|
||||
user = await self.client.fetch_user(int(source.identity))
|
||||
message = await user.send(content)
|
||||
return str(message.id)
|
||||
elif isinstance(source, GroupSource):
|
||||
# Send a group message
|
||||
channel = self.client.get_channel(int(source.identity))
|
||||
message = await channel.send(content)
|
||||
return str(message.id)
|
||||
else:
|
||||
raise ValueError(f"Unsupported source type: {type(source)}")
|
||||
|
||||
async def on_message(self, discord_message):
|
||||
"""
|
||||
Handle a message from Discord.
|
||||
|
||||
Args:
|
||||
discord_message: The Discord message
|
||||
"""
|
||||
# Convert the Discord message to a LangBot message
|
||||
message = self.convert_message(discord_message)
|
||||
|
||||
# Determine the type of message and emit the appropriate event
|
||||
if isinstance(message.source, PersonSource):
|
||||
# Emit a person message event
|
||||
await self.emit(PersonNormalMessageReceived(message))
|
||||
elif isinstance(message.source, GroupSource):
|
||||
# Emit a group message event
|
||||
await self.emit(GroupNormalMessageReceived(message))
|
||||
|
||||
def convert_message(self, discord_message):
|
||||
"""
|
||||
Convert a Discord message to a LangBot message.
|
||||
|
||||
Args:
|
||||
discord_message: The Discord message
|
||||
|
||||
Returns:
|
||||
A LangBot message
|
||||
"""
|
||||
# Extract message information
|
||||
message_id = str(discord_message.id)
|
||||
content = discord_message.content
|
||||
time = discord_message.created_at.timestamp()
|
||||
|
||||
# Extract sender information
|
||||
sender_id = str(discord_message.author.id)
|
||||
sender_name = discord_message.author.name
|
||||
sender = Sender(sender_id, sender_name)
|
||||
|
||||
# Determine the source type
|
||||
if discord_message.guild:
|
||||
# Group message
|
||||
group_id = str(discord_message.channel.id)
|
||||
source = GroupSource("discord", group_id)
|
||||
else:
|
||||
# Direct message
|
||||
source = PersonSource("discord", sender_id)
|
||||
|
||||
# Create and return the message
|
||||
return Message(
|
||||
source=source,
|
||||
content=content,
|
||||
message_id=message_id,
|
||||
sender=sender,
|
||||
time=time
|
||||
)
|
||||
```
|
||||
|
||||
## Testing Your Adapter
|
||||
|
||||
To test your adapter:
|
||||
|
||||
1. Add your adapter configuration to the `data/config.yaml` file:
|
||||
|
||||
```yaml
|
||||
bots:
|
||||
- id: my_platform
|
||||
type: my_platform
|
||||
config:
|
||||
api_key: your-api-key
|
||||
# Other platform-specific configuration
|
||||
```
|
||||
|
||||
2. Start LangBot and check the logs for any errors
|
||||
3. Send a test message on your platform and verify that LangBot receives and processes it
|
||||
4. Send a test message from LangBot to your platform and verify that it's delivered correctly
|
||||
|
||||
## Best Practices
|
||||
|
||||
- Handle errors gracefully and provide meaningful error messages
|
||||
- Implement proper rate limiting to avoid being blocked by the platform
|
||||
- Use asynchronous programming to avoid blocking the event loop
|
||||
- Document your adapter thoroughly, including configuration options and limitations
|
||||
- Follow the platform's terms of service and API guidelines
|
||||
- Implement proper logging to help with debugging
|
||||
- Consider implementing reconnection logic for platforms with unstable connections
|
||||
- Test your adapter thoroughly with different types of messages and scenarios
|
||||
|
||||
## Conclusion
|
||||
|
||||
Implementing a custom message platform adapter allows you to extend LangBot to work with new messaging platforms. By following the steps and best practices outlined in this guide, you can create a robust and reliable adapter that integrates seamlessly with LangBot's architecture.
|
||||
|
||||
If you encounter any issues or have questions, feel free to ask in the [community chat](https://qm.qq.com/q/Nnz7Vbj8OU) or open an issue on [GitHub](https://github.com/RockChinQ/LangBot/issues).
|
||||
Reference in New Issue
Block a user