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