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 logging
import asyncio import asyncio
import signal 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 import User, Guild, Activity
from .models.app import Shard from .models.app import Shard
from .utils import Snowflake, APIModelBase from .utils import Snowflake, APIModelBase
@ -28,7 +29,7 @@ class Client:
---------- ----------
token: :class:`str` token: :class:`str`
The token to login (you can found it in the developer portal) 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. The Discord Intents values.
activity: :class:`~models.user.presence.BotActivity` activity: :class:`~models.user.presence.BotActivity`
The Activity to set (on connecting) The Activity to set (on connecting)
@ -57,8 +58,8 @@ class Client:
def __init__( def __init__(
self, self,
token: str, token: str,
intents,
*, *,
intents: Union[Intents, Iterable[Intents]] = None,
activity: Activity = None, activity: Activity = None,
status: str = None, status: str = None,
mobile: bool = False, mobile: bool = False,
@ -76,7 +77,12 @@ class Client:
self._gateway_info = self._loop.run_until_complete(self._get_gateway()) 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._token = token
self._activity = activity self._activity = activity
@ -88,6 +94,18 @@ class Client:
init_logging(logs) 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): async def _get_gateway(self):
"""Get Gateway information""" """Get Gateway information"""
return GatewayBotInfo.from_dict(await self.http.get("gateway/bot")) return GatewayBotInfo.from_dict(await self.http.get("gateway/bot"))
@ -114,7 +132,8 @@ class Client:
inited_shard = Shard(self, 0, 1) inited_shard = Shard(self, 0, 1)
asyncio.ensure_future( asyncio.ensure_future(
inited_shard.launch(activity=self._activity, inited_shard.launch(
activity=self._activity,
status=self._status, status=self._status,
mobile=self._mobile, mobile=self._mobile,
loop=self._loop, loop=self._loop,
@ -140,9 +159,9 @@ class Client:
inited_shard = Shard(self, shard_id, num_shards) inited_shard = Shard(self, shard_id, num_shards)
asyncio.ensure_future( asyncio.ensure_future(
inited_shard.launch(activity=self._activity, inited_shard.launch(
status=self._status, activity=self._activity, status=self._status, mobile=self._mobile
mobile=self._mobile), ),
loop=self._loop, loop=self._loop,
) )
self._loop.run_forever() self._loop.run_forever()
@ -158,9 +177,9 @@ class Client:
inited_shard = Shard(self, shard_id, num_shards) inited_shard = Shard(self, shard_id, num_shards)
asyncio.ensure_future( asyncio.ensure_future(
inited_shard.launch(activity=self._activity, inited_shard.launch(
status=self._status, activity=self._activity, status=self._status, mobile=self._mobile
mobile=self._mobile), ),
loop=self._loop, loop=self._loop,
) )
self._loop.run_forever() self._loop.run_forever()

View file

@ -76,7 +76,9 @@ class Gateway:
"intents": self.intents, "intents": self.intents,
"properties": { "properties": {
"$os": sys.platform, "$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", "$device": "Melisa Python Library",
}, },
"compress": True, "compress": True,

View file

@ -79,7 +79,7 @@ class HTTPClient:
if ttl == 0: if ttl == 0:
raise ServerError(f"Maximum amount of retries for `{endpoint}`.") 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) await self.__rate_limiter.wait_until_not_ratelimited(endpoint, method)

View file

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