Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Migrated poll cog to new extension format #245

Merged
merged 23 commits into from
Nov 2, 2023
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
61b46e1
Fixed alignment in the rank card and improved trunacation
FirePlank Oct 25, 2023
b5a2e6a
Migrated poll cog to new extension format
FirePlank Oct 25, 2023
ff933c8
Migrated poll cog to new extension format
FirePlank Oct 26, 2023
fc181b3
Merge branch 'dev' of https://github.com/FirePlank/Discord-Bot into dev
FirePlank Oct 26, 2023
8d9c5e2
Fixed events and delete message after poll creation
FirePlank Oct 26, 2023
003e2c0
Update commands.py
FirePlank Oct 26, 2023
4de940b
Rename extension to polls
FirePlank Oct 26, 2023
a12979f
Added views.py
FirePlank Oct 26, 2023
0062559
linting tools
FirePlank Oct 26, 2023
de91f3b
Added poll_check to commands.py
FirePlank Oct 26, 2023
31991c2
slight fix
FirePlank Oct 26, 2023
62bfacb
Maded erros ephemeral, renamed variable and maintained wording consis…
FirePlank Oct 26, 2023
86fc558
linting tools
FirePlank Oct 26, 2023
81d26f2
Replaced try and except mess in show poll command with MessageTransfo…
FirePlank Oct 27, 2023
5a774c7
Did the suggested changes requested by Sylte
FirePlank Oct 27, 2023
7374de6
Fixed IgnorableException being sent to errors webhook
FirePlank Oct 27, 2023
cb4efd6
Did the suggested changes
FirePlank Oct 30, 2023
07ce16f
Did the suggested changes
FirePlank Oct 30, 2023
a38bc52
Added utils.py file
FirePlank Nov 1, 2023
981e843
Fixes
SylteA Nov 1, 2023
bfd14f3
Progress on new delete menu and updated button states
SylteA Nov 1, 2023
948c2b5
Update MessageTransformer
SylteA Nov 1, 2023
a70c7df
Fix
HETHAT Nov 2, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 PollsEvents


async def setup(bot: DiscordBot) -> None:
await bot.add_cog(Polls(bot=bot))
await bot.add_cog(PollsEvents(bot=bot))
87 changes: 26 additions & 61 deletions bot/cogs/poll.py → bot/extensions/polls/commands.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
import discord
from discord import app_commands
from discord.ext import commands

from bot import core
from bot.extensions.polls.views import PollButtons

class Polls(commands.Cog):

class Polls(commands.GroupCog, group_name="poll"):
def __init__(self, bot: commands.AutoShardedBot):
FirePlank marked this conversation as resolved.
Show resolved Hide resolved
self.__bot = bot
FirePlank marked this conversation as resolved.
Show resolved Hide resolved

Expand Down Expand Up @@ -30,80 +34,39 @@ def poll_check(self, message: discord.Message):
return message.author == self.__bot.user
return False

@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 self.poll_check(message):
return

emojis = list(self.reactions.values())
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)

@commands.group()
async def poll(self, ctx):
"""Polls"""
if ctx.invoked_subcommand is None:
return await ctx.send_help(self.__bot.get_command("poll"))

@poll.command()
@commands.cooldown(1, 10, commands.BucketType.channel)
async def new(self, ctx, desc: str, *choices):
@app_commands.command()
@app_commands.checks.cooldown(1, 10)
FirePlank marked this conversation as resolved.
Show resolved Hide resolved
async def new(self, interaction: core.InteractionType, title: str):
FirePlank marked this conversation as resolved.
Show resolved Hide resolved
"""Create a new poll"""
await ctx.message.delete()

if len(choices) < 2:
ctx.command.reset_cooldown(ctx)
if len(choices) == 1:
return await ctx.send("Can't make a poll with only one choice")
return await ctx.send("You have to enter two or more choices to make a poll")

if len(choices) > 10:
ctx.command.reset_cooldown(ctx)
return await ctx.send("You can't make a poll with more than 10 choices")

embed = discord.Embed(
description=f"**{desc}**\n\n"
+ "\n\n".join(f"{str(self.reactions[i])} {choice}" for i, choice in enumerate(choices, 1)),
description=f"**{title}**\n\n",
timestamp=discord.utils.utcnow(),
color=discord.colour.Color.gold(),
)
embed.set_footer(text=f"Poll by {str(ctx.author)}")
msg = await ctx.send(embed=embed)
for i in range(1, len(choices) + 1):
await msg.add_reaction(self.reactions[i])
embed.set_footer(text=f"Poll by {str(interaction.user.display_name)}")
FirePlank marked this conversation as resolved.
Show resolved Hide resolved
await interaction.response.send_message(embed=embed, ephemeral=True, view=PollButtons())

@poll.command()
async def show(self, ctx, message: str):
@app_commands.command()
async def show(self, interaction: core.InteractionType, message: str, ephemeral: bool = True):
"""Show a poll result"""
await ctx.message.delete()

try:
*_, channel_id, msg_id = message.split("/")

