63 lines
1.5 KiB
Go
63 lines
1.5 KiB
Go
package commands
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/url"
|
|
"strings"
|
|
|
|
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
|
|
)
|
|
|
|
type MolCommand struct{}
|
|
|
|
func (m MolCommand) Name() string {
|
|
return "mol"
|
|
}
|
|
|
|
func (m MolCommand) Help() string {
|
|
return "2D molecular structure. Example usage: /mol tetraethylgermane"
|
|
}
|
|
|
|
func (m MolCommand) Execute(update tgbotapi.Update, bot *tgbotapi.BotAPI) {
|
|
args := strings.TrimSpace(update.Message.CommandArguments())
|
|
if args == "" {
|
|
msg := tgbotapi.NewMessage(update.Message.Chat.ID, "Input a molecule name dumbass")
|
|
bot.Send(msg)
|
|
return
|
|
}
|
|
cid, err := fetchPubchemCID(args)
|
|
if err != nil {
|
|
msg := tgbotapi.NewMessage(update.Message.Chat.ID, "Structure not found")
|
|
bot.Send(msg)
|
|
return
|
|
}
|
|
imgURL := fmt.Sprintf("https://pubchem.ncbi.nlm.nih.gov/image/imgsrv.fcgi?t=l&cid=%s", cid)
|
|
photo := tgbotapi.NewPhoto(update.Message.Chat.ID, tgbotapi.FileURL(imgURL))
|
|
photo.Caption = args
|
|
bot.Send(photo)
|
|
}
|
|
|
|
func fetchPubchemCID(compound string) (string, error) {
|
|
apiURL := "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/name/" + url.QueryEscape(compound) + "/cids/TXT"
|
|
resp, err := http.Get(apiURL)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
defer resp.Body.Close()
|
|
body, err := io.ReadAll(resp.Body)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
cid := strings.TrimSpace(string(body))
|
|
if cid == "" || strings.Contains(cid, "Status:") {
|
|
return "", fmt.Errorf("CID not found")
|
|
}
|
|
return cid, nil
|
|
}
|
|
|
|
func init() {
|
|
Register(MolCommand{})
|
|
}
|