state.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. // Discordgo - Discord bindings for Go
  2. // Available at https://github.com/bwmarrin/discordgo
  3. // Copyright 2015-2016 Bruce Marriner <bruce@sqls.net>. All rights reserved.
  4. // Use of this source code is governed by a BSD-style
  5. // license that can be found in the LICENSE file.
  6. // This file contains code related to state tracking. If enabled, state
  7. // tracking will capture the initial READY packet and many other websocket
  8. // events and maintain an in-memory state of of guilds, channels, users, and
  9. // so forth. This information can be accessed through the Session.State struct.
  10. package discordgo
  11. import "errors"
  12. // ErrNilState is returned when the state is nil.
  13. var ErrNilState = errors.New("State not instantiated, please use discordgo.New() or assign Session.State.")
  14. // A State contains the current known state.
  15. // As discord sends this in a READY blob, it seems reasonable to simply
  16. // use that struct as the data store.
  17. type State struct {
  18. sync.RWMutex
  19. Ready
  20. MaxMessageCount int
  21. guildMap map[string]*Guild
  22. channelMap map[string]*Channel
  23. }
  24. // NewState creates an empty state.
  25. func NewState() *State {
  26. return &State{
  27. Ready: Ready{
  28. PrivateChannels: []*Channel{},
  29. Guilds: []*Guild{},
  30. },
  31. guildMap: make(map[string]*Guild),
  32. channelMap: make(map[string]*Channel),
  33. }
  34. }
  35. // OnReady takes a Ready event and updates all internal state.
  36. func (s *State) OnReady(r *Ready) error {
  37. if s == nil {
  38. return ErrNilState
  39. }
  40. s.Lock()
  41. defer s.Unlock()
  42. s.Ready = *r
  43. for _, g := range s.Guilds {
  44. s.guildMap[g.ID] = g
  45. for _, c := range g.Channels {
  46. c.GuildID = g.ID
  47. s.channelMap[c.ID] = c
  48. }
  49. }
  50. for _, c := range s.PrivateChannels {
  51. s.channelMap[c.ID] = c
  52. }
  53. return nil
  54. }
  55. // GuildAdd adds a guild to the current world state, or
  56. // updates it if it already exists.
  57. func (s *State) GuildAdd(guild *Guild) error {
  58. if s == nil {
  59. return ErrNilState
  60. }
  61. s.Lock()
  62. defer s.Unlock()
  63. // Update the channels to point to the right guild, adding them to the channelMap as we go
  64. for _, c := range guild.Channels {
  65. c.GuildID = guild.ID
  66. s.channelMap[c.ID] = c
  67. }
  68. // If the guild exists, replace it.
  69. if g, ok := s.guildMap[guild.ID]; ok {
  70. // If this guild already exists with data, don't stomp on props.
  71. if g.Unavailable != nil && !*g.Unavailable {
  72. guild.Members = g.Members
  73. guild.Presences = g.Presences
  74. guild.Channels = g.Channels
  75. guild.VoiceStates = g.VoiceStates
  76. }
  77. *g = *guild
  78. return nil
  79. }
  80. s.Guilds = append(s.Guilds, guild)
  81. s.guildMap[guild.ID] = guild
  82. return nil
  83. }
  84. // GuildRemove removes a guild from current world state.
  85. func (s *State) GuildRemove(guild *Guild) error {
  86. if s == nil {
  87. return ErrNilState
  88. }
  89. _, err := s.Guild(guild.ID)
  90. if err != nil {
  91. return err
  92. }
  93. s.Lock()
  94. defer s.Unlock()
  95. delete(s.guildMap, guild.ID)
  96. for i, g := range s.Guilds {
  97. if g.ID == guild.ID {
  98. s.Guilds = append(s.Guilds[:i], s.Guilds[i+1:]...)
  99. return nil
  100. }
  101. }
  102. return nil
  103. }
  104. // Guild gets a guild by ID.
  105. // Useful for querying if @me is in a guild:
  106. // _, err := discordgo.Session.State.Guild(guildID)
  107. // isInGuild := err == nil
  108. func (s *State) Guild(guildID string) (*Guild, error) {
  109. if s == nil {
  110. return nil, ErrNilState
  111. }
  112. s.RLock()
  113. defer s.RUnlock()
  114. if g, ok := s.guildMap[guildID]; ok {
  115. return g, nil
  116. }
  117. return nil, errors.New("Guild not found.")
  118. }
  119. // TODO: Consider moving Guild state update methods onto *Guild.
  120. // MemberAdd adds a member to the current world state, or
  121. // updates it if it already exists.
  122. func (s *State) MemberAdd(member *Member) error {
  123. if s == nil {
  124. return ErrNilState
  125. }
  126. guild, err := s.Guild(member.GuildID)
  127. if err != nil {
  128. return err
  129. }
  130. s.Lock()
  131. defer s.Unlock()
  132. for i, m := range guild.Members {
  133. if m.User.ID == member.User.ID {
  134. guild.Members[i] = member
  135. return nil
  136. }
  137. }
  138. guild.Members = append(guild.Members, member)
  139. return nil
  140. }
  141. // MemberRemove removes a member from current world state.
  142. func (s *State) MemberRemove(member *Member) error {
  143. if s == nil {
  144. return ErrNilState
  145. }
  146. guild, err := s.Guild(member.GuildID)
  147. if err != nil {
  148. return err
  149. }
  150. s.Lock()
  151. defer s.Unlock()
  152. for i, m := range guild.Members {
  153. if m.User.ID == member.User.ID {
  154. guild.Members = append(guild.Members[:i], guild.Members[i+1:]...)
  155. return nil
  156. }
  157. }
  158. return errors.New("Member not found.")
  159. }
  160. // Member gets a member by ID from a guild.
  161. func (s *State) Member(guildID, userID string) (*Member, error) {
  162. if s == nil {
  163. return nil, ErrNilState
  164. }
  165. guild, err := s.Guild(guildID)
  166. if err != nil {
  167. return nil, err
  168. }
  169. s.RLock()
  170. defer s.RUnlock()
  171. for _, m := range guild.Members {
  172. if m.User.ID == userID {
  173. return m, nil
  174. }
  175. }
  176. return nil, errors.New("Member not found.")
  177. }
  178. // ChannelAdd adds a guild to the current world state, or
  179. // updates it if it already exists.
  180. // Channels may exist either as PrivateChannels or inside
  181. // a guild.
  182. func (s *State) ChannelAdd(channel *Channel) error {
  183. if s == nil {
  184. return ErrNilState
  185. }
  186. s.Lock()
  187. defer s.Unlock()
  188. // If the channel exists, replace it
  189. if c, ok := s.channelMap[channel.ID]; ok {
  190. channel.Messages = c.Messages
  191. channel.PermissionOverwrites = c.PermissionOverwrites
  192. *c = *channel
  193. return nil
  194. }
  195. if channel.IsPrivate {
  196. s.PrivateChannels = append(s.PrivateChannels, channel)
  197. } else {
  198. guild, ok := s.guildMap[channel.GuildID]
  199. if !ok {
  200. return errors.New("Guild for channel not found.")
  201. }
  202. guild.Channels = append(guild.Channels, channel)
  203. }
  204. s.channelMap[channel.ID] = channel
  205. return nil
  206. }
  207. // ChannelRemove removes a channel from current world state.
  208. func (s *State) ChannelRemove(channel *Channel) error {
  209. if s == nil {
  210. return ErrNilState
  211. }
  212. _, err := s.Channel(channel.ID)
  213. if err != nil {
  214. return err
  215. }
  216. if channel.IsPrivate {
  217. s.Lock()
  218. defer s.Unlock()
  219. for i, c := range s.PrivateChannels {
  220. if c.ID == channel.ID {
  221. s.PrivateChannels = append(s.PrivateChannels[:i], s.PrivateChannels[i+1:]...)
  222. break
  223. }
  224. }
  225. } else {
  226. guild, err := s.Guild(channel.GuildID)
  227. if err != nil {
  228. return err
  229. }
  230. s.Lock()
  231. defer s.Unlock()
  232. for i, c := range guild.Channels {
  233. if c.ID == channel.ID {
  234. guild.Channels = append(guild.Channels[:i], guild.Channels[i+1:]...)
  235. break
  236. }
  237. }
  238. }
  239. delete(s.channelMap, channel.ID)
  240. return nil
  241. }
  242. // GuildChannel gets a channel by ID from a guild.
  243. // This method is Deprecated, use Channel(channelID)
  244. func (s *State) GuildChannel(guildID, channelID string) (*Channel, error) {
  245. return s.Channel(channelID)
  246. }
  247. // PrivateChannel gets a private channel by ID.
  248. // This method is Deprecated, use Channel(channelID)
  249. func (s *State) PrivateChannel(channelID string) (*Channel, error) {
  250. return s.Channel(channelID)
  251. }
  252. // Channel gets a channel by ID, it will look in all guilds an private channels.
  253. func (s *State) Channel(channelID string) (*Channel, error) {
  254. if s == nil {
  255. return nil, ErrNilState
  256. }
  257. if c, ok := s.channelMap[channelID]; ok {
  258. return c, nil
  259. }
  260. return nil, errors.New("Channel not found.")
  261. }
  262. // Emoji returns an emoji for a guild and emoji id.
  263. func (s *State) Emoji(guildID, emojiID string) (*Emoji, error) {
  264. if s == nil {
  265. return nil, ErrNilState
  266. }
  267. guild, err := s.Guild(guildID)
  268. if err != nil {
  269. return nil, err
  270. }
  271. s.RLock()
  272. defer s.RUnlock()
  273. for _, e := range guild.Emojis {
  274. if e.ID == emojiID {
  275. return e, nil
  276. }
  277. }
  278. return nil, errors.New("Emoji not found.")
  279. }
  280. // EmojiAdd adds an emoji to the current world state.
  281. func (s *State) EmojiAdd(guildID string, emoji *Emoji) error {
  282. if s == nil {
  283. return ErrNilState
  284. }
  285. guild, err := s.Guild(guildID)
  286. if err != nil {
  287. return err
  288. }
  289. s.Lock()
  290. defer s.Unlock()
  291. for i, e := range guild.Emojis {
  292. if e.ID == emoji.ID {
  293. guild.Emojis[i] = emoji
  294. return nil
  295. }
  296. }
  297. guild.Emojis = append(guild.Emojis, emoji)
  298. return nil
  299. }
  300. // EmojisAdd adds multiple emojis to the world state.
  301. func (s *State) EmojisAdd(guildID string, emojis []*Emoji) error {
  302. for _, e := range emojis {
  303. if err := s.EmojiAdd(guildID, e); err != nil {
  304. return err
  305. }
  306. }
  307. return nil
  308. }
  309. // MessageAdd adds a message to the current world state, or updates it if it exists.
  310. // If the channel cannot be found, the message is discarded.
  311. // Messages are kept in state up to s.MaxMessageCount
  312. func (s *State) MessageAdd(message *Message) error {
  313. if s == nil {
  314. return ErrNilState
  315. }
  316. if s.MaxMessageCount == 0 {
  317. return nil
  318. }
  319. c, err := s.Channel(message.ChannelID)
  320. if err != nil {
  321. return err
  322. }
  323. s.Lock()
  324. defer s.Unlock()
  325. // If the message exists, replace it.
  326. for i, m := range c.Messages {
  327. if m.ID == message.ID {
  328. c.Messages[i] = message
  329. return nil
  330. }
  331. }
  332. c.Messages = append(c.Messages, message)
  333. if len(c.Messages) > s.MaxMessageCount {
  334. c.Messages = c.Messages[len(c.Messages)-s.MaxMessageCount:]
  335. }
  336. return nil
  337. }
  338. // MessageRemove removes a message from the world state.
  339. func (s *State) MessageRemove(message *Message) error {
  340. if s == nil {
  341. return ErrNilState
  342. }
  343. if s.MaxMessageCount == 0 {
  344. return nil
  345. }
  346. c, err := s.Channel(message.ChannelID)
  347. if err != nil {
  348. return err
  349. }
  350. s.Lock()
  351. defer s.Unlock()
  352. for i, m := range c.Messages {
  353. if m.ID == message.ID {
  354. c.Messages = append(c.Messages[:i], c.Messages[i+1:]...)
  355. return nil
  356. }
  357. }
  358. return errors.New("Message not found.")
  359. }
  360. func (s *State) voiceStateUpdate(update *VoiceStateUpdate) error {
  361. guild, err := s.Guild(update.GuildID)
  362. if err != nil {
  363. return err
  364. }
  365. s.Lock()
  366. defer s.Unlock()
  367. // Handle Leaving Channel
  368. if update.ChannelID == "" {
  369. for i, state := range guild.VoiceStates {
  370. if state.UserID == update.UserID {
  371. guild.VoiceStates = append(guild.VoiceStates[:i], guild.VoiceStates[i+1:]...)
  372. return nil
  373. }
  374. }
  375. } else {
  376. for i, state := range guild.VoiceStates {
  377. if state.UserID == update.UserID {
  378. guild.VoiceStates[i] = update.VoiceState
  379. return nil
  380. }
  381. }
  382. guild.VoiceStates = append(guild.VoiceStates, update.VoiceState)
  383. }
  384. return nil
  385. }
  386. // Message gets a message by channel and message ID.
  387. func (s *State) Message(channelID, messageID string) (*Message, error) {
  388. if s == nil {
  389. return nil, ErrNilState
  390. }
  391. c, err := s.Channel(channelID)
  392. if err != nil {
  393. return nil, err
  394. }
  395. s.RLock()
  396. defer s.RUnlock()
  397. for _, m := range c.Messages {
  398. if m.ID == messageID {
  399. return m, nil
  400. }
  401. }
  402. return nil, errors.New("Message not found.")
  403. }
  404. // onInterface handles all events related to states.
  405. func (s *State) onInterface(se *Session, i interface{}) (err error) {
  406. if s == nil {
  407. return ErrNilState
  408. }
  409. if !se.StateEnabled {
  410. return nil
  411. }
  412. switch t := i.(type) {
  413. case *Ready:
  414. err = s.OnReady(t)
  415. case *GuildCreate:
  416. err = s.GuildAdd(t.Guild)
  417. case *GuildUpdate:
  418. err = s.GuildAdd(t.Guild)
  419. case *GuildDelete:
  420. err = s.GuildRemove(t.Guild)
  421. case *GuildMemberAdd:
  422. err = s.MemberAdd(t.Member)
  423. case *GuildMemberUpdate:
  424. err = s.MemberAdd(t.Member)
  425. case *GuildMemberRemove:
  426. err = s.MemberRemove(t.Member)
  427. case *GuildEmojisUpdate:
  428. err = s.EmojisAdd(t.GuildID, t.Emojis)
  429. case *ChannelCreate:
  430. err = s.ChannelAdd(t.Channel)
  431. case *ChannelUpdate:
  432. err = s.ChannelAdd(t.Channel)
  433. case *ChannelDelete:
  434. err = s.ChannelRemove(t.Channel)
  435. case *MessageCreate:
  436. err = s.MessageAdd(t.Message)
  437. case *MessageUpdate:
  438. err = s.MessageAdd(t.Message)
  439. case *MessageDelete:
  440. err = s.MessageRemove(t.Message)
  441. case *VoiceStateUpdate:
  442. err = s.voiceStateUpdate(t)
  443. }
  444. return
  445. }