Discord utils: added function for formatting discord objects for printing in logs

This commit is contained in:
Elnath 2021-01-23 23:01:53 +01:00
parent 66197c18f8
commit e9880e38a8
2 changed files with 41 additions and 9 deletions

View File

@ -3,7 +3,6 @@ import argparse
import logging import logging
import sys import sys
from pathlib import Path from pathlib import Path
from typing import List
import discord import discord
import discord.utils import discord.utils
@ -34,7 +33,7 @@ class VocalMaisBot(commands.Cog):
@commands.Cog.listener() @commands.Cog.listener()
async def on_ready(self): async def on_ready(self):
logger.info("Connected and ready!") logger.info("Connected and ready!")
logger.info(f"Logged in as {self.bot.user}") logger.info(f"Logged in as {discord_utils.to_string(self.bot.user)}")
self.owner = (await self.bot.application_info()).owner self.owner = (await self.bot.application_info()).owner
@ -80,7 +79,7 @@ class VocalMaisBot(commands.Cog):
else: else:
return await ctx.send(f":x: this command can not be run: {error}") return await ctx.send(f":x: this command can not be run: {error}")
else: else:
logger.error(f"Error when running command '{ctx.message.content}' by {ctx.author.name}#{ctx.author.discriminator} in {ctx.guild.name}", exc_info = error) logger.error(f"Error when running command '{ctx.message.content}' by {discord_utils.to_string(ctx.author)} in {discord_utils.to_string(ctx.guild)}", exc_info = error)
if isinstance(error, commands.CommandInvokeError): if isinstance(error, commands.CommandInvokeError):
await ctx.send(f":x: There was an error during the command execution :dizzy_face:") await ctx.send(f":x: There was an error during the command execution :dizzy_face:")
else: else:
@ -89,7 +88,7 @@ class VocalMaisBot(commands.Cog):
def cog_check(self, ctx: commands.Context): def cog_check(self, ctx: commands.Context):
# We silently ignore messages from bots, since we do not want bots to command us # We silently ignore messages from bots, since we do not want bots to command us
if ctx.author.bot or ctx.message.is_system(): if ctx.author.bot or ctx.message.is_system():
logger.info(f"[{ctx.guild.name}({ctx.guild.id})] Ignored command message from bot or system {ctx.author.name}{ctx.author.discriminator}({ctx.author.id}): {ctx.message.content}") logger.info(f"[{discord_utils.to_string(ctx.guild)}] Ignored command message from bot or system: {ctx.message.content}")
raise discord_utils.CheckFailDoNotNotify raise discord_utils.CheckFailDoNotNotify
return True return True
@ -233,7 +232,7 @@ class VocalMaisBot(commands.Cog):
return # It's not one of our special watched join-to-create channels return # It's not one of our special watched join-to-create channels
# The user is not a bot and connected to one of our special watched channels # The user is not a bot and connected to one of our special watched channels
logger.debug(f"[{channel.guild.name}({channel.guild.id})] User {user.name}#{user.discriminator}({user.id}) connected to watched channel {channel.name}({channel.id})") logger.debug(f"[{discord_utils.to_string(channel.guild)}] User {discord_utils.to_string(user)}) connected to watched channel {discord_utils.to_string(channel)})")
# We create a channel for them and move them into it # We create a channel for them and move them into it
category = channel.category category = channel.category
@ -258,10 +257,10 @@ class VocalMaisBot(commands.Cog):
channel_name = discord_utils.voice_channel_safe_name(user_default_channel_name, user_name_replacement = user.display_name) channel_name = discord_utils.voice_channel_safe_name(user_default_channel_name, user_name_replacement = user.display_name)
# Creating the channel and moving the user into it # Creating the channel and moving the user into it
logger.debug(f"[{channel.guild.name}({channel.guild.id})] Creating channel {channel_name} for {user.name}#{user.discriminator}({user.id})") logger.debug(f"[{discord_utils.to_string(channel.guild)}] Creating channel {channel_name} for {discord_utils.to_string(user)}")
user_channel = await category.create_voice_channel(channel_name, overwrites = channel_permissions) user_channel = await category.create_voice_channel(channel_name, overwrites = channel_permissions)
await user.move_to(user_channel) await user.move_to(user_channel)
logger.info(f"[{channel.guild.name}({channel.guild.id})] Created channel {user_channel.name}({user_channel.id}) for {user.name}#{user.discriminator}({user.id})") logger.info(f"[{discord_utils.to_string(channel.guild)}] Created channel {discord_utils.to_string(user_channel)} for {discord_utils.to_string(user)}")
# Saving the channel in the configuration # Saving the channel in the configuration
self.channels_config.add_channel_to_created(user_channel.guild, user_channel) self.channels_config.add_channel_to_created(user_channel.guild, user_channel)
@ -272,15 +271,16 @@ class VocalMaisBot(commands.Cog):
if not self.channels_config.is_created(channel.guild, channel): if not self.channels_config.is_created(channel.guild, channel):
return # It is not a channel that we manage, nothing to do return # It is not a channel that we manage, nothing to do
logger.debug(f"[{channel.guild.name}({channel.guild.id})] User left temporary channel {channel.name} ({channel.id})") logger.debug(f"[{discord_utils.to_string(channel.guild)}] User left temporary channel {discord_utils.to_string(channel)}")
# It is a channel that we manage # It is a channel that we manage
if len(channel.members) > 0: if len(channel.members) > 0:
return # There are still people inside it, nothing to do return # There are still people inside it, nothing to do
logger.debug(f"[{discord_utils.to_string(channel.guild)}] Temporary channel {discord_utils.to_string(channel)} is now empty")
try: try:
await channel.delete() await channel.delete()
except discord.NotFound: except discord.NotFound:
pass # The channel already does not exist, that's not a problem, that's what we want pass # The channel already does not exist, that's not a problem, that's what we want
logger.info(f"[{channel.guild.name}({channel.guild.id})] Deleted channel {channel.name}({channel.id}) because it was empty") logger.info(f"[{discord_utils.to_string(channel.guild)}] Deleted channel {discord_utils.to_string(channel)} because it was empty")
# updating the configuration # updating the configuration
self.channels_config.remove_channel_from_created(channel.guild, channel) self.channels_config.remove_channel_from_created(channel.guild, channel)

View File

@ -1,5 +1,6 @@
import discord import discord
import discord.ext.commands as commands import discord.ext.commands as commands
from functools import singledispatch
class CheckFailDoNotNotify(commands.CheckFailure): class CheckFailDoNotNotify(commands.CheckFailure):
@ -30,3 +31,34 @@ def voice_channel_safe_name(template: str, max_chars: int = 100, escape_mentions
message = message[:max_chars - 3] + "..." message = message[:max_chars - 3] + "..."
return message return message
@singledispatch
def to_string(obj) -> str:
"""
Convert the given discord object to a string, for logging purposes.
See functools.singledispatch
"""
return str(obj)
@to_string.register(discord.Object)
@to_string.register(discord.abc.Snowflake)
def _(obj) -> str:
return f"<{obj.id}>"
@to_string.register(discord.abc.User)
def _(user) -> str:
return f"{user.name}#{user.discriminator}({user.id})"
@to_string.register(discord.Guild)
def _(guild) -> str:
return f"{guild.name}({guild.id})"
@to_string.register(discord.abc.GuildChannel)
def _(channel) -> str:
return f"{channel.name}({channel.id})"