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

創建第一個機器人

本指南在 5 分鐘快速入門 的基礎上,帶你編寫第一個命令處理器並理解運行機制。

如果你尚未安裝 ErisPulse、初始化項目,請先完成 快速入門 的「安裝」「初始化項目」「運行項目」三步。

第一步:撰寫第一個命令

開啟 main.py,撰寫一個簡單的命令處理器:

from ErisPulse import sdk
from ErisPulse.Core.Event import command

@command("hello", help="發送問候訊息")
async def hello_handler(event):
    """處理 hello 命令"""
    user_name = event.get_user_nickname() or "朋友"
    await event.reply(f"你好,{user_name}!我是 ErisPulse 機器人。")

@command("ping", help="測試機器人是否在線")
async def ping_handler(event):
    """處理 ping 命令"""
    await event.reply("Pong!機器人運行正常。")

async def main():
    """主入口函數"""
    print("正在啟動 ErisPulse...")
    
    # keep_running=True(預設):框架阻塞維持運行,直到收到關閉訊號(如 Ctrl+C)
    await sdk.run(keep_running=True)

if __name__ == "__main__":
    import asyncio
    asyncio.run(main())

keep_running 參數

sdk.run(keep_running) 控制框架是否阻塞維持運行:

async def main():
    await sdk.run(keep_running=False)   # 初始化後立即返回
    # 框架已在背景運行,這裡可以繼續做別的事
    while True:
        await asyncio.sleep(3600)
        print("每小時檢查一次")

除了 run() 的兩種模式,還有 init()/uninit() 手動控制生命週期、單獨啟停適配器/路由等更精細的方式,請參閱 啟動流程與手動控制。

第二步:執行機器人

# 普通執行
epsdk run main.py

# 開發模式(支援熱重載)
epsdk run main.py --reload

第三步:測試機器人

在你的聊天平台中發送命令:

/hello

你應該會收到機器人的回覆。

代碼說明

命令裝飾器

@command("hello", help="發送問候訊息")

事件參數

async def hello_handler(event):

event 參數是一個 Event 物件,包含:

完整的 Event 物件方法請參考 Event 包裝類詳解。

發送回覆

await event.reply("回覆內容")

event.reply() 是一個便捷方法,用於向發送者發送訊息。

擴展:添加更多功能

ErisPulse 提供了豐富的事件處理和數據處理能力:

常見問題

命令沒有響應?

  1. 檢查適配器是否正確配置,確認 config/config.toml 中適配器的 status 為 true
  2. 查看終端日誌輸出,確認是否有錯誤資訊(特別是 ERROR 級別日誌)
  3. 確認命令前綴是否正確(預設是 /),可在設定檔中查看 [ErisPulse.event.command] 部分
  4. 確認命令名稱拼寫正確,注意大小寫敏感性設定

如何修改命令前綴?

在 config.toml 中添加:

[ErisPulse.event.command]
prefix = "!"
case_sensitive = false

如何支援多平台?

ErisPulse 使用 OneBot12 標準統一了不同平台的事件格式,@command 和 @message 註冊的處理器會自動接收所有平台的事件。透過 event.get_platform() 可以區分來源平台:

@command("hello")
async def hello_handler(event):
    platform = event.get_platform()
    
    if platform == "yunhu":
        await event.reply("你好!來自雲湖")
    elif platform == "telegram":
        await event.reply("Hello! From Telegram")
    else:
        await event.reply("你好!")

更多多平台適配技巧請參考 常見任務範例。

下一步