discord.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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. case discordgo.MessageTypeCall:
  148. b.WriteString("[#5865F2]")
  149. b.WriteString(m.Author.Username)
  150. b.WriteString("[-] started a call.")
  151. b.WriteByte('\n')
  152. case discordgo.MessageTypeChannelPinnedMessage:
  153. b.WriteString("[#5865F2]")
  154. b.WriteString(m.Author.Username)
  155. b.WriteString("[-] pinned a message.")
  156. b.WriteByte('\n')
  157. }
  158. if str := b.String(); str != "" {
  159. b := make([]byte, len(str)+1)
  160. copy(b, str)
  161. return b
  162. }
  163. return nil
  164. }
  165. func buildReferencedMessage(b *strings.Builder, rm *discordgo.Message) {
  166. if rm != nil {
  167. b.WriteString(" ╭ ")
  168. b.WriteString("[::d]")
  169. buildAuthor(b, rm.Author)
  170. if rm.Content != "" {
  171. rm.Content = buildMentions(rm.Content, rm.Mentions)
  172. b.WriteString(parseMarkdown(rm.Content))
  173. }
  174. b.WriteString("[::-]")
  175. b.WriteByte('\n')
  176. }
  177. }
  178. func buildContent(b *strings.Builder, m *discordgo.Message) {
  179. if m.Content != "" {
  180. m.Content = buildMentions(m.Content, m.Mentions)
  181. b.WriteString(parseMarkdown(m.Content))
  182. }
  183. }
  184. func buildEmbeds(b *strings.Builder, es []*discordgo.MessageEmbed) {
  185. for _, e := range es {
  186. if e.Type != discordgo.EmbedTypeRich {
  187. continue
  188. }
  189. var embedBuilder strings.Builder
  190. var hasHeading bool
  191. prefix := fmt.Sprintf("[#%06X]▐[-] ", e.Color)
  192. b.WriteByte('\n')
  193. embedBuilder.WriteString(prefix)
  194. if e.Author != nil {
  195. hasHeading = true
  196. embedBuilder.WriteString("[::u]")
  197. embedBuilder.WriteString(e.Author.Name)
  198. embedBuilder.WriteString("[::-]")
  199. }
  200. if e.Title != "" {
  201. hasHeading = true
  202. embedBuilder.WriteString("[::b]")
  203. embedBuilder.WriteString(e.Title)
  204. embedBuilder.WriteString("[::-]")
  205. }
  206. if e.Description != "" {
  207. if hasHeading {
  208. embedBuilder.WriteString("\n\n")
  209. }
  210. embedBuilder.WriteString(parseMarkdown(e.Description))
  211. }
  212. if len(e.Fields) != 0 {
  213. if hasHeading || e.Description != "" {
  214. embedBuilder.WriteString("\n\n")
  215. }
  216. for i, ef := range e.Fields {
  217. embedBuilder.WriteString("[::b]")
  218. embedBuilder.WriteString(ef.Name)
  219. embedBuilder.WriteString("[::-]")
  220. embedBuilder.WriteByte('\n')
  221. embedBuilder.WriteString(parseMarkdown(ef.Value))
  222. if i != len(e.Fields)-1 {
  223. embedBuilder.WriteString("\n\n")
  224. }
  225. }
  226. }
  227. if e.Footer != nil {
  228. if hasHeading {
  229. embedBuilder.WriteString("\n\n")
  230. }
  231. embedBuilder.WriteString(e.Footer.Text)
  232. }
  233. b.WriteString(strings.Replace(embedBuilder.String(), "\n", "\n"+prefix, -1))
  234. }
  235. }
  236. func buildAttachments(b *strings.Builder, as []*discordgo.MessageAttachment) {
  237. for _, a := range as {
  238. b.WriteByte('\n')
  239. b.WriteByte('[')
  240. b.WriteString(a.Filename)
  241. b.WriteString("]: ")
  242. b.WriteString(a.URL)
  243. }
  244. }
  245. func buildMentions(content string, mentions []*discordgo.User) string {
  246. for _, mUser := range mentions {
  247. var color string
  248. if mUser.ID == session.State.User.ID {
  249. color = "[:#5865F2]"
  250. } else {
  251. color = "[#EB459E]"
  252. }
  253. content = strings.NewReplacer(
  254. // <@USER_ID>
  255. "<@"+mUser.ID+">",
  256. color+"@"+mUser.Username+"[-:-]",
  257. // <@!USER_ID>
  258. "<@!"+mUser.ID+">",
  259. color+"@"+mUser.Username+"[-:-]",
  260. ).Replace(content)
  261. }
  262. return content
  263. }
  264. func buildAuthor(b *strings.Builder, u *discordgo.User) {
  265. if u.ID == session.State.User.ID {
  266. b.WriteString("[#57F287]")
  267. } else {
  268. b.WriteString("[#ED4245]")
  269. }
  270. b.WriteString(u.Username)
  271. b.WriteString("[-] ")
  272. // If the message author is a bot account, render the message with bot label
  273. // for distinction.
  274. if u.Bot {
  275. b.WriteString("[#EB459E]BOT[-] ")
  276. }
  277. }
  278. func parseMarkdown(md string) string {
  279. var res string
  280. res = boldRegex.ReplaceAllString(md, "[::b]$1[::-]")
  281. res = italicRegex.ReplaceAllString(res, "[::i]$1[::-]")
  282. res = underlineRegex.ReplaceAllString(res, "[::u]$1[::-]")
  283. res = strikeThroughRegex.ReplaceAllString(res, "[::s]$1[::-]")
  284. return res
  285. }