discord.go 8.1 KB

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