Skip to content

Instantly share code, notes, and snippets.

@SnowyJaguar1034
Created April 2, 2022 21:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SnowyJaguar1034/b0e22c478e5f516b390c9f4753d7058f to your computer and use it in GitHub Desktop.
Save SnowyJaguar1034/b0e22c478e5f516b390c9f4753d7058f to your computer and use it in GitHub Desktop.
This is a gist of what I already have loggers for in my private bot, Some if not all of these will be ported over to Zupie.

I will start off saying that some parts of these events use third party libs on my private bot (the buttons are a good example of this). I would prefer to create buttons using discord.py's buttons for Zupie.

Bot Joins Guild

@commands.Cog.listener()
async def on_guild_join(self, guild):
  self.bot.prom.guilds_join.inc({})
  embed = discord.Embed(title = "Server Join", description = f"{guild.name} ({guild.id})", colour = 0x00FF00, timestamp = datetime.datetime.utcnow(),)
  guilds = sum(await self.bot.comm.handler("guild_count", self.bot.cluster_count))
  embed.set_footer(text = f"{guilds} servers")
  if self.bot.config.join_channel:
      await self.bot.http.send_message(self.bot.config.join_channel, None, embed = embed.to_dict())
  if guild.id in self.bot.banned_guilds:
      await guild.leave()

Bot Leaves Guild

@commands.Cog.listener()
async def on_guild_remove(self, guild):
  self.bot.prom.guilds_leave.inc({})
  async with self.bot.pool.acquire() as conn:
      await conn.execute("DELETE FROM data WHERE guild=$1", guild.id)
  embed = discord.Embed(title = "Server Leave", description = f"{guild.name} ({guild.id})",colour = 0xFF0000, timestamp = datetime.datetime.utcnow(),)
  guilds = sum(await self.bot.comm.handler("guild_count", self.bot.cluster_count))
  embed.set_footer(text = f"{guilds} servers")
  if self.bot.config.join_channel:
      await self.bot.http.send_message(self.bot.config.join_channel, None, embed=embed.to_dict())

Member Joins Guild

