discord.go 8.3 KB

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