diff --git a/commands/mol.go b/commands/mol.go new file mode 100644 index 0000000..3d71d69 --- /dev/null +++ b/commands/mol.go @@ -0,0 +1,62 @@ +package commands + +import ( + "fmt" + "io" + "net/http" + "regexp" + "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) + msg := tgbotapi.NewMessage(update.Message.Chat.ID, imgURL) + bot.Send(msg) +} + +func fetchPubchemCID(compound string) (string, error) { + url := "https://pubchem.ncbi.nlm.nih.gov/compound/" + compound + resp, err := http.Get(url) + if err != nil { + return "", err + } + defer resp.Body.Close() + body, err := io.ReadAll(resp.Body) + if err != nil { + return "", err + } + re := regexp.MustCompile(``) + matches := re.FindStringSubmatch(string(body)) + if len(matches) < 2 { + return "", fmt.Errorf("CID not found") + } + return matches[1], nil +} + +func init() { + Register(MolCommand{}) +}