Skip to content

Commit 1267b81

Browse files
committed
Improved internal activity logic
1 parent 8e01aaa commit 1267b81

File tree

5 files changed

+106
-108
lines changed

5 files changed

+106
-108
lines changed

CHANGELOG.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,13 +37,16 @@ however, insignificant breaking changes does not guarantee a major version bump,
3737
- Added `?plugins update` for updating all installed plugins.
3838
- Reintroduce flake8 and use bandit for security issues detection.
3939
- Add travis checks for 3.6 in Linux and 3.7 for MacOS and Windows.
40+
- Eval commands are logged in debug logs.
41+
- Presence updates 30 minutes instead of 45 now.
4042

4143
### Internal
4244

4345
- Reworked `config.get` and `config.set`, it feeds through the converters before setting/getting.
4446
- To get/set the raw value, access through `config[]`.
4547
- Prerelease naming scheme is now `x.x.x-devN`.
4648
- `trigger_typing` has been moved to `core.utils.trigger_typing`, original location is deprecated.
49+
- Simpler status and activity logic.
4750

4851
# v3.2.2
4952

bot.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -444,7 +444,7 @@ async def setup_indexes(self):
444444
("key", "text"),
445445
]
446446
)
447-
logger.debug("Successfully set up database indexes.")
447+
logger.debug("Successfully configured and verified database indexes.")
448448

449449
async def on_ready(self):
450450
"""Bot startup, sets uptime."""

cogs/utility.py

Lines changed: 71 additions & 99 deletions
Original file line numberDiff line numberDiff line change
@@ -501,20 +501,23 @@ async def activity(self, ctx, activity_type: str.lower, *, message: str = ""):
501501
if not message:
502502
raise commands.MissingRequiredArgument(SimpleNamespace(name="message"))
503503

504-
activity, msg = (
505-
await self.set_presence(
506-
activity_identifier=activity_type,
507-
activity_by_key=True,
508-
activity_message=message,
509-
)
510-
)["activity"]
511-
if activity is None:
504+
try:
505+
activity_type = ActivityType[activity_type]
506+
except KeyError:
512507
raise commands.MissingRequiredArgument(SimpleNamespace(name="activity"))
513508

509+
activity, _ = await self.set_presence(activity_type=activity_type, activity_message=message)
510+
514511
self.bot.config["activity_type"] = activity.type.value
515-
self.bot.config["activity_message"] = message
512+
self.bot.config["activity_message"] = activity.name
516513
await self.bot.config.update()
517514

515+
msg = f"Activity set to: {activity.type.name.capitalize()} "
516+
if activity.type == ActivityType.listening:
517+
msg += f"to {activity.name}."
518+
else:
519+
msg += f"{activity.name}."
520+
518521
embed = discord.Embed(
519522
title="Activity Changed", description=msg, color=self.bot.main_color
520523
)
@@ -529,8 +532,7 @@ async def status(self, ctx, *, status_type: str.lower):
529532
Possible status types:
530533
- `online`
531534
- `idle`
532-
- `dnd`
533-
- `do_not_disturb` or `do not disturb`
535+
- `dnd` or `do not disturb`
534536
- `invisible` or `offline`
535537
536538
To remove the current status:
@@ -542,117 +544,85 @@ async def status(self, ctx, *, status_type: str.lower):
542544
await self.set_presence()
543545
embed = discord.Embed(title="Status Removed", color=self.bot.main_color)
544546
return await ctx.send(embed=embed)
545-
status_type = status_type.replace(" ", "_")
546547

547-
status, msg = (
548-
await self.set_presence(status_identifier=status_type, status_by_key=True)
549-
)["status"]
550-
if status is None:
548+
status_type = status_type.replace(" ", "_")
549+
try:
550+
status = Status[status_type]
551+
except KeyError:
551552
raise commands.MissingRequiredArgument(SimpleNamespace(name="status"))
552553

554+
_, status = await self.set_presence(status=status)
555+
553556
self.bot.config["status"] = status.value
554557
await self.bot.config.update()
555558

559+
msg = f"Status set to: {status.value}."
556560
embed = discord.Embed(
557561
title="Status Changed", description=msg, color=self.bot.main_color
558562
)
559563
return await ctx.send(embed=embed)
560564

