90 lines
2 KiB
Go
90 lines
2 KiB
Go
package discordBot
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"fmt"
|
|
"github.com/disgoorg/disgo"
|
|
"github.com/disgoorg/disgo/bot"
|
|
"github.com/disgoorg/disgo/discord"
|
|
"github.com/disgoorg/disgo/gateway"
|
|
"github.com/disgoorg/snowflake/v2"
|
|
log "github.com/sirupsen/logrus"
|
|
"tg-disc-bot/config"
|
|
"tg-disc-bot/dto"
|
|
)
|
|
|
|
type DiscordBot struct {
|
|
ctx context.Context
|
|
client bot.Client
|
|
guildID snowflake.ID
|
|
channelID snowflake.ID
|
|
token string
|
|
}
|
|
|
|
func NewDiscordBot(ctx context.Context, config config.DiscordConfig) (*DiscordBot, error) {
|
|
var err error
|
|
dsBot := &DiscordBot{
|
|
ctx: ctx,
|
|
channelID: config.ChannelID,
|
|
token: config.Token,
|
|
}
|
|
|
|
dsBot.client, err = disgo.New(config.Token,
|
|
bot.WithGatewayConfigOpts(
|
|
gateway.WithIntents(
|
|
gateway.IntentGuilds,
|
|
gateway.IntentGuildMessages,
|
|
gateway.IntentDirectMessages,
|
|
gateway.IntentMessageContent,
|
|
),
|
|
),
|
|
)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return dsBot, nil
|
|
}
|
|
|
|
func (d *DiscordBot) Start(fromTelegram <-chan dto.TelegramDTO) chan dto.DiscordDTO {
|
|
log.Info("Starting discord bot...")
|
|
|
|
msgChan := make(chan dto.DiscordDTO, 100)
|
|
d.client.AddEventListeners(&messageHandler{msgChan: msgChan})
|
|
|
|
go func() {
|
|
for msg := range fromTelegram {
|
|
log.WithField("content", msg).Debug("DS | Message from Telegram")
|
|
|
|
var files []*discord.File
|
|
for _, media := range *(msg.Images) {
|
|
file := &discord.File{
|
|
Name: media.Filename,
|
|
Reader: bytes.NewReader(media.Data),
|
|
}
|
|
files = append(files, file)
|
|
}
|
|
|
|
m := discord.MessageCreate{Content: fmt.Sprintf("**[%s]**\n%s", msg.AuthorName, msg.Content)}
|
|
|
|
if len(files) > 0 {
|
|
m.Files = append(m.Files, files...)
|
|
|
|
}
|
|
|
|
_, err := d.client.Rest().CreateMessage(d.channelID, m)
|
|
if err != nil {
|
|
log.Errorf("Failed to send message to Discord: %v", err)
|
|
continue
|
|
}
|
|
}
|
|
}()
|
|
|
|
go func() {
|
|
if err := d.client.OpenGateway(d.ctx); err != nil {
|
|
log.Fatalf("Failed to open discord gateway %v", err)
|
|
}
|
|
}()
|
|
|
|
return msgChan
|
|
}
|