@commands.Cog.listener()
async def on_member_join(self, member):
  data = await self.bot.get_data(member.guild.id)
  log = self.bot.get_channel(id = data[18])
  general = self.bot.get_channel(id = 448408754355175426) # General channel
  off_topic = self.bot.get_channel(id = 828293592585207839) # off topic channel
  staff_commands = self.bot.get_channel(id = 501004576866959391) # Server Manager channel
  server_info = self.bot.get_channel(id = 500413330368888882) # Server Info channel
  raid = self.bot.get_channel(id = data[16])
  acc_age = datetime.datetime.utcnow() - member.created_at
  joincount = await self.bot.get_member_guild(member.id, member.guild.id)
  count = joincount[2] + 1
  async with self.bot.pool.acquire() as conn:
      await conn.execute("UPDATE membersguilds SET joincount=$1 WHERE member=$2 and guild=$3", count, member.id, member.guild.id)
  await asyncio.sleep(2)

  member_status = "No status" if member.activity is None else member.activity.name

  embed = discord.Embed(title = f"Member Joined!", description = f"{member.mention} joined {member.guild.name}", colour = self.bot.config.user_colour)
  embed.set_author(name = f"{member.name}#{member.discriminator} | {member.id}", icon_url = member.avatar_url)
  embed.set_thumbnail(url = member.avatar_url)
  embed.set_footer(text = f"Members: {member.guild.member_count}")
  embed.add_field(name = f"Status **{member.status}**", value = f"*{member_status}*", inline = False)
  await Info(self).timestamps(member, embed, True)

  if member.id not in self.bot.config.admins:
      content = f"{member.id}"
      Direct_Message = discord.Embed(title = "Useful Information", description = f" Hey {member.mention} you have joined {member.guild}.\nIf you need to read the community guidelines again you can find them in the {server_info.mention} channel at the top of the channel list in the <#736235918339604491> category.", colour = self.bot.config.branding_colour)
      Direct_Message.set_footer(text = f"DM me {self.bot.user} here if you need to contact staff.")
      join_msg = await log.send(content = content, embed = embed)
      try:
          await member.send(embed = Direct_Message)
      except discord.Forbidden:
          content = content + f"\nI was unable to DM {member} due to their DM's being closed."
          await join_msg.edit(embed = embed, content = content)
          await log.send(f"{member.id}")

      if member.bot == False:
          await general.send(f"{member} Welcome to GTA Online Friendly Sessions, Thank you for joining")
      else:
          tmp = [] # some temp list to append the role objects in
          tmp.append(discord.Object(719518142086512651))
          await member.add_roles(*tmp, reason = f"{member} is a bot!", atomic = True)
          #async for entry in member.guild.audit_logs(action = discord.AuditLogAction.bot_add):
          #print(f'{0.user} added {0.target}')
          await staff_commands.send(f"{member.mention} was added.\n**Status:** {member_status}")


  if all([
      data[14] == True, 
      member.guild.id == data[0], 
      acc_age < datetime.timedelta(days = data[15])
  ]):
      if joincount[2] > 3:
          embed = discord.Embed(title = "Member Banned!", description = f'{member}\'s account is **{acc_age.days}** days old and has joined the server **{joincount[2]}** times so the member was banned by raidmode.')
          await member.ban(reason = f"Raidmode enabled: {member}\'s account was deemeed too new by your raidmode configuration. The required age is {data[15]} days old and this users account is {acc_age.days} days old. You can check the current required age with the modconfig command. This user has also joined the server {joincount[2]} times which resulted in their ban.")
          msg = await raid.send(embed = embed)
          try:
              await member.send(f"This server has raidmode **active** and requires users have a account that is older than **{data[15]}** days old and to have not joined more than **3** times. As your account is less than the servers threshold and you have joined {joincount[2]} times you have been banned.")
          except discord.Forbidden:
              await msg.edit("{member.id}", embed = embed, content = f"I was unable to DM {member} due to their DM's being closed.")
      else:
          embed = discord.Embed(title = "Member Kicked!", description = f'{member.name}#{member.discriminator} account is **{acc_age.days}** days old and so the member was kicked by raidmode.')
          await member.kick(reason = f"Raidmode enabled: {member}'s account was deemeed too new by your raidmode configuration. The required age is {data[15]} days old and this users account is {acc_age.days} days old. You can check the current required age with the modconfig command.")
          msg = await raid.send(embed = embed)
          try:
              await member.send(f"This server has raidmode **active** and requires users have a account that is older than **{data[15]}** days old. As your account is less than the servers threshold you have been kicked.")
          except discord.Forbidden:
              await msg.edit(embed = embed, content = f"I was unable to DM {member} due to their DM's being closed.")

  zalgo = re.search("/[\xCC\xCD]/", member.name)
  if zalgo:
      plain = ''.join(filter(str.isalnum, member.name))
      await member.edit(reason = "{member}'s nickname was changed to {plain}because Zalgo text was detected.", nick = plain)

  if "discord.gg/" in member.activity.name:
      try:
          await member.send("We identified a disord server invite link in your status message, Kindly change it before moderaton action is taken against you.")
      except discord.HTTPException:
          error = await off_topic.send(f"{member.mention} we were unable to DM you this message due to your DMs being closed\n\n> We identified a disord server invite link in your status message, Kindly change it before moderaton action is taken against you.\n\nThis message will be delted as soon as you react with <a:akoalathumbsup:895039904764026880>")
          await error.add_reaction("<a:akoalathumbsup:895039904764026880>")

          def check(payload):
              return payload.member == member and str(payload.emoji) == '<a:akoalathumbsup:895039904764026880>'

          payload = await self.bot.wait_for('raw_reaction_add', check = check)
          await error.delete()

Member Leaves Guild