561-
async def set_presence(
562-
self,
563-
*,
564-
status_identifier=None,
565-
status_by_key=True,
566-
activity_identifier=None,
567-
activity_by_key=True,
568-
activity_message=None,
569-
):
570-
571-
activity = status = None
572-
if status_identifier is None:
573-
status_identifier = self.bot.config["status"]
574-
status_by_key = False
565+
async def set_presence(self, *, status=None, activity_type=None, activity_message=None):
575566

576-
try:
577-
if status_by_key:
578-
status = Status[status_identifier]
579-
else:
580-
status = Status.try_value(status_identifier)
581-
except (KeyError, ValueError):
582-
if status_identifier is not None:
583-
msg = f"Invalid status type: {status_identifier}"
584-
logger.warning(msg)
585-
586-
if activity_identifier is None:
587-
if activity_message is not None:
588-
raise ValueError(
589-
"activity_message must be None if activity_identifier is None."
590-
)
591-
activity_identifier = self.bot.config["activity_type"]
592-
activity_by_key = False
593-
594-
try:
595-
if activity_by_key:
596-
activity_type = ActivityType[activity_identifier]
597-
else:
598-
activity_type = ActivityType.try_value(activity_identifier)
599-
except (KeyError, ValueError):
600-
if activity_identifier is not None:
601-
msg = f"Invalid activity type: {activity_identifier}"
602-
logger.warning(msg)
567+
if status is None:
568+
status = self.bot.config.get("status")
569+
570+
if activity_type is None:
571+
activity_type = self.bot.config.get("activity_type")
572+
573+
url = None
574+
activity_message = (activity_message or self.bot.config["activity_message"]).strip()
575+
if activity_type is not None and not activity_message:
576+
logger.warning("No activity message found whilst activity is provided, defaults to \"Modmail\".")
577+
activity_message = "Modmail"
578+
579+
if activity_type == ActivityType.listening:
580+
if activity_message.lower().startswith("to "):
581+
# The actual message is after listening to [...]
582+
# discord automatically add the "to"
583+
activity_message = activity_message[3:].strip()
584+
elif activity_type == ActivityType.streaming:
585+
url = self.bot.config["twitch_url"]
586+
587+
if activity_type is not None:
588+
activity = discord.Activity(
589+
type=activity_type, name=activity_message, url=url
590+
)
603591
else:
604-
url = None
605-
activity_message = (
606-
activity_message or self.bot.config["activity_message"]
607-
).strip()
608-
609-
if activity_type == ActivityType.listening:
610-
if activity_message.lower().startswith("to "):
611-
# The actual message is after listening to [...]
612-
# discord automatically add the "to"
613-
activity_message = activity_message[3:].strip()
614-
elif activity_type == ActivityType.streaming:
615-
url = self.bot.config["twitch_url"]
616-
617-
if activity_message:
618-
activity = discord.Activity(
619-
type=activity_type, name=activity_message, url=url
620-
)
621-
else:
622-
msg = "You must supply an activity message to use custom activity."
623-
logger.debug(msg)
624-
592+
activity = None
625593
await self.bot.change_presence(activity=activity, status=status)
626594

627-
presence = {
628-
"activity": (None, "No activity has been set."),
629-
"status": (None, "No status has been set."),
630-
}
631-
if activity is not None:
632-
use_to = "to " if activity.type == ActivityType.listening else ""
633-
msg = f"Activity set to: {activity.type.name.capitalize()} "
634-
msg += f"{use_to}{activity.name}."
635-
presence["activity"] = (activity, msg)
636-
if status is not None:
637-
msg = f"Status set to: {status.value}."
638-
presence["status"] = (status, msg)
639-
return presence
595+
return activity, status
640596

641-
@tasks.loop(minutes=45)
597+
@tasks.loop(minutes=30)
642598
async def loop_presence(self):
643599
"""Set presence to the configured value every 45 minutes."""
644-
# TODO: Does this even work?
645-
presence = await self.set_presence()
646-
logger.debug("Loop... %s - %s", presence["activity"][1], presence["status"][1])
600+
logger.debug("Resetting presence.")
601+
await self.set_presence()
647602