try:
channel = self.__bot.get_channel(int(channel_id))
message = await channel.fetch_message(int(msg_id))
except Exception:
return await ctx.send("Please provide the message ID/link for a valid poll")
return await interaction.response.send_message(
"Please provide the message ID/link for a valid poll", ephemeral=True
)
except Exception:
try:
message = await ctx.channel.fetch_message(message)
message = await interaction.channel.fetch_message(int(message))
except Exception:
return await ctx.send("Please provide the message ID/link for a valid poll")
return await interaction.response.send_message(
"Please provide the message ID/link for a valid poll", ephemeral=True
)

if self.poll_check(message):
FirePlank marked this conversation as resolved.
Show resolved Hide resolved
poll_embed = message.embeds[0]
Expand Down Expand Up @@ -142,10 +105,12 @@ async def show(self, ctx, message: str):
)

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

return await ctx.send("Please provide the message ID/link for a valid poll")
return await interaction.response.send_message(
"Please provide the message ID/link for a valid poll", ephemeral=True
)


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

from bot import core


class PollsEvents(commands.Cog):
FirePlank marked this conversation as resolved.
Show resolved Hide resolved
"""Events for polls in discord."""

def __init__(self, bot: core.DiscordBot):
self.bot = bot
self.emojis = ["1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "9️⃣", "🔟"]

def poll_check(self, message: discord.Message):
try:
embed = message.embeds[0]
except Exception:
return False
if str(embed.footer.text).count("Poll by") == 1:
return message.author == self.bot.user
return False
FirePlank marked this conversation as resolved.
Show resolved Hide resolved

@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 self.poll_check(message):
return

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

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

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


class PollModal(ui.Modal):
name = ui.TextInput(label="Choice name", placeholder="Enter poll choice", max_length=50, required=True)

def __init__(self, var: discord.Interaction):
self.var = var
super().__init__(title="Poll options")
FirePlank marked this conversation as resolved.
Show resolved Hide resolved

@property
def reactions(self):
return {
0: "1️⃣",
1: "2️⃣",
2: "3️⃣",
3: "4️⃣",
4: "5️⃣",
5: "6️⃣",
6: "7️⃣",
7: "8️⃣",
8: "9️⃣",
9: "🔟",
}

async def on_submit(self, interaction: discord.Interaction) -> None:
message = await self.var.followup.fetch_message(self.var.message.id)

# Determine the emoji to use based on the number of options
num = str(message.embeds[0].description).count("\n\n")
message.embeds[0].description += f"\n\n{str(self.reactions[num])} {self.name}"

await message.edit(embed=message.embeds[0])
await interaction.response.defer()


class PollButtons(ui.View):
FirePlank marked this conversation as resolved.
Show resolved Hide resolved
def __init__(self, *, timeout=180):
super().__init__(timeout=timeout)

@property
def reactions(self):
return {
0: "1️⃣",
1: "2️⃣",
2: "3️⃣",
3: "4️⃣",
4: "5️⃣",
5: "6️⃣",
6: "7️⃣",
7: "8️⃣",
8: "9️⃣",
9: "🔟",
}
FirePlank marked this conversation as resolved.
Show resolved Hide resolved

@discord.ui.button(label="Add Choice", style=discord.ButtonStyle.gray, emoji="➕")
async def add_choice(self, interaction: discord.Interaction, _button: ui.Button):
# Count the number of options
num = str(interaction.message.embeds[0].description).count("\n\n")
# If there are more than 10 options, return
if num >= 10:
return await interaction.response.send_message(
"You can't make a poll with more than 10 choices", ephemeral=True
)

modal = PollModal(var=interaction)
await interaction.response.send_modal(modal)

@discord.ui.button(label="Remove Choice", style=discord.ButtonStyle.gray, emoji="➖")
async def remove_choice(self, interaction: discord.Interaction, _button: ui.Button):
embed = interaction.message.embeds[0]

# If there are no options, return
if str(embed.description).count("\n\n") == 0:
return await interaction.response.send_message(
"You can't remove a choice from a poll with no choices", ephemeral=True
)

# Remove the last option
embed.description = "\n\n".join(embed.description.split("\n\n")[:-1])
await interaction.response.edit_message(embed=embed)
FirePlank marked this conversation as resolved.
Show resolved Hide resolved

@discord.ui.button(label="Create Poll", style=discord.ButtonStyle.gray, emoji="📝")
async def create_poll(self, interaction: discord.Interaction, _button: ui.Button):
embed = interaction.message.embeds[0]

# If there are less than 2 options, return
if str(embed.description).count("\n\n") < 2:
return await interaction.response.send_message(
"You can't create a poll with less than 2 choices", ephemeral=True
)
FirePlank marked this conversation as resolved.
Show resolved Hide resolved

message = await interaction.channel.send(embed=embed)

# Add reactions
for i in range(0, str(embed.description).count("\n\n")):
await message.add_reaction(self.reactions[i])

# Delete the original message
await interaction.response.defer()
await interaction.delete_original_response()
2 changes: 1 addition & 1 deletion cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,10 +137,10 @@ async def main(ctx):
"bot.extensions.tags",
"bot.extensions.levelling",
"bot.extensions.persistent_roles",
"bot.extensions.polls",
"bot.cogs._help",
"bot.cogs.clashofcode",
"bot.cogs.roles",
"bot.cogs.poll",
)

intents = discord.Intents.all()
Expand Down
Loading