discord.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  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 := channelsTree.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. channelsTree.SetCurrentNode(n)
  61. }
  62. func onSessionMessageCreate(_ *discordgo.Session, m *discordgo.MessageCreate) {
  63. c, err := session.State.Channel(m.ChannelID)
  64. if err != nil {
  65. return
  66. }
  67. if selectedChannel == nil || selectedChannel.ID != m.ChannelID {
  68. if conf.Notifications {
  69. for _, u := range m.Mentions {
  70. if u.ID == session.State.User.ID {
  71. g, err := session.State.Guild(m.GuildID)
  72. if err != nil {
  73. return
  74. }
  75. go beeep.Alert(fmt.Sprintf("%s (#%s)", g.Name, c.Name), m.ContentWithMentionsReplaced(), "")
  76. return
  77. }
  78. }
  79. }
  80. cn := getTreeNodeByReference(channelsTree, c.ID)
  81. if cn == nil {
  82. return
  83. }
  84. cn.SetText("[::b]" + channelToString(c) + "[::-]")
  85. app.Draw()
  86. } else {
  87. selectedChannel.Messages = append(selectedChannel.Messages, m.Message)
  88. messagesView.Write(buildMessage(m.Message))
  89. // Scroll to the end of the text if any message is selected.
  90. if len(messagesView.GetHighlights()) != 0 {
  91. messagesView.ScrollToEnd()
  92. }
  93. }
  94. }
  95. // channelToString constructs a string representation of the given channel. The string representation may vary for different channel types.
  96. func channelToString(c *discordgo.Channel) string {
  97. var repr string
  98. if c.Name != "" {
  99. repr = "#" + c.Name
  100. } else if len(c.Recipients) == 1 {
  101. rp := c.Recipients[0]
  102. repr = rp.Username + "#" + rp.Discriminator
  103. } else {
  104. rps := make([]string, len(c.Recipients))
  105. for i, r := range c.Recipients {
  106. rps[i] = r.Username + "#" + r.Discriminator
  107. }
  108. repr = strings.Join(rps, ", ")
  109. }
  110. return repr
  111. }
  112. type loginResponse struct {
  113. MFA bool `json:"mfa"`
  114. SMS bool `json:"sms"`
  115. Ticket string `json:"ticket"`
  116. Token string `json:"token"`
  117. }
  118. func login(email, password string) (*loginResponse, error) {
  119. data := struct {
  120. Email string `json:"email"`
  121. Password string `json:"password"`
  122. }{email, password}
  123. resp, err := session.RequestWithBucketID(
  124. "POST",
  125. discordgo.EndpointLogin,
  126. data,
  127. discordgo.EndpointLogin,
  128. )
  129. if err != nil {
  130. return nil, err
  131. }
  132. var lr loginResponse
  133. err = json.Unmarshal(resp, &lr)
  134. if err != nil {
  135. return nil, err
  136. }
  137. return &lr, nil
  138. }
  139. func totp(code, ticket string) (*loginResponse, error) {
  140. data := struct {
  141. Code string `json:"code"`
  142. Ticket string `json:"ticket"`
  143. }{code, ticket}
  144. e := discordgo.EndpointAuth + "mfa/totp"
  145. resp, err := session.RequestWithBucketID("POST", e, data, e)
  146. if err != nil {
  147. return nil, err
  148. }
  149. var lr loginResponse
  150. err = json.Unmarshal(resp, &lr)
  151. if err != nil {
  152. return nil, err
  153. }
  154. return &lr, nil
  155. }
  156. func buildMessage(m *discordgo.Message) []byte {
  157. var b strings.Builder
  158. switch m.Type {
  159. case discordgo.MessageTypeDefault, discordgo.MessageTypeReply:
  160. // Define a new region and assign message ID as the region ID.
  161. // Learn more:
  162. // https://pkg.go.dev/github.com/rivo/tview#hdr-Regions_and_Highlights
  163. b.WriteString("[\"")
  164. b.WriteString(m.ID)
  165. b.WriteString("\"]")
  166. // Build the message associated with crosspost, channel follow add, pin, or a reply.
  167. buildReferencedMessage(&b, m.ReferencedMessage)
  168. // Build the author of this message.
  169. buildAuthor(&b, m.Author)
  170. // Build the contents of the message.
  171. buildContent(&b, m)
  172. if m.EditedTimestamp != "" {
  173. b.WriteString(" [::d](edited)[::-]")
  174. }
  175. // Build the embeds associated with the message.
  176. buildEmbeds(&b, m.Embeds)
  177. // Build the message attachments (attached files to the message).
  178. buildAttachments(&b, m.Attachments)
  179. // Tags with no region ID ([""]) do not start new regions. They can
  180. // therefore be used to mark the end of a region.
  181. b.WriteString("[\"\"]")
  182. b.WriteByte('\n')
  183. case discordgo.MessageTypeGuildMemberJoin:
  184. b.WriteString("[#5865F2]")
  185. b.WriteString(m.Author.Username)
  186. b.WriteString("[-] joined the server.")
  187. b.WriteByte('\n')
  188. case discordgo.MessageTypeCall:
  189. b.WriteString("[#5865F2]")
  190. b.WriteString(m.Author.Username)
  191. b.WriteString("[-] started a call.")
  192. b.WriteByte('\n')
  193. case discordgo.MessageTypeChannelPinnedMessage:
  194. b.WriteString("[#5865F2]")
  195. b.WriteString(m.Author.Username)
  196. b.WriteString("[-] pinned a message.")
  197. b.WriteByte('\n')
  198. }
  199. if str := b.String(); str != "" {
  200. b := make([]byte, len(str)+1)
  201. copy(b, str)
  202. return b
  203. }
  204. return nil
  205. }
  206. func buildReferencedMessage(b *strings.Builder, rm *discordgo.Message) {
  207. if rm != nil {
  208. b.WriteString(" ╭ ")
  209. b.WriteString("[::d]")
  210. buildAuthor(b, rm.Author)
  211. if rm.Content != "" {
  212. rm.Content = buildMentions(rm.Content, rm.Mentions)
  213. b.WriteString(parseMarkdown(rm.Content))
  214. }
  215. b.WriteString("[::-]")
  216. b.WriteByte('\n')
  217. }
  218. }
  219. func buildContent(b *strings.Builder, m *discordgo.Message) {
  220. if m.Content != "" {
  221. m.Content = buildMentions(m.Content, m.Mentions)
  222. b.WriteString(parseMarkdown(m.Content))
  223. }
  224. }
  225. func buildEmbeds(b *strings.Builder, es []*discordgo.MessageEmbed) {
  226. for _, e := range es {
  227. if e.Type != discordgo.EmbedTypeRich {
  228. continue
  229. }
  230. var embedBuilder strings.Builder
  231. var hasHeading bool
  232. prefix := fmt.Sprintf("[#%06X]▐[-] ", e.Color)
  233. b.WriteByte('\n')
  234. embedBuilder.WriteString(prefix)
  235. if e.Author != nil {
  236. hasHeading = true
  237. embedBuilder.WriteString("[::u]")
  238. embedBuilder.WriteString(e.Author.Name)
  239. embedBuilder.WriteString("[::-]")
  240. }
  241. if e.Title != "" {
  242. hasHeading = true
  243. embedBuilder.WriteString("[::b]")
  244. embedBuilder.WriteString(e.Title)
  245. embedBuilder.WriteString("[::-]")
  246. }
  247. if e.Description != "" {
  248. if hasHeading {
  249. embedBuilder.WriteString("\n\n")
  250. }
  251. embedBuilder.WriteString(parseMarkdown(e.Description))
  252. }
  253. if len(e.Fields) != 0 {
  254. if hasHeading || e.Description != "" {
  255. embedBuilder.WriteString("\n\n")
  256. }
  257. for i, ef := range e.Fields {
  258. embedBuilder.WriteString("[::b]")
  259. embedBuilder.WriteString(ef.Name)
  260. embedBuilder.WriteString("[::-]")
  261. embedBuilder.WriteByte('\n')
  262. embedBuilder.WriteString(parseMarkdown(ef.Value))
  263. if i != len(e.Fields)-1 {
  264. embedBuilder.WriteString("\n\n")
  265. }
  266. }
  267. }
  268. if e.Footer != nil {
  269. if hasHeading {
  270. embedBuilder.WriteString("\n\n")
  271. }
  272. embedBuilder.WriteString(e.Footer.Text)
  273. }
  274. b.WriteString(strings.Replace(embedBuilder.String(), "\n", "\n"+prefix, -1))
  275. }
  276. }
  277. func buildAttachments(b *strings.Builder, as []*discordgo.MessageAttachment) {
  278. for _, a := range as {
  279. b.WriteByte('\n')
  280. b.WriteByte('[')
  281. b.WriteString(a.Filename)
  282. b.WriteString("]: ")
  283. b.WriteString(a.URL)
  284. }
  285. }
  286. func buildMentions(content string, mentions []*discordgo.User) string {
  287. for _, mUser := range mentions {
  288. var color string
  289. if mUser.ID == session.State.User.ID {
  290. color = "[:#5865F2]"
  291. } else {
  292. color = "[#EB459E]"
  293. }
  294. content = strings.NewReplacer(
  295. // <@USER_ID>
  296. "<@"+mUser.ID+">",
  297. color+"@"+mUser.Username+"[-:-]",
  298. // <@!USER_ID>
  299. "<@!"+mUser.ID+">",
  300. color+"@"+mUser.Username+"[-:-]",
  301. ).Replace(content)
  302. }
  303. return content
  304. }
  305. func buildAuthor(b *strings.Builder, u *discordgo.User) {
  306. if u.ID == session.State.User.ID {
  307. b.WriteString("[#57F287]")
  308. } else {
  309. b.WriteString("[#ED4245]")
  310. }
  311. b.WriteString(u.Username)
  312. b.WriteString("[-] ")
  313. // If the message author is a bot account, render the message with bot label
  314. // for distinction.
  315. if u.Bot {
  316. b.WriteString("[#EB459E]BOT[-] ")
  317. }
  318. }
  319. func parseMarkdown(md string) string {
  320. var res string
  321. res = boldRegex.ReplaceAllString(md, "[::b]$1[::-]")
  322. res = italicRegex.ReplaceAllString(res, "[::i]$1[::-]")
  323. res = underlineRegex.ReplaceAllString(res, "[::u]$1[::-]")
  324. res = strikeThroughRegex.ReplaceAllString(res, "[::s]$1[::-]")
  325. return res
  326. }
  327. // channelIsUnread returns `true` if the given channel is marked as read by the client user, otherwise `false`.
  328. func channelIsUnread(s *discordgo.State, c *discordgo.Channel) bool {
  329. if c.LastMessageID == "" {
  330. return false
  331. }
  332. for _, rs := range s.ReadState {
  333. if c.ID == rs.ID {
  334. return c.LastMessageID != rs.LastMessageID
  335. }
  336. }
  337. return false
  338. }
  339. // findMessageByID returns the index and the `*Message` struct of the current message if the given message ID *mID* is equal to the current message ID. If the given message ID *mID* is not found in the given slice *ms*, `-1` and `nil` are returned instead.
  340. func findMessageByID(ms []*discordgo.Message, mID string) (int, *discordgo.Message) {
  341. for i, m := range ms {
  342. if m.ID == mID {
  343. return i, m
  344. }
  345. }
  346. return -1, nil
  347. }