package main import ( "fmt" "github.com/bwmarrin/discordgo" "os" "os/signal" "strings"…
- User
package main
import ( "fmt" "github.com/bwmarrin/discordgo" "os" "os/signal" "strings" "syscall" )
const ( prefix = "+" prefix1 = "-" prefix2 = "!" promptConfig = "Отвечай мне только на русском, не пиши длинных сообщений, твой максимум это 2000 символов. Все коды пиши в таком формате:
название ЯП также прямо у кавычек тут код." firstBet = 100 )const asciiChars = "@%#*+=-:. "
var ( whiteList = map[string]bool{ "1184449624950460488": true, }
allowedChannels = map[string]bool{ "1087629024139943936": true, "1174286575878815855": true, })
func main() { token := "MTE4NDQ0OTYyNDk1MDQ2MDQ4OA.GTlyb_.u8d7SvMAq2Qgu4AyepwsRtTuNNjOsZhtUti4C4"
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] && !whiteList[m.Author.ID] { return }
fmt.Printf("Received message from %s [%s]: %s\n", m.Author.Username, m.ChannelID, m.Content) if strings.HasPrefix(m.Content, prefix) || strings.HasPrefix(m.Content, prefix1) || strings.HasPrefix(m.Content, prefix2) { parts := strings.Split(m.Content, " ") command := parts[0] switch command { case prefix2 + "as": } }}
помоги сделать ASCII для селф бота чтобы сначала картинка становилась чено белой или обводились контуры и потом из этого создавалась ASCII картинка и отправлялась в эот же чат
!as вложение(картинка) -> обработка -> ASCII изображение в этом же чате на golang discord go
для обработки картинок используй обычные дефолтные бибилиотеки golang
добавь
case prefix2 + "as": } - Assistant
To achieve your goal, you can use the Go standard library to process the image and convert it to ASCII art. You'll need some image processing to convert the image to grayscale and reduce it to ASCII characters. Here’s how you can integrate it into your Discord bot:
- Use the
image,image/color, andimage/drawlibraries to handle the image. - Use the
image/pngandimage/jpeglibraries to decode the image formats. - Use the
stringsandbyteslibraries to construct the ASCII art string.
Below is a complete function that handles the conversion of an image to ASCII art and sends it back to the Discord channel:
func imageToASCII(img image.Image) string { bounds := img.Bounds() width, height := bounds.Max.X, bounds.Max.Y // Character lookup string based on intensity asciiChars := "@%#*+=-:. " // ASCII string builder var asciiArt strings.Builder // Scale down the image for ASCII conversion (optional, for large images) scale := 0.1 newWidth, newHeight := int(float64(width)*scale), int(float64(height)*scale) for y := 0; y < newHeight; y++ { for x := 0; x < newWidth; x++ { // Scale down coordinates px := int(float64(x) / scale) py := int(float64(y) / scale) grayColor := color.GrayModel.Convert(img.At(px, py)).(color.Gray) intensity := grayColor.Y // Choose character based on intensity char := asciiChars[intensity*len(asciiChars)/255] asciiArt.WriteString(string(char)) } asciiArt.WriteString("\n") } return asciiArt.String() } func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) { if !allowedChannels[m.ChannelID] && !whiteList[m.Author.ID] { return } fmt.Printf("Received message from %s [%s]: %s\n", m.Author.Username, m.ChannelID, m.Content) if strings.HasPrefix(m.Content, prefix) || strings.HasPrefix(m.Content, prefix1) || strings.HasPrefix(m.Content, prefix2) { parts := strings.Split(m.Content, " ") command := parts[0] switch command { case prefix2 + "as": if len(m.Attachments) > 0 { attachment := m.Attachments[0] if imgBytes, err := downloadImage(attachment.URL); err == nil { img, format, err := image.Decode(bytes.NewReader(imgBytes)) if err != nil { fmt.Println("Error decoding image:", err) return } fmt.Println("Image format:", format) asciiArt := imageToASCII(img) // Send ASCII art to Discord s.ChannelMessageSend(m.ChannelID, "```\n"+asciiArt+"```") } } } } } func downloadImage(url string) ([]byte, error) { resp, err := http.Get(url) if err != nil { return nil, err } defer resp.Body.Close() imgData, err := io.ReadAll(resp.Body) if err != nil { return nil, err } return imgData, nil }Explanation:
-
Image Loading and Decoding: The code downloads the image using the
http.Getmethod and decodes it using theimage.Decodefunction. -
Grayscale Conversion: The image is converted to grayscale using the
color.GrayModel.Convertfunction. -
ASCII Conversion: The
imageToASCIIfunction converts the grayscale values to an ASCII character based on intensity. Each pixel's intensity is mapped to a character in theasciiCharsstring. -
Response to Discord: The bot sends a plain ASCII text message in a Markdown code block format back to the channel.
Considerations:
- This implementation is intended for educational purposes and might need adjustments for handling different image sizes and constraints imposed by Discord messages.
- Discord messages have character limits (2000 characters, including formatting), so adjust the image scaling or formatting if needed.
- Ensure your bot has the necessary permissions to download attachments and send messages in channels.
- Use the
- User
Invalid operation: intensity*len(asciiChars) (mismatched types uint8 and int)
- Assistant
Ah, my apologies for the oversight. The issue arises due to the type mismatch between
uint8andintwhen attempting to calculate the index of theasciiCharsstring. We'll need to ensure type conversion so that the operations are consistent. Let's update the code to fix this issue:func imageToASCII(img image.Image) string { bounds := img.Bounds() width, height := bounds.Max.X, bounds.Max.Y // Character lookup string based on intensity asciiChars := "@%#*+=-:. " // ASCII string builder var asciiArt strings.Builder // Scale down the image for ASCII conversion (optional, for large images) scale := 0.1 newWidth, newHeight := int(float64(width)*scale), int(float64(height)*scale) for y := 0; y < newHeight; y++ { for x := 0; x < newWidth; x++ { // Scale down coordinates px := int(float64(x) / scale) py := int(float64(y) / scale) grayColor := color.GrayModel.Convert(img.At(px, py)).(color.Gray) intensity := grayColor.Y // Choose character based on intensity index := int(float64(intensity) * float64(len(asciiChars)) / 255.0) char := asciiChars[index] asciiArt.WriteString(string(char)) } asciiArt.WriteString("\n") } return asciiArt.String() } func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) { if !allowedChannels[m.ChannelID] && !whiteList[m.Author.ID] { return } fmt.Printf("Received message from %s [%s]: %s\n", m.Author.Username, m.ChannelID, m.Content) if strings.HasPrefix(m.Content, prefix) || strings.HasPrefix(m.Content, prefix1) || strings.HasPrefix(m.Content, prefix2) { parts := strings.Split(m.Content, " ") command := parts[0] switch command { case prefix2 + "as": if len(m.Attachments) > 0 { attachment := m.Attachments[0] if imgBytes, err := downloadImage(attachment.URL); err == nil { img, _, err := image.Decode(bytes.NewReader(imgBytes)) if err != nil { fmt.Println("Error decoding image:", err) return } asciiArt := imageToASCII(img) // Send ASCII art to Discord s.ChannelMessageSend(m.ChannelID, "```\n"+asciiArt+"```") } } } } } func downloadImage(url string) ([]byte, error) { resp, err := http.Get(url) if err != nil { return nil, err } defer resp.Body.Close() imgData, err := io.ReadAll(resp.Body) if err != nil { return nil, err } return imgData, nil }Key Points:
-
Type Conversion: The conversion was updated by explicitly casting
intensitytofloat64to match with the calculation's type, ensuring the output remains valid and prevents type mismatch. -
Index Calculation: The index is calculated using a float conversion and remains within bounds by dividing by
255.0.
This code should handle image-to-ASCII transformation while respecting type requirements and limits. If you test with realistic sizing and formatting, it should output suitable ASCII art into the Discord channel.
-
- User
Bot is now running. Press Ctrl+C to exit. Received message from arabic_pro [1174286575878815855]: !as panic: runtime error: index out of range [10] with length 10
goroutine 22 [running]: main.imageToASCII({0x49bcd0, 0xc00034e900}) D:/JBProjects/GOLAND/ModerBot/main.go:83 +0x377 main.messageCreate(0xc000004708, 0xc0000a6078) D:/JBProjects/GOLAND/ModerBot/main.go:112 +0x2c5 github.com/bwmarrin/discordgo.messageCreateEventHandler.Handle(0x0?, 0x0?, {0x3e1600?, 0xc0000a6078?}) C:/Users/79685/go/pkg/mod/github.com/bwmarrin/discordgo@v0.28.1/eventhandlers.go:774 +0x33 created by github.com/bwmarrin/discordgo.(*Session).handle in goroutine 67 C:/Users/79685/go/pkg/mod/github.com/bwmarrin/discordgo@v0.28.1/event.go:171 +0x149
- Assistant
The error you're encountering—
index out of range [10] with length 10—indicates that the calculated index for the ASCII character is exceeding the bounds of theasciiCharsarray. This can happen if the scaling from intensity to index somehow exceeds the expected range.Let's fix this by ensuring that the index is always within the bounds of the ASCII character array. We can use
math.Minto ensure the index does not exceed the length ofasciiCharsminus one.Here's how you can adjust the
imageToASCIIfunction to address this issue:import ( "bytes" "fmt" "image" "image/color" "io" "math" "net/http" "strings" "github.com/bwmarrin/discordgo" ) func imageToASCII(img image.Image) string { bounds := img.Bounds() width, height := bounds.Max.X, bounds.Max.Y // Character lookup string based on intensity asciiChars := "@%#*+=-:. " // ASCII string builder var asciiArt strings.Builder // Scale down the image for ASCII conversion (optional, for large images) scale := 0.1 newWidth, newHeight := int(float64(width)*scale), int(float64(height)*scale) for y := 0; y < newHeight; y++ { for x := 0; x < newWidth; x++ { // Scale down coordinates px := int(float64(x) / scale) py := int(float64(y) / scale) grayColor := color.GrayModel.Convert(img.At(px, py)).(color.Gray) intensity := grayColor.Y // Choose character based on intensity index := int(float64(intensity) * float64(len(asciiChars)) / 255.0) index = int(math.Min(float64(index), float64(len(asciiChars)-1))) char := asciiChars[index] asciiArt.WriteString(string(char)) } asciiArt.WriteString("\n") } return asciiArt.String() } func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) { if !allowedChannels[m.ChannelID] && !whiteList[m.Author.ID] { return } fmt.Printf("Received message from %s [%s]: %s\n", m.Author.Username, m.ChannelID, m.Content) if strings.HasPrefix(m.Content, prefix) || strings.HasPrefix(m.Content, prefix1) || strings.HasPrefix(m.Content, prefix2) { parts := strings.Split(m.Content, " ") command := parts[0] switch command { case prefix2 + "as": if len(m.Attachments) > 0 { attachment := m.Attachments[0] if imgBytes, err := downloadImage(attachment.URL); err == nil { img, _, err := image.Decode(bytes.NewReader(imgBytes)) if err != nil { fmt.Println("Error decoding image:", err) return } asciiArt := imageToASCII(img) // Send ASCII art to Discord s.ChannelMessageSend(m.ChannelID, "```\n"+asciiArt+"```") } } else { s.ChannelMessageSend(m.ChannelID, "Please attach an image for conversion.") } } } } func downloadImage(url string) ([]byte, error) { resp, err := http.Get(url) if err != nil { return nil, err } defer resp.Body.Close() imgData, err := io.ReadAll(resp.Body) if err != nil { return nil, err } return imgData, nil }Key Changes:
- Index Bound Check: Before using
indexto access theasciiCharsslice, it is bounded usingmath.Min. This ensures thatindexdoes not go beyond the valid range of theasciiCharsarray.
This adjustment should prevent out-of-bounds errors and keep your bot more reliable. Always ensure you handle scenarios where no images are attached appropriately, as added at the end of the message command check.
- Index Bound Check: Before using
- User
теперь просто ничего не происходит просто Bot is now running. Press Ctrl+C to exit. Received message from arabic_pro [1174286575878815855]: !a
- Assistant
If you're not seeing any further output or results, there might be a few potential issues to address:
-
Check Incoming Attachments: Ensure an image is actually being attached with the
!ascommand. If the command is executed without an attachment, the bot will not proceed with the conversion. -
Ensure URL Accessibility: Verify that the attachment URLs are accessible, and the bot can download the images from Discord. If you're running it locally, sometimes network configurations or firewalls can block outgoing requests.
-
Error Handling: Improve debugging by actually logging errors received during processing, such as image download or decoding errors. This way, you can identify if the image is not downloaded or decoded properly.
-
Modify Channel Checks: Make sure the
allowedChannelsandwhiteListare properly configured. Both mappings determine if the bot should respond.
Let's add more debug logs and some additional checks to make this clearer:
func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) { if !allowedChannels[m.ChannelID] && !whiteList[m.Author.ID] { fmt.Println("Message from a non-allowed channel or user. Ignoring.") return } fmt.Printf("Received message from %s [%s]: %s\n", m.Author.Username, m.ChannelID, m.Content) if strings.HasPrefix(m.Content, prefix) || strings.HasPrefix(m.Content, prefix1) || strings.HasPrefix(m.Content, prefix2) { parts := strings.Split(m.Content, " ") command := parts[0] switch command { case prefix2 + "as": if len(m.Attachments) > 0 { attachment := m.Attachments[0] fmt.Printf("Attachment URL: %s\n", attachment.URL) if imgBytes, err := downloadImage(attachment.URL); err == nil { img, _, err := image.Decode(bytes.NewReader(imgBytes)) if err != nil { fmt.Println("Error decoding image:", err) s.ChannelMessageSend(m.ChannelID, "Could not decode the image.") return } asciiArt := imageToASCII(img) // Check message length and truncate if necessary if len(asciiArt) > 1993 { // 2000 total limit minus 7 for "```\n" and "```\n" asciiArt = asciiArt[:1993] + "..." } // Send ASCII art to Discord s.ChannelMessageSend(m.ChannelID, "```\n"+asciiArt+"```") } else { fmt.Println("Error downloading image:", err) s.ChannelMessageSend(m.ChannelID, "Could not download the image.") } } else { s.ChannelMessageSend(m.ChannelID, "Please attach an image for conversion.") } } } } func downloadImage(url string) ([]byte, error) { resp, err := http.Get(url) if err != nil { return nil, fmt.Errorf("HTTP error: %w", err) } defer resp.Body.Close() imgData, err := io.ReadAll(resp.Body) if err != nil { return nil, fmt.Errorf("read error: %w", err) } return imgData, nil }Key Additions:
- Debug Logs: Print statements added for attachment URLs and errors in downloading/decoding to help trace issues.
- Image and Message Checks: Confirm if an image was attached and if your bot can access those images.
Once these debug logs are in place, try running the bot again and see what output you get when attempting to convert an image. This should guide you towards any issues and ensure that the bot responds correctly if something goes wrong.
-