async def two_cats(self, ctx, *, text: commands.clean_content): """Write some text on two signs to write on both signs split the text with || or | if no separator is passed the text will be halved and written on both signs.""" image = ImageDrawText(self.bot, "images/two_cats.jpg") text = ctx.emote_unescape(text) try: text, text_two = text.split("|", 1) or text.split("||", 1) except ValueError: index = len(text) // 2 text_two = " ".join([text[index:]]) text = " ".join([text[:index]]) if not text: text = text_two # this is an invisible character text_two = "\u200b" text = self.string_splice(text, 41) text_two = self.string_splice(text_two, 41) image.font_setter(self.arial_unicode, 18, (6, 0, 15)) text = image.text_wrap(text, 14) text_two = image.text_wrap(text_two, 14) rotate = 358 await image.draw_text_on_image_rotated(text, [67, 217], rotate, True) await image.draw_text_on_image_rotated(text_two, [268, 232], rotate, True) file = discord.File(filename="sign.png", fp=image.save()) await ctx.send(file=file)
async def say(self, ctx, *, message: commands.clean_content): message_components = message.split() if "@everyone" in message_components or "@here" in message_components: await ctx.send("Nice try noob") return await ctx.send(message)
async def memegen(self, ctx, *, text: commands.clean_content = 'Вот такие пироги'): """Генератор мемов. *Сооруди свой топовый мем!* [!] Команда может быть выполнена лишь раз в 8 секунд. Аргументы: `:text` - текст (% - перенос вниз) __ __ Например: ``` n!memegen Вот такие пироги ``` """ string_list = text.split('%') templates = [f'templates/{x}' for x in os.listdir('templates/')] if len(string_list) == 1: make_meme(topString=string_list[0], bottomString='', outputFilename=ctx.guild.id, filename=choice(templates)) elif len(string_list) >= 2: make_meme(topString=string_list[0], bottomString=string_list[1], outputFilename=ctx.guild.id, filename=choice(templates)) await ctx.send(file=discord.File(fp=f'{ctx.guild.id}.png')) await asyncio.sleep(5) os.remove(f'{ctx.guild.id}.png')
async def repeat(self, ctx, num: int, *, text: commands.clean_content): if "spam" not in ctx.channel.name: raise commands.BadArgument("This command is only " "available in spam channels.") ssplit = text.split("\\") suffix = ssplit[-1] if len(ssplit) > 1 else "" text = ssplit[0] num = min(num, 50) fmt = (text.replace("%count%", "{0}").replace("%countBackwards%", "{1}").replace( "%enumerate%", "{2}")) for i in range(1, num + 1): if i % 10 == 1 and i != 11: enumend = "st" elif i % 10 == 2 and i != 12: enumend = "nd" elif i % 10 == 3 and i != 13: enumend = "rd" else: enumend = "th" text = fmt.format(i, num - i + 1, f"{i}{enumend}") await ctx.send(text) await asyncio.sleep(2) if suffix: await ctx.send(suffix)
async def poll(self, ctx, *, options: commands.clean_content = ""): '''Create a poll for members in the channel to vote on. Separate options using the " | " character.''' options = options or await ctx.ask("Give a list of options for the poll, separated by the `|` character:") letters = ["🇦", "🇧", "🇨", "🇩", "🇪", "🇫", "🇬", "🇭", "🇮", "🇯"] options = dict(zip(letters, options.split("|"))) self.ona.assert_(len(options) > 1, error="Only one option provided. Separate options with the `|` character.") embed = self.ona.embed("\n\n".join(f"{letter} {option}" for letter, option in options.items()), title=f"{ctx.author.display_name}'s Poll") poll = await ctx.send(f"{ctx.author.mention} React with ⏹ when you'd like to end the poll.", embed=embed) for letter in options: await poll.add_reaction(letter) await poll.add_reaction("⏹") def check(r, u): return u == ctx.author and r.message.id == poll.id and r.emoji == "⏹" await self.ona.wait_for("reaction_add", check=check) # Continue only after author reacts with the stop emote votes = defaultdict(list) for reaction in (await ctx.channel.fetch_message(poll.id)).reactions: if reaction.custom_emoji or reaction.emoji not in options: # Ignore miscellaneous reacts continue async for member in reaction.users().filter(lambda u: not u.bot): if not any(member == existing_member for emoji in votes for existing_member in votes[emoji]): votes[reaction.emoji].append(member) # Ignore duplicate votes if ctx.channel.permissions_for(ctx.me).manage_messages: await poll.clear_reactions() await ctx.table({options[letter]: len(voters) for letter, voters in votes.items()}, title="final results", label="vote")
async def remind(self, ctx, *, argument: commands.clean_content): """remind yourself after given time in the channel the command was invoked in or privately with a reason or without""" args = argument.split("\n") time = args.pop(0) if args: reason = "\n".join(args).strip()[:self.char_limit] else: reason = "No Reason" kwargs = {'locales': ["de-BE"], 'settings': self.set} expected_date = dateparser.parse(time, **kwargs) if expected_date is None: msg = "No valid time format" await ctx.send(msg) return current_date = datetime.now() difference = (expected_date - current_date).total_seconds() embed = discord.Embed(colour=discord.Color.green()) embed.description = "**Reminder registered:**" represent = expected_date.strftime(self.preset) embed.set_footer(text=represent) if difference < 0: msg = "The timestamp has already passed" await ctx.send(msg) return current_stamp = current_date.timestamp() expected_stamp = expected_date.timestamp() arguments = [ctx.author.id, ctx.channel.id, current_stamp, expected_stamp, reason] reminder = Timer(self.bot, arguments) if difference < 60: await ctx.send(embed=embed) await asyncio.sleep(difference) await reminder.send() else: query = 'INSERT INTO reminder ' \ '(author_id, channel_id, creation, expiration, reason)' \ ' VALUES ($1, $2, $3, $4, $5)' cursor = await self.bot.db.execute(query, arguments) reminder.id = cursor.lastrowid await self.bot.db.commit() if not self.current_reminder: self.current_reminder = reminder self._lock.set() else: if reminder.expiration < self.current_reminder.expiration: self.restart(reminder) logger.debug(f"reminder {reminder.id}: registered") embed.description = f"{embed.description[:-3]} (ID {reminder.id}):**" await ctx.send(embed=embed)
async def choose(self, ctx, *, choices: commands.clean_content): """choose! use , in between Parameters • choices - the choices to choose from separated using ,""" choices = choices.split(",") choices[0] = " " + choices[0] await ctx.send(str(random.choice(choices))[1:])
async def choose(self, ctx, *, choices: commands.clean_content): '''choose! use , in between''' choices = choices.split(',') if len(choices) < 2: return await ctx.send('Not enough choices to pick from.') choices[0] = ' ' + choices[0] await ctx.send(str(random.choice(choices))[1:])
async def choose(self, ctx, *, choices: commands.clean_content): '''Choose between multiple choices. Use `,` to seperate choices.''' choices = choices.split(',') if len(choices) < 2: return await ctx.send('Not enough choices to pick from.') choices[0] = ' ' + choices[0] await ctx.send(str(random.choice(choices))[1:])
async def get_color_image(self, ctx, *, color_list: clean_content): """ Post a picture of a color or multiple colors when specifying multiple colors make sure colors that have a space in them like light blue are written using quotes like this `red "light blue" green` By default colors are concatenated horizontally. For vertical stacking use a newline like this ``` {prefix}{name} red green blue yellow ``` Which would have red and green on top and blue and yellow on bottom Color can be a \u200b \u200b \u200b• hex value (`#000000` or `0x000000`) \u200b \u200b \u200b• RGB tuple `(0,0,0)` \u200b \u200b \u200b• Color name. All compatible names are listed [here](https://en.wikipedia.org/wiki/List_of_colors_(compact)) \u200b \u200b \u200b• Any of `invisible`, `none`, `transparent` for transparent spot """ color_list = [shlex.split(c) for c in color_list.split('\n')] lengths = map(len, color_list) if sum(lengths) > 100: raise BadArgument('Maximum amount of colors is 100') images = [] hex_colors = [] size = (50, 50) def do_the_thing(): for colors in color_list: ims = [] for color in colors: color = self.color_from_str(color) try: im = Image.new('RGBA', size, color) ims.append(im) if isinstance(color, tuple): color = self.rgb2hex(*color) hex_colors.append(color) except (TypeError, ValueError): raise BadArgument( f'Failed to create image using color {color}') images.append(self.concatenate_colors(ims)) if len(images) > 1: concat = self.stack_colors(images) else: concat = images[0] data = BytesIO() concat.save(data, 'PNG') data.seek(0) return data data = await self.bot.loop.run_in_executor(self.bot.threadpool, do_the_thing) await ctx.send(' '.join(hex_colors), file=discord.File(data, 'colors.png'))
async def binTotxt(self, ctx, *, content: commands.clean_content): """``binTotxt [hex code from .bin file]`` Converts .bin hex code into assembly.""" if await self.checklol(ctx): return content = content.replace("```\n", "").replace("```", "") out = (f"```c\nAddress\t\t\t Memory Content\n{'-'*49}\n" + "\n ".join( [(f'{int(j[0], 16)}\t{" ".join([str(bin(int(j[1], 16))).lstrip("0b").zfill(32)[m:m + 4] for m in range(0, 32, 4)])}' if len(j) > 1 else "") for j in [i.split() for i in content.split("\n")]]) + "```") await ctx.send(out)
async def remind(self, ctx, *, argument: commands.clean_content): args = argument.split("\n") time = args.pop(0) if args: reason = "\n".join(args).strip()[:self.char_limit] else: reason = "Kein Grund angegeben" expected_date = dateparser.parse(time, settings=self.set) if expected_date is None: msg = "Es konnte kein gültiges Zeitformat erkannt werden" return await ctx.send(embed=utils.error_embed(msg)) current_date = datetime.now() difference = (expected_date - current_date).total_seconds() embed = discord.Embed(colour=discord.Color.green()) embed.description = "**Erinnerung registriert:**" represent = expected_date.strftime(self.preset) embed.set_footer(text=represent) if difference < 0: msg = "Der Zeitpunkt ist bereits vergangen" return await ctx.send(embed=utils.error_embed(msg)) arguments = [ ctx.author.id, ctx.channel.id, current_date, expected_date, reason ] reminder = Timer.from_arguments(self.bot, arguments) if difference < 60: await ctx.send(embed=embed) await asyncio.sleep(difference) await reminder.send() else: query = 'INSERT INTO reminder ' \ '(author_id, channel_id, creation, expiration, reason)' \ ' VALUES ($1, $2, $3, $4, $5) RETURNING id' async with self.bot.ress.acquire() as conn: resp = await conn.fetchrow(query, *arguments) reminder.id = resp['id'] if not self.current_reminder: self.current_reminder = reminder self._lock.set() else: if reminder.expiration < self.current_reminder.expiration: self.restart(reminder) logger.debug(f"reminder {resp['id']}: registered") embed.description = f"{embed.description[:-3]} (ID {resp['id']}):**" await ctx.send(embed=embed)
async def clapup( self, ctx, *, text: commands. clean_content = 'you forgot to supply text :bigbrain10000:'): """clap 👏 up 👏 some 👏 text""" text = str(text) text = text.replace('.', '\u200B.') return await ctx.send( str(' \N{CLAPPING HANDS SIGN} '.join(text.split()))[:2000])
async def cardexp(self, ctx: commands.Context, *, arg: commands.clean_content = ''): assert isinstance(arg, str) exp = self.bot.assets[Server.JP].card_exp_master def comma_number(n): return '{:,}'.format(n) def format_exp(e): return comma_number(e.total_exp).rjust(9) if not arg: embed = discord.Embed(title='Card Exp', description='```' + '\n'.join(f'Lvl {n}: {format_exp(exp[n])}' for n in range(10, 90, 10)) + '```') await ctx.send(embed=embed) else: try: if arg.isnumeric(): level = int(arg) level_total = exp[level].total_exp desc = ( f'```\n' f'Total: {comma_number(level_total)}\n' f'Change: {comma_number(level_total - exp[level - 1].total_exp) if level > 1 else "N/A"}\n' f'```') await ctx.send(embed=discord.Embed( title=f'Card Exp Lvl {level}', description=desc)) else: start, end = arg.split('-') start = int(start) end = int(end) if start > end: await ctx.send('End exp is greater than start exp.') return start_exp = exp[start] end_exp = exp[end] change_amount = end_exp.total_exp - start_exp.total_exp embed = discord.Embed( title=f'Card Exp Lvl {start}-{end}', description=f'```\n' f'Lvl {str(start).rjust(2)}: {format_exp(start_exp)}\n' f'Lvl {str(end).rjust(2)}: {format_exp(end_exp)}\n' f'Change: {comma_number(change_amount).rjust(9)}\n' f'```') await ctx.send(embed=embed) except Exception: await ctx.send(f'Invalid card exp {arg}')
async def match(self, ctx, *, content: commands.clean_content): """<person1>, <person2>|||Returns a match percentage between two people <3""" match = str(random.randint(0, 100)) content = content.replace(", ", ",").replace(" ,", ",") if "," not in content: raise commands.UserInputError() content = content.split(",") left, right = content await self.Hamood.quick_embed( ctx, description= f"**{left}** and **{right}** are **{match}%** compatible.")
async def remove_hashtag(self, ctx, hashtag: commands.clean_content): """ Removes a hashtag Example usage: `{prefix}twitter remove 아이린` """ # in case they enter it with the hashtag character tag_conditioned = hashtag.split("#")[-1] async with self.bot.Session() as session: logger.info( "%s (%d) deleted hashtag %s", ctx.guild.name, ctx.guild.id, tag_conditioned, ) await db.delete_twitter_sorting(session, tag_conditioned, ctx.guild.id) await session.commit()
async def graph(self, ctx, *, content: commands.clean_content): """<equation>, [equation], [equations]...|||Graphs given equations. Only 'x' can be used as a variable.""" content = content.lower() content = content.split(", ") if ", " in content else [content] done = graph_eq(content) if isinstance(done, io.BytesIO): await self.Hamood.quick_embed( ctx, author={ "name": f"{ctx.author}'s Graph", "icon_url": ctx.author.avatar.url, }, bimage=done, ) else: await self.Hamood.quick_embed(ctx, author={"name": "Could not graph"}, description=f"```{done}```")
async def base(self, ctx, *, content: commands.clean_content): """<number>)<base>, <new base>|||Converts numbers between bases. Max Base = 36.""" try: number, base2 = content.split(", ") number, base1 = number.split(")") answer = base_conversion(number, min(int(base1), 36), min(int(base2), 36)) except: await self.Hamood.quick_embed( ctx, title="Could not convert number between bases.", description="Follow the format: `<number>)<base>`, `<base>`", ) else: await self.Hamood.quick_embed( ctx, author={"name": "Base Conversion"}, description= f"**Base {base1}:** `{number}`\n**Base {base2}:** `{answer}`\n", footer={"text": f"Base {base1} to Base {base2}"}, )
async def remove_account(self, ctx, account: commands.clean_content): """ Unfollows a twitter account for the server Example usage: `{prefix}twitter remove account thinkB329` """ # in case they enter it with the @ character account_conditioned = account.split("@")[-1] account = await self.get_account(ctx, account=account_conditioned) async with self.bot.Session() as session: logger.info( "%s (%d) removed account %s", ctx.guild.name, ctx.guild.id, account.id_str, ) await db.delete_accounts(session, account.id_str, ctx.guild.id) await session.commit() await self.restart_stream()
async def drilify(self, ctx: Context, *, text: clean_content): """this Is so coole....""" words = text.split(' ') after = '' for index, word in enumerate(words): # randomly capitalize words if index % 2 == 0 or random.random() > 0.9: words[index] = word.title() if (index % 3 == 0 or random.random() > 0.8) and \ not word.endswith('e') and \ word[-1].lower() not in list('aeiou.,!:'): words[index] = word + 'e' if random.random() > 0.7: after = '.' * random.randint(1, 6) else: after = ',' if random.random() < 0.8 else ',' * random.randint( 1, 2) await ctx.send(' '.join(words) + after)
async def add_hashtag(self, ctx, hashtag: commands.clean_content, channel: discord.TextChannel): """ Associates a hashtag with a specific channel, more than one hashtag can be associated with any channel Example usage: `{prefix}twitter add hashtag <hashtag> <channel> ` `{prefix}twitter add hashtag 아이린 #Irene` """ # in case they enter it with the hashtag character tag_conditioned = hashtag.split("#")[-1] # check if hashtag already exists async with self.bot.Session() as session: twitter_sorting = await db.get_twitter_sorting( session, hashtag=tag_conditioned, guild_id=ctx.guild.id) if twitter_sorting: await db.delete_twitter_sorting(session, tag_conditioned, ctx.guild.id) logger.debug( "%s (%d) updated %s to %s", ctx.guild.name, ctx.guild.id, tag_conditioned, channel, ) await ctx.send( f"#{tag_conditioned} channel updated to {channel}") else: logger.info( f"{ctx.guild.name} added {tag_conditioned} to #{channel}") twitter_sorting = TwtSorting(_guild=ctx.guild.id, hashtag=tag_conditioned, _channel=channel.id) session.add(twitter_sorting) await session.commit()
async def memegen(self, ctx, *, text: commands.clean_content): """[RU] Соорудить собственный мем [EN] Build your own meme""" string_list = text.split('%') templates = [f'templates/{x}' for x in os.listdir('templates/')] try: attachment = ctx.message.attachments[0] if attachment.filename.lower().endswith( 'png') or attachment.filename.lower().endswith( 'jpg') or attachment.filename.lower().endswith('jpeg'): await attachment.save(f'meme_{ctx.author.id}.png') else: await ctx.send(':x: Не могу работать с этим типом файла.') return False except: fn = choice(templates) else: fn = f'meme_{ctx.author.id}.png' if len(string_list) == 1: make_meme(bottomString=string_list[0], topString='', outputFilename='meme_' + str(ctx.author.id), filename=fn) elif len(string_list) >= 2: make_meme(topString=string_list[0], bottomString=string_list[1], outputFilename='meme_' + str(ctx.author.id), filename=fn) await ctx.send(file=discord.File(fp=f'meme_{ctx.author.id}.png')) await asyncio.sleep(1.5) os.remove(f'meme_{ctx.author.id}.png')
async def random_choice(self, ctx, *, args: commands.clean_content): """Chooses a random option out of a coma separated list.""" choices = args.split(',') choice = ran.choice(choices) await ctx.send(f'{ctx.author.mention}. I choose *"{choice.strip()}"*.')
async def choose(self, ctx, *, content: commands.clean_content): """`choose [option]|[option]|[option]` Chooses between multiple choices.""" content = content.split("|") await ctx.send(f"> Selected: `{random.choice(content)}`")
async def choose(self, ctx, *, things: commands.clean_content): ssplit = things.split("\\") suffix = ssplit[-1] if len(ssplit) > 1 else "" options = ssplit[0].split("|") await ctx.send(f"{random.choice(options).strip()} {suffix.strip()}")
async def choose(self, ctx, *, choices: commands.clean_content): """Choose randomly from the options you give. choose this | that""" await ctx.send("I choose: ``{}``".format( random.choice(choices.split("|"))))
async def clap(self, ctx, *, text: commands.clean_content): """:clap:""" clap = "\U0001f44f" clapped = clap.join(text.split()) await ctx.send(f"{clap}{clapped}{clap}")
async def clapify(self, ctx, *, text: commands.clean_content): """Add clap emojis after each word.""" res = " 👏 ".join(text.split()) await ctx.send(res, embed=self._create_embed(ctx.author))
async def choose(self, ctx, *, content: commands.clean_content): """<choice1>, <choice2>, [choice3], ...|||Choose between multiple choices.""" await self.Hamood.quick_embed( ctx, title=random.choice(content.split(",")).strip(), )
async def b(self, ctx, *, text: commands.clean_content): """ 🅱🅱🅱🅱🅱🅱🅱 """ text = ' '.join('\U0001f171' + w[1:] for w in text.split(' ')) await ctx.send(text.replace('b', '\U0001f171'))