discord.go 7.9 KB

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