Compare commits

..

23 Commits

Author SHA1 Message Date
a83ccdd054 Add Makefile 2024-10-21 17:51:29 +02:00
ekzyis
d5723e7e17 Fix parse error on trailing spaces 2024-10-21 15:33:56 +00:00
ec8384f282 Fetch me from API + low balance warnings 2024-10-19 19:48:41 +02:00
e7498352b8 Use lightningvolt.ttf for coordinates 2024-10-19 19:01:29 +02:00
da5f67df46 Respond with e5 if initial move was given else e4 2024-10-18 23:15:51 +02:00
8347bf0cbc Highlight last move 2024-10-18 22:24:41 +02:00
7a5b044b9d Add info to game starts 2024-10-18 21:38:36 +02:00
392cf19ae6 Parse checkmates but don't verify 2024-10-16 20:18:42 +02:00
c1ad076828 Move error handling into own function 2024-10-16 19:55:26 +02:00
b6991ce3e5 Ignore nested replies 2024-10-16 19:51:55 +02:00
2037fb0578 Remove noisy log message 2024-10-16 19:46:50 +02:00
894ad95d73 Move logic into alreadyHandled function 2024-10-16 19:46:50 +02:00
bd24198b05 Move logic into isRecent function 2024-10-16 19:46:50 +02:00
ca2ccc569d Fix parse error during game update 2024-10-16 05:21:24 +02:00
0a877f9f27 Fix API key env var 2024-10-16 05:06:55 +02:00
58b1eabadf Fix EntityTooSmall error from S3 2024-10-16 04:59:57 +02:00
60b4739ac3 Fix empty algebraic notation returned 2024-10-16 03:34:48 +02:00
e414728965 Consistent logging 2024-10-16 03:30:18 +02:00
eb82b89571 Ignore old notifications 2024-10-16 03:28:39 +02:00
a346a849db Use meId from prod 2024-10-16 03:16:41 +02:00
506cb7f6f1 Fix error message 2024-10-16 03:13:55 +02:00
dbf10e6980 Fix image uploads with snappy v0.6.1 2024-10-16 03:09:24 +02:00
cec8aaf274 Ignore known parents 2024-09-26 19:54:38 +02:00
12 changed files with 256 additions and 58 deletions

View File

@ -1,3 +1,3 @@
SN_BASE_URL=
SN_API_TOKEN=
SN_API_KEY=
SN_MEDIA_URL=

1
.gitignore vendored
View File

