setwallet.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package handler
  2. import (
  3. tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
  4. "fmt"
  5. "gogs.veloe.link/toomanysugar/GoEthemineTelegramBot/internal/database"
  6. log "gogs.veloe.link/toomanysugar/GoEthemineTelegramBot/internal/logger"
  7. )
  8. // whata
  9. var wrongFormatErr error = fmt.Errorf("Wrong format!")
  10. // returns wallet in format 0x%.40s or error if format is wrong
  11. func parseWallet(walletStr string) (wallet string, err error) {
  12. if len(walletStr) == 40 {
  13. return "0x" + walletStr, nil
  14. }
  15. if len(walletStr) == 42 && walletStr[0] == '0' && walletStr[1] == 'x' {
  16. return walletStr, nil
  17. }
  18. return "", wrongFormatErr
  19. }
  20. func (ah ActionHandler) SetWalletHandler(chatId int64, params []string) []tgbotapi.MessageConfig {
  21. if len(params) != 1 {
  22. return []tgbotapi.MessageConfig{tgbotapi.NewMessage(chatId, "usage: /setwallet <wallet>")}
  23. }
  24. walletStr := params[0]
  25. // Check if user registered
  26. var user database.User
  27. ah.dbconn.GormDb.
  28. Model(&database.User{}).
  29. Where(&database.User{ChatId: chatId}).FirstOrInit(&user)
  30. if user == (database.User{}) {
  31. return []tgbotapi.MessageConfig{
  32. tgbotapi.NewMessage(chatId, "You are not registered! Type /start first!")}
  33. }
  34. wallet, err := parseWallet(walletStr)
  35. if err != nil {
  36. if err == wrongFormatErr {
  37. return []tgbotapi.MessageConfig{
  38. tgbotapi.NewMessage(chatId, "wallet must be in format:\n" +
  39. "[0x]****************************************!")}
  40. }
  41. }
  42. user.Wallet = wallet
  43. err = ah.dbconn.GormDb.Save(&user).Error
  44. if err != nil {
  45. log.LogError.Printf("failed querying user: %s", err.Error())
  46. return []tgbotapi.MessageConfig{
  47. tgbotapi.NewMessage(chatId, "An exception occurred while executing this command.")}
  48. }
  49. log.LogInfo.Printf("Updated wallet of user %d to %s\n", chatId, wallet)
  50. return []tgbotapi.MessageConfig{
  51. tgbotapi.NewMessage(chatId, fmt.Sprintf("%s set!", wallet))}
  52. }