async def poll(self, ctx: Context, duration: str, emoji1: Union[Emoji, str], emoji2: Union[Emoji, str], *, question: str): """Posts a poll""" # Validate emojis async def ensure_emoji(*args): for emo in args: if not isinstance(emo, Emoji) and not emo in emoji.UNICODE_EMOJI: await ctx.send( embed=Embed(description=f"{emo} is not a valid emoji.", color=Color.orange())) return False return True if not await ensure_emoji(emoji1, emoji2): return # Parse and validate duration duration_delta = self.parse_duration(duration) if duration_delta is None: await ctx.send(embed=Embed(description='Invalid duration!', color=Color.orange())) return await ctx.message.delete() finish_time = datetime.utcnow() + duration_delta embed = Embed(title="New Poll", description=question + "\n\n" + f"Time left: {duration_delta}", color=Color.orange()).set_footer( text=f"React with a {emoji1} or {emoji2}") message = await ctx.send(embed=embed) await message.add_reaction(emoji1) await message.add_reaction(emoji2) poll_id = await self.bot.db.insert_poll(ctx.channel.id, message.id, round(finish_time.timestamp()), question, str(emoji1), str(emoji2)) future = self.finish_poll({ 'id': poll_id, 'channel_id': ctx.channel.id, 'message_id': message.id, 'question': question, 'emoji1': emoji1, 'emoji2': emoji2 }) await self._schedule_or_call(future, finish_time)
async def tplan(self, ctx): if self.tournament.status != Status.Pending: raise commands.BadArgument( f"The tournament cannot be scheduled at the moment.") req = ['name', 'host', 'time'] missing = [] for attr in req: if getattr(self.tournament, attr) is None: missing.append("`" + attr + "`") if missing: items = " and ".join(item for item in missing) raise commands.BadArgument( f"You have not specified a {items} for the tournament.") embed = Embed(title=self.tournament.name, color=Color.orange()) embed.set_author(name="Tournament Scheduled") for attr in self.attr: val = getattr(self.tournament, attr) if attr == 'time': val = val.strftime("%A %d %b at %I:%M%p *GMT*") if attr == 'host': val = val.mention if attr not in ['name', 'roles'] and val is not None: embed.add_field(name=attr.title(), value=val) embed.set_footer( text= f"This tournament will take place in {TimeUntil(self.tournament.time)}!" ) await ctx.message.add_reaction(Emote.check) await self.channels.t_planned.send( f"New tournament scheduled! {self.roles.schedule.mention}", embed=embed) # Add stuff and Log Log("Tournament Planned", description= f"{ctx.author.mention} scheduled **{self.tournament.name}**.", color=Color.orange(), fields=[{ "name": "Host", "value": self.tournament.host }, { "name": "Time", "value": self.tournament.time }]) self.tournament.status = Status.Scheduled self.tournament.save() await ctx.send("Tournament ID: " + str(self.tournament.id)) if self.tournament not in self.queue: self.queue.append(self.tournament) self.tournament = Tournament()
async def ddg(ctx, *args): if args: url = "http://duckduckgo.com/?q=" + "+".join(args) await client.say( embed=Embed(description="**[DuckDuckGo Search](%s)**" % url, color=Color.orange())) await client.delete_message(ctx.message)
def random(): # type: () -> Color chilipepper = Color(0x9B1B30) tan = Color(0xBEAA3E) icedcoffee = Color(0xB18F6A) return choice([ Color.teal(), Color.dark_teal(), Color.green(), Color.dark_green(), Color.blue(), Color.dark_blue(), Color.purple(), Color.dark_purple(), Color.magenta(), Color.dark_magenta(), Color.gold(), Color.dark_gold(), Color.orange(), Color.dark_orange(), Color.red(), Color.dark_red(), Color.lighter_grey(), Color.darker_grey(), Color.blurple(), tan, icedcoffee, chilipepper, ])
def _get_basic_embed(self, show_influences): # Set up the embed player_embed = Embed( color = Color.orange(), timestamp = datetime.utcnow(), ) # Keep track of all the player's influences influences = [] for i in range(len(self._influences)): influence = self._influences[i] if influence is not None: if influence.alive: # influence card is alive if show_influences: influences.append(f"{influence.type.capitalize()}") else: influences.append("[HIDDEN]") else: # influence card is dead (revealed) influences.append(f"~~{influence.type.capitalize()}~~") i += 1 indices = [str(i + 1) for i in range(len(self._influences))] player_embed.add_field(name="тнР", value="\n".join(indices)) player_embed.add_field(name="Influences", value="\n".join(influences)) player_embed.add_field(name="Coins ЁЯкЩ", value=self._coins) player_embed.set_thumbnail(url=self._user.avatar_url) player_embed.set_footer(text="Requested at") return player_embed
def random(): c = [ Color.teal(), Color.dark_teal(), Color.green(), Color.dark_green(), Color.blue(), Color.dark_blue(), Color.purple(), Color.dark_purple(), Color.magenta(), Color.dark_magenta(), Color.gold(), Color.dark_gold(), Color.orange(), Color.dark_orange(), Color.red(), Color.dark_red(), Color.lighter_grey(), Color.darker_grey(), Color.blurple(), tan, icedcoffee, chilipepper ] return c[randint(0, len(c) - 1)]
class UpdatedMessageEmbed(EventEmbed): color = Color.orange() event = "has updated a message" def __init__(self, original_message: Message, updated_message: Message, original_message_has_content=True): super().__init__(original_message.author, self.event, self.color) self.original_message = original_message self.updated_message = updated_message self.original_message_has_content = original_message_has_content def build_embed(self, *args, **kwargs): super().build_embed(*args, **kwargs) self.embed.add_field(name="Channel:", value=self.original_message.channel.name) if self.original_message_has_content: original_content = self.original_message.clean_content else: original_content = "<Original message had no content!>" self.embed.add_field(name="Initial message:", value=escape_markdown(original_content), inline=False) self.embed.add_field(name="Updated message:", value=escape_markdown( self.updated_message.clean_content), inline=False)
async def log_message(self, msg): # pass only if in direct messages if msg.guild: return if msg.author.id in self.blocked_list["ids"]: return # log own messages as an embed in the proper channel if msg.author == self.bot.user: embed = Embed( title= f"Direct Message → {msg.channel.recipient} ({msg.channel.recipient.id})", description=msg.content, color=Color.orange()) return await self.bot.config.channels.log.send(embed=embed) # log message only if is not bot user elif msg.author.bot: return else: embed = Embed( title=f"Direct Message — {msg.author} ({msg.author.id})", description=msg.content, color=Color.dark_blue()) if msg.attachments: embed.set_image(url=msg.attachments[0].url) if len(msg.attachments) > 1: embed.set_footer( text= f"{len(msg.attachments) - 1} attachment(s) not shown") else: embed.set_footer(text="1 attachment") await self.bot.config.channels.log.send(embed=embed) # also save for later if self.latest_task: self.latest_task.cancel() self.latest_task = self.bot.loop.create_task( self.latest_message(msg))
async def unregister(self, ctx): if not len( list( self.bot.userCollection.find( {'discordID': str(ctx.author.id)}))): await ctx.send(embed=Embed(title='가입이 안되있습니다', color=Color.red())) return msg = await ctx.send(embed=Embed( title='정말 탈퇴하시겠습니까?', description= '정말 가입을 하실거면 `네넹` 이라고 보내주세요(30초 동안 `네넹`을 안보내시면 자동으로 취소됩니다)', color=Color.orange())) try: await self.bot.wait_for('message', check=(lambda m: (m.content == '네넹') and (m.channel == ctx.channel) and (m.author == ctx.author)), timeout=30) except TimeoutError: await msg.edit(embed=Embed(title='탈퇴를 취소했습니다', color=Color.green()) ) return self.bot.userCollection.remove({'discordID': str(ctx.author.id)}) await msg.edit(embed=Embed(title='탈퇴를 했습니다', color=Color.green()))
async def register(self, ctx): if len( list( self.bot.userCollection.find( {'discordID': str(ctx.author.id)}))): await ctx.send(embed=Embed(title='이미 가입되셨습니다', color=Color.red())) return msg = await ctx.send(embed=Embed( title='정말 가입하시겠습니까?', description= 'DB에는 사용자의 정보중 `ID`만 저장합니다\n정말 가입을 하실거면 `네넹` 이라고 보내주세요(30초 동안 `네넹`을 안보내시면 자동으로 취소됩니다)', color=Color.orange())) try: await self.bot.wait_for('message', check=(lambda m: (m.content == '네넹') and (m.channel == ctx.channel) and (m.author == ctx.author)), timeout=30) except TimeoutError: await msg.edit(embed=Embed(title='가입을 취소했습니다', color=Color.green()) ) return self.bot.userCollection.insert({ 'discordID': str(ctx.author.id), 'point': 0, 'permissions': [], 'following': [] }) await msg.edit(embed=Embed(title='가입을 했습니다', color=Color.green()))
async def embd(ctx, *args): colors = { "red": Color.red(), "green": Color.green(), "gold": Color.gold(), "orange": Color.orange(), "blue": Color.blue(), "purple": Color.purple(), "teal": Color.teal(), "magenta": Color.magenta(), "grey": Color.lighter_grey() } if args: argstr = " ".join(args) if "-c " in argstr: text = argstr.split("-c ")[0] color_str = argstr.split("-c ")[1] color = colors[ color_str] if color_str in colors else Color.default() else: text = argstr color = Color.default() await client.say(embed=Embed(color=color, description=text)) await client.delete_message(ctx.message)
def pending_players_embed(self): ''' Gets the embed representing which players have pending actions, and for what reason ''' pending_embed = Embed( title="Pending Actions", description="Awaiting actions from the following players:", color=Color.orange(), ) if self.action is None: # Waiting for player to make their Action player = self.get_turn() pending_embed.add_field(name="Waiting for Action ...", value=player.get_mention(), inline=False) elif self.response is None and self.action.done_to is not None: # Waiting for affected player to respond pending_embed.add_field(name="Waiting for Response ...", value=self.action.done_to.get_mention(), inline=False) for player in self.get_pending_players(): pending_embed.add_field(name="Player", value=player.get_mention()) pending_embed.add_field(name="Must Kill", value=player.must_kill) pending_embed.add_field(name="Must Swap Cards", value=player.must_swap) return pending_embed
async def poll(ctx, col, arg2): try: if col == "red": embedcolor = Color.red() if col == "orange": embedcolor = Color.orange() if col == "yellow": embedcolor = Color.yellow() if col == "green": embedcolor = Color.green() if col == "blue": embedcolor = Color.blue() if col == "purple": embedcolor = Color.purple() if col == "black": embedcolor = Color.black() if col == "none": embedcolor = Color.default() embed=discord.Embed(title="POLL:", description=arg2, color=embedcolor) embed.set_footer(text="Vote by reacting") embedmsg = await ctx.send(embed=embed) await ctx.message.delete() await embedmsg.add_reaction("👍") await embedmsg.add_reaction("👎") print(Fore.GREEN+f'[>] Poll "{arg2}" sent!') except: print(Fore.RED+"[>] Poll failed") print(Fore.RESET)
def random(): # type: () -> Color tan = Color(0xBEAA3E) return choice([ Color.teal(), Color.dark_teal(), Color.green(), Color.dark_green(), Color.blue(), Color.dark_blue(), Color.purple(), Color.dark_purple(), Color.magenta(), Color.dark_magenta(), Color.gold(), Color.dark_gold(), Color.orange(), Color.dark_orange(), Color.red(), Color.dark_red(), Color.lighter_grey(), Color.darker_grey(), Color.blurple(), tan, ])
def __init__(self, client): self.client = client self.client_color = Color.red() self.color_dict = { 1: [Color.teal(), 'teal'], 2: [Color.dark_teal(), 'dark_teal'], 3: [Color.green(), 'green'], 4: [Color.dark_green(), 'dark_green'], 5: [Color.blue(), 'blue'], 6: [Color.dark_blue(), 'dark_blue'], 7: [Color.purple(), 'purple'], 8: [Color.dark_purple(), 'dark_purple'], 9: [Color.magenta(), 'magenta'], 10: [Color.dark_magenta(), 'dark_magenta'], 11: [Color.gold(), 'gold'], 12: [Color.dark_gold(), 'dark_gold'], 13: [Color.orange(), 'orange'], 14: [Color.dark_orange(), 'dark_orange'], 15: [Color.red(), 'red'], 16: [Color.dark_red(), 'dark_red'], 17: [Color.lighter_grey(), 'lighter_grey'], 18: [Color.dark_grey(), 'grey'], 19: [Color.light_grey(), 'light_grey'], 20: [Color.darker_grey(), 'darker_grey'] }
async def finish_poll(self, poll_row): """Called when the poll finishes- i.e. when the poll time is up""" try: channel = await self.bot.fetch_channel(poll_row['channel_id']) message = await channel.fetch_message(poll_row['message_id']) reaction1, reaction2, *_ = filter( lambda r: str(r.emoji) in (str(poll_row['emoji1']), str(poll_row['emoji2'])), message.reactions) try: await message.delete() except NotFound: pass # Ignored await channel.send(embed=Embed( title="Poll results", description=f"**Question:** {poll_row['question']}\n\n" + f"{reaction1.count - 1} people reacted {reaction1.emoji}\n" + f"{reaction2.count - 1} people reacted {reaction2.emoji}", color=Color.orange())) finally: await self.bot.db.delete_poll(poll_row['id'])
async def ban(self, ctx: Context, member: Member, *, reason: ActionReason = "No specific reason.") -> None: """Ban a user.""" server_embed = Embed( title="User Banned", description=textwrap.dedent( f""" **Reason**: {reason} **User**: {member.mention} (`{member.id}`) **Moderator**: {ctx.author.mention} (`{ctx.author.id}`) """ ), color=Color.orange(), timestamp=datetime.utcnow(), ) server_embed.set_thumbnail(url=member.avatar_url_as(format="png", size=256)) dm_embed = Embed( title="You were Banned", description=textwrap.dedent( f""" {reason} *Server: {ctx.guild.name}* """ ), color=Color.red(), timestamp=datetime.utcnow(), ) dm_embed.set_thumbnail(url=ctx.guild.icon_url) await ctx.send(embed=server_embed) await member.send(embed=dm_embed) await member.ban(reason=reason) logger.debug(f"User <@{ctx.author.id}> has banned <@{member.id}> from {ctx.guild.id}")
async def get(self, ctx: Context, *, mention: Member = None) -> None: """Get a user's friend code. If a mention is omitted, then it gets the users' own friend code.""" member = ctx.message.author if mention is None else mention systems = self.config.scan_iter( match="user:{}:fc:*:code".format(member.id)) if systems is None: await ctx.send("No game info registered for {}.".format( member.display_name)) return else: embed = Embed(title="Game info for {}:".format( member.display_name), color=Color.orange()) embed.set_author(name=member.name, icon_url=member.avatar_url) # First, want to add 3DS friend code, then follow it with in game igns for system in systems: sys_name = system.split(":")[-2] embed.add_field(name=sys_name, value=self.config.get( "user:{}:fc:{}:code".format( member.id, sys_name))) igns = "" for game, name in self.config.hgetall( "user:{}:fc:{}:ign".format(member.id, sys_name)).items(): igns += "{}: {}\n".format(game.title(), name) if igns: embed.add_field(name="IGNs", value=igns) await ctx.send(embed=embed)
async def embed(ctx, col, arg1, arg2, arg3): try: if col == "red": embedcolor = Color.red() if col == "orange": embedcolor = Color.orange() if col == "yellow": embedcolor = Color.yellow() if col == "green": embedcolor = Color.green() if col == "blue": embedcolor = Color.blue() if col == "purple": embedcolor = Color.purple() if col == "black": embedcolor = Color.black() if col == "none": embedcolor = "none" if embedcolor == "none": embed=discord.Embed(title=arg1, description=arg2) embed.set_footer(text=arg3) await ctx.send(embed=embed) await ctx.message.delete() if embedcolor != "none": embed=discord.Embed(title=arg1, description=arg2, color=embedcolor) embed.set_footer(text=arg3) await ctx.send(embed=embed) await ctx.message.delete() except: print(Fore.RED+"[>] Failed to send embed")
async def thanks(self, ctx: Context, member: Member, *, reason: str = None) -> None: """Thank a Member.""" if ctx.author == member: embed = Embed( title="WARNING", description= f"{ctx.author.mention} **You Cannot Thank Yourself!**", color=Color.orange(), ) await ctx.send(embed=embed) else: embed = Embed( title="THANKS", description=textwrap.dedent(f""" {member.mention} was thanked by {ctx.author.mention}! {'**MESSAGE**:' + reason if reason else ''} """), color=Color.blurple(), ) embed.set_image( url="https://media.giphy.com/media/6tHy8UAbv3zgs/giphy.gif") await ctx.send(embed=embed)
async def giveaway_countdown_updater(self): """Updates countdown on all giveaway messages in the db""" await self.bot.wait_until_ready() for giveaway_row in await self.bot.db.get_all_giveaways(): if datetime.utcnow().timestamp() > giveaway_row['finish_time']: continue try: channel = await self.bot.fetch_channel( giveaway_row['channel_id']) message = await channel.fetch_message( giveaway_row['message_id']) except NotFound: # No longer relevent await self.bot.db.delete_giveaway(giveaway_row['id']) continue duration_delta = timedelta( seconds=round(giveaway_row['finish_time'] - datetime.utcnow().timestamp())) embed = Embed(title="Giveaway!", description=f"{giveaway_row['prize']}\n\n" + f"*Time left: {duration_delta}*\n" + f"*Hosted by: <@{giveaway_row['author_id']}>*", color=Color.orange()).set_footer( text="React with \N{party popper} to enter") try: await message.edit(embed=embed) except NotFound: pass
async def remove_entry(): current = get_list() if AUTHOR not in current.keys(): await error("You are not registered in this list, so why to remove you form it? :^)") else: del current[AUTHOR] save_list(current) await message("Successfully removed you from the list.", Color.orange())
def warn(self, **kwargs): embed = Embed( description=self.message, color=Color.orange() ) for i in kwargs: embed.add_field(name=i.replace("_", " "), value=kwargs[i]) return embed
async def _afk(self, ctx, *, reason="No reason submitted."): if ctx.author.id not in afk: embed = discord.Embed(title="AFK", color=Color.orange(), description=f"{ctx.author.mention} has gone AFK.") embed.add_field(name="Reason", value=f"```{reason}```") embed.set_footer(text=f"Requested by {ctx.author}", icon_url=ctx.author.avatar_url) await ctx.send(embed=embed) afk[ctx.author.id] = {"reason": reason, "afk_time": datetime.now()}
async def _afk(self, ctx, *, reason="No reason submitted."): embed = discord.Embed(title="AFK", color=Color.orange(), description=f"{ctx.author.mention} is now AFK.") embed.add_field(name="Reason", value=f"```{reason}```") embed.set_footer(text=f"Requested by {ctx.author}", icon_url=ctx.author.avatar_url) await ctx.send(embed=embed)
async def ensure_emoji(*args): for emo in args: if not isinstance(emo, Emoji) and not emo in emoji.UNICODE_EMOJI: await ctx.send( embed=Embed(description=f"{emo} is not a valid emoji.", color=Color.orange())) return False return True
async def action(message, client): ext_embed = Embed(title='Playing...', type='rich', color=Color.orange()) ext_embed.set_image(url=cards['extension']['image']) msg = await client.send_message(message.channel, embed=ext_embed) random_card = random.choice(ext_cards) time.sleep(1) msg_text = 'Your card is...' embed_msg = create_embed(random_card) await client.edit_message(msg, new_content=msg_text, embed=embed_msg) return
def status_embed(ctx, member: Member) -> Embed: """ Construct status embed for certain member. Status will have info such as member device, online status, activity, roles etc. :param ctx: context variable to get the member :param member: member to get data from :return: discord.Embed """ color_dict = { Status.online: Color.green(), Status.offline: 0x000000, Status.idle: Color.orange(), Status.dnd: Color.red() } embed = Embed(title=str(member), color=color_dict[member.status]) embed.description = get_badges(member) embed.set_thumbnail(url=member.avatar_url) bot = constants.tick_no nick = member.nick verified = constants.tick_no join_pos = get_join_pos(ctx, member) activities = "" if member.bot: bot = constants.tick_yes if has_verified_role(ctx, member): verified = constants.tick_yes if not nick: nick = constants.tick_no for activity in member.activities: clean_activity = format_activity(activity) activities += f"{clean_activity}\n" embed.add_field( name=f"{constants.pin_emoji} General info", value=f"**Nick** : {nick}\n**Bot** : {bot}\n" f"**Verified** : {verified}\n**Join position** : {join_pos}") embed.add_field(name=f"{constants.user_emoji} Status", value=get_device_status(member), inline=False) embed.add_field(name="📆 Dates", value=f"**Join date** : {format_date(member.joined_at)}\n " f"**Creation Date** : {format_date(member.created_at)}", inline=False) if not activities == "": embed.add_field(name='Activities', value=activities, inline=False) return embed
def ping_em(p: int) -> Embed: if p > 600: color = Color.red() elif p > 200: color = Color.orange() else: color = Color.green() return Embed(title=':ping_pong: Pong', description=f'Ping wynosi **{p}** ms.', color=color)
class DisconnectEmbed(EventEmbed): color = Color.orange() event = "has disconnected from a channel" def __init__(self, member: Member, channel: GroupChannel): super().__init__(member=member, event=self.event, color=self.color) self.channel = channel def build_embed(self, *args, **kwargs): super().build_embed(*args, **kwargs) self.embed.add_field(name="Channel:", value=self.channel.name)