@ -2,3 +2,4 @@
!assets/*.png
.env
*.sqlite3
chessbot

13
Makefile Normal file
View File

@ -0,0 +1,13 @@
.PHONY: build test
SOURCES := main.go $(shell find chess -name '*.go')
build: chessbot
chessbot: $(SOURCES)
go build -o chessbot .
test:
## -count=1 is used to disable cache
## use -run <regexp> to only run tests that match <regexp>
go test ./chess -v -count=1

View File

@ -12,13 +12,19 @@ import (
"golang.org/x/image/font"
"golang.org/x/image/font/basicfont"
"golang.org/x/image/font/opentype"
"golang.org/x/image/math/fixed"
)
type Board struct {
tiles [8][8]*Piece
turn Color
Moves []string
tiles [8][8]*Piece
turn Color
Moves []string
moveIndicators []Tile
}
type Tile struct {
X, Y int
}
func NewBoard() *Board {
@ -101,7 +107,7 @@ func (b *Board) Image() *image.RGBA {
x := xi * 128
y := yi * 128
rect = image.Rect(x, y, x+128, y+128)
bg = image.NewUniform(getTileColor(xi, yi))
bg = image.NewUniform(getTileColor(b, xi, yi))
draw.Draw(img, rect, bg, p, draw.Src)
piece = b.tiles[xi][yi]
@ -186,17 +192,23 @@ func drawCoordinate(img *image.RGBA, x, y int, flipped bool) {
}
drawString := func(s string, origin fixed.Point26_6) {
color := getTileColor(x, y)
color := getTileColor(nil, x, y)
if !flipped && color == Light {
color = Dark
} else if !flipped {
color = Light
}
// TODO: use SN font and make it bold
face, err := loadFontFace("lightningvolt.ttf")
if err != nil {
log.Printf("error loading font: %v\n", err)
face = basicfont.Face7x13
}
d := &font.Drawer{
Dst: img,
Src: image.NewUniform(color),
Face: basicfont.Face7x13,
Face: face,
Dot: origin,
}
d.DrawString(s)
@ -209,11 +221,36 @@ func drawCoordinate(img *image.RGBA, x, y int, flipped bool) {
}
if row != "" {
origin = fixed.P((x+1)*128-12, y*128+15)
origin = fixed.P((x+1)*128-20, y*128+23)
drawString(row, origin)
}
}
func loadFontFace(path string) (font.Face, error) {
fontBytes, err := os.ReadFile(path)
if err != nil {
return nil, err
}
ttfFont, err := opentype.Parse(fontBytes)
if err != nil {
return nil, err
}
faceOptions := &opentype.FaceOptions{
Size: 32,
DPI: 72,
Hinting: font.HintingNone,
}
fontFace, err := opentype.NewFace(ttfFont, faceOptions)
if err != nil {
return nil, err
}
return fontFace, nil
}
func (b *Board) SetPiece(name PieceName, color Color, position string) error {
var (
piece *Piece
@ -240,6 +277,10 @@ func (b *Board) SetPiece(name PieceName, color Color, position string) error {
}
func (b *Board) AlgebraicNotation() string {
if len(b.Moves) == 0 {
return ""
}
var text string
for i, m := range b.Moves {
if i%2 == 0 {
@ -356,7 +397,7 @@ func (b *Board) Move(move string) error {
}
// make sure the move is marked as a check if it was
if b.InCheck() && !strings.HasSuffix(move, "+") {
if b.InCheck() && !strings.HasSuffix(move, "+") && !strings.HasSuffix(move, "#") {
move += "+"
}
@ -375,6 +416,7 @@ func parseMove(move string) (string, int, int, string, error) {
)
move = strings.TrimSuffix(move, "+")
move = strings.TrimSuffix(move, "#")
if move == "O-O" {
return "K", 5, 7, "g1", nil
@ -797,6 +839,7 @@ func (b *Board) movePawn(position string, fromX int, fromY int, promotion string
if promotion != "" {
return b.promotePawn(toX, toY, promotion)
}
b.moveIndicators = []Tile{{fromX, fromY}, {toX, toY}}
return nil
}
@ -819,6 +862,7 @@ func (b *Board) movePawn(position string, fromX int, fromY int, promotion string
if promotion != "" {
return b.promotePawn(toX, toY, promotion)
}
b.moveIndicators = []Tile{{toX, yPrev}, {toX, toY}}
return nil
}
@ -835,6 +879,7 @@ func (b *Board) movePawn(position string, fromX int, fromY int, promotion string
if promotion != "" {
return b.promotePawn(toX, toY, promotion)
}
b.moveIndicators = []Tile{{toX, yPrev}, {toX, toY}}
return nil
}
@ -944,6 +989,7 @@ func (b *Board) moveRook(position string, queen bool, fromX int, fromY int) erro
p = b.getPiece(xPrev, yPrev)
b.tiles[x][y] = p
b.tiles[xPrev][yPrev] = nil
b.moveIndicators = []Tile{{xPrev, yPrev}, {x, y}}
return nil
}
@ -974,6 +1020,7 @@ func (b *Board) moveBishop(position string, queen bool) error {
if ((!queen && piece.Name == Bishop) || (queen && piece.Name == Queen)) && piece.Color == b.turn {
b.tiles[xPrev][yPrev] = nil
b.tiles[x][y] = piece
b.moveIndicators = []Tile{{xPrev, yPrev}, {x, y}}
return nil
} else {
// direction blocked by other piece
@ -992,6 +1039,7 @@ func (b *Board) moveBishop(position string, queen bool) error {
if ((!queen && piece.Name == Bishop) || (queen && piece.Name == Queen)) && piece.Color == b.turn {
b.tiles[xPrev][yPrev] = nil
b.tiles[x][y] = piece
b.moveIndicators = []Tile{{xPrev, yPrev}, {x, y}}
return nil
} else {
break
@ -1009,6 +1057,7 @@ func (b *Board) moveBishop(position string, queen bool) error {
if ((!queen && piece.Name == Bishop) || (queen && piece.Name == Queen)) && piece.Color == b.turn {
b.tiles[xPrev][yPrev] = nil
b.tiles[x][y] = piece
b.moveIndicators = []Tile{{xPrev, yPrev}, {x, y}}
return nil
} else {
break
@ -1026,6 +1075,7 @@ func (b *Board) moveBishop(position string, queen bool) error {
if ((!queen && piece.Name == Bishop) || (queen && piece.Name == Queen)) && piece.Color == b.turn {
b.tiles[xPrev][yPrev] = nil
b.tiles[x][y] = piece
b.moveIndicators = []Tile{{xPrev, yPrev}, {x, y}}
return nil
} else {
break
@ -1119,6 +1169,7 @@ func (b *Board) moveKnight(position string, fromX int, fromY int) error {
p = b.getPiece(xPrev, yPrev)
b.tiles[x][y] = p
b.tiles[xPrev][yPrev] = nil
b.moveIndicators = []Tile{{xPrev, yPrev}, {x, y}}
return nil
}
@ -1190,6 +1241,8 @@ func (b *Board) moveKing(position string, castle bool) error {
b.tiles[5][y] = rook
b.tiles[7][y] = nil
b.moveIndicators = []Tile{{4, y}, {x, y}, {5, y}, {7, y}}
return nil
}
@ -1223,6 +1276,8 @@ func (b *Board) moveKing(position string, castle bool) error {
b.tiles[3][y] = rook
b.tiles[0][y] = nil
b.moveIndicators = []Tile{{2, y}, {4, y}, {3, y}, {0, y}}
return nil
}
}
@ -1234,6 +1289,7 @@ func (b *Board) moveKing(position string, castle bool) error {
if piece != nil && piece.Name == King && piece.Color == b.turn {
b.tiles[xPrev][yPrev] = nil
b.tiles[x][y] = piece
b.moveIndicators = []Tile{{xPrev, yPrev}, {x, y}}
return nil
}
@ -1244,6 +1300,7 @@ func (b *Board) moveKing(position string, castle bool) error {
if piece != nil && piece.Name == King && piece.Color == b.turn {
b.tiles[xPrev][yPrev] = nil
b.tiles[x][y] = piece
b.moveIndicators = []Tile{{xPrev, yPrev}, {x, y}}
return nil
}
@ -1254,6 +1311,7 @@ func (b *Board) moveKing(position string, castle bool) error {
if piece != nil && piece.Name == King && piece.Color == b.turn {
b.tiles[xPrev][yPrev] = nil
b.tiles[x][y] = piece
b.moveIndicators = []Tile{{xPrev, yPrev}, {x, y}}
return nil
}
@ -1264,6 +1322,7 @@ func (b *Board) moveKing(position string, castle bool) error {
if piece != nil && piece.Name == King && piece.Color == b.turn {
b.tiles[xPrev][yPrev] = nil
b.tiles[x][y] = piece
b.moveIndicators = []Tile{{xPrev, yPrev}, {x, y}}
return nil
}
@ -1274,6 +1333,7 @@ func (b *Board) moveKing(position string, castle bool) error {
if piece != nil && piece.Name == King && piece.Color == b.turn {
b.tiles[xPrev][yPrev] = nil
b.tiles[x][y] = piece
b.moveIndicators = []Tile{{xPrev, yPrev}, {x, y}}
return nil
}
@ -1284,6 +1344,7 @@ func (b *Board) moveKing(position string, castle bool) error {
if piece != nil && piece.Name == King && piece.Color == b.turn {
b.tiles[xPrev][yPrev] = nil
b.tiles[x][y] = piece
b.moveIndicators = []Tile{{xPrev, yPrev}, {x, y}}
return nil
}
@ -1294,6 +1355,7 @@ func (b *Board) moveKing(position string, castle bool) error {
if piece != nil && piece.Name == King && piece.Color == b.turn {
b.tiles[xPrev][yPrev] = nil
b.tiles[x][y] = piece
b.moveIndicators = []Tile{{xPrev, yPrev}, {x, y}}
return nil
}
@ -1304,6 +1366,7 @@ func (b *Board) moveKing(position string, castle bool) error {
if piece != nil && piece.Name == King && piece.Color == b.turn {
b.tiles[xPrev][yPrev] = nil
b.tiles[x][y] = piece
b.moveIndicators = []Tile{{xPrev, yPrev}, {x, y}}
return nil
}
@ -1388,8 +1451,25 @@ func (b *Board) getCollision(position string) (*Piece, error) {
return nil, nil
}
func getTileColor(x, y int) Color {
if x%2 == y%2 {
func getTileColor(b *Board, x, y int) Color {
lightTile := x%2 == y%2
if b != nil {
// highlight move
// TODO: refactor using alpha channels
for _, t := range b.moveIndicators {
if t.X == x && t.Y == y {
if lightTile {
return LightGreen
} else {
return DarkGreen
}
}
}
}
if lightTile {
return Light
} else {
return Dark

View File

@ -472,6 +472,22 @@ func TestBoardCheck(t *testing.T) {
assertParse(t, b, "Kxf7")
}
func TestBoardCheckmate(t *testing.T) {
t.Parallel()
b := chess.NewBoard()
assert.False(t, b.InCheck())
// fool's mate
assertParse(t, b, "f3 e6 g4 Qh4#")
assert.True(t, b.InCheck())
assert.True(t, strings.HasSuffix(b.Moves[len(b.Moves)-1], "#"), "checkmate move should end with #")
assertMoveError(t, b, "a3", "invalid move a3: king is in check")
}
func TestBoardPin(t *testing.T) {
t.Parallel()

View File

@ -58,8 +58,10 @@ const (
type Color color.Color
var (
Light Color = color.RGBA{240, 217, 181, 255}
Dark Color = color.RGBA{181, 136, 99, 255}
Light Color = color.RGBA{240, 217, 181, 255}
Dark Color = color.RGBA{181, 136, 99, 255}
LightGreen Color = color.RGBA{205, 210, 106, 255}
DarkGreen Color = color.RGBA{170, 162, 58, 255}
)
func NewPiece(name PieceName, color Color) (*Piece, error) {

View File

@ -53,6 +53,15 @@ func ItemHasReply(parentId int, userId int) (bool, error) {
return true, err
}
if count > 0 {
return true, nil
}
// check if parent already exists, this means we ignored it
if err = db.QueryRow(`SELECT COUNT(1) FROM items WHERE id = ?`, parentId).Scan(&count); err != nil {
return true, err
}
return count > 0, nil
}

3
go.mod
View File

@ -3,7 +3,7 @@ module github.com/ekzyis/chessbot
go 1.23.0
require (
github.com/ekzyis/snappy v0.5.5-0.20240923014110-b880c1256e13
github.com/ekzyis/snappy v0.7.0
github.com/mattn/go-sqlite3 v1.14.23
github.com/stretchr/testify v1.9.0
golang.org/x/image v0.20.0
@ -12,6 +12,7 @@ require (
require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
golang.org/x/text v0.18.0 // indirect
gopkg.in/guregu/null.v4 v4.0.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

6
go.sum
View File

@ -1,7 +1,7 @@
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/ekzyis/snappy v0.5.5-0.20240923014110-b880c1256e13 h1:yxDqMo4HzCVzhxPNTBpST0KVVHVMwGouzwfXsb4WYw4=
github.com/ekzyis/snappy v0.5.5-0.20240923014110-b880c1256e13/go.mod h1:UksYI0dU0+cnzz0LQjWB1P0QQP/ghx47e4atP99a5Lk=
github.com/ekzyis/snappy v0.7.0 h1:RcFTUHdZFTBFOnh6cG9HCL/RPK6L13qdxDrjBNZFjEM=
github.com/ekzyis/snappy v0.7.0/go.mod h1:UksYI0dU0+cnzz0LQjWB1P0QQP/ghx47e4atP99a5Lk=
github.com/mattn/go-sqlite3 v1.14.23 h1:gbShiuAP1W5j9UOksQ06aiiqPMxYecovVGwmTxWtuw0=
github.com/mattn/go-sqlite3 v1.14.23/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
@ -10,6 +10,8 @@ github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsT
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
golang.org/x/image v0.20.0 h1:7cVCUjQwfL18gyBJOmYvptfSHS8Fb3YUDtfLIZ7Nbpw=
golang.org/x/image v0.20.0/go.mod h1:0a88To4CYVBAHp5FXJm8o7QbUl37Vd85ply1vyD8auM=
golang.org/x/text v0.18.0 h1:XvMDiNzPAl0jr17s6W9lcaIhGUfUORdGCNsuLmPG224=
golang.org/x/text v0.18.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/guregu/null.v4 v4.0.0 h1:1Wm3S1WEA2I26Kq+6vcW+w0gcDo44YKYD7YIEJNHDjg=

BIN
lightningvolt.ttf Normal file

Binary file not shown.

155
main.go
View File

@ -14,20 +14,54 @@ import (
)
var (
c = sn.GetClient()
// TODO: fetch our id from SN API
meId = 21858
c = sn.GetClient()
me *sn.User
)
func main() {
for {
updateMe()
tickGameStart(c)
tickGameProgress(c)
time.Sleep(15 * time.Second)
}
}
func updateMe() {
var (
oldMe *sn.User
err error
warnThreshold = 100
)
maybeWarn := func() {
if me.Privates.Sats < warnThreshold {
log.Printf("~~~ warning: low balance ~~~\n")
}
}
if me == nil {
// make sure first update is successful
if me, err = c.Me(); err != nil {
log.Fatalf("failed to fetch me: %v\n", err)
}
log.Printf("fetched me: id=%d name=%s balance=%d\n", me.Id, me.Name, me.Privates.Sats)
maybeWarn()
return
}
oldMe = me
if me, err = c.Me(); err != nil {
log.Printf("failed to update me: %v\n", err)
me = oldMe
} else {
log.Printf("updated me. balance: %d\n", me.Privates.Sats)
}
maybeWarn()
}
func tickGameStart(c *sn.Client) {
var (
mentions []sn.Notification
@ -39,33 +73,26 @@ func tickGameStart(c *sn.Client) {
return
}
log.Printf("fetched %d mention(s)\n", len(mentions))
log.Printf("fetched %d mentions\n", len(mentions))
for _, n := range mentions {
if exists, err := db.ItemHasReply(n.Item.Id, meId); err != nil {
if !isRecent(n.Item.CreatedAt) {
log.Printf("ignoring old mention %d\n", n.Item.Id)
continue
}
if handled, err := alreadyHandled(n.Item.Id); err != nil {
log.Printf("failed to check for existing reply to game start in item %d: %v\n", n.Item.Id, err)
continue
} else if exists {
} else if handled {
// TODO: check if move changed
log.Printf("reply to game start in item %d already exists\n", n.Item.Id)
continue
}
if err = handleGameStart(&n.Item); err != nil {
// don't reply to mentions that we failed to parse as a game start
// to support unrelated mentions
if err.Error() == "failed to parse game start" {
log.Printf("ignoring error for item %d: %v\n", n.Item.Id, err)
return
}
if _, err2 := createComment(n.Item.Id, fmt.Sprintf("`%v`", err)); err2 != nil {
log.Printf("failed to reply with error to item %d: %v\n", n.Item.Id, err2)
} else {
log.Printf("replied to game start in item %d with error: %v\n", n.Item.Id, err)
}
handleError(&n.Item, err)
} else {
log.Printf("started new game via item %d\n", n.Item.Id)
}
@ -87,27 +114,30 @@ func tickGameProgress(c *sn.Client) {
for _, n := range replies {
if exists, err := db.ItemHasReply(n.Item.Id, meId); err != nil {
if !isRecent(n.Item.CreatedAt) {
log.Printf("ignoring old reply %d\n", n.Item.Id)
continue
}
if handled, err := alreadyHandled(n.Item.Id); err != nil {
log.Printf("failed to check for existing reply to game update in item %d: %v\n", n.Item.Id, err)
continue
} else if exists {
} else if handled {
// TODO: check if move changed
log.Printf("reply to game update in item %d already exists\n", n.Item.Id)
continue
}
if parent, err := c.Item(n.Item.ParentId); err != nil {
log.Printf("failed to fetch parent %d of %d\n", n.Item.ParentId, n.Item.Id)
continue
} else if parent.User.Id != me.Id {
log.Printf("ignoring nested reply %d\n", n.Item.Id)
continue
}
if err = handleGameProgress(&n.Item); err != nil {
if err.Error() == "failed to parse game update" {
log.Printf("ignoring error for item %d: %v\n", n.Item.Id, err)
return
}
if _, err2 := createComment(n.Item.Id, fmt.Sprintf("`%v`", err)); err2 != nil {
log.Printf("failed to reply with error to item %d: %v\n", n.Item.Id, err2)
} else {
log.Printf("replied to game start in item %d with error: %v\n", n.Item.Id, err)
}
handleError(&n.Item, err)
} else {
log.Printf("updated game via item %d\n", n.Item.Id)
}
@ -149,8 +179,15 @@ func handleGameStart(req *sn.Item) error {
return fmt.Errorf("failed to upload image for item %d: %v\n", req.Id, err)
}
// reply with algebraic notation and image
res = strings.Trim(fmt.Sprintf("%s\n\n%s", b.AlgebraicNotation(), imgUrl), " ")
// reply with algebraic notation, image and info
infoMove := "e4"
if len(b.Moves) > 0 {
infoMove = "e5"
}
info := fmt.Sprintf("_A new chess game has been started!_\n\n"+
"_Reply with a move like `%s` to continue the game. "+
"See [here](https://stacker.news/chess#how-to-continue) for details._", infoMove)
res = strings.Trim(fmt.Sprintf("%s\n\n%s\n\n%s", b.AlgebraicNotation(), imgUrl, info), " ")
if _, err = createComment(req.Id, res); err != nil {
return fmt.Errorf("failed to reply to item %d: %v\n", req.Id, err)
}
@ -179,7 +216,7 @@ func handleGameProgress(req *sn.Item) error {
}
for _, item := range thread {
if item.User.Id == meId {
if item.User.Id == me.Id {
continue
}
@ -222,6 +259,27 @@ func handleGameProgress(req *sn.Item) error {
return nil
}
func handleError(req *sn.Item, err error) {
// don't reply to mentions that we failed to parse as a game start
// to support unrelated mentions
if err.Error() == "failed to parse game start" {
log.Printf("ignoring error for item %d: %v\n", req.Id, err)
return
}
if err.Error() == "failed to parse game update" {
log.Printf("ignoring error for item %d: %v\n", req.Id, err)
return
}
if _, err2 := createComment(req.Id, fmt.Sprintf("`%v`", err)); err2 != nil {
log.Printf("failed to reply with error to item %d: %v\n", req.Id, err2)
} else {
log.Printf("replied to game start in item %d with error: %v\n", req.Id, err)
}
}
func createComment(parentId int, text string) (*sn.Item, error) {
var (
commentId int
@ -238,7 +296,7 @@ func createComment(parentId int, text string) (*sn.Item, error) {
}
if err = db.InsertItem(comment); err != nil {
return nil, fmt.Errorf("failed to insert item %d into db: %v\n", err, comment.Id)
return nil, fmt.Errorf("failed to insert item %d into db: %v\n", comment.Id, err)
}
return comment, nil
@ -248,31 +306,46 @@ func parseGameStart(input string) (string, error) {
for _, line := range strings.Split(input, "\n") {
line = strings.Trim(line, " ")
if !strings.HasPrefix(line, "@chess") {
var found bool
if line, found = strings.CutPrefix(line, "@chess"); !found {
continue
}
return strings.Trim(strings.ReplaceAll(line, "@chess", ""), " "), nil
return strings.Trim(line, " "), nil
}
return "", errors.New("failed to parse game start")
}
func parseGameProgress(input string) (string, error) {
input = strings.Trim(input, " ")
lines := strings.Split(input, "\n")
words := strings.Split(input, " ")
if len(lines) == 1 && len(words) == 1 {
return strings.Trim(input, " "), nil
return strings.Trim(strings.ReplaceAll(input, "@chess", ""), " "), nil
}
for _, line := range strings.Split(input, "\n") {
if !strings.Contains(line, "@chess") {
line = strings.Trim(line, " ")
var found bool
if line, found = strings.CutPrefix(line, "@chess"); !found {
continue
}
return strings.Trim(strings.ReplaceAll(line, "@chess", ""), " "), nil
return strings.Trim(line, " "), nil
}
return "", errors.New("failed to parse game update")
}
func isRecent(t time.Time) bool {
x := time.Now().Add(-30 * time.Second)
return t.After(x)
}
func alreadyHandled(id int) (bool, error) {
return db.ItemHasReply(id, me.Id)
}

View File

@ -13,6 +13,7 @@ import (
type Client = snappy.Client
type Notification = snappy.Notification
type Item = snappy.Item
type User = snappy.User
var (
c *Client