Skip to content

Commit

Permalink
Update bot functions & scripts
Browse files Browse the repository at this point in the history
  • Loading branch information
STARRY-S committed Oct 5, 2023
1 parent 4d73490 commit 1b37c9c
Show file tree
Hide file tree
Showing 11 changed files with 108 additions and 40 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
go-version: [ '1.20' ]
go-version: [ '1.21' ]

steps:
- uses: actions/checkout@v3
Expand Down
13 changes: 7 additions & 6 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
FROM archlinux

# Configure Arch Linux CN repository & Install dependencies
RUN echo "Server = https://mirrors.bfsu.edu.cn/archlinux/\$repo/os/\$arch" > /etc/pacman.d/mirrorlist && \
echo "Server = https://mirrors.tuna.tsinghua.edu.cn/archlinux/\$repo/os/\$arch" >> /etc/pacman.d/mirrorlist && \
pacman --noconfirm -Syyu && \
pacman --noconfirm -S lm_sensors words && \
ENV http_proxy=${http_proxy} https_proxy=${https_proxy} no_proxy=${no_proxy}

# Install dependencies
RUN pacman --noconfirm -Syyu && \
pacman --noconfirm -S lm_sensors words openssh pacman-contrib && \
pacman --noconfirm -Scc

WORKDIR /telebot
COPY . .
COPY config.yaml.example telebot ./

# Install telebot
RUN cp config.yaml.example config.yaml && \
mv telebot /usr/local/bin/
Expand Down
11 changes: 10 additions & 1 deletion config.yaml.example
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# API token
# API token (also set by ENV 'TELEGRAM_APITOKEN')
apiToken: ""

# Owner of this bot
Expand All @@ -21,3 +21,12 @@ execWhitelist:
- "free"
- "sensors"
- "sleep"
- "bash"
- "pacman"
- "ss"
- "cat"
- "wget"
- "sed"

# Execute command timeout (seconds), default 30s
execTimeout: 30
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ module github.com/STARRY-S/telebot
go 1.20

