discord.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "regexp"
  6. "strings"
  7. "github.com/ayntgl/discordgo"
  8. "github.com/gen2brain/beeep"
  9. "github.com/rivo/tview"
  10. )
  11. var (
  12. boldRegex = regexp.MustCompile(`(?m)\*\*(.*?)\*\*`)
  13. italicRegex = regexp.MustCompile(`(?m)\*(.*?)\*`)
  14. underlineRegex = regexp.MustCompile(`(?m)__(.*?)__`)
  15. strikeThroughRegex = regexp.MustCompile(`(?m)~~(.*?)~~`)
  16. )
  17. func newSession() *discordgo.Session {
  18. s, err := discordgo.New()
  19. if err != nil {
  20. panic(err)
  21. }
  22. s.UserAgent = conf.UserAgent
  23. s.Identify.Compress = false
  24. s.Identify.Intents = 0
  25. s.Identify.LargeThreshold = 0
  26. s.Identify.Properties.Device = ""
  27. s.Identify.Properties.Browser = "Chrome"
  28. s.Identify.Properties.OS = "Linux"
  29. s.AddHandlerOnce(onSessionReady)
  30. s.AddHandler(onSessionMessageCreate)
  31. return s
  32. }
  33. func onSessionReady(_ *discordgo.Session, r *discordgo.Ready) {
  34. dmNode := tview.NewTreeNode("Direct Messages").
  35. Collapse()
  36. n := channelsTree.GetRoot()
  37. n.AddChild(dmNode)
  38. createPrivateChannels(dmNode)
  39. createGuilds(n)
  40. channelsTree.SetCurrentNode(n)
  41. }
  42. func onSessionMessageCreate(_ *discordgo.Session, m *discordgo.MessageCreate) {
  43. c, err := session.State.Channel(m.ChannelID)
  44. if err != nil {
  45. return
  46. }
  47. if selectedChannel == nil || selectedChannel.ID != m.ChannelID {
  48. if conf.Notifications {
  49. for _, u := range m.Mentions {
  50. if u.ID == session.State.User.ID {
  51. g, err := session.State.Guild(m.GuildID)
  52. if err != nil {
  53. return
  54. }
  55. go beeep.Alert(fmt.Sprintf("%s (#%s)", g.Name, c.Name), m.ContentWithMentionsReplaced(), "")
  56. return
  57. }
  58. }
  59. }
  60. cn := getTreeNodeByReference(c.ID)
  61. if cn == nil {
  62. return
  63. }
  64. cn.SetText("[::b]" + generateChannelRepr(c) + "[::-]")
  65. app.Draw()
  66. } else {
  67. selectedChannel.Messages = append(selectedChannel.Messages, m.Message)
  68. messagesView.Write(buildMessage(m.Message))
  69. }
  70. }
  71. type loginResponse struct {
  72. MFA bool `json:"mfa"`
  73. SMS bool `json:"sms"`
  74. Ticket string `json:"ticket"`
  75. Token string `json:"token"`
  76. }
  77. func login(email, password string) (*loginResponse, error) {
  78. data := struct {
  79. Email string `json:"email"`
  80. Password string `json:"password"`
  81. }{email, password}
  82. resp, err := session.RequestWithBucketID(
  83. "POST",
  84. discordgo.EndpointLogin,
  85. data,
  86. discordgo.EndpointLogin,
  87. )
  88. if err != nil {
  89. return nil, err
  90. }
  91. var lr loginResponse
  92. err = json.Unmarshal(resp, &lr)
  93. if err != nil {
  94. return nil, err
  95. }
  96. return &lr, nil
  97. }
  98. func totp(code, ticket string) (*loginResponse, error) {
  99. data := struct {
  100. Code string `json:"code"`
  101. Ticket string `json:"ticket"`
  102. }{code, ticket}
  103. e := discordgo.EndpointAuth + "mfa/totp"
  104. resp, err := session.RequestWithBucketID("POST", e, data, e)
  105. if err != nil {
  106. return nil, err
  107. }
  108. var lr loginResponse
  109. err = json.Unmarshal(resp, &lr)
  110. if err != nil {
  111. return nil, err
  112. }
  113. return &lr, nil
  114. }
  115. func buildMessage(m *discordgo.Message) []byte {
  116. var b strings.Builder
  117. switch m.Type {
  118. case discordgo.MessageTypeDefault, discordgo.MessageTypeReply:
  119. // Define a new region and assign message ID as the region ID.
  120. // Learn more:
  121. // https://pkg.go.dev/github.com/rivo/tview#hdr-Regions_and_Highlights
  122. b.WriteString("[\"")
  123. b.WriteString(m.ID)
  124. b.WriteString("\"]")
  125. // Build the message associated with crosspost, channel follow add, pin, or a reply.
  126. buildReferencedMessage(&b, m.ReferencedMessage)
  127. // Build the author of this message.
  128. buildAuthor(&b, m.Author)
  129. // Build the contents of the message.
  130. buildContent(&b, m)
  131. if m.EditedTimestamp != "" {
  132. b.WriteString(" [::d](edited)[::-]")
  133. }
  134. // Build the embeds associated with the message.
  135. buildEmbeds(&b, m.Embeds)
  136. // Build the message attachments (attached files to the message).
  137. buildAttachments(&b, m.Attachments)
  138. // Tags with no region ID ([""]) do not start new regions. They can
  139. // therefore be used to mark the end of a region.
  140. b.WriteString("[\"\"]")
  141. b.WriteByte('\n')
  142. case discordgo.MessageTypeGuildMemberJoin:
  143. b.WriteString("[#5865F2]")
  144. b.WriteString(m.Author.Username)
  145. b.WriteString("[-] joined the server")
  146. b.WriteByte('\n')
  147. }
  148. if str := b.String(); str != "" {
  149. b := make([]byte, len(str)+1)
  150. copy(b, str)
  151. return b
  152. }
  153. return nil
  154. }
  155. func buildReferencedMessage(b *strings.Builder, rm *discordgo.Message) {
  156. if rm != nil {
  157. b.WriteString(" ╭ ")
  158. b.WriteString("[::d]")
  159. buildAuthor(b, rm.Author)
  160. if rm.Content != "" {
  161. rm.Content = buildMentions(rm.Content, rm.Mentions)
  162. b.WriteString(parseMarkdown(rm.Content))
  163. }
  164. b.WriteString("[::-]")
  165. b.WriteByte('\n')
  166. }
  167. }
  168. func buildContent(b *strings.Builder, m *discordgo.Message) {
  169. if m.Content != "" {
  170. m.Content = buildMentions(m.Content, m.Mentions)
  171. b.WriteString(parseMarkdown(m.Content))
  172. }
  173. }
  174. func buildEmbeds(b *strings.Builder, es []*discordgo.MessageEmbed) {
  175. for _, e := range es {
  176. if e.Type != discordgo.EmbedTypeRich {
  177. continue
  178. }
  179. var embedBuilder strings.Builder
  180. var hasHeading bool
  181. prefix := fmt.Sprintf("[#%06X]▐[-] ", e.Color)
  182. b.WriteByte('\n')
  183. embedBuilder.WriteString(prefix)
  184. if e.Author != nil {
  185. hasHeading = true
  186. embedBuilder.WriteString("[::u]")
  187. embedBuilder.WriteString(e.Author.Name)
  188. embedBuilder.WriteString("[::-]")
  189. }
  190. if e.Title != "" {
  191. hasHeading = true
  192. embedBuilder.WriteString("[::b]")
  193. embedBuilder.WriteString(e.Title)
  194. embedBuilder.WriteString("[::-]")
  195. }
  196. if e.Description != "" {
  197. if hasHeading {
  198. embedBuilder.WriteString("\n\n")
  199. }
  200. embedBuilder.WriteString(parseMarkdown(e.Description))
  201. }
  202. if len(e.Fields) != 0 {
  203. if hasHeading || e.Description != "" {
  204. embedBuilder.WriteString("\n\n")
  205. }
  206. for i, ef := range e.Fields {
  207. embedBuilder.WriteString("[::b]")
  208. embedBuilder.WriteString(ef.Name)
  209. embedBuilder.WriteString("[::-]")
  210. embedBuilder.WriteByte('\n')
  211. embedBuilder.WriteString(parseMarkdown(ef.Value))
  212. if i != len(e.Fields)-1 {
  213. embedBuilder.WriteString("\n\n")
  214. }
  215. }
  216. }
  217. if e.Footer != nil {
  218. if hasHeading {
  219. embedBuilder.WriteString("\n\n")
  220. }
  221. embedBuilder.WriteString(e.Footer.Text)
  222. }
  223. b.WriteString(strings.Replace(embedBuilder.String(), "\n", "\n"+prefix, -1))
  224. }
  225. }
  226. func buildAttachments(b *strings.Builder, as []*discordgo.MessageAttachment) {
  227. for _, a := range as {
  228. b.WriteByte('\n')
  229. b.WriteByte('[')
  230. b.WriteString(a.Filename)
  231. b.WriteString("]: ")
  232. b.WriteString(a.URL)
  233. }
  234. }
  235. func buildMentions(content string, mentions []*discordgo.User) string {
  236. for _, mUser := range mentions {
  237. var color string
  238. if mUser.ID == session.State.User.ID {
  239. color = "[:#5865F2]"
  240. } else {
  241. color = "[#EB459E]"
  242. }
  243. content = strings.NewReplacer(
  244. // <@USER_ID>
  245. "<@"+mUser.ID+">",
  246. color+"@"+mUser.Username+"[-:-]",
  247. // <@!USER_ID>
  248. "<@!"+mUser.ID+">",
  249. color+"@"+mUser.Username+"[-:-]",
  250. ).Replace(content)
  251. }
  252. return content
  253. }
  254. func buildAuthor(b *strings.Builder, u *discordgo.User) {
  255. if u.ID == session.State.User.ID {
  256. b.WriteString("[#57F287]")
  257. } else {
  258. b.WriteString("[#ED4245]")
  259. }
  260. b.WriteString(u.Username)
  261. b.WriteString("[-] ")
  262. // If the message author is a bot account, render the message with bot label
  263. // for distinction.
  264. if u.Bot {
  265. b.WriteString("[#EB459E]BOT[-] ")
  266. }
  267. }
  268. func parseMarkdown(md string) string {
  269. var res string
  270. res = boldRegex.ReplaceAllString(md, "[::b]$1[::-]")
  271. res = italicRegex.ReplaceAllString(res, "[::i]$1[::-]")
  272. res = underlineRegex.ReplaceAllString(res, "[::u]$1[::-]")
  273. res = strikeThroughRegex.ReplaceAllString(res, "[::s]$1[::-]")
  274. return res
  275. }