Skip to content

Commit 1ffc867

Browse files
committed
Fixed update
1 parent fcba3b3 commit 1ffc867

File tree

7 files changed

+85
-90
lines changed

7 files changed

+85
-90
lines changed

src/daf/client.py

Lines changed: 30 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -387,7 +387,7 @@ def get_server(
387387

388388
return None
389389

390-
async def _close(self):
390+
async def _close(self, _delete = True):
391391
"""
392392
Signals the tasks of this account to finish and
393393
waits for them.
@@ -402,6 +402,7 @@ async def _close(self):
402402
exc
403403
)
404404

405+
self.tasks.clear()
405406
selenium = self.selenium
406407
if selenium is not None:
407408
selenium._close()
@@ -410,7 +411,10 @@ async def _close(self):
410411
await guild_._close()
411412

412413
await self._client.close()
413-
self._delete()
414+
self.client.clear()
415+
416+
if _delete:
417+
self._delete()
414418

415419
async def _loop(self):
416420
"""
@@ -446,17 +450,16 @@ async def __loop():
446450
await asyncio.sleep(TASK_SLEEP_DELAY_S)
447451

448452
@misc._async_safe("_update_sem")
449-
async def update(self, *, _init = True, **kwargs):
453+
async def update(self, **kwargs):
450454
"""
451455
Updates the object with new parameters and afterwards updates all lower layers (GUILD->MESSAGE->CHANNEL).
452456
453457
.. WARNING::
454458
After calling this method the entire object is reset.
455459
"""
456460
if self._running:
457-
await self._close()
461+
await self._close(False)
458462

459-
self._deleted = False # Prevents cleanup task from cleaning this up
460463
selenium = self._selenium
461464
if "token" not in kwargs:
462465
kwargs["token"] = self._token if selenium is None else None
@@ -470,32 +473,28 @@ async def update(self, *, _init = True, **kwargs):
470473
if isinstance(intents, discord.Intents) and intents.value == 0:
471474
kwargs["intents"] = None
472475

473-
servers = kwargs.pop("servers", self.servers)
474-
kwargs["servers"] = [] # Servers are updated at the end
476+
servers = kwargs.pop("servers", self.servers + self._uiservers)
475477

476-
acc_exc = None
477-
try:
478-
await misc._update(self, _init=_init, **kwargs)
479-
except Exception as exc:
480-
self._client = discord.Client(intents=self.intents) # Issues when relogging in?
481-
await self.initialize() # re-login
482-
acc_exc = exc
483-
484-
# Update the guilds in the end finnaly
485-
guilds = []
486-
autoguilds = []
487-
for server in servers:
488-
try:
489-
await server.update(init_options={"parent": self}, _init=_init)
490-
if isinstance(server, guild.AutoGUILD):
491-
autoguilds.append(server)
492-
else:
493-
guilds.append(server)
494-
except Exception as exc:
495-
trace(f"Could not update server after updating account, server: {server}", TraceLEVELS.ERROR, exc)
478+
async def update_servers():
479+
_servers = []
480+
_autoguilds = []
481+
for server in servers:
482+
try:
483+
await server.update(init_options={"parent": self})
484+
if isinstance(server, guild._BaseGUILD):
485+
_servers.append(server)
486+
else:
487+
_autoguilds.append(servers)
488+
except Exception as exc:
489+
trace(f"Could not update {server} after updating {self} - Skipping server.", TraceLEVELS.ERROR, exc)
496490

497-
self._servers = guilds
498-
self._autoguilds = autoguilds
491+
self._servers = _servers
492+
self._autoguilds = _autoguilds
499493

500-
if acc_exc is not None:
501-
raise acc_exc
494+
try:
495+
await misc._update(self, **kwargs)
496+
await update_servers()
497+
except Exception:
498+
await self.initialize() # re-login
499+
await update_servers()
500+
raise

src/daf/core.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -107,11 +107,10 @@ async def schema_load_from_file() -> None:
107107
trace("Updating accounts.", TraceLEVELS.DEBUG)
108108
for account in accounts:
109109
try:
110-
await account.update(_init=False) # Refresh without __init__ call
110+
await account.update() # Refresh without __init__ call
111111
GLOBALS.accounts.append(account)
112112
except Exception as exc:
113113
trace(f"Unable to restore account {account}", TraceLEVELS.ERROR, exc)
114-
GLOBALS.accounts.remove(account)
115114

116115
trace(f"Restored objects from file ({len(GLOBALS.accounts)} accounts).", TraceLEVELS.NORMAL)
117116

@@ -380,6 +379,7 @@ async def shutdown() -> None:
380379
for task in GLOBALS.tasks: # Wait for core tasks to finish
381380
await task
382381

382+
GLOBALS.tasks.clear()
383383
for account in GLOBALS.accounts:
384384
await account._close()
385385

src/daf/guild.py

Lines changed: 28 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
regarding the guild and also defines a USER class from the
44
_BaseGUILD class.
55
"""
6-
from typing import Any, Coroutine, Union, List, Optional, Dict, Callable, Set
6+
from typing import Any, Coroutine, Union, List, Optional, Dict, Callable
77
from typeguard import typechecked
88
from datetime import timedelta, datetime
99
from copy import deepcopy
@@ -429,9 +429,9 @@ class GUILD(_BaseGUILD):
429429
430430
.. note::
431431
432-
Accounts are required to have *Manage Channels* and *Manage Server* permissions inside a guild for tracking to
433-
fully function. *Manage Server* is needed for getting information about invite links, *Manage Channels*
434-
is needed to delete the invite from the list if it has been deleted,
432+
Accounts are required to have *Manage Channels* and *Manage Server* permissions inside a guild for
433+
tracking to fully function. *Manage Server* is needed for getting information about invite links,
434+
*Manage Channels* is needed to delete the invite from the list if it has been deleted,
435435
however tracking still works without it.
436436
"""
437437
__slots__ = (
@@ -481,7 +481,7 @@ async def get_invites(self) -> List[discord.Invite]:
481481

482482
return [] # Return empty on error or no permissions
483483

484-
async def initialize(self, parent: Any, _init = True) -> None:
484+
async def initialize(self, parent: Any) -> None:
485485
"""
486486
This function initializes the API related objects and
487487
then tries to initialize the MESSAGE objects.
@@ -568,7 +568,7 @@ def generate_invite_log_context(self, member: discord.Member, invite_id: str) ->
568568
}
569569

570570
@misc._async_safe("update_semaphore", 1)
571-
async def update(self, init_options = None, _init = True, **kwargs):
571+
async def update(self, init_options = None, **kwargs):
572572
"""
573573
Used for changing the initialization parameters,
574574
the object was initialized with.
@@ -600,23 +600,22 @@ async def update(self, init_options = None, _init = True, **kwargs):
600600
if "invite_track" not in kwargs:
601601
kwargs["invite_track"] = list(self.join_count.keys())
602602

603+
messages = kwargs.pop("messages", self.messages + self._messages_uninitialized)
604+
603605
if init_options is None:
604606
init_options = {"parent": self.parent}
605607

606-
# Add uninitialized servers
607-
messages = kwargs.pop("messages", self.messages + self._messages_uninitialized)
608-
kwargs["messages"] = [] # Messages are updated at the end
609-
610-
await misc._update(self, init_options=init_options, _init=_init, **kwargs)
608+
await misc._update(self, init_options=init_options, **kwargs)
611609

612-
# Update messages
610+
_messages = []
613611
for message in messages:
614612
try:
615-
await message.update(_init_options={"parent": self}, _init=_init)
613+
await message.update()
614+
_messages.append(message)
616615
except Exception as exc:
617-
trace(f"Unable to update message after updating GUILD, message: {message}", TraceLEVELS.ERROR, exc)
616+
trace(f"Could not update {message} after updating {self} - Skipping message.", TraceLEVELS.ERROR, exc)
618617

619-
self._messages = messages
618+
self._messages = _messages
620619

621620

622621
@misc.doc_category("Guilds")
@@ -692,7 +691,7 @@ async def initialize(self, parent: Any):
692691
)
693692

694693
@misc._async_safe("update_semaphore", 1)
695-
async def update(self, init_options = None, _init = True, **kwargs):
694+
async def update(self, init_options = None, **kwargs):
696695
"""
697696
.. versionadded:: v2.0
698697
@@ -721,23 +720,22 @@ async def update(self, init_options = None, _init = True, **kwargs):
721720
if "snowflake" not in kwargs:
722721
kwargs["snowflake"] = self.snowflake
723722

723+
messages = kwargs.pop("messages", self.messages + self._messages_uninitialized)
724+
724725
if init_options is None:
725726
init_options = {"parent": self.parent}
726727

727-
messages = kwargs.pop("messages", self.messages)
728-
kwargs["messages"] = [] # Messages are updated at the end
729-
730-
await misc._update(self, init_options=init_options, _init=_init, **kwargs)
728+
await misc._update(self, init_options=init_options, **kwargs)
731729

732-
# Update messages
730+
_messages = []
733731
for message in messages:
734732
try:
735-
await message.update(_init_options={"parent": self}, _init=_init)
733+
await message.update()
734+
_messages.append(message)
736735
except Exception as exc:
737-
trace(f"Unable to update message after updating GUILD, message: {message}", TraceLEVELS.ERROR, exc)
736+
trace(f"Could not update {message} after updating {self} - Skipping message.", TraceLEVELS.ERROR, exc)
738737

739-
740-
self._messages = messages
738+
self._messages = _messages
741739

742740

743741
@misc.doc_category("Auto objects")
@@ -1097,7 +1095,7 @@ async def _advertise(self):
10971095
return GUILD_ADVERT_STATUS_SUCCESS
10981096

10991097
@misc._async_safe("_safe_sem", 1)
1100-
async def update(self, init_options = None, _init = True, **kwargs):
1098+
async def update(self, init_options = None, **kwargs):
11011099
"""
11021100
Updates the object with new initialization parameters.
11031101
@@ -1110,6 +1108,8 @@ async def update(self, init_options = None, _init = True, **kwargs):
11101108

11111109
await self._close()
11121110
try:
1113-
return await misc._update(self, init_options=init_options, _init=_init, **kwargs)
1114-
finally:
1111+
return await misc._update(self, init_options=init_options, **kwargs)
1112+
except Exception:
1113+
self.cache.clear()
11151114
await self.initialize(self.parent) # Reopen any async related connections
1115+
raise

src/daf/message/base.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -529,7 +529,7 @@ def remove(self, channel: ChannelType):
529529
"""
530530
self.cache.remove(channel)
531531

532-
async def update(self, init_options = None, _init = True, **kwargs):
532+
async def update(self, init_options = None, **kwargs):
533533
"""
534534
Updates the object with new initialization parameters.
535535
@@ -551,5 +551,4 @@ async def update(self, init_options = None, _init = True, **kwargs):
551551

552552
return await misc._update(self,
553553
init_options=init_options,
554-
_init=_init,
555554
**kwargs)

src/daf/message/text_based.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -525,7 +525,7 @@ async def _send(self) -> MessageSendResult:
525525

526526
@typechecked
527527
@misc._async_safe("update_semaphore")
528-
async def update(self, _init_options: Optional[dict] = None, _init = True, **kwargs: Any):
528+
async def update(self, _init_options: Optional[dict] = None, **kwargs: Any):
529529
"""
530530
.. versionadded:: v2.0
531531
@@ -557,15 +557,14 @@ async def update(self, _init_options: Optional[dict] = None, _init = True, **kwa
557557

558558
channels = kwargs.get("channels", self.channels)
559559
if isinstance(channels, AutoCHANNEL):
560-
kwargs["channels"] = channels
561-
await channels.update(init_options={"parent": self, "channel_type": "text_channels"}, _init=_init)
562-
else:
560+
await channels.update(init_options={"parent": self, "channel_type": "text_channels"})
561+
elif not isinstance(self.channels[0], int): # Not initialized (newly created):
563562
kwargs["channels"] = [x.id for x in self.channels]
564563

565564
if _init_options is None:
566565
_init_options = {"parent": self.parent}
567566

568-
await misc._update(self, init_options=_init_options, _init=_init, **kwargs)
567+
await misc._update(self, init_options=_init_options, **kwargs)
569568

570569

571570
@misc.doc_category("Messages", path="message")
@@ -878,7 +877,7 @@ async def _send(self) -> MessageSendResult:
878877

879878
@typechecked
880879
@misc._async_safe("update_semaphore")
881-
async def update(self, _init_options: Optional[dict] = None, _init = True, **kwargs):
880+
async def update(self, _init_options: Optional[dict] = None, **kwargs):
882881
"""
883882
.. versionadded:: v2.0
884883
@@ -911,4 +910,4 @@ async def update(self, _init_options: Optional[dict] = None, _init = True, **kwa
911910
if _init_options is None:
912911
_init_options = {"parent": self.parent}
913912

914-
await misc._update(self, init_options=_init_options, _init=_init, **kwargs)
913+
await misc._update(self, init_options=_init_options, **kwargs)

src/daf/message/voice_based.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -387,7 +387,7 @@ async def _send(self) -> MessageSendResult:
387387

388388
@typechecked
389389
@misc._async_safe("update_semaphore")
390-
async def update(self, _init_options: Optional[dict] = None, _init = True, **kwargs):
390+
async def update(self, _init_options: Optional[dict] = None, **kwargs):
391391
"""
392392
.. versionadded:: v2.0
393393
@@ -419,12 +419,11 @@ async def update(self, _init_options: Optional[dict] = None, _init = True, **kwa
419419

420420
channels = kwargs.get("channels", self.channels)
421421
if isinstance(channels, AutoCHANNEL):
422-
kwargs["channels"] = channels
423-
await channels.update(_init=_init)
424-
else:
422+
await channels.update(init_options={"parent": self, "channel_type": "voice_channels"})
423+
elif not isinstance(self.channels[0], int): # Not initialized (newly created):
425424
kwargs["channels"] = [x.id for x in self.channels]
426425

427426
if _init_options is None:
428427
_init_options = {"parent": self.parent}
429428

430-
await misc._update(self, init_options=_init_options, _init=_init, **kwargs)
429+
await misc._update(self, init_options=_init_options, **kwargs)

0 commit comments

Comments
 (0)