Skip to content

Commit

Permalink
Merge pull request #27 from matthewflegg/dev
Browse files Browse the repository at this point in the history
Fixed reaction role errors and ~poll issues
  • Loading branch information
v0idzdev authored Mar 30, 2022
2 parents f2873a8 + d2d5681 commit e7c6d72
Show file tree
Hide file tree
Showing 7 changed files with 83 additions and 39 deletions.
10 changes: 7 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -164,15 +164,19 @@ Deletes all reaction role messages for a particular role.<br>
Randomly chooses an option from a list. Use quote marks "" around the options if they are longer than one word.

⚠️ The slash command version does not support choices with multiple words.
⚠️ `/choose` does not currently support choices with multiple words.

> **~meme** or **/meme**
Sends a random meme from Reddit.

> **~poll `yes/no question`** or **/poll `yes/no question`**
> **~poll `yes/no question` | ~poll `question` `option a`, `option b`, `option c`** or **/poll `yes/no question`**
Creates a poll that users can react with yes or no to.
Creates a poll that users can react with yes or no to.<br>

📢 Put quote marks "" around **all** of the arguments if using the prefix command version.<br>

⚠️ `/poll` does not yet support multiple options.

> **~twitch `streamer name`** or **/twitch `streamer name`**
Expand Down
49 changes: 40 additions & 9 deletions cogs/misc/misc_cog.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@
import datetime
import random
import humanize

import discord

from typing import Optional
from discord.ext import commands
from utils.models import TwitchBroadcast

Expand Down Expand Up @@ -128,33 +129,63 @@ async def meme(self, ctx: commands.Context):
await ctx.reply(embed=meme)

@commands.command()
async def poll(self, ctx: commands.Context, *poll: str):
async def poll(self, ctx: commands.Context, poll: str, *options: str):
"""
🎲 Creates a simple yes or no poll.
❓ This command is also available as a slash command.
You can create a simple yes or no poll by simply using `~poll`. You can,
however, add up to six options after the question.
Usage:
```
~poll <question>
~poll <question> [...options]
```
Or:
```
/poll
/poll <question>
```
"""
if not poll:
return await ctx.send(f':x: {ctx.author.mention}: You need to specify a question.')

embed = discord.Embed(
title=f"Poll by **{ctx.author.name}**:",
description=" ".join(poll)
title=f"📢 Poll by **{ctx.author.name}**:",
description=f"```❓ {poll}```\n"
)

message = await ctx.send(embed=embed)
# If the user doesn't specify any options, just make a yes/no poll.
if not options:
embed.set_footer(text='Vote ✔️ Yes or ❌ No.')
message = await ctx.send(embed=embed)

await message.add_reaction("✔️")
return await message.add_reaction("❌")

await message.add_reaction("✔️")
await message.add_reaction("❌")
if len(options) < 2:
return await ctx.reply(f"❌ You need to add more than one option.")

if len(options) > 6:
return await ctx.reply(f"❌ You can't add more than 6 options.")

key = {
"A": "🔴",
"B": "🟠",
"C": "🟡",
"D": "🟢",
"E": "🔵",
"F": "🟣"
}

# Add fields
for (letter, emoji), option in zip(key.items(), options):
embed.add_field(name=f'{emoji} Option {letter}:', value=option, inline=False)

# Send message and add reactions
message = await ctx.send(embed=embed)
for (letter, emoji), option in zip(key.items(), options):
await message.add_reaction(emoji)


