make intents more user-friendly (you can use iter to specify them) and SIGNAL handler

This commit is contained in:
grey-cat-1908 2022-03-29 22:05:23 +03:00
parent f215a4ea50
commit 0888054587
4 changed files with 47 additions and 26 deletions

View file

@ -4,8 +4,9 @@
import logging
import asyncio
import signal
from typing import Dict, List, Union, Any
from typing import Dict, List, Union, Any, Iterable
from .models.app.intents import Intents
from .models import User, Guild, Activity
from .models.app import Shard
from .utils import Snowflake, APIModelBase
@ -28,7 +29,7 @@ class Client:
----------
token: :class:`str`
The token to login (you can found it in the developer portal)
intents: :class:`~melisa.Intents`
intents: :class:`Union[~melisa.Intents, Iterable[~melisa.Intents]]`
The Discord Intents values.
activity: :class:`~models.user.presence.BotActivity`
The Activity to set (on connecting)
@ -55,14 +56,14 @@ class Client:
"""
def __init__(
self,
token: str,
intents,
*,
activity: Activity = None,
status: str = None,
mobile: bool = False,
logs: Union[None, int, str, Dict[str, Any]] = "INFO",
self,
token: str,
*,
intents: Union[Intents, Iterable[Intents]] = None,
activity: Activity = None,
status: str = None,
mobile: bool = False,
logs: Union[None, int, str, Dict[str, Any]] = "INFO",
):
self.shards: Dict[int, Shard] = {}
self.http: HTTPClient = HTTPClient(token)
@ -76,7 +77,12 @@ class Client:
self._gateway_info = self._loop.run_until_complete(self._get_gateway())
self.intents = intents
if isinstance(intents, Iterable):
self.intents = sum(intents)
if intents is None:
self.intents = Intents.all() - Intents.GUILD_PRESENCES - Intents.GUILD_MEMBERS
self._token = token
self._activity = activity
@ -88,6 +94,18 @@ class Client:
init_logging(logs)
def sigint_handler(_signal, _frame):
_logger.info("SIGINT received, shutting down...")
asyncio.create_task(self.http.close())
if self._loop.is_running():
self._loop.stop()
print("(SIGINT received some seconds ago) Successfully stopped client loop")
signal.signal(signal.SIGINT, sigint_handler)
async def _get_gateway(self):
"""Get Gateway information"""
return GatewayBotInfo.from_dict(await self.http.get("gateway/bot"))
@ -114,11 +132,12 @@ class Client:
inited_shard = Shard(self, 0, 1)
asyncio.ensure_future(
inited_shard.launch(activity=self._activity,
status=self._status,
mobile=self._mobile,
loop=self._loop,
)
inited_shard.launch(
activity=self._activity,
status=self._status,
mobile=self._mobile,
loop=self._loop,
)
)
self._loop.run_forever()
@ -140,9 +159,9 @@ class Client:
inited_shard = Shard(self, shard_id, num_shards)
asyncio.ensure_future(
inited_shard.launch(activity=self._activity,
status=self._status,
mobile=self._mobile),
inited_shard.launch(
activity=self._activity, status=self._status, mobile=self._mobile
),
loop=self._loop,
)
self._loop.run_forever()
@ -158,9 +177,9 @@ class Client:
inited_shard = Shard(self, shard_id, num_shards)
asyncio.ensure_future(
inited_shard.launch(activity=self._activity,
status=self._status,
mobile=self._mobile),
inited_shard.launch(
activity=self._activity, status=self._status, mobile=self._mobile
),
loop=self._loop,
)
self._loop.run_forever()
@ -198,7 +217,7 @@ class Client:
return Guild.from_dict(data)
async def fetch_channel(
self, channel_id: Union[Snowflake, str, int]
self, channel_id: Union[Snowflake, str, int]
) -> Union[Channel, Any]:
"""
Fetch Channel from the Discord API (by id).

View file

@ -76,7 +76,9 @@ class Gateway:
"intents": self.intents,
"properties": {
"$os": sys.platform,
"$browser": "Discord iOS" if kwargs.get("mobile") is not None else "MelisaPy",
"$browser": "Discord iOS"
if kwargs.get("mobile") is not None
else "MelisaPy",
"$device": "Melisa Python Library",
},
"compress": True,

View file

@ -79,7 +79,7 @@ class HTTPClient:
if ttl == 0:
raise ServerError(f"Maximum amount of retries for `{endpoint}`.")
_logger.debug(f"Send {method} request to the {endpoint}")
_logger.debug(f"Sending {method} request to the {endpoint}")
await self.__rate_limiter.wait_until_not_ratelimited(endpoint, method)

View file

@ -41,7 +41,7 @@ class Shard:
self._num_shards,
start_activity=kwargs.get("activity"),
start_status=kwargs.get("status"),
mobile=kwargs.get("mobile")
mobile=kwargs.get("mobile"),
)
self._client.shards[self._shard_id] = self