648603
@loop_presence.before_loop
649604
async def before_loop_presence(self):
650605
await self.bot.wait_for_connected()
651606
logger.line()
652-
presence = await self.set_presence()
653-
logger.info(presence["activity"][1])
654-
logger.info(presence["status"][1])
655-
await asyncio.sleep(2700)
607+
activity, status = await self.set_presence()
608+
609+
if activity is not None:
610+
msg = f"Activity set to: {activity.type.name.capitalize()} "
611+
if activity.type == ActivityType.listening:
612+
msg += f"to {activity.name}."
613+
else:
614+
msg += f"{activity.name}."
615+
logger.info(msg)
616+
else:
617+
logger.info("No activity has been set.")
618+
if status is not None:
619+
msg = f"Status set to: {status.value}."
620+
logger.info(msg)
621+
else:
622+
logger.info("No status has been set.")
623+
624+
await asyncio.sleep(1800)
625+
logger.info("Starting presence loop.")
656626

657627
@commands.command()
658628
@checks.has_permissions(PermissionLevel.ADMINISTRATOR)
@@ -1789,6 +1759,8 @@ async def oauth_show(self, ctx):
17891759
async def eval_(self, ctx, *, body: str):
17901760
"""Evaluates Python code."""
17911761

1762+
logger.warning("Running eval command:\n%s", body)
1763+
17921764
env = {
17931765
"ctx": ctx,
17941766
"bot": self.bot,

core/config.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,8 @@ class ConfigManager:
120120
"enable_plugins",
121121
}
122122

123+
special_types = {"status", "activity_type"}
124+
123125
defaults = {**public_keys, **private_keys, **protected_keys}
124126
all_keys = set(defaults.keys())
125127

@@ -236,6 +238,26 @@ def get(self, key: str, convert=True) -> typing.Any:
236238
except ValueError:
237239
value = self.remove(key)
238240

241+
elif key in self.special_types:
242+
if value is None:
243+
return
244+
245+
if key == "status":
246+
try:
247+
# noinspection PyArgumentList
248+
value = discord.Status(value)
249+
except ValueError:
250+
logger.warning("Invalid status %s.", value)
251+
value = self.remove(key)
252+
253+
elif key == "activity_type":
254+
try:
255+
# noinspection PyArgumentList
256+
value = discord.ActivityType(value)
257+
except ValueError:
258+
logger.warning("Invalid activity %s.", value)
259+
value = self.remove(key)
260+
239261
return value
240262

241263
def set(self, key: str, item: typing.Any, convert=True) -> None:
@@ -294,6 +316,9 @@ def set(self, key: str, item: typing.Any, convert=True) -> None:
294316
except ValueError:
295317
raise InvalidConfigError("Must be a yes/no value.")
296318

319+
# elif key in self.special_types:
320+
# if key == "status":
321+
297322
return self.__setitem__(key, item)
298323

299324
def remove(self, key: str) -> typing.Any:

core/thread.py

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -661,8 +661,6 @@ async def send(
661661
url=message.jump_url,
662662
)
663663

664-
delete_message = not bool(message.attachments)
665-
666664
ext = [(a.url, a.filename) for a in message.attachments]
667665

668666
images = []
@@ -736,6 +734,12 @@ async def send(
736734
embed.set_footer(text=mod_tag) # Normal messages
737735
else:
738736
embed.set_footer(text=self.bot.config["anon_tag"])
737+
delete_message = not bool(message.attachments)
738+
if delete_message:
739+
try:
740+
await message.delete()
741+
except Exception as e:
742+
logger.warning('Cannot delete message: %s.', str(e))
739743
elif note:
740744
embed.colour = self.bot.main_color
741745
else:
@@ -760,12 +764,6 @@ async def send(
760764
await asyncio.gather(*additional_images)
761765
self.ready = True
762766

763-
if delete_message:
764-
try:
765-
if isinstance(message.channel, discord.TextChannel):
766-
await message.delete()
767-
except Exception:
768-
logger.warning('Cannot delete message.', exc_info=True)
769767
return msg
770768

771769
def get_notifications(self) -> str:

0 commit comments

Comments
 (0)