require (
github.com/sirupsen/logrus v1.9.1
github.com/sirupsen/logrus v1.9.3
github.com/stretchr/testify v1.8.4
github.com/tjarratt/babble v0.0.0-20210505082055-cbca2a4833c1
golang.org/x/exp v0.0.0-20230510235704-dd950f8aeaea
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -355,8 +355,8 @@ github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88=
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/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA=
github.com/spf13/afero v1.8.2/go.mod h1:CtAatgMJh6bJEIs48Ay/FOnkljP3WeGUG0MC1RfAqwo=
github.com/spf13/cast v1.5.0/go.mod h1:SpXXQ5YoyJw6s3/6cMTQuxvgRl3PCJiyaX9p6b155UU=
Expand Down
38 changes: 23 additions & 15 deletions pkg/botcmd/owner.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package botcmd
import (
"bytes"
"fmt"
"os"
"os/exec"
"strings"
"time"
Expand All @@ -14,10 +15,6 @@ import (
"gopkg.in/telebot.v3"
)

const (
ExecTimeout = time.Second * 3
)

func AddOwnerCommands(bot *telebot.Bot) {
bot.Handle("/add_admin", func(c telebot.Context) error {
if !isOwner(c) {
Expand Down Expand Up @@ -83,26 +80,23 @@ func AddOwnerCommands(bot *telebot.Bot) {
)
}

cmdout := make(chan string)
cmderr := make(chan string)
cmd := exec.Command("bash", "-c", strings.Join(cmdArgs, " "))
outch := make(chan string)
errch := make(chan string)
go func() {
out := &bytes.Buffer{}
cmd.Stdout = out
cmd.Stderr = out
if err := cmd.Start(); err != nil {
cmderr <- fmt.Sprintf("%s\n%s", out.String(), err.Error())
return
errch <- fmt.Sprintf("%s\n%s", out.String(), err.Error())
}
if err := cmd.Wait(); err != nil {
cmderr <- fmt.Sprintf("%s\n%s", out.String(), err.Error())
return
errch <- fmt.Sprintf("%s\n%s", out.String(), err.Error())
}

cmdout <- out.String()
outch <- out.String()
}()

timer := time.NewTimer(ExecTimeout)
timer := time.NewTimer(config.ExecTimeout())
select {
case <-timer.C:
// command executes timeout
Expand All @@ -121,17 +115,19 @@ func AddOwnerCommands(bot *telebot.Bot) {
telebot.ModeHTML)
}
return c.Reply("Failed: execute timeout, killed")
case out := <-cmdout:
case out := <-outch:
// command executes successfully
timer.Stop()
if len(out) > 3000 {
out = out[:3000] + "\n......"
} else if len(out) == 0 {
return c.Reply("Command execute successfully with no output.")
}
return c.Reply(
fmt.Sprintf("<pre>%s</pre>", out),
telebot.ModeHTML,
)
case e := <-cmderr:
case e := <-errch:
// command executes failed
timer.Stop()
return c.Reply(
Expand All @@ -140,12 +136,24 @@ func AddOwnerCommands(bot *telebot.Bot) {
)
}
})

bot.Handle("/restart", func(c telebot.Context) error {
if !isOwner(c) {
return c.Reply(utils.ReplyPermissionDenied)
}

c.Send("Bot will restart now.")
logrus.Warnf("Bot will restart now.")
os.Exit(0)
return nil
})
}

func GetOwnerHelpMessage() string {
b := &bytes.Buffer{}
fmt.Fprintln(b, "/add_admin Register temporary admin user (Owner)")
fmt.Fprintln(b, "/del_admin Remove admin temporally (Owner)")
fmt.Fprintln(b, "/exec Run commands (Private) (Owner)")
fmt.Fprintln(b, "/restart Restart (kill) this bot (Owner)")
return b.String()
}
4 changes: 2 additions & 2 deletions pkg/botcmd/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ func AddUserCommands(bot *telebot.Bot) {
if len(c.Args()) == 0 {
return c.Reply("Usage: /sha256 <text>")
}
text := strings.TrimLeft(c.Text(), "/sha256 ")
text := strings.TrimPrefix(c.Text(), "/sha256 ")
sum := sha256.Sum256([]byte(text))
return c.Reply(
fmt.Sprintf("`%x`", sum),
Expand All @@ -56,7 +56,7 @@ func AddUserCommands(bot *telebot.Bot) {
if len(c.Args()) == 0 {
return c.Reply("Usage: /md5 <text>")
}
text := strings.TrimLeft(c.Text(), "/md5 ")
text := strings.TrimPrefix(c.Text(), "/md5 ")
return c.Reply(
fmt.Sprintf("`%x`", md5.Sum([]byte(text))),
telebot.ModeMarkdownV2,
Expand Down
6 changes: 6 additions & 0 deletions pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package config
import (
"os"
"strconv"
"time"

"github.com/sirupsen/logrus"
"golang.org/x/exp/slices"
Expand All @@ -15,6 +16,7 @@ type Config struct {
OwnerID string `yaml:"ownerID"`
Admins []string `yaml:"admins"`
ExecWhiteList []string `yaml:"execWhitelist"`
ExecTimeout int `yaml:"execTimeout"`
}

const (
Expand Down Expand Up @@ -62,6 +64,10 @@ func ExecWhiteListContains(s string) bool {
return slices.Contains(config.ExecWhiteList, s)
}

func ExecTimeout() time.Duration {
return time.Duration(config.ExecTimeout) * time.Second
}

func Owner() string {
return config.Owner
}
Expand Down
33 changes: 30 additions & 3 deletions scripts/build.sh
Original file line number Diff line number Diff line change
@@ -1,11 +1,38 @@
#!/bin/bash
#!/usr/bin/env bash

set -euo pipefail

cd $(dirname $0)/../

if [[ ! -e "config.yaml" ]]; then
cp config.yaml.example config.yaml
fi

go build .
GITCOMMIT=$(git rev-parse HEAD || true)
VERSION=$(git describe --tags 2>/dev/null || true)
BUILD_FLAG=""
if [[ "${GITCOMMIT}" != "UNKNOW" ]]; then
BUILD_FLAG="${BUILD_FLAG} -X 'github.com/STARRY-S/telebot/pkg/utils.gitCommit=${GITCOMMIT}'"
fi
BUILD_FLAG="${BUILD_FLAG} -X 'github.com/STARRY-S/telebot/pkg/utils.version=${VERSION}'"

CGO_ENABLED=0 go build -ldflags "${BUILD_FLAG}" .

echo "--------------------------"
ls -alh telebot
echo "--------------------------"

TAG=""
if [[ ! -z "$VERSION" ]]; then
TAG=":${VERSION}"
fi

docker build -t telebot .
docker build \
--build-arg http_proxy=${http_proxy:-} \
--build-arg https_proxy=${https_proxy:-} \
--build-arg HTTP_PROXY=${HTTP_PROXY:-} \
--build-arg HTTPS_PROXY=${HTTPS_PROXY:-} \
--build-arg no_proxy=${no_proxy:-} \
--build-arg NO_PROXY=${NO_PROXY:-} \
--network=host \
-t hxstarrys/telebot${TAG} .
15 changes: 13 additions & 2 deletions scripts/release.sh
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
#!/bin/bash
#!/usr/bin/env bash

docker kill telebot && docker rm telebot
set -euo pipefail

docker kill telebot || true
docker rm telebot || true

VERSION=$(git describe --tags 2>/dev/null || true)
TAG=""
if [[ ! -z "$VERSION" ]]; then
TAG=":${VERSION}"
fi

docker image rm hxstarrys/telebot${TAG}

exit 0
20 changes: 13 additions & 7 deletions scripts/start.sh
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
#!/bin/bash
#!/usr/bin/env bash

set -euo pipefail

cd $(dirname $0)/../

docker run -d \
-e TELEGRAM_APITOKEN=$TELEGRAM_APITOKEN \
-e HTTPS_PROXY=$HTTPS_PROXY \
-e AWS_ACCESS_KEY_ID=$AWS_ACCESS_KEY_ID \
-e AWS_SECRET_ACCESS_KEY=$AWS_SECRET_ACCESS_KEY \
-e TELEGRAM_APITOKEN=${TELEGRAM_APITOKEN:-} \
-e HTTP_PROXY=${HTTP_PROXY:-} \
-e http_proxy=${http_proxy:-} \
-e HTTPS_PROXY=${HTTPS_PROXY:-} \
-e https_proxy=${https_proxy:-} \
-e NO_PROXY=${NO_PROXY:-} \
-e no_proxy=${no_proxy:-} \
-v $(pwd)/config.yaml:/telebot/config.yaml \
--restart=unless-stopped \
--network=host \
--restart=always \
--name=telebot \
telebot
hxstarrys/telebot

0 comments on commit 1b37c9c

Please sign in to comment.