Compare commits

...

5 Commits

Author SHA1 Message Date
vaalacat
80cae65b98 fix: unbind
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/promote/production Build is passing
2024-04-28 03:53:12 +00:00
vaalacat
e39db56969 feat: upgrade mod
All checks were successful
continuous-integration/drone/push Build is passing
2024-04-23 12:31:18 +00:00
vaalacat
75944abbc2 feat: gateway
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/promote/production Build is passing
2024-04-23 11:18:16 +00:00
Vaala Cat
a42fecfc63 feat: drone ci
All checks were successful
continuous-integration/drone Build is passing
2023-12-06 21:47:12 +08:00
Vaala Cat
511c96c57e feat: upgrade to new version go-mc 2023-12-06 21:40:12 +08:00
21 changed files with 623 additions and 198 deletions

126
.drone.yml Normal file
View File

@@ -0,0 +1,126 @@
kind: pipeline
name: build-and-publish
steps:
- name: download modules
image: git.vaala.cloud/vaalacat/golang:1.20.0-alpine3.17
commands:
- sed -i 's/dl-cdn.alpinelinux.org/mirrors.tuna.tsinghua.edu.cn/g' /etc/apk/repositories
- apk update --no-cache && apk add --no-cache tzdata git
- GOPRIVATE=git.vaala.cloud CGO_ENABLED=0 GOPROXY=https://goproxy.cn,https://proxy.golang.org,direct go mod download
- mkdir -p etc
- cp /etc/ssl/certs/ca-certificates.crt ./etc/ca-certificates.crt
- cp /usr/share/zoneinfo/Asia/Shanghai ./etc/Shanghai
volumes:
- name: gocache
path: /go/pkg/mod
- name: build
path: /tmp/app
when:
event:
- pull_request
- promote
- rollback
- name: build - amd64
image: git.vaala.cloud/vaalacat/golang:1.20.0-alpine3.17
commands:
- GOOS=linux GOARCH=amd64 GOPRIVATE=git.vaala.cloud CGO_ENABLED=0 GOPROXY=https://goproxy.cn,https://proxy.golang.org,direct go build -ldflags="-s -w" -o mcbot-amd64 main.go
volumes:
- name: gocache
path: /go/pkg/mod
- name: build
path: /tmp/app
depends_on:
- download modules
when:
event:
- pull_request
- promote
- rollback
- name: build - arm64
image: git.vaala.cloud/vaalacat/golang:1.20.0-alpine3.17
commands:
- GOOS=linux GOARCH=arm64 GOPRIVATE=git.vaala.cloud CGO_ENABLED=0 GOPROXY=https://goproxy.cn,https://proxy.golang.org,direct go build -ldflags="-s -w" -o mcbot-arm64 main.go
volumes:
- name: gocache
path: /go/pkg/mod
- name: build
path: /tmp/app
depends_on:
- download modules
when:
event:
- pull_request
- promote
- rollback
- name: publish - amd64
image: git.vaala.cloud/vaalacat/drone-docker-buildx:24
privileged: true
environment:
HTTP_PROXY:
from_secret: HTTP_PROXY
HTTPS_PROXY:
from_secret: HTTP_PROXY
settings:
mirror: https://docker.lab.vaala.tech
debug: true
platforms:
- linux/amd64
build_args:
- ARCH=amd64
repo: git.vaala.cloud/vaalacat/mcbot
tags:
- amd64
registry:
from_secret: docker_registry
username:
from_secret: docker_username
password:
from_secret: docker_password
depends_on:
- build - amd64
when:
event:
- promote
- rollback
target:
- production
- name: publish - arm64
image: git.vaala.cloud/vaalacat/drone-docker-buildx:24
privileged: true
environment:
HTTP_PROXY:
from_secret: HTTP_PROXY
HTTPS_PROXY:
from_secret: HTTP_PROXY
settings:
mirror: https://docker.lab.vaala.tech
debug: true
platforms:
- linux/arm64
build_args:
- ARCH=arm64
repo: git.vaala.cloud/vaalacat/mcbot
tags:
- arm64
registry:
from_secret: docker_registry
username:
from_secret: docker_username
password:
from_secret: docker_password
depends_on:
- build - arm64
when:
event:
- promote
- rollback
target:
- production
volumes:
- name: build
temp: {}
- name: gocache
host:
path: /tmp/drone/mcbot/gocache

3
.gitignore vendored
View File

@@ -2,3 +2,6 @@
run.sh run.sh
mcbot mcbot
*.sqlite *.sqlite
tmp
tg-mc.db

View File

@@ -1,12 +1,11 @@
FROM git.vaala.cloud/vaalacat/golang:1.20 AS builder
# WORKDIR $GOPATH/src/mcbot
# COPY . .
# RUN mkdir /app && \
# CGO_ENABLED=0 GOPROXY=https://goproxy.cn,direct go build -o mcbot main.go && \
# cp mcbot /app/
FROM git.vaala.cloud/vaalacat/alpine FROM git.vaala.cloud/vaalacat/alpine
# COPY --from=builder /app/mcbot /app/mcbot
COPY mcbot /app/mcbot ARG ARCH
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.tuna.tsinghua.edu.cn/g' /etc/apk/repositories && \
apk update --no-cache && apk --no-cache add curl
WORKDIR /app
COPY mcbot-${ARCH} /app/mcbot
ENTRYPOINT [ "/app/mcbot" ] ENTRYPOINT [ "/app/mcbot" ]

View File

