main.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package main
  2. import (
  3. "encoding/base64"
  4. "flag"
  5. "fmt"
  6. "io/ioutil"
  7. "net/http"
  8. "os"
  9. "github.com/bwmarrin/discordgo"
  10. )
  11. // Variables used for command line parameters
  12. var (
  13. Token string
  14. AvatarFile string
  15. AvatarURL string
  16. )
  17. func init() {
  18. flag.StringVar(&Token, "t", "", "Bot Token")
  19. flag.StringVar(&AvatarFile, "f", "", "Avatar File Name")
  20. flag.StringVar(&AvatarURL, "u", "", "URL to the avatar image")
  21. flag.Parse()
  22. if Token == "" || (AvatarFile == "" && AvatarURL == "") {
  23. flag.Usage()
  24. os.Exit(1)
  25. }
  26. }
  27. func main() {
  28. // Create a new Discord session using the provided login information.
  29. dg, err := discordgo.New("Bot " + Token)
  30. if err != nil {
  31. fmt.Println("error creating Discord session,", err)
  32. return
  33. }
  34. // Declare these here so they can be used in the below two if blocks and
  35. // still carry over to the end of this function.
  36. var base64img string
  37. var contentType string
  38. // If we're using a URL link for the Avatar
  39. if AvatarURL != "" {
  40. resp, err := http.Get(AvatarURL)
  41. if err != nil {
  42. fmt.Println("Error retrieving the file, ", err)
  43. return
  44. }
  45. defer func() {
  46. _ = resp.Body.Close()
  47. }()
  48. img, err := ioutil.ReadAll(resp.Body)
  49. if err != nil {
  50. fmt.Println("Error reading the response, ", err)
  51. return
  52. }
  53. contentType = http.DetectContentType(img)
  54. base64img = base64.StdEncoding.EncodeToString(img)
  55. }
  56. // If we're using a local file for the Avatar
  57. if AvatarFile != "" {
  58. img, err := ioutil.ReadFile(AvatarFile)
  59. if err != nil {
  60. fmt.Println(err)
  61. }
  62. contentType = http.DetectContentType(img)
  63. base64img = base64.StdEncoding.EncodeToString(img)
  64. }
  65. // Now lets format our base64 image into the proper format Discord wants
  66. // and then call UserUpdate to set it as our user's Avatar.
  67. avatar := fmt.Sprintf("data:%s;base64,%s", contentType, base64img)
  68. _, err = dg.UserUpdate("", avatar)
  69. if err != nil {
  70. fmt.Println(err)
  71. }
  72. }