시작하기
마지막 업데이트
go-bot을 Go module에 추가하고 하나의 플랫폼에서 최소 구성의 에코 bot을 실행합니다.
사전 요구 사항
| 항목 | 요구 사항 |
|---|---|
| Go | 1.25.0 이상 (go.mod) |
| Telegram | BotFather에서 발급받은 Bot token |
| Discord | Bot token. Developer Portal에서 Message Content Intent를 활성화해야 합니다 |
| LINE | Channel secret, 장기 channel access token, webhook 포트로 전달되는 공개 HTTPS URL |
Telegram과 Discord는 아웃바운드로 연결하므로 NAT 뒤에서도 동작합니다. LINE은 이벤트를 서버로 푸시하므로 인바운드 HTTPS 엔드포인트가 필요합니다(로컬 테스트에는 ngrok 같은 리버스 프록시를 사용할 수 있습니다).
설치
- go get github.com/pardnchiu/go-bot@latest
사용하는 플랫폼 패키지만 import합니다.
- import (
- "github.com/pardnchiu/go-bot/core/telegram"
- "github.com/pardnchiu/go-bot/core/discord"
- "github.com/pardnchiu/go-bot/core/line"
- )
최소 구성의 에코 bot
모든 플랫폼은 같은 순서를 따릅니다.
New, Reply, Start, 그리고 종료 시 Close입니다. handler가 비어 있지 않은 값을 반환하면 그 값이 답장으로 전송됩니다.- package main
- import (
- "context"
- "log"
- "os"
- "os/signal"
- "syscall"
- "github.com/pardnchiu/go-bot/core/telegram"
- )
- func main() {
- bot, err := telegram.New(os.Getenv("TELEGRAM_TOKEN"))
- if err != nil {
- log.Fatal(err)
- }
- bot.Reply(func(ctx context.Context, in telegram.Input) string {
- return "you said: " + in.Text
- })
- ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
- defer stop()
- if err := bot.Start(ctx); err != nil {
- log.Fatal(err)
- }
- <-ctx.Done()
- bot.Close()
- }
Discord와 LINE 버전은 생성자와
Input 타입만 다릅니다.| 플랫폼 | 생성자 | Handler 입력 |
|---|---|---|
| Telegram | telegram.New(token) | telegram.Input |
| Discord | discord.New(token) | discord.Input |
| LINE | line.New(secret, token, "8080") | line.Input |
라이브러리는 환경 변수를 읽지 않습니다. 위의 변수 이름은 여러분의 프로그램에 속한 것입니다.
다음 단계
- Bot 라이프사이클 —
Start가 무엇을 검증하고Close가 어떻게 종료하는지 - Reply Handler — 답장이 어디로 가는지, panic이 발생하면 어떻게 되는지
- 플랫폼 설정: Telegram, Discord, LINE