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