Merge branch 'MelisaDev:master' into master

This commit is contained in:
Jungle 2022-05-22 12:13:55 +03:00 committed by GitHub
commit 6c5379ef28
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 124 additions and 18 deletions

View file

@ -11,7 +11,7 @@ from typing import Dict, List, Union, Any, Iterable, Optional, Callable
from .models.app.cache import CacheManager from .models.app.cache import CacheManager
from .rest import RESTApp from .rest import RESTApp
from .core.gateway import GatewayBotInfo from .core.gateway import GatewayBotInfo
from .models.guild.channel import Channel from .models.guild.channel import Channel, ChannelType
from .models import Activity, AllowedMentions from .models import Activity, AllowedMentions
from .models.app.shard import Shard from .models.app.shard import Shard
from .models.app.intents import Intents from .models.app.intents import Intents
@ -266,7 +266,12 @@ class Client:
# ToDo: Update cache if CHANNEL_CACHE enabled. # ToDo: Update cache if CHANNEL_CACHE enabled.
return await self.rest.fetch_channel(channel_id) data = await self.rest.fetch_channel(channel_id)
if data.type not in [ChannelType.DM, ChannelType.GROUP_DM]:
self.cache.set_guild_channel(data)
return data
async def wait_for( async def wait_for(
self, self,

View file

@ -4,15 +4,13 @@
from __future__ import annotations from __future__ import annotations
from ..utils.types import Coro from ..utils.types import Coro
from ..models.guild import Channel, ChannelType, channel_types_for_converting from ..models.guild.channel import ChannelType, _choose_channel_type
async def channel_delete_listener(self, gateway, payload: dict): async def channel_delete_listener(self, gateway, payload: dict):
payload.update({"type": ChannelType(payload.pop("type"))}) payload.update({"type": ChannelType(payload.pop("type"))})
channel_cls = channel_types_for_converting.get(payload["type"], Channel) channel = _choose_channel_type(payload)
channel = channel_cls.from_dict(payload)
await self.dispatch("on_channel_delete", (channel,)) await self.dispatch("on_channel_delete", (channel,))

View file

@ -7,7 +7,7 @@ from enum import Enum
from typing import List, Dict, Optional, Any, Union from typing import List, Dict, Optional, Any, Union
from melisa.utils.types import UNDEFINED from melisa.utils.types import UNDEFINED
from melisa.models.guild import Guild, ChannelType, UnavailableGuild from melisa.models.guild import Guild, ChannelType, UnavailableGuild, Channel
from melisa.utils.snowflake import Snowflake from melisa.utils.snowflake import Snowflake
@ -16,6 +16,7 @@ class AutoCacheModels(Enum):
""" """ """ """
FULL_GUILDS = "FULL_GUILDS"
GUILD_ROLES = "GUILD_ROLES" GUILD_ROLES = "GUILD_ROLES"
GUILD_THREADS = "GUILD_THREADS" GUILD_THREADS = "GUILD_THREADS"
GUILD_EMOJIS = "GUILD_EMOJIS" GUILD_EMOJIS = "GUILD_EMOJIS"
@ -30,11 +31,12 @@ class CacheManager:
def __init__( def __init__(
self, self,
*, *,
auto_models: Optional[List[AutoCacheModels]] = None, disabled: bool = False,
disabled_auto_models: Optional[List[AutoCacheModels]] = None,
auto_unused_attributes: Optional[Dict[Any, List[str]]] = None, auto_unused_attributes: Optional[Dict[Any, List[str]]] = None,
): ):
self._auto_models: List[AutoCacheModels] = ( self._disabled_auto_models: List[AutoCacheModels] = (
[] if auto_models is None else auto_models [] if disabled_auto_models is None else disabled_auto_models
) )
self.auto_unused_attributes: Dict[Any, List[str]] = ( self.auto_unused_attributes: Dict[Any, List[str]] = (
{} if auto_unused_attributes is not None else auto_unused_attributes {} if auto_unused_attributes is not None else auto_unused_attributes
@ -44,6 +46,8 @@ class CacheManager:
self._raw_users: Dict[Snowflake, Any] = {} self._raw_users: Dict[Snowflake, Any] = {}
self._raw_dm_channels: Dict[Snowflake, Any] = {} self._raw_dm_channels: Dict[Snowflake, Any] = {}
self._disabled = disabled
# We use symlinks to cache guild channels # We use symlinks to cache guild channels
# like we save channel in Guild and save it here # like we save channel in Guild and save it here
# and if you need channel, and you don't know its guild # and if you need channel, and you don't know its guild
@ -90,6 +94,9 @@ class CacheManager:
Guild to save into cache Guild to save into cache
""" """
if self._disabled:
return
if guild is None: if guild is None:
return None return None
@ -98,21 +105,81 @@ class CacheManager:
if hasattr(guild, "channels"): if hasattr(guild, "channels"):
channels = guild.channels.values() channels = guild.channels.values()
if AutoCacheModels.TEXT_CHANNELS not in self._auto_models: if AutoCacheModels.TEXT_CHANNELS not in self._disabled_auto_models:
channels = filter( channels = filter(
lambda channel: channel.type != ChannelType.GUILD_TEXT, channels lambda channel: channel.type == ChannelType.GUILD_TEXT, channels
) )
for sym in channels: for sym in channels:
if self._channel_symlinks.get(sym.id, UNDEFINED) is not UNDEFINED: sym_id = Snowflake(int(sym.id))
self._channel_symlinks.pop(sym.id) if self._channel_symlinks.get(sym_id, UNDEFINED) is not UNDEFINED:
self._channel_symlinks.pop(sym_id)
self._channel_symlinks[sym.id] = guild.id self._channel_symlinks[sym_id] = guild.id
self._raw_guilds.update({guild.id: guild}) self._raw_guilds.update({guild.id: guild})
return guild return guild
def set_guild_channel(self, channel: Optional[Channel] = None):
"""
Save Guild into cache
Parameters
----------
channel: Optional[`~melisa.models.guild.Channel`]
Guild Channel to save into cache
"""
if self._disabled:
return
if channel is None:
return None
channel = self.__remove_unused_attributes(channel, Channel) # ToDo: add channel type
guild = self._raw_guilds.get(channel.guild_id, UNDEFINED)
channel_id = Snowflake(int(channel.id))
if guild != UNDEFINED:
if hasattr(guild, "channels"):
self._raw_guilds[guild.id].channels.update({channel_id: channel})
self._channel_symlinks.update({channel_id: channel.guild_id})
return channel
def get_guild_channel(self, channel_id: Union[Snowflake, str, int]):
"""
Get guild channel from cache
Parameters
----------
channel_id: Optional[:class:`~melisa.utils.snowflake.Snowflake`, `str`, `int`]
ID of guild channel to get from cache.
"""
if self._disabled:
return None
channel_id = Snowflake(int(channel_id))
guild_id = self._channel_symlinks.get(channel_id, UNDEFINED)
if guild_id == UNDEFINED:
return None
guild = self.get_guild(guild_id)
if guild is None:
return None
if hasattr(guild, "channels") is False:
return None
return guild.channels.get(channel_id)
def get_guild(self, guild_id: Union[Snowflake, str, int]): def get_guild(self, guild_id: Union[Snowflake, str, int]):
""" """
Get guild from cache Get guild from cache
@ -123,6 +190,9 @@ class CacheManager:
ID of guild to get from cache. ID of guild to get from cache.
""" """
if self._disabled:
return None
if not isinstance(guild_id, Snowflake): if not isinstance(guild_id, Snowflake):
guild_id = Snowflake(int(guild_id)) guild_id = Snowflake(int(guild_id))
return self._raw_guilds.get(guild_id, None) return self._raw_guilds.get(guild_id, None)
@ -137,8 +207,11 @@ class CacheManager:
Data of guilds tso insert to the cache Data of guilds tso insert to the cache
""" """
if self._disabled:
return
guilds_dict = dict( guilds_dict = dict(
map(lambda i: (i["id"], UnavailableGuild.from_dict(i)), guilds) map(lambda i: (Snowflake(int(i["id"])), UnavailableGuild.from_dict(i)), guilds)
) )
self._raw_guilds.update(guilds_dict) self._raw_guilds.update(guilds_dict)
@ -154,6 +227,9 @@ class CacheManager:
ID of guild to remove from cache. ID of guild to remove from cache.
""" """
if self._disabled:
return
if not isinstance(guild_id, Snowflake): if not isinstance(guild_id, Snowflake):
guild_id = Snowflake(int(guild_id)) guild_id = Snowflake(int(guild_id))

View file

@ -116,6 +116,8 @@ class Channel(APIModelBase):
guild_id: :class:`~melisa.utils.types.Snowflake` guild_id: :class:`~melisa.utils.types.Snowflake`
The id of the guild The id of the guild
(may be missing for some channel objects received over gateway guild dispatches) (may be missing for some channel objects received over gateway guild dispatches)
guild: Optional[:class:`~melisa.models.guild.Guild`]
Object of guild where channel is
position: :class:`int` position: :class:`int`
Sorting position of the channel Sorting position of the channel
permission_overwrites: :class:`typing.Any` permission_overwrites: :class:`typing.Any`
@ -203,6 +205,12 @@ class Channel(APIModelBase):
def mention(self): def mention(self):
return f"<#{self.id}>" return f"<#{self.id}>"
@property
def guild(self):
if self.guild_id is not None:
return self._client.cache.get_guild(self.guild_id)
return None
async def edit(self, *, reason: Optional[str] = None, **kwargs): async def edit(self, *, reason: Optional[str] = None, **kwargs):
"""|coro| """|coro|
Edit a channel with the specified keyword arguments. Edit a channel with the specified keyword arguments.
@ -769,7 +777,7 @@ class TextChannel(MessageableChannel):
self: TextChannel = super().__new__(cls) self: TextChannel = super().__new__(cls)
self.id = data["id"] self.id = data["id"]
self.type = data["type"] self.type = ChannelType(data["type"])
self.position = data.get("position") self.position = data.get("position")
self.permission_overwrites = data["permission_overwrites"] self.permission_overwrites = data["permission_overwrites"]
self.name = data.get("name") self.name = data.get("name")

View file

@ -470,7 +470,7 @@ class Guild(APIModelBase):
for channel in data.get("channels", []): for channel in data.get("channels", []):
channel = _choose_channel_type(channel) channel = _choose_channel_type(channel)
self.channels[channel.id] = channel self.channels[Snowflake(int(channel.id))] = channel
return self return self

View file

@ -184,6 +184,10 @@ class Message(APIModelBase):
Id of the message Id of the message
channel_id: :class:`~melisa.utils.types.snowflake.Snowflake` channel_id: :class:`~melisa.utils.types.snowflake.Snowflake`
Id of the channel the message was sent in Id of the channel the message was sent in
channel: :class:`~melisa.models.guild.Channel`
Object of channel where message was sent in
guild: :class:`~melisa.models.guild.Guild`
Object of guild where message was sent in
guild_id: :class:`~melisa.utils.types.snowflake.Snowflake` guild_id: :class:`~melisa.utils.types.snowflake.Snowflake`
Id of the guild the message was sent in Id of the guild the message was sent in
author: :class:`typing.Any` author: :class:`typing.Any`
@ -351,6 +355,21 @@ class Message(APIModelBase):
return self return self
@property
def guild(self):
if self.guild_id is not None:
return self._client.cache.get_guild(self.guild_id)
return None
@property
def channel(self):
print(self.channel_id)
print(self._client.cache._channel_symlinks)
if self.channel_id is not None:
return self._client.cache.get_guild_channel(self.channel_id)
return None
async def pin(self, *, reason: Optional[str] = None): async def pin(self, *, reason: Optional[str] = None):
"""|coro| """|coro|