Last active
May 29, 2022 05:07
-
-
Save tdakkota/2441f2cdd0a96c6ae1f23b70e4e8451d to your computer and use it in GitHub Desktop.
Example Telegram Go bot which uses SOCKS5 proxy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"golang.org/x/net/proxy" | |
"log" | |
"net/http" | |
"net/url" | |
"os" | |
"time" | |
tb "gopkg.in/tucnak/telebot.v2" | |
) | |
func buildClientWithProxy(addr string) (*http.Client, error) { | |
if addr != "" { | |
u, err := url.Parse(addr) | |
if err != nil { | |
panic(err) | |
} | |
var auth *proxy.Auth | |
if u.User != nil { // credentials are set | |
pass, _ := u.User.Password() | |
auth = &proxy.Auth{ | |
User: u.User.Username(), | |
Password: pass, | |
} | |
} | |
dialer, err := proxy.SOCKS5("tcp", addr, auth, proxy.Direct) | |
if err != nil { | |
return nil, err | |
} | |
// Patch client transport | |
httpTransport := &http.Transport{Dial: dialer.Dial} | |
hc := &http.Client{Transport: httpTransport} | |
return hc, nil | |
} | |
return nil, nil // use default | |
} | |
func main() { | |
token := os.Getenv("BOT_TOKEN") | |
if token == "" { | |
log.Println("Set token via environment\nBOT_TOKEN=<your_token>") | |
return | |
} | |
client, err := buildClientWithProxy(os.Getenv("BOT_PROXY")) | |
if err != nil { | |
log.Fatal(err) | |
return | |
} | |
b, err := tb.NewBot(tb.Settings{ | |
Token: token, | |
Poller: &tb.LongPoller{Timeout: 10 * time.Second}, | |
Client: client, | |
}) | |
if err != nil { | |
log.Fatal(err) | |
return | |
} | |
log.Printf("Bot started[%s]", b.Me.Username) | |
b.Handle("/start", func(m *tb.Message) { | |
_, err := b.Send(m.Sender, "hello world") | |
if err != nil { | |
log.Fatal(err) | |
return | |
} | |
}) | |
b.Start() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment