class AskConfirmation(discord.ui.View): def __init__(self): super().__init__(timeout=500) self.value = None # When the confirm button is pressed, set the inner value to `True` and # stop the View from listening to more input. # We also send the user an ephemeral message that we're confirming their choice. @discord.ui.button(label='Confirmer', style=discord.ButtonStyle.green, emoji=discord.PartialEmoji(name="emoji_yes", id=867082117375459340)) async def confirm(self, button: discord.ui.Button, interaction: discord.Interaction): await interaction.response.pong() self.value = True self.stop() # This one is similar to the confirmation button except sets the inner value to `False` @discord.ui.button(label='Annuler', style=discord.ButtonStyle.grey, emoji=discord.PartialEmoji(name="emoji_no", id=867082117782568980)) async def cancel(self, button: discord.ui.Button, interaction: discord.Interaction): await interaction.response.pong() self.value = False self.stop()
def __init__(self, label, value, description=None, emoji=None, default=False): if not isinstance(label, str) or description and not isinstance( description, str): raise TypeError('label and description have to be str') if emoji and not isinstance( emoji, (discord.PartialEmoji, str, discord.Emoji)): raise TypeError('emoji has to be the type of PartialEmoji') elif emoji: if isinstance(emoji, str): emoji = discord.PartialEmoji(name=emoji) elif isinstance(emoji, discord.Emoji): emoji = discord.PartialEmoji(name=emoji.name, animated=emoji.animated, id=emoji.id) if not isinstance(default, bool): raise TypeError('default has to be boolean') self.label = label self.value = str(value) self.description = description self.emoji = emoji self.default = default
def convert_emoji(s) -> discord.PartialEmoji: match = re.search(r'<?(a?):([A-Za-z0-9_]+):([0-9]{17,})>?', s) if match: return discord.PartialEmoji(animated=match[1], name=match[2], id=int(match[3])) return discord.PartialEmoji(animated=None, name=s, id=None)
async def tally(self, ctx, poll_id: commands.MessageConverter): """Get polls results""" error_message = ErrorEmbed( description=f"**{poll_id.id}** is not a poll!") if len(poll_id.embeds) <= 0: await ctx.send(embed=error_message) return embed = poll_id.embeds[0] if poll_id.author == ctx.message.author: await ctx.send(embed=error_message) return if isinstance(embed.footer.text, discord.embeds._EmptyEmbed): await ctx.send(embed=error_message) return if not embed.footer.text.startswith('Poll'): await ctx.send(embed=error_message) return if len(poll_id.reactions) < 2: await ctx.send(embed=error_message) return valid_reactions = list( filter( lambda x: x in list( map(lambda x: str(discord.PartialEmoji(name=x.emoji)), poll_id.reactions)), list( map(lambda x: str(discord.PartialEmoji(name=x.emoji)), poll_id.reactions)))) if len(list(valid_reactions)) < 2: await ctx.send(embed=error_message) return valid_reactions_list = list( map( lambda x: (x, discord.utils.find(lambda z: str(z.emoji) == str( x), poll_id.reactions).count), valid_reactions)) valid_reactions_list.sort(reverse=True) valid_reactions_list = [('Option', 'Reacted Counts') ] + valid_reactions_list embed = Embed(title='Poll Results') lengths = [[len(str(x)) for x in row] for row in valid_reactions_list] max_lengths = [ max(map(itemgetter(x), lengths)) for x in range(0, len(valid_reactions_list[0])) ] format_str = ''.join(map(lambda x: '%%-%ss | ' % x, max_lengths)) embed.description = '```markdown\n' + ( format_str % valid_reactions_list[0] ) + '\n' + '-' * (sum(max_lengths) + len(max_lengths) * 3 - 1) for x in valid_reactions_list[1:]: embed.description += f'\n{format_str % x}' embed.description += '\n```' embed.timestamp = poll_id.created_at await ctx.send(embed=embed, reference=poll_id)
async def _to_dpy_emoji(ctx, argument: str) -> discord.PartialEmoji: match = __emoji_pattern.match(argument) if match is not None: groups = match.groupdict() animated = bool(groups['animated']) emoji_id = int(groups['id']) name = groups['name'] return discord.PartialEmoji(name=name, animated=animated, id=emoji_id) return discord.PartialEmoji(name=argument, id=None, animated=False)
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.role_message_id = 0 # ID of the message that can be reacted to to add/remove a role. self.emoji_to_role = { discord.PartialEmoji(name='🔴'): 0, # ID of the role associated with unicode emoji '🔴'. discord.PartialEmoji(name='🟡'): 0, # ID of the role associated with unicode emoji '🟡'. discord.PartialEmoji(name='green', id=0): 0, # ID of the role associated with a partial emoji's ID. }
def fake_partial_emoji() -> discord.PartialEmoji: if random.choice([True, False]): fake_emoji = discord.PartialEmoji(name=fake_custom_emoji_name_str(), animated=random.choice([True, False]), id=dpyfactory.make_id) else: fake_emoji = discord.PartialEmoji(name=fake_unicode_emoji()) return fake_emoji
async def addrole(ctx, role_name, emoji): if ctx.guild != guild: return mem = ctx.author admin_role = d.utils.get(mem.roles, name=config.admin_role) if admin_role is None: return try: await ctx.message.add_reaction(emoji) except (d.errors.HTTPException, d.errors.NotFound, d.errors.InvalidArgument): await ctx.channel.send( f'"{emoji}" is not an emoji that can be added as a reaction on this server.' ) return message = await ctx.channel.fetch_message(ctx.message.id) await ctx.message.remove_reaction(emoji, guild.me) if len(message.reactions) != 1: await ctx.channel.send( 'Do not add any reactions to the command message!') return emoji = message.reactions[0].emoji if isinstance(emoji, str): emoji = d.PartialEmoji(animated=False, name=emoji) elif isinstance(emoji, d.Emoji): emoji = d.PartialEmoji(animated=emoji.animated, id=emoji.id, name=emoji.name) if emoji in react_roles: await ctx.channel.send( f'There is already a reaction role for the emoji "{emoji}"!') return roles = await guild.fetch_roles() react_role = d.utils.get(roles, name=role_name) if react_role is not None: await ctx.channel.send( f'Cannot create a role listener for an existing role!') return react_role = await guild.create_role( name=role_name, mentionable=True, reason="Add reaction role with !addrole.") react_roles[emoji] = react_role.id persist_roles() if role_message is None: await refresh(ctx) if role_message is not None: await role_message.add_reaction(emoji) await ctx.channel.send('Successfully created reaction role!') else: await ctx.channel.send( f'Create a role message in {role_channel}, and then run `!refresh`.' )
async def create_paged_message(self, channel_id: int, pages: List[discord.Embed]): self.pages = pages for index, page in enumerate(self.pages): page.set_footer(text = f"Page: {index + 1} / {len(pages)}") self.message = await self.bot.get_channel(channel_id).send(embed=self.pages[0]) await self.bot.reactionHandler.add_function(self.message, True, discord.PartialEmoji(name="◀"), self.previous_page) await self.bot.reactionHandler.add_function(self.message, False, discord.PartialEmoji(name="◀"), self.previous_page) await self.bot.reactionHandler.add_function(self.message, True, discord.PartialEmoji(name="▶"), self.next_page) await self.bot.reactionHandler.add_function(self.message, False, discord.PartialEmoji(name="▶"), self.next_page)
def __init__(self, notification_type: NotificationType, servers=None) -> None: self.servers = servers self.notification_type = notification_type self.message = None self.lock_emojis = { # Keys are the boolean int values returned by "password_protected" 1: discord.PartialEmoji(name=":lock:"), 0: discord.PartialEmoji(name=":unlock:") }
def _cast_emoji(obj, *, _custom_emoji=_custom_emoji): if isinstance(obj, discord.PartialEmoji): return obj obj = str(obj) match = _custom_emoji.match(obj) if match is not None: groups = match.groupdict() animated = bool(groups['animated']) emoji_id = int(groups['id']) name = groups['name'] return discord.PartialEmoji(name=name, animated=animated, id=emoji_id) return discord.PartialEmoji(name=obj, id=None, animated=False)
async def convert(self, ctx, argument): match = await self.find_match(ctx, argument) if match: return match try: return await commands.converter.EmojiConverter().convert( ctx, argument) except commands.BadArgument: pass try: return await commands.PartialEmojiConverter().convert( ctx, argument) except commands.BadArgument: pass lax_id_match = lax_id_regex.match(argument) if lax_id_match: return discord.PartialEmoji(name="unknown", id=int(lax_id_match.group(1)), animated=False) raise commands.BadArgument('Emoji "{}" not found'.format( await prettify(ctx, argument)))
async def wait_for_dms(self, event, check, timeout=30): try: data = ( await self.cogs["Sharding"].handler( action="wait_for_dms", args={"event": event, "check": check, "timeout": timeout}, expected_count=1, _timeout=timeout, ) )[0] except IndexError: raise asyncio.TimeoutError() if event == "message": channel_id = int(data["channel_id"]) channel = ( self.get_channel(channel_id) or self.get_user(int(data["author"]["id"])).dm_channel ) return discord.Message(state=self._connection, channel=channel, data=data) elif event == "reaction_add": emoji = discord.PartialEmoji( name=data["emoji"]["name"], id=int(id_) if (id_ := data["emoji"]["id"]) else id_, animated=data["emoji"]["animated"], ) message = discord.utils.get( self._connection._messages, id=int(data["message_id"]) ) reaction = discord.Reaction( message=message, emoji=emoji, data={"me": False} ) return reaction, await self.get_user_global(int(data["user_id"]))
async def quickpoll(self, ctx, *questions_and_choices: str): """ Makes a poll quickly. The first argument is the question and the rest are the choices. Also can't use the tally command here **Example:** `)quickpoll question option1 option2` """ if len(questions_and_choices) < 3: return await ctx.send("Need at least 1 question with 2 choices.") if len(questions_and_choices) > 21: return await ctx.send("You can only have up to 20 choices.") perms = ctx.channel.permissions_for(ctx.me) if not (perms.read_message_history or perms.add_reactions): return await ctx.send( "Need Read Message History and Add Reactions permissions.") question = questions_and_choices[0] choices = list(enumerate(questions_and_choices[1:])) try: await ctx.message.delete() except (discord.Forbidden, discord.HTTPException, discord.NotFound): pass body = "\n".join(f"{key}: {c}" for key, c in choices) poll = await ctx.send(f"{ctx.author} asks: **{question}**\n\n{body}") for emoji, _ in choices: await poll.add_reaction( discord.PartialEmoji(name=self.reactions[int(emoji)]))
async def emoji(self, ctx, emoji = None): '''Outputs the passed emoji... but bigger!''' if emoji is None: await ctx.send("Usage: `{}emoji [emoji]`".format(ctx.prefix)) return if len(emoji) < 3: # Try to get just the unicode h = "-".join([hex(ord(x)).lower()[2:] for x in emoji]) url = "https://raw.githubusercontent.com/twitter/twemoji/gh-pages/2/72x72/{}.png".format(h) f = await GetImage.download(url) if not f: await ctx.send("I couldn't get that emoji :(") else: await ctx.send(file=discord.File(f)) return emojiparts = emoji.replace("<","").replace(">","").split(":") if emoji else [] if not len(emojiparts) == 3: await ctx.send("Usage: `{}emoji [emoji]`".format(ctx.prefix)) return emoji_obj = discord.PartialEmoji(animated=len(emojiparts[0]) > 0, name=emojiparts[1], id=emojiparts[2]) if not emoji_obj.url: await ctx.send("Could not find a url for that emoji :(") return f = await GetImage.download(emoji_obj.url) if not f: await ctx.send("I couldn't get that emoji :(") return await ctx.send(file=discord.File(f))
async def poll_debug(self, ctx: MyContext, poll: PollManager): """Create a dummy reaction on a running poll""" user_id = random.choice([ member.id for member in poll.message.guild.members if not member.bot ]) if user_id in poll.votes: event = 'REACTION REMOVE' emoji = poll.emojis[poll.votes[user_id]] else: event = 'REACTION ADD' emoji = random.choice(poll.emojis) payload = discord.RawReactionActionEvent( { 'guild_id': poll.message.guild.id, 'channel_id': poll.channel_id, 'message_id': poll.message_id, 'user_id': user_id }, discord.PartialEmoji(name=emoji), event ) self.bot.dispatch('raw_' + event.lower().replace(' ', '_'), payload) await ctx.reply(f'Dispatched a {event} event')
async def addemoji( self, ctx: vbu.Context, emoji: typing.Optional[typing.Union[discord.PartialEmoji, int, ImageUrl]] = None, name: str = None, animated: bool = False, ): """ Copies an emoji and uploads it to your server. """ # Default to the first attachment in the message's URL if `emoji` (the image url) is None if emoji is None: if ctx.message.attachments: emoji = ctx.message.attachments[0].url await ImageUrl().convert(ctx, emoji ) # Make sure the url is an image else: raise vbu.errors.MissingRequiredArgumentString("emoji") # See if we gave an emoji ID if isinstance(emoji, int): if name is None: raise vbu.errors.MissingRequiredArgumentString("name") emoji = discord.PartialEmoji(name=name, animated=animated, id=emoji) # See if we gave an image URL or an emoji if isinstance(emoji, discord.PartialEmoji): url = str(emoji.url) name = name or emoji.name else: url = emoji # Grab image data async with self.bot.session.get(url) as r: data = await r.read() # If the size is too big for Discord if len(data) > 256_000: original_image = Image.open(io.BytesIO(data)) new_size = self.calculate_new_size(original_image) resized_image = original_image.resize(new_size) # .tobytes() new_image_file_handle = io.BytesIO() resized_image.save(new_image_file_handle, format="png") new_image_file_handle.seek(0) data = new_image_file_handle.read() # Upload that to Discord try: e = await ctx.guild.create_custom_emoji(name=name, image=data) except discord.HTTPException as e: return await ctx.send(f"I couldn't create that emoji - {e}") except discord.InvalidArgument: return await ctx.send( "Unsupported image type - make sure you're providing the correct argument for the image's animation state." ) await ctx.send(f"Emoji added - {e!s}")
def __init__(self, style, label=None, emoji=None, url=None, disabled=False, custom_id=None, **_): if not isinstance(style, ButtonStyle): raise TypeError('style has to be one of ButtonStyle') if label and len(label) > 80: raise discord.InvalidArgument( 'label cannot be longer than 80 characters') if emoji and not isinstance( emoji, (discord.PartialEmoji, str, discord.Emoji)): raise TypeError('emoji has to be the type of PartialEmoji') elif emoji: if isinstance(emoji, str): emoji = discord.PartialEmoji(name=emoji) elif isinstance(emoji, discord.Emoji): emoji = discord.PartialEmoji(name=emoji.name, animated=emoji.animated, id=emoji.id) if not isinstance(disabled, bool): raise TypeError('disabled must be boolean') if url and style is not ButtonStyle.Link: raise discord.InvalidArgument( 'url cannot be passed when not using Link style') elif not url and style is ButtonStyle.Link: raise discord.InvalidArgument( 'url nas to be passed when using Link style') if not custom_id and style is not ButtonStyle.Link: raise discord.InvalidArgument( 'custom_id has to be passed when not using Link style') if url and custom_id: raise discord.InvalidArgument( 'cannot provide both custom_id and url') self.custom_id = str(custom_id) self.disabled = disabled self.url = url self.style = style self.label = label self.emoji = emoji
async def fetch(self) -> discord.PartialEmoji: if self.is_custom: if not self.guild.is_fetched: await self.guild.fetch() self.guild: discord.Guild emoji = await self.guild.fetch_emoji(self.id) discord_emoji = discord.PartialEmoji(name=emoji.name, animated=emoji.animated, id=emoji.id) if self.name != emoji.name: self.name = emoji.name await self.async_save() else: discord_emoji = discord.PartialEmoji(name=self.name) self._discord_obj = discord_emoji return discord_emoji
def _partial_emoji_converter(argument: str) -> discord.PartialEmoji: if len(argument) < 5: # Sometimes unicode emojis are actually more than 1 symbol return discord.PartialEmoji(name=argument) match = re.match(r"<(a?):([a-zA-Z0-9\_]+):([0-9]+)>$", argument) if match is not None: emoji_animated = bool(match.group(1)) emoji_name = match.group(2) emoji_id = int(match.group(3)) return discord.PartialEmoji(name=emoji_name, animated=emoji_animated, id=emoji_id) raise discord.InvalidArgument( f"Failed to convert {argument} to PartialEmoji")
async def test(self, ctx, num: int): if num == 1: s = ":x:" elif num == 2: s = ":white_check_mark:" else: s = "\U0000274C" e = discord.PartialEmoji(name=s) await ctx.send(e)
async def convert(self, ctx: commands.Context, arg: str): emojis = emoji.unicode_codes.EMOJI_UNICODE["en"].values() try: return await commands.PartialEmojiConverter().convert(ctx, arg) except commands.PartialEmojiConversionFailure: pass if arg.rstrip("\N{variation selector-16}") in emojis or arg in emojis: return discord.PartialEmoji(name=arg) else: raise commands.BadArgument(f"{arg} is not an emoji")
async def removerole(ctx, emoji): if ctx.guild != guild: return mem = ctx.author admin_role = d.utils.get(mem.roles, name=config.admin_role) if admin_role is None: return try: await ctx.message.add_reaction(emoji) except (d.errors.HTTPException, d.errors.NotFound, d.errors.InvalidArgument): await ctx.channel.send( f'"{emoji}" is not an emoji that can be added as a reaction on this server.' ) return message = await ctx.channel.fetch_message(ctx.message.id) await ctx.message.remove_reaction(emoji, guild.me) if len(message.reactions) != 1: await ctx.channel.send( 'Do not add any reactions to the command message!') return emoji = message.reactions[0].emoji if isinstance(emoji, str): emoji = d.PartialEmoji(name=emoji) elif isinstance(emoji, d.Emoji): emoji = d.PartialEmoji(animated=emoji.animated, id=emoji.id, name=emoji.name) if emoji not in react_roles: await ctx.channel.send( 'There is no reaction role listener for the emoji "{emoji}"') return roles = await guild.fetch_roles() react_role = d.utils.get(roles, id=react_roles[emoji]) await role_message.clear_reaction(emoji) await react_role.delete() del react_roles[emoji] persist_roles() await ctx.channel.send('Successfuly removed reaction role!')
def return_emoji( url: str, category: str, ctx: commands.Context ) -> Union[discord.Emoji, discord.PartialEmoji]: STRIPPED_STRING_LIST: list = url.lstrip( LinksAndVars.character_data.value.rstrip('img_data.json') + 'photo_data/').split('/') STRIPPED_STRING_LIST.append(category) for i in STRIPPED_STRING_LIST: if i.lower() in ShinobiMatch.name_exclusion.value: return ctx.get_config_emoji_by_name_or_id(i) return discord.PartialEmoji(name='\U0001f5e1')
async def convert(self, ctx, argument): match = re.match(r'<(a?):([a-zA-Z0-9\_]+):([0-9]+)>$', argument) if match: emoji_animated = bool(match.group(1)) emoji_name = match.group(2) emoji_id = int(match.group(3)) return discord.PartialEmoji(animated=emoji_animated, name=emoji_name, id=emoji_id) raise BadArgument('Couldn\'t convert "{}" to PartialEmoji.'.format(argument))
async def on_raw_reaction_add(payload): # Participant role. if payload.emoji != discord.PartialEmoji(name="🖐️"): return if payload.channel_id == 736238486696493237: challenge_winner = discord.utils.get(payload.member.guild.roles, name="Challenge Winner") if challenge_winner in payload.member.roles: return participant = discord.utils.get(payload.member.guild.roles, name="Participant") await payload.member.add_roles(participant)
def emoji_value(self) -> Optional[Union[discord.PartialEmoji, str]]: """ Return the value that must be given to discord to represent an emoji. """ if self.is_custom: if not self.cached: return None p = discord.PartialEmoji(name=self.custom_name(), id=self.emoji) return p else: return self.emoji
def __init__(self, bot, settings): self.bot = bot self.rsvps = {} # Register out callbacks with the reactionTracker self.tracker = self.bot.get_cog('reactTracker') self.tracker.registerCallbacks( type(self).__name__, self.msgGenerator, self.parseMsg) # Create sign-up emoji from settings # If we have a user setting for it, use it. Otherwise we use a ":raisedhands:" emoji as a default if 'rsvpEmoji' in settings: self.rsvpEmoji = discord.PartialEmoji( animated=False, name=settings['rsvpEmoji']['name'], id=settings['rsvpEmoji']['id']) else: self.rsvpEmoji = discord.PartialEmoji(animated=False, name='\U0001F64C')
async def callback(self, interaction: discord.Interaction): if self.view is None: raise AssertionError data = await self.view.database.get(interaction.message.id) if data is None: return unique = bool(data.get("limit_to_one")) if unique: roles_id_list = [ data.get("reactions")[i] for i in data.get("reactions") ] if list(map(lambda i: i.id, interaction.user.roles)) in roles_id_list: await interaction.response.send_message( "You cannot have more than 1 role from this message", ephemeral=True) return for i in data.get("reactions"): if str(self.emoji) == str(discord.PartialEmoji(name=i)): role_id = data.get("reactions")[i] role_model = discord.utils.get(interaction.guild.roles, id=role_id) if role_model in interaction.user.roles: try: await interaction.user.remove_roles( role_model, reason="Reaction Roles", atomic=True) await interaction.response.send_message( f"Removed {role_model.mention} role", ephemeral=True) return except discord.Forbidden: await interaction.response.send_message( "I don't have the `Manage Roles` permissions", ephemeral=True, ) except discord.HTTPException: await interaction.response.send_message( "Removing roles failed", ephemeral=True) try: await interaction.user.add_roles(role_model, reason="Reaction Roles", atomic=True) await interaction.response.send_message( f"Added {role_model.mention} role", ephemeral=True) except discord.Forbidden: await interaction.response.send_message( "I don't have the `Manage Roles` permissions", ephemeral=True) except discord.HTTPException: await interaction.response.send_message( "Adding roles failed", ephemeral=True)
async def on_ready(self): print(discord.__version__) print('Logged on as', self.user) varStatus = "Text Status" varEmoji = "🐻" #varActivity = discord.Activity(type=discord.ActivityType.custom, name=varEmoji+" "+varStatus, state=varEmoji+" "+varStatus) varActivity = discord.CustomActivity( name=varStatus, state=varStatus, emoji=discord.PartialEmoji(name=varEmoji)) await client.change_presence(status=discord.Status.online, activity=varActivity)