From 808a05ff2dd37c63020d099827e4248b4e49059d Mon Sep 17 00:00:00 2001 From: Rapptz Date: Wed, 4 Jan 2017 05:16:59 -0500 Subject: [PATCH] Move global user cache to a WeakValueDictionary. --- discord/client.py | 14 +++++++++++++- discord/state.py | 6 +++++- discord/user.py | 2 +- 3 files changed, 19 insertions(+), 3 deletions(-) diff --git a/discord/client.py b/discord/client.py index d35b9b3be..2e0696c90 100644 --- a/discord/client.py +++ b/discord/client.py @@ -507,14 +507,26 @@ class Client: # helpers/getters + @property + def users(self): + """Returns a list of all the :class:`User` the bot can see.""" + return list(self.connection._users.values()) + def get_channel(self, id): - """Returns a :class:`Channel` or :class:`PrivateChannel` with the following ID. If not found, returns None.""" + """Returns a :class:`abc.GuildChannel` or :class:`abc.PrivateChannel` with the following ID. + + If not found, returns None. + """ return self.connection.get_channel(id) def get_guild(self, id): """Returns a :class:`Guild` with the given ID. If not found, returns None.""" return self.connection._get_guild(id) + def get_user(self, id): + """Returns a :class:`User` with the given ID. If not found, returns None.""" + return self.connection.get_user(id) + def get_all_emojis(self): """Returns a generator with every :class:`Emoji` the client can see.""" for guild in self.guilds: diff --git a/discord/state.py b/discord/state.py index e839d5ab0..1629b8db6 100644 --- a/discord/state.py +++ b/discord/state.py @@ -42,6 +42,7 @@ import copy, enum, math import datetime import asyncio import logging +import weakref class ListenerType(enum.Enum): chunk = 0 @@ -66,8 +67,8 @@ class ConnectionState: self.user = None self.sequence = None self.session_id = None + self._users = weakref.WeakValueDictionary() self._calls = {} - self._users = {} self._emojis = {} self._guilds = {} self._voice_clients = {} @@ -133,6 +134,9 @@ class ConnectionState: self._users[user_id] = user = User(state=self, data=data) return user + def get_user(self, id): + return self._users.get(id) + def store_emoji(self, guild, data): emoji_id = int(data['id']) try: diff --git a/discord/user.py b/discord/user.py index 387c20b05..e9a19935e 100644 --- a/discord/user.py +++ b/discord/user.py @@ -61,7 +61,7 @@ class User(discord.abc.Messageable): Specifies if the user is a bot account. """ - __slots__ = ('name', 'id', 'discriminator', 'avatar', 'bot', '_state') + __slots__ = ('name', 'id', 'discriminator', 'avatar', 'bot', '_state', '__weakref__') def __init__(self, *, state, data): self._state = state