discord.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. package util
  2. import (
  3. "encoding/json"
  4. "regexp"
  5. "github.com/ayntgl/discordgo"
  6. )
  7. var (
  8. boldRegex = regexp.MustCompile(`(?m)\*\*(.*?)\*\*`)
  9. italicRegex = regexp.MustCompile(`(?m)\*(.*?)\*`)
  10. underlineRegex = regexp.MustCompile(`(?m)__(.*?)__`)
  11. strikeThroughRegex = regexp.MustCompile(`(?m)~~(.*?)~~`)
  12. )
  13. func ParseMarkdown(md string) string {
  14. var res string
  15. res = boldRegex.ReplaceAllString(md, "[::b]$1[::-]")
  16. res = italicRegex.ReplaceAllString(res, "[::i]$1[::-]")
  17. res = underlineRegex.ReplaceAllString(res, "[::u]$1[::-]")
  18. res = strikeThroughRegex.ReplaceAllString(res, "[::s]$1[::-]")
  19. return res
  20. }
  21. func FindMessageByID(ms []*discordgo.Message, mID string) (int, *discordgo.Message) {
  22. for i, m := range ms {
  23. if m.ID == mID {
  24. return i, m
  25. }
  26. }
  27. return -1, nil
  28. }
  29. func ChannelIsUnread(s *discordgo.State, c *discordgo.Channel) bool {
  30. if c.LastMessageID == "" {
  31. return false
  32. }
  33. for _, rs := range s.ReadState {
  34. if c.ID == rs.ID {
  35. return c.LastMessageID != rs.LastMessageID
  36. }
  37. }
  38. return false
  39. }
  40. func HasPermission(s *discordgo.State, cID string, p int64) bool {
  41. perm, err := s.UserChannelPermissions(s.User.ID, cID)
  42. if err != nil {
  43. return false
  44. }
  45. return perm&p == p
  46. }
  47. type loginResponse struct {
  48. MFA bool `json:"mfa"`
  49. SMS bool `json:"sms"`
  50. Ticket string `json:"ticket"`
  51. Token string `json:"token"`
  52. }
  53. func Login(s *discordgo.Session, email string, password string) (*loginResponse, error) {
  54. data := struct {
  55. Email string `json:"email"`
  56. Password string `json:"password"`
  57. }{email, password}
  58. resp, err := s.RequestWithBucketID(
  59. "POST",
  60. discordgo.EndpointLogin,
  61. data,
  62. discordgo.EndpointLogin,
  63. )
  64. if err != nil {
  65. return nil, err
  66. }
  67. var lr loginResponse
  68. err = json.Unmarshal(resp, &lr)
  69. if err != nil {
  70. return nil, err
  71. }
  72. return &lr, nil
  73. }
  74. func TOTP(s *discordgo.Session, code string, ticket string) (*loginResponse, error) {
  75. data := struct {
  76. Code string `json:"code"`
  77. Ticket string `json:"ticket"`
  78. }{code, ticket}
  79. e := discordgo.EndpointAuth + "mfa/totp"
  80. resp, err := s.RequestWithBucketID("POST", e, data, e)
  81. if err != nil {
  82. return nil, err
  83. }
  84. var lr loginResponse
  85. err = json.Unmarshal(resp, &lr)
  86. if err != nil {
  87. return nil, err
  88. }
  89. return &lr, nil
  90. }