package main import ( "fmt" "image" "image/color" "image/draw" "image/png" "io/ioutil"…
- User
package main
import ( "fmt" "image" "image/color" "image/draw" "image/png" "io/ioutil" "net/http" "os" "os/signal" "strings" "syscall"
"github.com/bwmarrin/discordgo")
const ( prefix = "+" prefix1 = "-" prefix2 = "!" )
var ( allowedChannels = map[string]bool{ "1087629024139943936": true, "1174286575878815855": true, } )
func main() { token := "YOUR_BOT_TOKEN"
dg, err := discordgo.New(token) if err != nil { fmt.Println("Error creating Discord session:", err) return } dg.AddHandler(messageCreate) err = dg.Open() if err != nil { fmt.Println("Error opening Discord session:", err) return } defer dg.Close() fmt.Println("Bot is now running. Press Ctrl+C to exit.") sc := make(chan os.Signal, 1) signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt) <-sc}
func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) { if !allowedChannels[m.ChannelID] { return }
if strings.HasPrefix(m.Content, prefix2+"as") { if len(m.Attachments) == 0 { s.ChannelMessageSend(m.ChannelID, "Please attach an image.") return } // Get the first attachment URL attachment := m.Attachments[0] resp, err := http.Get(attachment.URL) if err != nil { s.ChannelMessageSend(m.ChannelID, "Error downloading image.") return } defer resp.Body.Close() img, _, err := image.Decode(resp.Body) if err != nil { s.ChannelMessageSend(m.ChannelID, "Error decoding image.") return } asciiArt := convertImageToASCII(img) sendASCIIArt(s, m.ChannelID, asciiArt) }}
func convertImageToASCII(img image.Image) string { // Resize the image to a manageable size for ASCII conversion. img = resizeImage(img, 100) // Adjust width as needed
asciiChars := "@%#*+=-:. " var asciiArt strings.Builder for y := 0; y < img.Bounds().Dy(); y++ { for x := 0; x < img.Bounds().Dx(); x++ { c := color.GrayModel.Convert(img.At(x, y)).(color.Gray) index := c.Y * (len(asciiChars)-1) / 255 // Map grayscale value to ASCII index asciiArt.WriteByte(asciiChars[index]) } asciiArt.WriteByte('\n') } return asciiArt.String()}
func resizeImage(img image.Image, width uint) image.Image { // Resize the image while maintaining aspect ratio. newImg := resize.Resize(width, 0, img, resize.Lanczos3) return newImg }
func sendASCIIArt(s *discordgo.Session, channelID string, asciiArt string) { const maxMessageLength = 2000
// Split the ASCII art into chunks if it exceeds Discord's message length limit. for len(asciiArt) > maxMessageLength { s.ChannelMessageSend(channelID, asciiArt[:maxMessageLength]) asciiArt = asciiArt[maxMessageLength:] }// Send remaining part of ASCII art. if len(asciiArt) > 0 { s.ChannelMessageSend(channelID, asciiArt) } }
- Assistant
The provided Go program is a Discord bot that listens for messages in specified channels and can convert images to ASCII art when triggered by a specific command.