discord.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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. // Scroll to the end of the text after the message has been written to the TextView.
  70. messagesView.ScrollToEnd()
  71. }
  72. }
  73. type loginResponse struct {
  74. MFA bool `json:"mfa"`
  75. SMS bool `json:"sms"`
  76. Ticket string `json:"ticket"`
  77. Token string `json:"token"`
  78. }
  79. func login(email, password string) (*loginResponse, error) {
  80. data := struct {
  81. Email string `json:"email"`
  82. Password string `json:"password"`
  83. }{email, password}
  84. resp, err := session.RequestWithBucketID(
  85. "POST",
  86. discordgo.EndpointLogin,
  87. data,
  88. discordgo.EndpointLogin,
  89. )
  90. if err != nil {
  91. return nil, err
  92. }
  93. var lr loginResponse
  94. err = json.Unmarshal(resp, &lr)
  95. if err != nil {
  96. return nil, err
  97. }
  98. return &lr, nil
  99. }
  100. func totp(code, ticket string) (*loginResponse, error) {
  101. data := struct {
  102. Code string `json:"code"`
  103. Ticket string `json:"ticket"`
  104. }{code, ticket}
  105. e := discordgo.EndpointAuth + "mfa/totp"
  106. resp, err := session.RequestWithBucketID("POST", e, data, e)
  107. if err != nil {
  108. return nil, err
  109. }
  110. var lr loginResponse
  111. err = json.Unmarshal(resp, &lr)
  112. if err != nil {
  113. return nil, err
  114. }
  115. return &lr, nil
  116. }
  117. func buildMessage(m *discordgo.Message) []byte {
  118. var b strings.Builder
  119. switch m.Type {
  120. case discordgo.MessageTypeDefault, discordgo.MessageTypeReply:
  121. // Define a new region and assign message ID as the region ID.
  122. // Learn more:
  123. // https://pkg.go.dev/github.com/rivo/tview#hdr-Regions_and_Highlights
  124. b.WriteString("[\"")
  125. b.WriteString(m.ID)
  126. b.WriteString("\"]")
  127. // Build the message associated with crosspost, channel follow add, pin, or a reply.
  128. buildReferencedMessage(&b, m.ReferencedMessage)
  129. // Build the author of this message.
  130. buildAuthor(&b, m.Author)
  131. // Build the contents of the message.
  132. buildContent(&b, m)
  133. if m.EditedTimestamp != "" {
  134. b.WriteString(" [::d](edited)[::-]")
  135. }
  136. // Build the embeds associated with the message.
  137. buildEmbeds(&b, m.Embeds)
  138. // Build the message attachments (attached files to the message).
  139. buildAttachments(&b, m.Attachments)
  140. // Tags with no region ID ([""]) do not start new regions. They can
  141. // therefore be used to mark the end of a region.
  142. b.WriteString("[\"\"]")
  143. b.WriteByte('\n')
  144. case discordgo.MessageTypeGuildMemberJoin:
  145. b.WriteString("[#5865F2]")
  146. b.WriteString(m.Author.Username)
  147. b.WriteString("[-] joined the server.")
  148. b.WriteByte('\n')
  149. case discordgo.MessageTypeCall:
  150. b.WriteString("[#5865F2]")
  151. b.WriteString(m.Author.Username)
  152. b.WriteString("[-] started a call.")
  153. b.WriteByte('\n')
  154. case discordgo.MessageTypeChannelPinnedMessage:
  155. b.WriteString("[#5865F2]")
  156. b.WriteString(m.Author.Username)
  157. b.WriteString("[-] pinned a message.")
  158. b.WriteByte('\n')
  159. }
  160. if str := b.String(); str != "" {
  161. b := make([]byte, len(str)+1)
  162. copy(b, str)
  163. return b
  164. }
  165. return nil
  166. }
  167. func buildReferencedMessage(b *strings.Builder, rm *discordgo.Message) {
  168. if rm != nil {
  169. b.WriteString(" ╭ ")
  170. b.WriteString("[::d]")
  171. buildAuthor(b, rm.Author)
  172. if rm.Content != "" {
  173. rm.Content = buildMentions(rm.Content, rm.Mentions)
  174. b.WriteString(parseMarkdown(rm.Content))
  175. }
  176. b.WriteString("[::-]")
  177. b.WriteByte('\n')
  178. }
  179. }
  180. func buildContent(b *strings.Builder, m *discordgo.Message) {
  181. if m.Content != "" {
  182. m.Content = buildMentions(m.Content, m.Mentions)
  183. b.WriteString(parseMarkdown(m.Content))
  184. }
  185. }
  186. func buildEmbeds(b *strings.Builder, es []*discordgo.MessageEmbed) {
  187. for _, e := range es {
  188. if e.Type != discordgo.EmbedTypeRich {
  189. continue
  190. }
  191. var embedBuilder strings.Builder
  192. var hasHeading bool
  193. prefix := fmt.Sprintf("[#%06X]▐[-] ", e.Color)
  194. b.WriteByte('\n')
  195. embedBuilder.WriteString(prefix)
  196. if e.Author != nil {
  197. hasHeading = true
  198. embedBuilder.WriteString("[::u]")
  199. embedBuilder.WriteString(e.Author.Name)
  200. embedBuilder.WriteString("[::-]")
  201. }
  202. if e.Title != "" {
  203. hasHeading = true
  204. embedBuilder.WriteString("[::b]")
  205. embedBuilder.WriteString(e.Title)
  206. embedBuilder.WriteString("[::-]")
  207. }
  208. if e.Description != "" {
  209. if hasHeading {
  210. embedBuilder.WriteString("\n\n")
  211. }
  212. embedBuilder.WriteString(parseMarkdown(e.Description))
  213. }
  214. if len(e.Fields) != 0 {
  215. if hasHeading || e.Description != "" {
  216. embedBuilder.WriteString("\n\n")
  217. }
  218. for i, ef := range e.Fields {
  219. embedBuilder.WriteString("[::b]")
  220. embedBuilder.WriteString(ef.Name)
  221. embedBuilder.WriteString("[::-]")
  222. embedBuilder.WriteByte('\n')
  223. embedBuilder.WriteString(parseMarkdown(ef.Value))
  224. if i != len(e.Fields)-1 {
  225. embedBuilder.WriteString("\n\n")
  226. }
  227. }
  228. }
  229. if e.Footer != nil {
  230. if hasHeading {
  231. embedBuilder.WriteString("\n\n")
  232. }
  233. embedBuilder.WriteString(e.Footer.Text)
  234. }
  235. b.WriteString(strings.Replace(embedBuilder.String(), "\n", "\n"+prefix, -1))
  236. }
  237. }
  238. func buildAttachments(b *strings.Builder, as []*discordgo.MessageAttachment) {
  239. for _, a := range as {
  240. b.WriteByte('\n')
  241. b.WriteByte('[')
  242. b.WriteString(a.Filename)
  243. b.WriteString("]: ")
  244. b.WriteString(a.URL)
  245. }
  246. }
  247. func buildMentions(content string, mentions []*discordgo.User) string {
  248. for _, mUser := range mentions {
  249. var color string
  250. if mUser.ID == session.State.User.ID {
  251. color = "[:#5865F2]"
  252. } else {
  253. color = "[#EB459E]"
  254. }
  255. content = strings.NewReplacer(
  256. // <@USER_ID>
  257. "<@"+mUser.ID+">",
  258. color+"@"+mUser.Username+"[-:-]",
  259. // <@!USER_ID>
  260. "<@!"+mUser.ID+">",
  261. color+"@"+mUser.Username+"[-:-]",
  262. ).Replace(content)
  263. }
  264. return content
  265. }
  266. func buildAuthor(b *strings.Builder, u *discordgo.User) {
  267. if u.ID == session.State.User.ID {
  268. b.WriteString("[#57F287]")
  269. } else {
  270. b.WriteString("[#ED4245]")
  271. }
  272. b.WriteString(u.Username)
  273. b.WriteString("[-] ")
  274. // If the message author is a bot account, render the message with bot label
  275. // for distinction.
  276. if u.Bot {
  277. b.WriteString("[#EB459E]BOT[-] ")
  278. }
  279. }
  280. func parseMarkdown(md string) string {
  281. var res string
  282. res = boldRegex.ReplaceAllString(md, "[::b]$1[::-]")
  283. res = italicRegex.ReplaceAllString(res, "[::i]$1[::-]")
  284. res = underlineRegex.ReplaceAllString(res, "[::u]$1[::-]")
  285. res = strikeThroughRegex.ReplaceAllString(res, "[::s]$1[::-]")
  286. return res
  287. }