main.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package main
  2. import (
  3. "flag"
  4. "fmt"
  5. "log"
  6. "os"
  7. "os/signal"
  8. "strings"
  9. "time"
  10. "github.com/bwmarrin/discordgo"
  11. )
  12. // Flags
  13. var (
  14. BotToken = flag.String("token", "", "Bot token")
  15. )
  16. const timeout time.Duration = time.Second * 10
  17. var games map[string]time.Time = make(map[string]time.Time)
  18. func init() { flag.Parse() }
  19. func main() {
  20. s, _ := discordgo.New("Bot " + *BotToken)
  21. s.AddHandler(func(s *discordgo.Session, r *discordgo.Ready) {
  22. fmt.Println("Bot is ready")
  23. })
  24. s.AddHandler(func(s *discordgo.Session, m *discordgo.MessageCreate) {
  25. if strings.Contains(m.Content, "ping") {
  26. if ch, err := s.State.Channel(m.ChannelID); err != nil || !ch.IsThread() {
  27. thread, err := s.MessageThreadStartComplex(m.ChannelID, m.ID, &discordgo.ThreadStart{
  28. Name: "Pong game with " + m.Author.Username,
  29. AutoArchiveDuration: 60,
  30. Invitable: false,
  31. RateLimitPerUser: 10,
  32. })
  33. if err != nil {
  34. panic(err)
  35. }
  36. _, _ = s.ChannelMessageSend(thread.ID, "pong")
  37. m.ChannelID = thread.ID
  38. } else {
  39. _, _ = s.ChannelMessageSendReply(m.ChannelID, "pong", m.Reference())
  40. }
  41. games[m.ChannelID] = time.Now()
  42. <-time.After(timeout)
  43. if time.Since(games[m.ChannelID]) >= timeout {
  44. _, err := s.ChannelEditComplex(m.ChannelID, &discordgo.ChannelEdit{
  45. Archived: true,
  46. Locked: true,
  47. })
  48. if err != nil {
  49. panic(err)
  50. }
  51. }
  52. }
  53. })
  54. s.Identify.Intents = discordgo.MakeIntent(discordgo.IntentsAllWithoutPrivileged)
  55. err := s.Open()
  56. if err != nil {
  57. log.Fatalf("Cannot open the session: %v", err)
  58. }
  59. defer s.Close()
  60. stop := make(chan os.Signal, 1)
  61. signal.Notify(stop, os.Interrupt)
  62. <-stop
  63. log.Println("Graceful shutdown")
  64. }