async def setup(client: commands.Bot):
Expand Down
45 changes: 24 additions & 21 deletions cogs/role/role_cog.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,14 @@ async def reactrole(
Usage:
```
~reactrole | ~rrr <@role>
~reactrole | ~crr <emoji> <@role> <message>
```
"""
embed = discord.Embed(description=message)
msg = await ctx.channel.send(embed=embed)

await msg.add_reaction(emoji)
data = self.client.cache.reactionrole
data = self.client.cache.reactionroles

react_role = { # Create a dictionary to store in the JSON file
"guild_id": ctx.guild.id,
Expand All @@ -53,22 +53,23 @@ async def reactrole(
async def removereactrole(self, ctx: commands.Context, role: discord.Role):
"""
🏷️ Removes a reaction role message.
Usage:
```
~removereactrole | ~rrr <@role>
```
"""

data = self.client.cache.reactionrole
data = self.client.cache.reactionroles
instances = [item for item in data if item["role_id"] == role.id]
if len(instances) == 0:
raise commands.RoleNotFound(role.__str__())
for instance in instances:
msg = ctx.channel.get_partial_message(instance["msg_id"])
await msg.delete()
data.remove(instance)
self.update_json(FILEPATH, data)
embed = discord.Embed(title=f"🔧 Removed the '{role.name}' reaction role.")
self.client.update_json(FILEPATH, data)
embed = discord.Embed(title="👍🏻 Done.", description=f"🔧 Removed '{role.name}'.")
await ctx.send(embed=embed)

@reactrole.error
Expand All @@ -86,36 +87,37 @@ async def reactrole_error(self, ctx: commands.Context, error):
message += "Sorry, that emoji was not found. Please try again."
case commands.UserInputError:
message += (
"Invalid input, please try again.\n"
+ f"Use **{ctx.prefix}reactrole `emoji` `@role` `message`**."
"Invalid input, please try again. "
+ "Use `~help crr` for more information."
)
case commands.MissingRequiredArgument:
message += (
"Please enter all the required arguments.\n"
+ f"Use **{ctx.prefix}reactrole `emoji` `@role` `message`**."
"Please enter all the required arguments. "
+ "Use `~help crr` for more information."
)
case discord.HTTPException: # An invalid emoji raises a HTTP exception
if (
"Unknown Emoji" in error.__str__()
): # Prevents this handler from catching unrelated errors
await ctx.channel.purge(limit=1)
message += "Sorry, that emoji is invalid. Please use a valid emoji."
message += "Sorry, that emoji is invalid."
case discord.Forbidden:
message += (
"BB.Bot is forbidden from assigning/removing this role.\n"
+ f"Try moving this role above the reaction role."
"BB.Bot is forbidden from assigning/removing this role. "
+ "Try moving this role above the reaction role."
)
case _:
print(error.args, error.__traceback__)
message += (
"An unknown error occurred while creating your reaction role.\n"
+ f"Please try again later."
"An unknown error occurred while creating your reaction role. "
+ "Please try again later."
)
await ctx.send(message)

@removereactrole.error
async def removeractrole_error(self, ctx: commands.Context, error):
"""
Error handler for the removeractrole command.
Error handler for the removereactrole command.
"""
error = getattr(error, "original", error)
message = f":x: {ctx.author.mention}: "
Expand All @@ -130,20 +132,21 @@ async def removeractrole_error(self, ctx: commands.Context, error):

case commands.UserInputError:
message += (
"Invalid input, please try again.\n"
+ f"Use **{ctx.prefix}reactrole `emoji` `@role` `message`**."
"Invalid input, please try again. "
+ "Use `~help crr` for more information."
)

case commands.MissingRequiredArgument:
message += (
"Please enter all the required arguments.\n"
+ f"Use **{ctx.prefix}removereactrole `@role`**."
"Please enter all the required arguments. "
+ "Use `~help crr` for more information."
)

case _:
print(error.args, error.__traceback__)
message += (
"An unknown error occurred while creating your reaction role.\n"
+ f"Please try again later."
"An unknown error occurred while creating your reaction role. "
+ "Please try again later."
)

await ctx.send(message)
Expand Down
11 changes: 7 additions & 4 deletions handlers/event_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,16 +97,19 @@ async def on_reaction_add(self, reaction: discord.Reaction, user: discord.User):
"""
Prevents users from voting more than once on a poll.
"""
user = reaction.message.author
cached = discord.utils.get(self.client.cached_messages, id=reaction.message.id) # why
cached = discord.utils.get(self.client.cached_messages, id=reaction.message.id)

if user.id == self.client.user.id:
return

for react in cached.reactions:
users = await react.users().flatten()
users = [user async for user in react.users()]

if any({user not in users, user.bot, str(react) == str(reaction.emoji)}):
if any({
user not in users,
user.bot,
str(react) == str(reaction.emoji)
}):
continue

await cached.remove_reaction(react.emoji, user)
Expand Down
4 changes: 2 additions & 2 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def get_prefix(bot: commands.Bot, message: discord.Message):
"""
Returns the client's command prefix.
"""
return '~' if bot.user.name == 'BB.Bot' else '?' # Set the prefix to '?' if the bot is the development version
return '?' if bot.user.name == 'BB.Bot | Dev' else '~' # Set the prefix to '?' if the bot is the development version


class BeepBoop(commands.Bot):
Expand Down Expand Up @@ -146,7 +146,7 @@ async def load_handlers(self):
# @client.tree.command(description="People really like this command!")
# async def nice(interaction: discord.Interaction):
# await interaction.response.send_message("Haha, cool indeed!")

i =9
async def main():
"""
Main entry point of the application.
Expand Down
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,4 @@ yarl==1.7.2
youtube-dl==2021.12.17
pillow==9.0.1
humanize
jishaku @ git+https://github.com/Gorialis/jishaku
2 changes: 2 additions & 0 deletions utils/buttons.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ async def no(self, interaction: discord.Interaction, _: discord.Button):
await interaction.response.send_message('👍🏻 Aborting command!')
await self.disable_all_buttons(interaction)


class BlacklistClearButton(discord.ui.View):
def __init__(self, ctx: commands.Context, *, data: dict, timeout: Optional[float] = 180):
super().__init__(timeout=timeout)
Expand Down Expand Up @@ -140,6 +141,7 @@ async def on_submit(self, interaction: discord.Interaction) -> None:
await interaction.message.edit(view=self.view)
return await super().on_submit(interaction=interaction)


class BlacklistDropdown(discord.ui.Select):
def __init__(self, ctx: commands.Context):
self.ctx = ctx
Expand Down

0 comments on commit e7c6d72

Please sign in to comment.