@commands.Cog.listener()
async def on_member_remove(self, member):
  data = await self.bot.get_data(member.guild.id)
  log = self.bot.get_channel(id = data[18])
  general = self.bot.get_channel(id = 448408754355175426) # General channel
  snowyjaguar = self.bot.get_user(self.bot.config.owner)
  member_status = "No status" if member.activity is None else member.activity.name
  embed = discord.Embed(title = f"Member left!", description = f"{member.mention} left {member.guild.name}", colour = self.bot.config.mod_colour)
  embed.set_author(name = f"{member.name}#{member.discriminator} | {member.id}", icon_url = member.avatar_url)
  embed.set_thumbnail(url = member.avatar_url)
  embed.set_footer(text = f"Members: {member.guild.member_count}")
  embed.add_field(name = f"Status **{member.status}**", value = f"*{member_status}*", inline = False)
  await Info(self).timestamps(member, embed, True)

  if member.id not in self.bot.config.admins:
      await log.send(f"{member.id}", embed = embed)
      if member.bot == False:
          await general.send(f"{member} left :sob:")
      else:
          await snowyjaguar.send(f"{member} was removed from {member.guild}.")
  else:
      invite = await self.bot.comm.handler("invite_guild", -1, {"guild_id": member.guild.id})
      if not invite:
          await member.send(embed = discord.Embed(description = "No permissions to create an invite link.", colour = self.bot.primary_colour))
      else:
          buttons = [create_button(style = ButtonStyle.blue.URL, url = f"https://discord.gg/{invite.code}", label = f"Invite Code: {invite.code}")]
          action_row = create_actionrow(*buttons)

          await member.send(content = f"You can rejoin {member.guild} by clicking the button", components = [action_row])
          button_ctx: ComponentContext = await wait_for_component(self.bot, components = action_row)
          await button_ctx.edit_origin(content = "You pressed a button!")

Member updates their profile

I use this on my private bot to send members a thank you msg when they boost the server.

@commands.Cog.listener()
async def on_member_update(self, before, after):
  booster_channel = discord.utils.get(after.guild.text_channels, id = 851793810086166568)
  bwelcome = 851793924372693022
  booster_welcome = discord.utils.get(after.guild.text_channels, id = bwelcome)
  booster_role = discord.utils.get(after.guild.roles, id = 769898504591769610)
  general = discord.utils.get(after.guild.text_channels, id = 448408754355175426)
  promo = discord.utils.get(after.guild.roles, id = 797166495993692160)
  promo_channel = discord.utils.get(after.guild.text_channels, id = 783337245364322344)

  booster = discord.Embed(title = f"Welcome {after.name}#{after.discriminator}", description = f"Thank you for choosing to boost {after.guild.name}.\nYou can head over to <#{bwelcome}> to see the awesome perks you now have.", colour = self.bot.config.booster_colour)
  if booster_role in after.roles and booster_role not in before.roles:
      await general.send(f"{after.name}#{after.discriminator} just boosted the server!<:booster:834372178958745600>")
      await booster_channel.send(f"{after.mention}", embed = booster)

  for role in after.roles:
      if all([
          role not in before.roles,
          role.id in self.bot.config.rewards[2:],
          datetime.datetime.utcnow() - after.joined_at >= datetime.timedelta(days = 7),
          datetime.datetime.utcnow() - after.created_at >= datetime.timedelta(weeks = 10), # 2.5 months
          promo not in before.roles,
          ]):
          await after.add_roles(promo, reason = f"{after} received the {promo} role as they meet all of the criteria.", atomic = True)
          await general.send(f"{after} can now send messages in {promo_channel.mention}")
          await after.send(f"Hey, you can now send promotional messages in {promo_channel.mention}.")

Message Edits

@commands.Cog.listener()
async def on_message_edit(self, before, after):
  data = await self.bot.get_data(before.guild.id)
  log = discord.utils.get(after.guild.text_channels, id = data[24])
  if before.content != after.content:
      embed = discord.Embed(title = "📝 Message Edited", description = f"{after.author.display_name} edited a message in {after.channel.mention} ||`{after.channel}`||", colour = after.author.colour, url = after.jump_url, timestamp = datetime.datetime.utcnow())
      embed.set_author(name = f"{after.author} | {after.author.id}", icon_url = after.author.avatar_url)
      embed.add_field(name = "Old Message:", value = f"{before.content}", inline = False)
      embed.add_field(name = "New Message:", value = f"{after.content}", inline = False)
      embed.set_footer(text = f"Message ID: {after.id}.")
      await log.send(embed = embed)

Message Deltions

