Telegram 訊息
最後更新
本頁說明如何用
core/telegram 傳送文字、刪除訊息,以及上傳檔案、圖片與語音。文字
- msg, err := bot.Send(ctx, chatID, replyTo, "*bold*", telegram.WithSendType(telegram.TypeMarkdown))
| 參數 | 意義 |
|---|---|
replyTo int | > 0 時以 reply 方式回覆該訊息 ID;0 為獨立訊息 |
opts ...MessageOption | WithSendType(TypeMarkdown) → MarkdownV2、WithSendType(TypeHTML) → HTML;不傳則為純文字 |
使用 MarkdownV2 時需自行跳脫 Telegram 的保留字元;函式庫原樣送出文字。
Delete(ctx, chatID, msgID) 刪除一則訊息,API 錯誤原樣回傳。文件、影片、音訊
- msg, err := bot.SendFile(ctx, chatID, telegram.TypeDocument, "./report.pdf", "Q3 report")
FileType | API |
|---|---|
TypeDocument | sendDocument |
TypeVideo | sendVideo |
TypeAudio | sendAudio |
檔案以
os.Open 開啟並串流上傳;上傳檔名為 filepath.Base(path)。只使用第一個 caption 參數。空路徑回 path is required;其他 FileType 值回 unknown file type。圖片與相簿
- msgs, err := bot.SendPhoto(ctx, chatID, []string{"a.jpg", "b.jpg"}, "Trip")
先移除空字串。剩一個路徑時走
sendPhoto;2 到 10 個走 sendMediaGroup,Telegram 以單一相簿顯示,caption 掛在第一張。0 個或超過 10 個回 error。回傳值為每張圖片各一個 *models.Message。語音
- msg, err := bot.SendVoice(ctx, chatID, "./reply.ogg", "caption")
SendVoice 上傳既有檔案。檔案為 OPUS 編碼的 OGG 時,Telegram 會顯示為語音泡泡;該檔案需自行產生(例如 TTS 服務加 ffmpeg)。沒有 replyTo 參數。尾端的字串都是 caption。為 v0.4.x 撰寫的
SendVoice(ctx, chatID, text, apiKey) 在 v0.5.0 仍可編譯,但會把 text 當成檔案路徑上傳,並把 apiKey 當成 caption 發出。見已移除 API。