Skip to content

Commit

Permalink
Merge pull request #245 from FirePlank/dev
Browse files Browse the repository at this point in the history
Migrated poll cog to new extension format
  • Loading branch information
SylteA authored Nov 2, 2023
2 parents 29f237d + a70c7df commit 23dcfc1
Show file tree
Hide file tree
Showing 12 changed files with 270 additions and 176 deletions.
151 changes: 0 additions & 151 deletions bot/cogs/poll.py

This file was deleted.

5 changes: 3 additions & 2 deletions bot/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ async def when_online(self):
await self.wait_until_ready()

await self.load_extensions()
await self.sync_commands()
# await self.sync_commands()

async def load_extensions(self):
for ext in self.initial_extensions:
Expand Down Expand Up @@ -96,7 +96,8 @@ async def process_commands(self, message: discord.Message, /):

async def on_app_command_error(self, interaction: "InteractionType", error: app_commands.AppCommandError):
"""Handle errors in app commands."""
if isinstance(error, IgnorableException):

if isinstance(error.__cause__, IgnorableException):
return

if interaction.command is None:
Expand Down
7 changes: 2 additions & 5 deletions bot/extensions/levelling/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -230,14 +230,13 @@ def convert_int(integer):
xp_offset_x -= xp_text_size[2] - xp_text_size[0]
draw.text((xp_offset_x, xp_offset_y), text, font=self.small_font, fill="#fff")

if len(username) >= 15:
if len(username) >= 18:
# Truncating the name
username = username[:15] + "..."

text_bbox = draw.textbbox((0, 0), username, font=self.medium_font)
text_offset_x = bar_offset_x - 10
text_offset_y = bar_offset_y - (text_bbox[3] - text_bbox[1]) - 20
draw.text((text_offset_x, text_offset_y), username, font=self.medium_font, fill="#fff")
draw.text((bar_offset_x, text_offset_y), username, font=self.medium_font, fill="#fff")

# create copy of background
background = self.background.copy()
Expand Down Expand Up @@ -274,8 +273,6 @@ async def rank(self, interaction: core.InteractionType, member: discord.Member =

record = await LevellingUser.pool.fetchrow(query, interaction.guild.id, member.id)

log.info(record)

if record.total_xp is None:
if member.id == interaction.user.id:
return await interaction.response.send_message(
Expand Down
9 changes: 9 additions & 0 deletions bot/extensions/polls/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from bot.core import DiscordBot

from .commands import Polls
from .events import PollEvents


async def setup(bot: DiscordBot) -> None:
await bot.add_cog(Polls(bot=bot))
await bot.add_cog(PollEvents(bot=bot))
76 changes: 76 additions & 0 deletions bot/extensions/polls/commands.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import discord
from discord import app_commands
from discord.ext import commands

from bot import core
from bot.extensions.polls.utils import emojis, poll_check
from bot.extensions.polls.views import CreatePollView
from utils.transformers import MessageTransformer


class Polls(commands.GroupCog, group_name="poll"):
def __init__(self, bot: core.DiscordBot):
self.bot = bot

self._create_poll_view = CreatePollView(timeout=None)
self.bot.add_view(self._create_poll_view)

@app_commands.command()
@app_commands.describe(question="Your question")
async def new(self, interaction: core.InteractionType, question: str):
"""Create a new poll"""

embed = discord.Embed(
description=f"**{question}**\n\n",
timestamp=discord.utils.utcnow(),
color=discord.colour.Color.gold(),
)
embed.set_footer(text=f"Poll by {interaction.user.display_name}")
await interaction.response.send_message(embed=embed, ephemeral=True, view=self._create_poll_view)

@app_commands.command()
async def show(
self,
interaction: core.InteractionType,
message: app_commands.Transform[discord.Message, MessageTransformer],
ephemeral: bool = True,
):
"""Show a poll result"""

if not poll_check(message, self.bot.user):
return await interaction.response.send_message("Please provide a valid poll message", ephemeral=True)

poll_embed = message.embeds[0]
reactions = message.reactions
reactions_total = sum([reaction.count - 1 if str(reaction.emoji) in emojis else 0 for reaction in reactions])

options = [field.name for field in poll_embed.fields]
desc = poll_embed.description.split("1️")[0]

embed = discord.Embed(
description=desc,
timestamp=poll_embed.timestamp,
color=discord.Color.gold(),
)

for i, option in enumerate(options):
reaction_count = reactions[i].count - 1
indicator = "░" * 20
if reactions_total != 0:
indicator = "█" * int(((reaction_count / reactions_total) * 100) / 5) + "░" * int(
(((reactions_total - reaction_count) / reactions_total) * 100) / 5
)

embed.add_field(
name=option,
value=f"{indicator} {int((reaction_count / (reactions_total or 1)*100))}%"
f" (**{reaction_count} votes**)",
inline=False,
)

embed.set_footer(text="Poll Result")
return await interaction.response.send_message(embed=embed, ephemeral=ephemeral)


async def setup(bot: core.DiscordBot):
await bot.add_cog(Polls(bot=bot))
34 changes: 34 additions & 0 deletions bot/extensions/polls/events.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import discord
from discord.ext import commands

from bot import core
from bot.extensions.polls.utils import emojis, poll_check


class PollEvents(commands.Cog):
"""Events for polls in discord."""

def __init__(self, bot: core.DiscordBot):
self.bot = bot

@commands.Cog.listener()
async def on_raw_reaction_add(self, payload: discord.RawReactionActionEvent):
channel: discord.TextChannel = self.bot.get_channel(payload.channel_id)
message: discord.Message = await channel.fetch_message(payload.message_id)

if payload.user_id == self.bot.user.id:
return

if not poll_check(message, self.bot.user):
return

if str(payload.emoji) not in emojis:
return

for reaction in message.reactions:
if str(reaction) not in emojis:
return

if str(reaction.emoji) != str(payload.emoji):
user = self.bot.get_user(payload.user_id)
await message.remove_reaction(reaction.emoji, user)
12 changes: 12 additions & 0 deletions bot/extensions/polls/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import discord

emojis = ["1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟"]


def poll_check(message: discord.Message, bot: discord.ClientUser):
if not message.embeds:
return False

embed = message.embeds[0]
if str(embed.footer.text).count("Poll by") == 1:
return message.author == bot
Loading

0 comments on commit 23dcfc1

Please sign in to comment.