@@ -1,6 +1,8 @@
package conf package conf
import ( import (
"log"
"github.com/ilyakaznacheev/cleanenv" "github.com/ilyakaznacheev/cleanenv"
"github.com/joho/godotenv" "github.com/joho/godotenv"
) )
@@ -11,9 +13,20 @@ type botSettings struct {
MCServer string `env:"MC_SERVER"` MCServer string `env:"MC_SERVER"`
MCBotName string `env:"MC_BOT_NAME"` MCBotName string `env:"MC_BOT_NAME"`
GroupID int64 `env:"GROUP_ID"` GroupID int64 `env:"GROUP_ID"`
DBPath string `env:"DB_PATH"` DBPath string `env:"DB_PATH" env-default:"tg-mc.db"`
BotAPI string `env:"TG_BOT_API"` BotAPI string `env:"TG_BOT_API"`
AdminID []int64 `env:"ADMIN_ID"` AdminID []int64 `env:"ADMIN_ID"`
GatewaySettings GatewaySettings `env-prefix:"GATEWAY_"`
EnableGateway bool `env:"ENABLE_GATEWAY" env-default:"true"`
EnableBridge bool `env:"ENABLE_BRIDGE" env-default:"true"`
EnableBot bool `env:"ENABLE_BOT" env-default:"true"`
}
type GatewaySettings struct {
ServerHost string `json:"server_host" env:"MC_SERVER_HOST" env-default:"127.0.0.1"`
ServerPort int `json:"server_port" env:"MC_SERVER_PORT" env-default:"25566"`
ProxyHost string `json:"proxy_host" env:"PROXY_HOST" env-default:"127.0.0.1"`
ProxyPort int `json:"proxy_port" env:"PROXY_PORT" env-default:"25565"`
} }
var ( var (
@@ -23,6 +36,7 @@ var (
func init() { func init() {
godotenv.Load() godotenv.Load()
cleanenv.ReadEnv(&botSettingsInstance) cleanenv.ReadEnv(&botSettingsInstance)
log.Printf("Bot settings: %+v", botSettingsInstance)
} }
func GetBotSettings() *botSettings { func GetBotSettings() *botSettings {

4
go.mod
View File

@@ -3,7 +3,7 @@ module tg-mc
go 1.20 go 1.20
require ( require (
github.com/Tnze/go-mc v1.19.4 github.com/Tnze/go-mc v1.20.2-0.20231123224931-bc3d77d78437
github.com/glebarez/sqlite v1.9.0 github.com/glebarez/sqlite v1.9.0
github.com/go-co-op/gocron v1.32.1 github.com/go-co-op/gocron v1.32.1
github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1 github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1
@@ -35,4 +35,4 @@ require (
olympos.io/encoding/edn v0.0.0-20201019073823-d3554ca0b0a3 // indirect olympos.io/encoding/edn v0.0.0-20201019073823-d3554ca0b0a3 // indirect
) )
replace github.com/Tnze/go-mc => /Users/vaala/Workdir/Code/go-mc // replace github.com/Tnze/go-mc => /home/coder/go-mc

38
go.sum
View File

@@ -1,45 +1,32 @@
github.com/BurntSushi/toml v1.1.0/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ=
github.com/BurntSushi/toml v1.2.1/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= github.com/BurntSushi/toml v1.2.1/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ=
github.com/BurntSushi/toml v1.3.2 h1:o7IhLm0Msx3BaB+n3Ag7L8EVlByGnpq14C4YWiu/gL8= github.com/BurntSushi/toml v1.3.2 h1:o7IhLm0Msx3BaB+n3Ag7L8EVlByGnpq14C4YWiu/gL8=
github.com/BurntSushi/toml v1.3.2/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= github.com/BurntSushi/toml v1.3.2/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ=
github.com/Tnze/go-mc v1.19.4-pre1 h1:0yBCeK9EGICdIzxSPbvD88HqcNRho8PRgKtpAC02W0E= github.com/Tnze/go-mc v1.20.2-0.20231123224931-bc3d77d78437 h1:cINogPegf6TCIEmAon1kyVuKJttjoM0H7kyIM5WXre4=
github.com/Tnze/go-mc v1.19.4-pre1/go.mod h1:c1znJQglgqa1Jjs3Dr29woN/msguiJrlNtWXhKedh2U= github.com/Tnze/go-mc v1.20.2-0.20231123224931-bc3d77d78437/go.mod h1:geoRj2HsXSkB3FJBuhr7wCzXegRlzWsVXd7h7jiJ6aQ=
github.com/Tnze/go-mc v1.19.4 h1:9qtxH+xRJWswOYnlf/dsFY4EI2f5jsFhtqTYOObaGIE=
github.com/Tnze/go-mc v1.19.4/go.mod h1:c1znJQglgqa1Jjs3Dr29woN/msguiJrlNtWXhKedh2U=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 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/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/glebarez/go-sqlite v1.21.1 h1:7MZyUPh2XTrHS7xNEHQbrhfMZuPSzhkm2A1qgg0y5NY=
github.com/glebarez/go-sqlite v1.21.1/go.mod h1:ISs8MF6yk5cL4n/43rSOmVMGJJjHYr7L2MbZZ5Q4E2E=
github.com/glebarez/go-sqlite v1.21.2 h1:3a6LFC4sKahUunAmynQKLZceZCOzUthkRkEAl9gAXWo= github.com/glebarez/go-sqlite v1.21.2 h1:3a6LFC4sKahUunAmynQKLZceZCOzUthkRkEAl9gAXWo=
github.com/glebarez/go-sqlite v1.21.2/go.mod h1:sfxdZyhQjTM2Wry3gVYWaW072Ri1WMdWJi0k6+3382k= github.com/glebarez/go-sqlite v1.21.2/go.mod h1:sfxdZyhQjTM2Wry3gVYWaW072Ri1WMdWJi0k6+3382k=
github.com/glebarez/sqlite v1.8.0 h1:02X12E2I/4C1n+v90yTqrjRa8yuo7c3KeHI3FRznCvc=
github.com/glebarez/sqlite v1.8.0/go.mod h1:bpET16h1za2KOOMb8+jCp6UBP/iahDpfPQqSaYLTLx8=
github.com/glebarez/sqlite v1.9.0 h1:Aj6bPA12ZEx5GbSF6XADmCkYXlljPNUY+Zf1EQxynXs= github.com/glebarez/sqlite v1.9.0 h1:Aj6bPA12ZEx5GbSF6XADmCkYXlljPNUY+Zf1EQxynXs=
github.com/glebarez/sqlite v1.9.0/go.mod h1:YBYCoyupOao60lzp1MVBLEjZfgkq0tdB1voAQ09K9zw= github.com/glebarez/sqlite v1.9.0/go.mod h1:YBYCoyupOao60lzp1MVBLEjZfgkq0tdB1voAQ09K9zw=
github.com/go-co-op/gocron v1.28.3 h1:swTsge6u/1Ei51b9VLMz/YTzEzWpbsk5SiR7m5fklTI=
github.com/go-co-op/gocron v1.28.3/go.mod h1:39f6KNSGVOU1LO/ZOoZfcSxwlsJDQOKSu8erN0SH48Y=
github.com/go-co-op/gocron v1.32.1 h1:h+StA6Qzlv+ImlCaLfA26rLN9eS/l4sO7oWmPUbRVIY= github.com/go-co-op/gocron v1.32.1 h1:h+StA6Qzlv+ImlCaLfA26rLN9eS/l4sO7oWmPUbRVIY=
github.com/go-co-op/gocron v1.32.1/go.mod h1:UGz2oYvVS6PsqlwuOdo5L1Djsg/cQjxJ6T5ntkhp9Bg= github.com/go-co-op/gocron v1.32.1/go.mod h1:UGz2oYvVS6PsqlwuOdo5L1Djsg/cQjxJ6T5ntkhp9Bg=
github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1 h1:wG8n/XJQ07TmjbITcGiUaOtXxdrINDz1b0J1w0SzqDc= github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1 h1:wG8n/XJQ07TmjbITcGiUaOtXxdrINDz1b0J1w0SzqDc=
github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1/go.mod h1:A2S0CWkNylc2phvKXWBBdD3K0iGnDBGbzRpISP2zBl8= github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1/go.mod h1:A2S0CWkNylc2phvKXWBBdD3K0iGnDBGbzRpISP2zBl8=
github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26 h1:Xim43kblpZXfIBQsbuBVKCudVG457BR2GZFIz3uw3hQ= github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26 h1:Xim43kblpZXfIBQsbuBVKCudVG457BR2GZFIz3uw3hQ=
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/google/uuid v1.3.1 h1:KjJaJ9iWZ3jOFZIf1Lqf4laDRCasjl0BCmnEGxkdLb4= github.com/google/uuid v1.3.1 h1:KjJaJ9iWZ3jOFZIf1Lqf4laDRCasjl0BCmnEGxkdLb4=
github.com/google/uuid v1.3.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.3.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/ilyakaznacheev/cleanenv v1.4.2 h1:nRqiriLMAC7tz7GzjzUTBHfzdzw6SQ7XvTagkFqe/zU=
github.com/ilyakaznacheev/cleanenv v1.4.2/go.mod h1:i0owW+HDxeGKE0/JPREJOdSCPIyOnmh6C0xhWAkF/xA=
github.com/ilyakaznacheev/cleanenv v1.5.0 h1:0VNZXggJE2OYdXE87bfSSwGxeiGt9moSR2lOrsHHvr4= github.com/ilyakaznacheev/cleanenv v1.5.0 h1:0VNZXggJE2OYdXE87bfSSwGxeiGt9moSR2lOrsHHvr4=
github.com/ilyakaznacheev/cleanenv v1.5.0/go.mod h1:a5aDzaJrLCQZsazHol1w8InnDcOX0OColm64SlIi6gk= github.com/ilyakaznacheev/cleanenv v1.5.0/go.mod h1:a5aDzaJrLCQZsazHol1w8InnDcOX0OColm64SlIi6gk=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ= github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/joho/godotenv v1.4.0/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
@@ -50,14 +37,11 @@ github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/mattn/go-isatty v0.0.17 h1:BTarxUcIeDqL27Mc+vyvdWYSL28zpIhv3RoTdsLMPng=
github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA=
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs= github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
@@ -67,8 +51,6 @@ github.com/rogpeppe/go-internal v1.8.1 h1:geMPLpDpQOgVyCg5z5GoRwLHepNdb71NXb67XF
github.com/rogpeppe/go-internal v1.8.1/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o= github.com/rogpeppe/go-internal v1.8.1/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o=
github.com/samber/lo v1.38.1 h1:j2XEAqXKb09Am4ebOg31SpvzUTTs6EN3VfgeLUhPdXM= github.com/samber/lo v1.38.1 h1:j2XEAqXKb09Am4ebOg31SpvzUTTs6EN3VfgeLUhPdXM=
github.com/samber/lo v1.38.1/go.mod h1:+m/ZKRl6ClXCE2Lgf3MsQlWfh4bn1bz6CXEOxnEXnEA= github.com/samber/lo v1.38.1/go.mod h1:+m/ZKRl6ClXCE2Lgf3MsQlWfh4bn1bz6CXEOxnEXnEA=
github.com/sirupsen/logrus v1.9.1 h1:Ou41VVR3nMWWmTiEUnj0OlsgOSCUFgsPAOl6jRIcVtQ=
github.com/sirupsen/logrus v1.9.1/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
@@ -80,18 +62,12 @@ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8= github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8=
github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE=
go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
golang.org/x/exp v0.0.0-20230321023759-10a507213a29 h1:ooxPy7fPvB4kwsA2h+iBNHkAbp/4JxTSwCmvdjEYmug=
golang.org/x/exp v0.0.0-20230321023759-10a507213a29/go.mod h1:CxIveKay+FTh1D0yPZemJVgC/95VzuuOLq5Qi4xnoYc=
golang.org/x/exp v0.0.0-20230817173708-d852ddb80c63 h1:m64FZMko/V45gv0bNmrNYoDEq8U5YUhetc9cBWKS1TQ= golang.org/x/exp v0.0.0-20230817173708-d852ddb80c63 h1:m64FZMko/V45gv0bNmrNYoDEq8U5YUhetc9cBWKS1TQ=
golang.org/x/exp v0.0.0-20230817173708-d852ddb80c63/go.mod h1:0v4NqG35kSWCMzLaMeX+IQrlSnVE/bqGSyC2cz/9Le8= golang.org/x/exp v0.0.0-20230817173708-d852ddb80c63/go.mod h1:0v4NqG35kSWCMzLaMeX+IQrlSnVE/bqGSyC2cz/9Le8=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.4.0 h1:Zr2JFtRQNX3BCZ8YtxRE9hNJYC8J6I1MVbMg6owUp18=
golang.org/x/sys v0.4.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.11.0 h1:eG7RXZHdqOJ1i+0lgLgCpSXAp6M3LYlAo6osgSi0xOM= golang.org/x/sys v0.11.0 h1:eG7RXZHdqOJ1i+0lgLgCpSXAp6M3LYlAo6osgSi0xOM=
golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
@@ -103,24 +79,14 @@ gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/gorm v1.25.1 h1:nsSALe5Pr+cM3V1qwwQ7rOkw+6UeLrX5O4v3llhHa64=
gorm.io/gorm v1.25.1/go.mod h1:L4uxeKpfBml98NYqVqwAdmV1a2nBtAec/cf3fpucW/k=
gorm.io/gorm v1.25.4 h1:iyNd8fNAe8W9dvtlgeRI5zSVZPsq3OpcTu37cYcpCmw= gorm.io/gorm v1.25.4 h1:iyNd8fNAe8W9dvtlgeRI5zSVZPsq3OpcTu37cYcpCmw=
gorm.io/gorm v1.25.4/go.mod h1:L4uxeKpfBml98NYqVqwAdmV1a2nBtAec/cf3fpucW/k= gorm.io/gorm v1.25.4/go.mod h1:L4uxeKpfBml98NYqVqwAdmV1a2nBtAec/cf3fpucW/k=
modernc.org/libc v1.22.3 h1:D/g6O5ftAfavceqlLOFwaZuA5KYafKwmr30A6iSqoyY=
modernc.org/libc v1.22.3/go.mod h1:MQrloYP209xa2zHome2a8HLiLm6k0UT8CoHpV74tOFw=
modernc.org/libc v1.24.1 h1:uvJSeCKL/AgzBo2yYIPPTy82v21KgGnizcGYfBHaNuM= modernc.org/libc v1.24.1 h1:uvJSeCKL/AgzBo2yYIPPTy82v21KgGnizcGYfBHaNuM=
modernc.org/libc v1.24.1/go.mod h1:FmfO1RLrU3MHJfyi9eYYmZBfi/R+tqZ6+hQ3yQQUkak= modernc.org/libc v1.24.1/go.mod h1:FmfO1RLrU3MHJfyi9eYYmZBfi/R+tqZ6+hQ3yQQUkak=
modernc.org/mathutil v1.5.0 h1:rV0Ko/6SfM+8G+yKiyI830l3Wuz1zRutdslNoQ0kfiQ=
modernc.org/mathutil v1.5.0/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E=
modernc.org/mathutil v1.6.0 h1:fRe9+AmYlaej+64JsEEhoWuAYBkOtQiMEU7n/XgfYi4= modernc.org/mathutil v1.6.0 h1:fRe9+AmYlaej+64JsEEhoWuAYBkOtQiMEU7n/XgfYi4=
modernc.org/mathutil v1.6.0/go.mod h1:Ui5Q9q1TR2gFm0AQRqQUaBWFLAhQpCwNcuhBOSedWPo= modernc.org/mathutil v1.6.0/go.mod h1:Ui5Q9q1TR2gFm0AQRqQUaBWFLAhQpCwNcuhBOSedWPo=
modernc.org/memory v1.5.0 h1:N+/8c5rE6EqugZwHii4IFsaJ7MUhoWX07J5tC/iI5Ds=
modernc.org/memory v1.5.0/go.mod h1:PkUhL0Mugw21sHPeskwZW4D6VscE/GQJOnIpCnW6pSU=
modernc.org/memory v1.7.1 h1:9J+2/GKTlV503mk3yv8QJ6oEpRCUrRy0ad8TXEPoV8M= modernc.org/memory v1.7.1 h1:9J+2/GKTlV503mk3yv8QJ6oEpRCUrRy0ad8TXEPoV8M=
modernc.org/memory v1.7.1/go.mod h1:NO4NVCQy0N7ln+T9ngWqOQfi7ley4vpwvARR+Hjw95E= modernc.org/memory v1.7.1/go.mod h1:NO4NVCQy0N7ln+T9ngWqOQfi7ley4vpwvARR+Hjw95E=
modernc.org/sqlite v1.21.1 h1:GyDFqNnESLOhwwDRaHGdp2jKLDzpyT/rNLglX3ZkMSU=
modernc.org/sqlite v1.21.1/go.mod h1:XwQ0wZPIh1iKb5mkvCJ3szzbhk+tykC8ZWqTRTgYRwI=
modernc.org/sqlite v1.25.0 h1:AFweiwPNd/b3BoKnBOfFm+Y260guGMF+0UFk0savqeA= modernc.org/sqlite v1.25.0 h1:AFweiwPNd/b3BoKnBOfFm+Y260guGMF+0UFk0savqeA=
modernc.org/sqlite v1.25.0/go.mod h1:FL3pVXie73rg3Rii6V/u5BoHlSoyeZeIgKZEgHARyCU= modernc.org/sqlite v1.25.0/go.mod h1:FL3pVXie73rg3Rii6V/u5BoHlSoyeZeIgKZEgHARyCU=
olympos.io/encoding/edn v0.0.0-20201019073823-d3554ca0b0a3 h1:slmdOY3vp8a7KQbHkL+FLbvbkgMqmXojpFUO/jENuqQ= olympos.io/encoding/edn v0.0.0-20201019073823-d3554ca0b0a3 h1:slmdOY3vp8a7KQbHkL+FLbvbkgMqmXojpFUO/jENuqQ=

View File

@@ -9,9 +9,9 @@ import (
type User struct { type User struct {
gorm.Model gorm.Model
TGID int64 `gorm:"unique"` TGID int64 `gorm:"column:tgid;NOT NULL;index"`
MCName string MCName string `gorm:"column:mc_name;NOT NULL;unique"`
Status int // 0: pending, 1: normal, 2: banned Status int `gorm:"column:status;NOT NULL"` // 0: pending, 1: normal, 2: banned
} }
func init() { func init() {
@@ -24,6 +24,13 @@ func (u *User) TableName() string {
return "users" return "users"
} }
func GetUsersByTGID(tgID int64) (users []User, err error) {
err = database.GetDB().Where(
&User{TGID: tgID},
).Find(&users).Error
return
}
func GetUserByTGID(tgID int64) (user User, err error) { func GetUserByTGID(tgID int64) (user User, err error) {
err = database.GetDB().Where( err = database.GetDB().Where(
&User{TGID: tgID}, &User{TGID: tgID},

86
services/gateway/auth.go Normal file
View File

@@ -0,0 +1,86 @@
package gateway
import (
"fmt"
"sync"
"tg-mc/conf"
"tg-mc/defs"
"tg-mc/models"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
)
type Auth interface {
IsAuthed(u models.User) bool
RequestAuth(u models.User, req *LoginRequest)
Reject(u models.User)
SetAuth(u models.User)
}
type Authcator struct {
UserMap *sync.Map
}
var authcator *Authcator
func GetAuthcator() Auth {
if authcator == nil {
authcator = &Authcator{
UserMap: &sync.Map{},
}
}
return authcator
}
func (a *Authcator) getUserLoginReq(u models.User) *LoginRequest {
chAny, ok := a.UserMap.Load(u.MCName)
if !ok {
return nil
}
loginReq, ok := chAny.(*LoginRequest)
if !ok {
return nil
}
return loginReq
}
func (a *Authcator) IsAuthed(u models.User) bool {
loginReq := a.getUserLoginReq(u)
if loginReq == nil {
return false
}
return <-loginReq.Resolve
}
func (a *Authcator) RequestAuth(u models.User, req *LoginRequest) {
a.UserMap.Store(u.MCName, req)
m := tgbotapi.NewMessage(u.TGID, fmt.Sprintf("MC用户%v 尝试登录,请选择操作", u.MCName))
m.ReplyMarkup = tgbotapi.NewInlineKeyboardMarkup(
tgbotapi.NewInlineKeyboardRow(
tgbotapi.NewInlineKeyboardButtonData("批准", defs.NewApproveCommand(u.MCName).ToJSON()),
tgbotapi.NewInlineKeyboardButtonData("拒绝", defs.NewRejectCommand(u.MCName).ToJSON())),
)
conf.Bot.Send(m)
}
func (a *Authcator) Reject(u models.User) {
loginReq := a.getUserLoginReq(u)
if loginReq == nil {
return
}
loginReq.Resolve <- false
}
func (a *Authcator) SetAuth(u models.User) {
loginReq := a.getUserLoginReq(u)
if loginReq == nil {
return
}
loginReq.Resolve <- true
}

214
services/gateway/gw.go Normal file
View File

@@ -0,0 +1,214 @@
package gateway
import (
"errors"
"fmt"
"strconv"
"tg-mc/conf"
"tg-mc/models"
"time"
"github.com/Tnze/go-mc/net"
pk "github.com/Tnze/go-mc/net/packet"
"github.com/Tnze/go-mc/offline"
"github.com/google/uuid"
"github.com/sirupsen/logrus"
)
type LoginRequest struct {
ChatID int64
Resolve chan bool
}
func requestVerify(mcid string) (bool, error) {
user, err := models.GetUserByMCName(mcid)
if err != nil {
return false, errors.New("mcid not found in settings")
}
// Send a message to the user to accept or reject using your bot logic
logrus.Infof("Requesting verification for MCID: %s with ChatID: %d\n", mcid, user.TGID)
// The channel to await a response from the verification process
loginRequest := &LoginRequest{
ChatID: user.TGID,
Resolve: make(chan bool),
}
GetAuthcator().RequestAuth(user, loginRequest)
select {
case result := <-loginRequest.Resolve:
return result, nil
case <-time.After(10 * time.Second): // Replace with your actual timeout handling logic
return false, nil
}
}
// This function should be called when a new client connection is accepted
func HandleClientConnection(clientConn net.Conn) {
settings := conf.GetBotSettings().GatewaySettings
targetConns, err := net.DialMC(settings.ServerHost + ":" + strconv.Itoa(settings.ServerPort))
targetConn := *targetConns
// targetConn, err := gonet.Dial("tcp", settings.ServerHost+":"+strconv.Itoa(settings.ServerPort))
if err != nil {
logrus.Errorf("Failed to connect to target: %s", err)
return
}
protocol, intention, err := handshake(clientConn, targetConn)
if err != nil {
logrus.Errorf("Handshake error: %v", err)
return
}
logrus.Infof("Protocol: %v, Intention: %v", protocol, intention)
switch intention {
default: // unknown error
logrus.Errorf("Unknown handshake intention: %v", intention)
case 1: // for status
handleProxyConnection(clientConn, targetConn)
case 2: // for login
handlePlaying(clientConn, targetConn)
}
}
type PlayerInfo struct {
Name string
UUID uuid.UUID
OPLevel int
}
func handlePlaying(conn, target net.Conn) {
// login, get player info
info, err := acceptLogin(conn, target)
if err != nil {
logrus.Errorf("user [%s] Login failed", info.Name)
return
}
logrus.Infof("Login successful: %s", info.Name)
// Write LoginSuccess packet
handleProxyConnection(conn, target)
}
// acceptLogin check player's account
func acceptLogin(conn, target net.Conn) (info PlayerInfo, err error) {
// login start
var p pk.Packet
err = conn.ReadPacket(&p)
if err != nil {
return
}
err = p.Scan((*pk.String)(&info.Name)) // decode username as pk.String
if err != nil {
return
}
if ok, err := requestVerify(info.Name); !ok || err != nil {
err = errors.New("verify failed")
conn.Close()
target.Close()
return info, err
}
if err := target.WritePacket(p); err != nil {
return info, err
}
// auth
const OnlineMode = false
if OnlineMode {
info.UUID = offline.NameToUUID(info.Name)
} else {
// offline-mode UUID
info.UUID = offline.NameToUUID(info.Name)
}
return
}
func handshake(conn, target net.Conn) (protocol, intention int32, err error) {
var (
p pk.Packet
Protocol, Intention pk.VarInt
ServerAddress pk.String // ignored
ServerPort pk.UnsignedShort // ignored
)
// receive handshake packet
if err = conn.ReadPacket(&p); err != nil {
return
}
err = p.Scan(&Protocol, &ServerAddress, &ServerPort, &Intention)
if err != nil {
return
}
err = target.WritePacket(p)
return int32(Protocol), int32(Intention), err
}
func handleProxyConnection(clientConn net.Conn, targetConn net.Conn) {
defer clientConn.Close()
go func() {
for {
var p pk.Packet
if err := clientConn.ReadPacket(&p); err != nil {
logrus.Errorf("ReadPacket error: %v", err)
break
}
if err := targetConn.WritePacket(p); err != nil {
logrus.Errorf("WritePacket error: %v", err)
break
}
}
}()
func() {
for {
var p pk.Packet
if err := targetConn.ReadPacket(&p); err != nil {
logrus.Errorf("ReadPacket error: %v", err)
break
}
if err := clientConn.WritePacket(p); err != nil {
logrus.Errorf("WritePacket error: %v", err)
break
}
}
}()
}
func startProxyServer(proxyHost string, proxyPort int) {
settings := conf.GetBotSettings().GatewaySettings
l, err := net.ListenMC(fmt.Sprintf(":%d", settings.ProxyPort))
if err != nil {
logrus.Fatalf("Error starting proxy server: %s", err)
}
defer l.Close()
logrus.Infof("Proxy server started on %s:%d", proxyHost, proxyPort)
for {
clientConn, err := l.Accept()
if err != nil {
logrus.Errorf("Error accepting connection: %s", err)
continue
}
go HandleClientConnection(clientConn)
}
}
func StartGateway() {
settings := conf.GetBotSettings().GatewaySettings
startProxyServer(settings.ProxyHost, settings.ProxyPort)
}

View File

@@ -1,18 +1,28 @@
package services package services
import ( import (
"tg-mc/conf"
"tg-mc/services/gateway"
"tg-mc/services/mc" "tg-mc/services/mc"
"tg-mc/services/tgbot" "tg-mc/services/tgbot"
"tg-mc/services/utils"
) )
func Run() { func Run() {
go func() { settings := conf.GetBotSettings()
for {
if err := mc.Run(); err != nil { if settings.EnableGateway {
utils.SendMsg("致命错误:" + err.Error()) go gateway.StartGateway()
} }
if settings.EnableBridge {
go mc.StartBridgeClient()
} }
}()
if settings.EnableBot {
if settings.EnableBridge {
tgbot.Run(mc.SendMsg, mc.SendCommand) tgbot.Run(mc.SendMsg, mc.SendCommand)
} else {
tgbot.Run(mc.SendMsg, func(s string) error { return nil })
}
}
} }

View File

@@ -1,52 +0,0 @@
package mc
import (
"sync"
"tg-mc/models"
"time"
)
type Auth interface {
IsAuthed(u models.User, expireMode bool) bool
Auth(u models.User)
Reject(u models.User)
}
type Authcator struct {
UserMap *sync.Map
}
var authcator *Authcator
func GetAuthcator() Auth {
if authcator == nil {
authcator = &Authcator{
UserMap: &sync.Map{},
}
}
return authcator
}
func (a *Authcator) IsAuthed(u models.User, expireMode bool) bool {
// if u.MCName != "VaalaCat" {
// return true
// }
if approveTime, ok := a.UserMap.Load(u.MCName); ok {
if !expireMode {
return true
} else if time.Since(approveTime.(time.Time)) < 30*time.Second {
return true
} else {
return false
}
}
return false
}
func (a *Authcator) Auth(u models.User) {
a.UserMap.Store(u.MCName, time.Now())
}
func (a *Authcator) Reject(u models.User) {
a.UserMap.Delete(u.MCName)
}

View File

@@ -4,10 +4,7 @@ import (
"crypto/rand" "crypto/rand"
"encoding/binary" "encoding/binary"
"errors" "errors"
"fmt"
"tg-mc/conf" "tg-mc/conf"
"tg-mc/defs"
"tg-mc/models"
su "tg-mc/services/utils" su "tg-mc/services/utils"
"tg-mc/utils" "tg-mc/utils"
"time" "time"
@@ -15,8 +12,6 @@ import (
"github.com/Tnze/go-mc/chat" "github.com/Tnze/go-mc/chat"
"github.com/Tnze/go-mc/data/packetid" "github.com/Tnze/go-mc/data/packetid"
"github.com/Tnze/go-mc/net/packet" "github.com/Tnze/go-mc/net/packet"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"github.com/sirupsen/logrus"
) )
func GetJoinedPlayer(m chat.Message) (userName string, err error) { func GetJoinedPlayer(m chat.Message) (userName string, err error) {
@@ -36,45 +31,46 @@ func GetLeftPlayer(m chat.Message) (userName string, err error) {
} }
func HandleJoinGame(userName string, mention bool, expireMode bool) { func HandleJoinGame(userName string, mention bool, expireMode bool) {
// return
u, err := models.GetUserByMCName(userName) // u, err := models.GetUserByMCName(userName)
if err != nil { // if err != nil {
logrus.Error("get user name error: ", err) // logrus.Error("get user name error: ", err)
} // }
switch u.Status { // switch u.Status {
case StatusNormal: // case StatusNormal:
if !GetAuthcator().IsAuthed(u, expireMode) { // if !GetAuthcator().IsAuthed(u, expireMode) {
m := tgbotapi.NewMessage(u.TGID, fmt.Sprintf("MC用户%v 尝试登录请手动允许每次授权持续30秒", userName)) // m := tgbotapi.NewMessage(u.TGID, fmt.Sprintf("MC用户%v 尝试登录请手动允许每次授权持续30秒", userName))
m.ReplyMarkup = tgbotapi.NewInlineKeyboardMarkup( // m.ReplyMarkup = tgbotapi.NewInlineKeyboardMarkup(
tgbotapi.NewInlineKeyboardRow( // tgbotapi.NewInlineKeyboardRow(
tgbotapi.NewInlineKeyboardButtonData("批准", defs.NewApproveCommand(u.MCName).ToJSON()), // tgbotapi.NewInlineKeyboardButtonData("批准", defs.NewApproveCommand(u.MCName).ToJSON()),
tgbotapi.NewInlineKeyboardButtonData("拒绝", defs.NewRejectCommand(u.MCName).ToJSON())), // tgbotapi.NewInlineKeyboardButtonData("拒绝", defs.NewRejectCommand(u.MCName).ToJSON())),
) // )
conf.Bot.Send(m) // conf.Bot.Send(m)
KickPlayer(userName) // KickPlayer(userName)
return // return
} // }
if mention { if mention {
SendMsgToPlayer("欢迎回来!", userName) SendMsgToPlayer("欢迎回来!", userName)
} }
case StatusPending: // case StatusPending:
SendMsgToPlayer("你还没有绑定 Telegram 哦, 5秒后你将会被踢出。请在群组中发送 /bind <你的 MC 用户名> 进行绑定。", userName) // SendMsgToPlayer("你还没有绑定 Telegram 哦, 5秒后你将会被踢出。请在群组中发送 /bind <你的 MC 用户名> 进行绑定。", userName)
time.Sleep(5 * time.Second) // time.Sleep(5 * time.Second)
KickPlayer(userName) // KickPlayer(userName)
m := tgbotapi.NewMessage(conf.GetBotSettings().GroupID, fmt.Sprintf("用户:%v 没有绑定尝试登录已被T出", userName)) // m := tgbotapi.NewMessage(conf.GetBotSettings().GroupID, fmt.Sprintf("用户:%v 没有绑定尝试登录已被T出", userName))
conf.Bot.Send(m) // conf.Bot.Send(m)
case StatusBanned: // case StatusBanned:
SendMsgToPlayer("你已被封禁,如有疑问请联系管理员。", userName) // SendMsgToPlayer("你已被封禁,如有疑问请联系管理员。", userName)
m := tgbotapi.NewMessage(conf.GetBotSettings().GroupID, fmt.Sprintf("用户:%v 已被封禁尝试登录已被T出", userName)) // m := tgbotapi.NewMessage(conf.GetBotSettings().GroupID, fmt.Sprintf("用户:%v 已被封禁尝试登录已被T出", userName))
conf.Bot.Send(m) // conf.Bot.Send(m)
default: // default:
SendMsgToPlayer("未知错误,请联系管理员,你将被踢出", userName) // SendMsgToPlayer("未知错误,请联系管理员,你将被踢出", userName)
time.Sleep(3 * time.Second) // time.Sleep(3 * time.Second)
KickPlayer(userName) // KickPlayer(userName)
m := tgbotapi.NewMessage(conf.GetBotSettings().GroupID, fmt.Sprintf("用户:%v 登录失败错误未知已被T出", userName)) // m := tgbotapi.NewMessage(conf.GetBotSettings().GroupID, fmt.Sprintf("用户:%v 登录失败错误未知已被T出", userName))
conf.Bot.Send(m) // conf.Bot.Send(m)
} // }
} }
func SendCommand(cmd string) error { func SendCommand(cmd string) error {
@@ -114,9 +110,9 @@ func isBotMsg(msg chat.Message) bool {
} }
func HandleLeftGame(userName string) { func HandleLeftGame(userName string) {
u, err := models.GetUserByMCName(userName) // u, err := models.GetUserByMCName(userName)
if err != nil { // if err != nil {
logrus.Error("get user name error: ", err) // logrus.Error("get user name error: ", err)
} // }
GetAuthcator().Reject(u) // GetAuthcator().Reject(u)
} }

View File

@@ -5,6 +5,7 @@ import (
"log" "log"
"strings" "strings"
"tg-mc/conf" "tg-mc/conf"
"tg-mc/services/utils"
"time" "time"
"github.com/Tnze/go-mc/bot" "github.com/Tnze/go-mc/bot"
@@ -17,6 +18,15 @@ import (
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
) )
func StartBridgeClient() {
for {
if err := Run(); err != nil {
utils.SendMsgToGroup("致命错误:" + err.Error())
}
time.Sleep(time.Second * 5)
}
}
func Run() error { func Run() error {
conf.Client = bot.NewClient() conf.Client = bot.NewClient()
conf.Client.Auth.Name = conf.GetBotSettings().MCBotName conf.Client.Auth.Name = conf.GetBotSettings().MCBotName
@@ -44,7 +54,8 @@ func Run() error {
) )
if err != nil { if err != nil {
log.Fatal(err) log.Printf("joinserver error: %v", err)
return err
} }
log.Println("Login success") log.Println("Login success")

View File

@@ -5,18 +5,19 @@ import (
"tg-mc/conf" "tg-mc/conf"
"tg-mc/defs" "tg-mc/defs"
"tg-mc/models" "tg-mc/models"
"tg-mc/services/mc" "tg-mc/services/gateway"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
) )
func ApproveHandler(update tgbotapi.Update, cmd defs.Command) { func ApproveHandler(update tgbotapi.Update, cmd defs.Command) {
u, err := models.GetUserByTGID(update.CallbackQuery.From.ID) u, err := models.GetUserByMCName(cmd.Argstr)
if err != nil { if err != nil {
return return
} }
mc.GetAuthcator().Auth(u) gateway.GetAuthcator().SetAuth(u)
callback := tgbotapi.NewCallback(update.CallbackQuery.ID, "已授权") callback := tgbotapi.NewCallback(update.CallbackQuery.ID, "已授权")
if _, err := conf.Bot.Request(callback); err != nil { if _, err := conf.Bot.Request(callback); err != nil {
logrus.Panic(err) logrus.Panic(err)
@@ -26,3 +27,19 @@ func ApproveHandler(update tgbotapi.Update, cmd defs.Command) {
conf.Bot.Send(tgbotapi.NewMessage(update.CallbackQuery.Message.Chat.ID, conf.Bot.Send(tgbotapi.NewMessage(update.CallbackQuery.Message.Chat.ID,
fmt.Sprintf("已授权☑️: %s 登录MC", u.MCName))) fmt.Sprintf("已授权☑️: %s 登录MC", u.MCName)))
} }
// func ApproveHandler(update tgbotapi.Update, cmd defs.Command) {
// u, err := models.GetUserByTGID(update.CallbackQuery.From.ID)
// if err != nil {
// return
// }
// mc.GetAuthcator().Auth(u)
// callback := tgbotapi.NewCallback(update.CallbackQuery.ID, "已授权")
// if _, err := conf.Bot.Request(callback); err != nil {
// logrus.Panic(err)
// }
// conf.Bot.Send(tgbotapi.NewDeleteMessage(update.CallbackQuery.Message.Chat.ID,
// update.CallbackQuery.Message.MessageID))
// conf.Bot.Send(tgbotapi.NewMessage(update.CallbackQuery.Message.Chat.ID,
// fmt.Sprintf("已授权☑️: %s 登录MC", u.MCName)))
// }

View File

@@ -3,12 +3,14 @@ package tgbot
import ( import (
"fmt" "fmt"
"strconv" "strconv"
"strings"
"tg-mc/conf" "tg-mc/conf"
"tg-mc/models" "tg-mc/models"
"tg-mc/services/utils" "tg-mc/services/utils"
commonUtils "tg-mc/utils" commonUtils "tg-mc/utils"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"github.com/samber/lo"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
) )
@@ -33,7 +35,7 @@ func GetHandler(msg *tgbotapi.Message, i interface{}) {
conf.Bot.Send(tgbotapi.NewMessage(msg.Chat.ID, "ID错误应该为int64")) conf.Bot.Send(tgbotapi.NewMessage(msg.Chat.ID, "ID错误应该为int64"))
return return
} }
u, err := models.GetUserByTGID(tgid) u, err := models.GetUsersByTGID(tgid)
if err != nil { if err != nil {
tm := tgbotapi.NewMessage(msg.Chat.ID, fmt.Sprintf("查询出错err\n```\n%+v\n```", err)) tm := tgbotapi.NewMessage(msg.Chat.ID, fmt.Sprintf("查询出错err\n```\n%+v\n```", err))
tm.ParseMode = "Markdown" tm.ParseMode = "Markdown"
@@ -59,13 +61,14 @@ func GetHandler(msg *tgbotapi.Message, i interface{}) {
return return
} }
logrus.Infof("id is %d", msg.Chat.ID) logrus.Infof("id is %d", msg.Chat.ID)
u, err := models.GetUserByTGID(msg.From.ID) u, err := models.GetUsersByTGID(msg.From.ID)
if err != nil { if err != nil {
m := tgbotapi.NewMessage(msg.Chat.ID, "你还没有绑定") m := tgbotapi.NewMessage(msg.Chat.ID, "你还没有绑定")
conf.Bot.Send(m) conf.Bot.Send(m)
return return
} }
m := tgbotapi.NewMessage(msg.Chat.ID, fmt.Sprintf("你的MCID是%v", u.MCName)) ans := strings.Join(lo.Map(u, func(u models.User, _ int) string { return u.MCName }), "\n")
m := tgbotapi.NewMessage(msg.Chat.ID, fmt.Sprintf("你的MCID绑定有\n%v", ans))
conf.Bot.Send(m) conf.Bot.Send(m)
return return
} }

View File

@@ -5,16 +5,19 @@ import (
"tg-mc/conf" "tg-mc/conf"
"tg-mc/defs" "tg-mc/defs"
"tg-mc/models" "tg-mc/models"
"tg-mc/services/gateway"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
) )
func RejectHandler(update tgbotapi.Update, cmd defs.Command) { func RejectHandler(update tgbotapi.Update, cmd defs.Command) {
u, err := models.GetUserByTGID(update.CallbackQuery.From.ID) u, err := models.GetUserByMCName(cmd.Argstr)
if err != nil { if err != nil {
return return
} }
gateway.GetAuthcator().Reject(u)
callback := tgbotapi.NewCallback(update.CallbackQuery.ID, "已拒绝") callback := tgbotapi.NewCallback(update.CallbackQuery.ID, "已拒绝")
if _, err := conf.Bot.Request(callback); err != nil { if _, err := conf.Bot.Request(callback); err != nil {
logrus.Panic(err) logrus.Panic(err)

View File

@@ -5,24 +5,38 @@ import (
"tg-mc/models" "tg-mc/models"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"github.com/samber/lo"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
) )
func UnbindHandler(msg *tgbotapi.Message, i interface{}) { func UnbindHandler(msg *tgbotapi.Message, i interface{}) {
logrus.Infof("id is %d", msg.Chat.ID) logrus.Infof("id is %d", msg.Chat.ID)
u, err := models.GetUserByTGID(msg.From.ID) if len(msg.CommandArguments()) == 0 {
m := tgbotapi.NewMessage(msg.Chat.ID, "请输入正确的参数")
conf.Bot.Send(m)
return
}
us, err := models.GetUsersByTGID(msg.From.ID)
if err != nil { if err != nil {
m := tgbotapi.NewMessage(msg.Chat.ID, "你还没有绑定") m := tgbotapi.NewMessage(msg.Chat.ID, "你还没有绑定")
conf.Bot.Send(m) conf.Bot.Send(m)
return return
} }
lo.Map(us, func(u models.User, _ int) bool {
if u.MCName == msg.CommandArguments() {
u.Status = 0
err = u.Delete(msg.From.ID) err = u.Delete(msg.From.ID)
if err != nil { if err != nil {
m := tgbotapi.NewMessage(msg.Chat.ID, "解绑失败") m := tgbotapi.NewMessage(msg.Chat.ID, "解绑失败")
conf.Bot.Send(m) conf.Bot.Send(m)
return return false
} }
m := tgbotapi.NewMessage(msg.Chat.ID, "解绑成功") m := tgbotapi.NewMessage(msg.Chat.ID, "解绑成功")
conf.Bot.Send(m) conf.Bot.Send(m)
return return false
}
return true
})
} }

View File

@@ -7,12 +7,18 @@ import (
"github.com/samber/lo" "github.com/samber/lo"
) )
func SendMsg(msg string) error { func SendMsgToGroup(msg string) error {
msgT := tgbotapi.NewMessage(conf.GetBotSettings().GroupID, msg) msgT := tgbotapi.NewMessage(conf.GetBotSettings().GroupID, msg)
_, err := conf.Bot.Send(msgT) _, err := conf.Bot.Send(msgT)
return err return err
} }
func SendMsg(chatID int64, msg string) error {
msgT := tgbotapi.NewMessage(chatID, msg)
_, err := conf.Bot.Send(msgT)
return err
}
func IsAdmin(m *tgbotapi.Message) bool { func IsAdmin(m *tgbotapi.Message) bool {
return lo.Contains(conf.GetBotSettings().AdminID, m.From.ID) || return lo.Contains(conf.GetBotSettings().AdminID, m.From.ID) ||
lo.Contains(conf.GetBotSettings().AdminID, m.Chat.ID) lo.Contains(conf.GetBotSettings().AdminID, m.Chat.ID)

View File

@@ -11,6 +11,7 @@ var (
) )
func CronStart(f func()) { func CronStart(f func()) {
return
s.Every("1m").Do(f) s.Every("1m").Do(f)
s.StartAsync() s.StartAsync()
} }

View File

@@ -2,7 +2,6 @@ package database
import ( import (
"github.com/joho/godotenv" "github.com/joho/godotenv"
"github.com/sirupsen/logrus"
"gorm.io/gorm" "gorm.io/gorm"
) )
@@ -15,10 +14,10 @@ func GetDB() *gorm.DB {
return GetSqlite() return GetSqlite()
} }
func CloseDB(db *gorm.DB) { // func CloseDB(db *gorm.DB) {
tdb, err := db.DB() // tdb, err := db.DB()
if err != nil { // if err != nil {
logrus.WithError(err).Errorf("Close DB error") // logrus.WithError(err).Errorf("Close DB error")
} // }
tdb.Close() // tdb.Close()
} // }

View File

@@ -9,23 +9,25 @@ import (
"gorm.io/gorm" "gorm.io/gorm"
) )
var (
db *gorm.DB
)
func initSqlite() { func initSqlite() {
var err error var err error
godotenv.Load() godotenv.Load()
dbPath := conf.GetBotSettings().DBPath dbPath := conf.GetBotSettings().DBPath
db, err := gorm.Open(sqlite.Open(dbPath), &gorm.Config{}) db, err = gorm.Open(sqlite.Open(dbPath), &gorm.Config{})
if err != nil { if err != nil {
logrus.Panic(err, "Initializing DB Error") logrus.Panic(err, "Initializing DB Error")
} }
CloseDB(db) logrus.Info("Initialized DB at ", dbPath)
} }
func GetSqlite() *gorm.DB { func GetSqlite() *gorm.DB {
dbPath := conf.GetBotSettings().DBPath if db == nil {
db, err := gorm.Open(sqlite.Open(dbPath), &gorm.Config{}) initSqlite()
if err != nil {
return nil
} }
return db return db
} }