@commands.Cog.listener()
async def on_message_delete(self, message):
  data = await self.bot.get_data(message.guild.id)
  log = discord.utils.get(message.guild.text_channels, id = data[23])
  embed = discord.Embed(title = "🗑 Message Deleted", description = f"{message.author.display_name} deleted a message in {message.channel.mention} ||`{message.channel}`||", colour = message.author.colour, timestamp = datetime.datetime.utcnow())
  embed.set_author(name = f"{message.author} | {message.author.id}", icon_url = message.author.avatar_url)
  embed.add_field(name = "Content", value = f"{message.content}", inline = False)
  embed.set_footer(text = f"Message ID: {message.id}.")
  await log.send(embed = embed)

Bulk Message Deltions

@commands.Cog.listener()
async def on_bulk_message_delete(self, messages):
  history = ""
  authors = ""
  authors_sorted = []
  for message in messages:
      server = message.guild.id
      channel = message.channel
      history = (f"[{str(message.created_at.replace(microsecond=0))}] Author: {message.author} Message: ({message.id}) {message.content}\n\n" + history)
  data = await self.bot.get_data(server)
  log = self.bot.get_channel(data[23])
  embed = discord.Embed(title = "A bulk message deletion occured.", description = f"**{len(messages)}** messages were deleted from {channel.mention} ||`{channel}`||.", colour = message.author.colour, timestamp = datetime.datetime.utcnow())
  embed.set_footer(text = f"Channel {channel} | {channel.id}.")

  history = io.StringIO(history)
  file = discord.File(history, f"[{datetime.datetime.utcnow().strftime('%d.%m.%Y %I.%M.%S %p')}] {channel} Bulk Message Deletion.txt") # replace(microsecond=0)
  await log.send(embed = embed, file = file)

Member Bans

@commands.Cog.listener()
async def on_member_ban(self, guild, user):
  if user.id in self.bot.config.admins:
      await user.unban(reason = "This account is a test acount for SnowyJaguar#1034")
      await member.send(embed = discord.Embed(description = "A message.", colour = self.bot.primary_colour))

AFK feature

@commands.Cog.listener()
async def on_message(self, message):
  if message.author.bot:
      return
  if message.guild != None:
      data = await self.bot.get_data(message.guild.id)
      afk_return = await self.bot.get_member_guild(message.author.id, message.guild.id)
      if afk_return[4] == True:
          async with self.bot.pool.acquire() as conn:
              await conn.execute("UPDATE membersguilds SET afk=$1, afkmessage=$2 WHERE member=$3 and guild=$4", False, None, message.author.id, message.guild.id)
          await message.reply(f"Welcome back {message.author.mention}")        
      if message.mentions:
          for mention in message.mentions:
              afk = await self.bot.get_member_guild(mention.id, message.guild.id)
              if afk[4] == True:
                  await message.channel.send(f"{mention} is AFK:\n\t{afk[5]}:")
      server_info = self.bot.get_channel(id = 500413330368888882) # Server Info channel
      text = f"Please don't mention `@everyone` unnecessarily. If you want to ping a large group of members we have roles for activities or games which can be found in {server_info.mention} or you could ping `@here`."
      print(f"\nMessage event: {message.content}\n{message}")
      if bad := [word for word in data[28] or self.bot.config.default_bad_words if word in message.content]:
      #if message.content in data[28] or message.content in self.bot.config.default_bad_words:
          #if message.author.has_any_role(data[3]) or message.author.has_guild_permissions(self.bot.config.moderator_permissions):
          if (len(set(data[3]) & set([role.id for role in message.author.roles])) > 0) or self.bot.config.moderator_permissions in message.author.guild_permissions:
              return
          else:
              print(f"\nMessage event: {message.content}\n{message}")
              await message.delete()
              try:
                  await message.author.send(f'Your message had `{", ".join(bad)}` in it, This word is conssidered a "bad" word on this server so your message was removed.')
              except discord.HTTPException:
                  await message.channel.send(f'{message.author.mention} `{bad}` is conssidered a "bad" word on this server.')
              if "@everyone" in message.content:
              #if message.mention_everyone:
                  try:
                      await message.author.send(text)
                  except discord.HTTPException:
                      await message.channel.send(f'{message.author.mention} {text}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment