async def quote_alias(self, ctx: utils.Context, quote_id: commands.clean_content, alias: commands.clean_content): """ Adds an alias to a quote. """ # Grab data from db async with self.bot.database() as db: rows = await db( "SELECT * FROM user_quotes WHERE quote_id=$1 AND guild_id=$1", quote_id.lower(), ctx.guild.id) if not rows: return await ctx.send( f"There's no quote with the ID `{quote_id.upper()}`.") # Insert alias into db async with self.bot.database() as db: rows = await db("SELECT * FROM quote_aliases WHERE alias=$1", alias) if rows: return await ctx.send( f"The alias `{alias}` is already being used.") await db( "INSERT INTO quote_aliases (quote_id, alias) VALUES ($1, $2)", quote_id.lower(), alias.lower()) await ctx.send( f"Added the alias `{alias.upper()}` to quote ID `{quote_id.upper()}`." )
async def create(self, ctx, tag_name: commands.clean_content, *, tag_value: commands.clean_content): tag_name = str(tag_name) if tag_name.lower() in ['remove', 'create']: return await ctx.send("Cannot make tag that is a tag command.") if len(tag_name.strip() ) > 100: # tbh idk if this check is really a good one return await ctx.send("Tag name too long (100 or less characters)") if len(str(tag_value)) >= 1800: return await ctx.send("Tag value too long (1800 or less characters" ) g = mongo_setup.mod_and_logging_config.find_one( {'_id': ctx.guild.id} ) # if theres tags for ctx.guild, then the dict should be formatted like: {'tag name': {'author': user id, 'value': 'tag value'}} if not g: mongo_setup.tags.insert_one({'_id': ctx.guild.id }) # if theres no tags for ctx.guild g = mongo_setup.tags.find_one({'_id': ctx.guild.id}) t = g.get(tag_name, None) # checking if the tag is already in the dict if not t: d = {'value': tag_value, 'author': ctx.author.id} mongo_setup.tags.update_one({'_id': ctx.guild.id}, {'$set': { tag_name: d }}) return await ctx.send(f"Tag {tag_name} created!") await ctx.send(f"Tag {tag_name} already exists")
async def get(self, ctx:utils.Context, identifier:commands.clean_content): """Gets a quote from the database""" # Get quote from database async with self.bot.database() as db: quote_rows = await db( """SELECT user_quotes.quote_id as quote_id, user_id, channel_id, message_id FROM user_quotes LEFT JOIN quote_aliases ON user_quotes.quote_id=quote_aliases.quote_id WHERE user_quotes.quote_id=$1 OR quote_aliases.alias=$1""", identifier.lower(), ) if not quote_rows: return await ctx.send(f"There's no quote with the identifier `{identifier.upper()}`.") # Get the message data = quote_rows[0] if data['channel_id'] is None: return await ctx.send("There's no quote channel set for that quote.") channel = self.bot.get_channel(data['channel_id']) if channel is None: return await ctx.send("I wasn't able to get your quote channel.") try: message = await channel.fetch_message(data['message_id']) assert message is not None except (AssertionError, discord.HTTPException): return await ctx.send("I wasn't able to get your quote message.") # Output to user return await ctx.send(embed=message.embeds[0])
async def cryptoprice(self, ctx, cryptocurrency: commands.clean_content = 'bitcoin', \ currency: commands.clean_content = 'rub'): """Стоимость криптовалют. Аргументы: `:cryptocurrency` - имя криптовалюты `:currency` - имя валюты __ __ Например: ``` n!cryptoprice bitcoin rub ``` """ request = requests.get(f'https://api.coinmarketcap.com/v1/ticker/{cryptocurrency}/?convert={currency}') resp = request.json() if type(resp) is dict: return await ctx.send(f'Что-то пошло не так.\n*Может быть, {ctx.author.mention} ввел несуществующую валюту?') price = 'price_' + currency.lower() try: resp[0][price] except KeyError: await ctx.send(f'Что-то пошло не так.\n*Может быть, {ctx.author.mention} ввел несуществующую валюту?') else: embed = discord.Embed(color=0xF4F624, title=f'Стоимость криптовалюты {cryptocurrency}.', description=f'USD: `{resp[0]["price_usd"]}`\n{currency.upper()}: `{resp[0][price]}`') embed.set_author(name=ctx.author.name, icon_url=ctx.author.avatar_url) embed.set_footer(text=f'{ctx.prefix}{ctx.command}') await ctx.send(embed=embed)
async def _remove(self, ctx, channel: discord.TextChannel = None, *, target: commands.clean_content): """ Remove a competition from a live-scores channel Either perform ls remove <league name> in the channel you wish to delete it from, or use ls remove #channel <league name> to delete it from another channel.""" # Verify we have a valid livescores channel target. channel = ctx.channel if channel is None else channel if channel.id not in {i[1] for i in self.cache}: return await ctx.send(f'{channel.mention} is not set as a scores channel.') # Verify which league the user wishes to remove. target = target.strip("'\",") # Remove quotes, idiot proofing. leagues = self.cache[(ctx.guild.id, channel.id)] matches = [i for i in leagues if target.lower() in i.lower()] index = await embed_utils.page_selector(ctx, matches) if index is None: return # rip. target = matches[index] connection = await self.bot.db.acquire() async with connection.transaction(): await connection.execute(""" DELETE FROM scores_leagues WHERE (league,channel_id) = ($1,$2)""", target, channel.id) leagues.remove(target) leagues = ", ".join(leagues) await ctx.send(f"✅ **{target}** was deleted from the tracked leagues for {channel.mention}," f" the new tracked leagues list is: ```yaml\n{leagues}```\n") await self.bot.db.release(connection) await self.update_cache()
async def alias_remove(self, ctx:utils.Context, alias:commands.clean_content): """Deletes an alias from a quote""" # Grab data from db async with self.bot.database() as db: await db("DELETE FROM quote_aliases WHERE alias=$1", alias.lower()) return await ctx.send(f"Deleted alias `{alias.upper()}`.")
async def quote_alias_remove(self, ctx: vbu.Context, alias: commands.clean_content): """ Deletes an alias from a quote. """ # Grab data from db async with self.bot.database() as db: quote_rows = await db( """SELECT user_quotes.quote_id as quote_id, user_id, channel_id, message_id FROM user_quotes LEFT JOIN quote_aliases ON user_quotes.quote_id=quote_aliases.quote_id WHERE quote_aliases.alias=$1 AND guild_id=$2""", alias.lower(), ctx.guild.id ) if not quote_rows: return await ctx.send(f"There's no quote with the alias `{alias.upper()}`.") await db("DELETE FROM quote_aliases WHERE alias=$1", alias.lower()) return await ctx.send(f"Deleted alias `{alias.upper()}`.")
async def nitro(self, ctx, *, emoji: commands.clean_content): """ Allows you to use nitro emojis """ nitromote = discord.utils.find( lambda e: e.name.lower() == emoji.lower(), self.bot.emojis) if nitromote is None: return await ctx.send( f":warning: | **Sorry, no matches found for `{emoji.lower()}`**" ) await ctx.send(f"{nitromote}")
async def _help(self, ctx, *, cmd: commands.clean_content = None): """The help command. Use this to view other commands.""" if cmd == "all": _all = True cmd = None else: _all = False if not cmd: embed = discord.Embed(color=discord.Color.blurple()) embed.set_author(name=f"{ctx.me.display_name}'s Commands.", icon_url=ctx.me.avatar_url_as(format="png", size=32)) embed.set_footer(text=f"Prefix: {ctx.prefix}") n = [] for cog in self.bot.cogs.values(): if sum(1 for n in cog.get_commands() if not (n.hidden and not _all)) == 0: continue n.append(f"**{cog.qualified_name}**\n") for cmd in self.formatter(cog.get_commands(), ignore_hidden=_all): n.append(cmd) join = "".join(n) if len(join) < 2048: embed.description = join await ctx.reply(embed=embed) else: try: await ctx.author.send("") except discord.Forbidden: return await ctx.reply("Cannot DM you!") except discord.HTTPException: pass await ctx.message.add_reaction("\U0001f4ec") for chunk in [n[x:x + 25] for x in range(0, len(n), 25)]: await ctx.author.send("".join(chunk)) else: item = self.bot.get_cog(cmd.lower()) or self.bot.get_command( cmd.lower()) if not item: return await ctx.reply( f"Couldn't find any cog/command named '{cmd}'.") await ctx.reply(embed=self.format_help_for(item))
async def default(self, ctx, mode, *, qry: commands.clean_content = None): """Set a default team or league for your server's lookup commands""" # Validate mode = mode.lower() if mode not in ["league", "team"]: return await ctx.reply(':no_entry_sign: Invalid default type specified, valid types are "league" or "team"', mention_author=True) db_mode = "default_team" if mode == "team" else "default_league" if qry is None: connection = await self.bot.db.acquire() async with connection.transaction(): record = await connection.fetchrow(""" SELecT * FROM scores_settings WHERE (guild_id) = $1 AND (default_league is NOT NULL OR default_team IS NOT NULL) """, ctx.guild.id) await self.bot.db.release(connection) if not record: return await ctx.reply(f"{ctx.guild.name} does not currently have a default team or league set.", mention_author=False) league = "not set." if record["default_league"] is None else record["default_league"] team = "not set." if record["default_team"] is None else record["default_team"] return await ctx.reply(f"Your default league is: <{league}>\nYour default team is: <{team}>", mention_author=False) if qry.lower() == "none": # Intentionally set Null for DB entry url = None else: # Find m = await ctx.reply(f'Searching for {qry}...', mention_author=False) fsr = await self._search(ctx, qry, mode=mode, status_message=m) if fsr is None: return url = fsr.link connection = await self.bot.db.acquire() async with connection.transaction(): await connection.execute( f"""INSERT INTO scores_settings (guild_id,{db_mode}) VALUES ($1,$2) ON CONFLICT (guild_id) DO UPDATE SET {db_mode} = $2 WHERE excluded.guild_id = $1 """, ctx.guild.id, url) await self.bot.db.release(connection) if url is None: return await ctx.reply(f'Your commands will no longer use a default {mode}', mention_author=False) else: return await ctx.reply(f'Your commands will now use <{url}> as a default {mode}', mention_author=False)
async def rate(self, ctx: commands.Context, *, thing: commands.clean_content): """Rates something out of 10 `thing`: The thing to rate. """ rating = int( hashlib.md5(re.sub(r'\W+', '', thing.lower()).encode('utf-8')).hexdigest(), 16) % 11 await ctx.send(f'I rate {thing} a {rating}/10.')
async def move(self, ctx, *, content: commands.clean_content = None): """<coord> <coord>|||Used to move your chess peices, ex. 'e2 e4'. Can only be used if you are in a chess match!.""" _id = str(ctx.guild.id) + str(ctx.author.id) if _id not in self.Hamood.active_games: return await ctx.send("`You are not currently in a game!`") msg = await self.Hamood.active_games[_id].game_update( member=ctx.author, move=content.lower().replace(" ", "").replace(",", "")) if msg is not None: await ctx.send(f"`{msg}`")
async def b(self, ctx, *, message: commands.clean_content): """This is a bad idea.""" if 'b' in message.lower(): return await ctx.send( message.replace('b', ':b:').replace('B', ':b:')) consonants = set( [x for x in message if x.lower() in "bcdfghjklmnpqrstvwxyz"]) await ctx.send( message.replace( random.choice(tuple(consonants) if consonants else message), ':b:'))
async def status(ctx, name: commands.clean_content): with open("text.json", "r") as read_file: usernames = json.load(read_file) memberid = ctx.message.author.id if ctx.message.mentions: return await ctx.send("No mentions allowed buddy") for x in usernames: if x.lower() == name.lower(): honorem = usernames[x]['honorem'] await ctx.send(f"{x} is a protectee, honorem: **{honorem}**.") break else: await ctx.send(f"{name} is not a protectee.")
async def getitem(self, ctx: utils.Context, *, item_name: commands.clean_content): """ Gets you an item from the server. """ # Get the item from the db item_name = item_name.lower() db = await self.bot.database.get_connection() acquire_information = await db( "SELECT * FROM guild_item_acquire_methods WHERE guild_id=$1 AND item_name=$2 AND acquired_by='Command'", ctx.guild.id, item_name) if not acquire_information: await db.disconnect() return await ctx.send( f"You can't acquire **{item_name}** items via the `getitem` command." ) acquire_information = acquire_information[0] # See if they hit the timeout last_run = self.last_command_run[(ctx.guild.id, ctx.author.id, item_name)] if last_run + timedelta( seconds=acquire_information['acquire_per']) > dt.utcnow(): cooldown_seconds = ( (last_run + timedelta(seconds=acquire_information['acquire_per'])) - dt.utcnow()).total_seconds() cooldown_timevalue = utils.TimeValue(cooldown_seconds) await db.disconnect() return await ctx.send( f"You can't run this command again for another `{cooldown_timevalue.clean_spaced}`." ) self.last_command_run[(ctx.guild.id, ctx.author.id, item_name)] = dt.utcnow() # Add to database amount = random.randint(acquire_information['min_acquired'], acquire_information['max_acquired']) await db( """INSERT INTO user_inventories (guild_id, user_id, item_name, amount) VALUES ($1, $2, $3, $4) ON CONFLICT (guild_id, user_id, item_name) DO UPDATE SET amount=user_inventories.amount+excluded.amount""", ctx.guild.id, ctx.author.id, item_name, amount, ) await db.disconnect() return await ctx.send(f"You've received `{amount:,}x {item_name}`.")
async def nitro(self, ctx, *, emoji: commands.clean_content): """Allows you to use nitro emoji ------ n.nitro thonk Will send a thonk emoji in chat """ try: await ctx.send( discord.utils.find(lambda e: e.name.lower() == emoji.lower(), self.bot.emojis)) except BaseException: await ctx.send( f":warning: | **Sorry, no matches found for `{emoji.lower()}`**", delete_after=5, )
async def _remove(self, ctx, channels: commands.Greedy[discord.TextChannel], *, target: commands.clean_content): """ Remove a competition from an existing live-scores channel """ # Verify we have a valid livescores channel target. channels = await self._pick_channels(ctx, channels) if not channels: return # rip all_leagues = set() target = target.strip("'\",") # Remove quotes, idiot proofing. for c in channels: # Fetch All partial matches leagues = self.cache[(ctx.guild.id, c.id)] all_leagues |= set( [i for i in leagues if target.lower() in i.lower()]) # Verify which league the user wishes to remove. all_leagues = list(all_leagues) index = await embed_utils.page_selector(ctx, all_leagues) if index is None: return # rip. target = all_leagues[index] for c in channels: if c.id not in {i[1] for i in self.cache}: await ctx.reply(f'{c.mention} is not set as a scores channel.', mention_author=True) continue connection = await self.bot.db.acquire() async with connection.transaction(): await connection.execute( """ DELETE FROM scores_leagues WHERE (league,channel_id) = ($1,$2)""", target, c.id) await self.bot.db.release(connection) leagues = self.cache[(ctx.guild.id, c.id)].copy() leagues.remove(target) await ctx.reply( f"✅ **{target}** deleted from the tracked leagues for {c.mention}", mention_author=False) await self.update_channel(c.guild.id, c.id) await send_leagues(ctx, c, leagues) await self.update_cache()
async def mode(self, ctx, channels: commands.Greedy[discord.TextChannel], toggle: commands.clean_content = ""): """ Toggle Short mode or Embed mode for transfer data """ channels = await self._pick_channels(ctx, channels) guild_cache = [i for i in self.cache if ctx.guild.id in i] if not toggle: if not channels: return await ctx.reply( 'This server has no transfer ticker channels set.', message_author=True) for c in channels: mode = "Short" if [i[2] for i in self.cache if c.id in i][0] else "Embed" await ctx.reply(f"{c.mention} is set to {mode} mode.", mention_author=False) return if toggle.lower() not in ["embed", "short"]: return await ctx.reply( f'🚫 Invalid mode "{toggle}", use either "embed" or "short"', mention_author=True) update_toggle = True if toggle == "short" else False for c in channels: if c.id not in [i[1] for i in guild_cache]: await ctx.reply( f"🚫 {c.mention} is not set as a transfer channel.", mentiion_author=True) continue connection = await self.bot.db.acquire() async with connection.transaction(): await connection.execute( """UPDATE transfers_channels SET short_mode = $1 WHERE (channel_id) = $2""", update_toggle, c.id) await self.bot.db.release(connection) await ctx.reply(f"✅ {c.mention} was set to {toggle} mode", mention_author=False) await self.update_cache()
async def emojilettres(self, ctx, *, texte: commands.clean_content): """ Permet de parler 🇨​🇴​🇲​🇲​🇪​ 🇨​🇦​ """ texte = texte.lower() out = [] for char in texte: if char in "qwertyuiopasdfghjklzxcvbnm": out.append(self.reg_map[char]) out.append("\u200b") else: out.append(char) out = "".join(out) if len(out) > 2000: await ctx.send(await self.bot.safe_bin_post(out)) else: await ctx.send(out)
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 createitem(self, ctx: utils.Context, *, item_name: commands.clean_content): """ Creates an item that people are able to get. """ item_name = item_name.lower() async with self.bot.database() as db: try: await db( "INSERT INTO guild_items (guild_id, item_name) VALUES ($1, $2)", ctx.guild.id, item_name) except asyncpg.UniqueViolationError: return await ctx.send( f"There's already an item with the name **{item_name}** in your guild." ) return await ctx.send( f"Added an item with name **{item_name}** to your guild. Add acquire methods with the `{ctx.clean_prefix}getitem {item_name}` command." )
async def scores(self, ctx, *, search_query: commands.clean_content = ""): """ Fetch current scores for a specified league """ embeds = [] e = discord.Embed() e.colour = discord.Colour.blurple() if search_query: e.set_author(name=f'Live Scores matching "{search_query}"') else: e.set_author(name="Live Scores for all known competitions") e.timestamp = datetime.datetime.now() dtn = datetime.datetime.now().strftime("%H:%M") q = search_query.lower() matches = [ i for i in self.bot.games if q in (i.home + i.away + i.league + i.country).lower() ] if not matches: e.description = "No results found!" return await embed_utils.paginate(ctx, [e]) game_dict = defaultdict(list) for i in matches: game_dict[i.full_league].append(i.live_score_embed_row) for league in game_dict: games = game_dict[league] if not games: continue output = f"**{league}**\n" discarded = 0 for i in games: if len(output + i) < 1944: output += i + "\n" else: discarded += 1 e.description = output + f"*and {discarded} more...*" if discarded else output e.description += f"\n*Time now: {dtn}\nPlease note this menu will NOT auto-update. It is a snapshot.*" embeds.append(deepcopy(e)) await embed_utils.paginate(ctx, embeds)
async def quote_get(self, ctx: utils.Context, identifier: commands.clean_content): """ Gets a quote from the guild's quote channel. """ # Get quote from database async with self.bot.database() as db: quote_rows = await db( """SELECT user_quotes.quote_id as quote_id, user_id, channel_id, message_id FROM user_quotes LEFT JOIN quote_aliases ON user_quotes.quote_id=quote_aliases.quote_id WHERE user_quotes.quote_id=$1 OR quote_aliases.alias=$1""", identifier.lower(), ) if not quote_rows: return await ctx.send( f"There's no quote with the identifier `{identifier.upper()}`." ) # Get the message data = quote_rows[0] if data['channel_id'] is None: return await ctx.send( "There's no quote channel set for that quote.") channel = self.bot.get_channel(data['channel_id']) if channel is None: return await ctx.send("I wasn't able to get your quote channel.") try: message = await channel.fetch_message(data['message_id']) assert message is not None except (AssertionError, discord.HTTPException): return await ctx.send("I wasn't able to get your quote message.") # try to refresh the user name and icon of the embed by getting the user from the user ID in the DB quote_embed = message.embeds[0] quote_author = self.bot.get_user(data['user_id']) if quote_author: quote_embed.set_author(name=quote_author.display_name, icon_url=quote_author.avatar_url) # Output to user return await ctx.send(embed=quote_embed)
async def mode(self, ctx, channels: commands.Greedy[discord.TextChannel], toggle: commands.clean_content = ""): """ Toggle Short mode or Embed mode for transfer data """ channels = await self._pick_channels(ctx, channels) guild_cache = self.channel_cache[ctx.guild.id] if not toggle: replies = [] for c in channels: mode = "Short" if guild_cache[c.id]["short_mode"] else "Embed" replies.append(f"{c.mention} is set to {mode} mode.") return await ctx.send("\n".join(replies)) if toggle.lower() not in ["embed", "short"]: return await ctx.send( f'🚫 Invalid mode "{toggle}" specified, mode can either be "embed" or "short"' ) update_toggle = True if toggle == "short" else False replies = [] connection = await self.bot.db.acquire() async with connection.transaction(): for c in channels: if c.id not in guild_cache: replies.append( f"🚫 {c.mention} is not a transfers channel.") continue await connection.execute( """UPDATE transfers_channels (mode) VALUES ($1) WHERE (channel_id) = $2""", update_toggle, c.id) replies.append(f"✅ {c.mention} was set to {toggle} mode") await ctx.send("\n".join(replies)) await self.bot.db.release(connection) await self.update_cache()
async def roleinfo(self, ctx, *, msg: commands.clean_content): """Get more info about a specific role. You need to quote roles with spaces. You may also specify a server to check the role for. Aliases: rinfo, ri """ #guild = ctx.message.guild guild_roles = ctx.message.guild.roles for role in guild_roles: if msg.lower() == role.name.lower() or msg == role.id: all_users = [str(x) for x in role.members] all_users.sort() all_users = ', '.join(all_users) em = discord.Embed(title='Role Info', color=role.color) em.add_field(name='Name', value=role.name) em.add_field(name='ID', value=role.id, inline=False) em.add_field(name='Users in this role', value=str(len(role.members))) em.add_field(name='Role color hex value', value=str(role.color)) em.add_field(name='Role color RGB value', value=role.color.to_rgb()) em.add_field(name='Mentionable', value=role.mentionable) if len(role.members) >= 1: em.add_field(name='All users', value=all_users, inline=False) else: em.add_field(name='All users', value='There are no users in this role!', inline=False) em.add_field(name='Created at', value=role.created_at.__format__('%x at %X')) em.set_thumbnail(url='http://www.colorhexa.com/{}.png'.format( str(role.color).strip("#"))) return await ctx.send(content=None, embed=em) await ctx.send('Could not find role ``{}``'.format(msg))
async def mock(self, ctx, *, msg: commands.clean_content): """dOeS thIS To yOuR meSsaGE""" await ctx.send("".join( list( map(lambda x: x if random.random() < 0.5 else x.upper(), msg.lower()))))
async def craftitem(self, ctx: utils.Context, *, crafted_item_name: commands.clean_content): """ Crafts a new item from your current inventory. """ # See if there's a crafting recipe set up crafted_item_name = crafted_item_name.lower() async with self.bot.database() as db: item_craft_amount = await db( "SELECT * FROM craftable_items WHERE guild_id=$1 AND item_name=$2", ctx.guild.id, crafted_item_name) if not item_craft_amount: return await ctx.send( f"You can't acquire **{crafted_item_name}** items via the crafting." ) item_craft_ingredients = await db( "SELECT * FROM craftable_item_ingredients WHERE guild_id=$1 AND item_name=$2", ctx.guild.id, crafted_item_name) user_inventory = await db( "SELECT * FROM user_inventories WHERE guild_id=$1 AND user_id=$2", ctx.guild.id, ctx.author.id) # Add in some dictionaries to make this a lil easier ingredients = { i['ingredient_name']: i['amount'] for i in item_craft_ingredients } inventory_original = { i['item_name']: i['amount'] for i in user_inventory if i['item_name'] in ingredients } inventory = inventory_original.copy() # See if they have enough of the items max_craftable_amount = [] for ingredient, required_amount in ingredients.items(): if inventory.get(ingredient, 0) - required_amount < 0: return await ctx.send( f"You don't have enough **{ingredient}** items to craft this." ) max_craftable_amount.append( inventory.get(ingredient) // required_amount) max_craftable_amount = min(max_craftable_amount) # Make sure they wanna make it ingredient_string = [f"`{o}x {i}`" for i, o in ingredients.items()] await ctx.send( f"This craft gives you **{item_craft_amount[0]['amount_created']}x {crafted_item_name}** and is made from {', '.join(ingredient_string)}. You can make this between 0 and {max_craftable_amount} times - how many times would you like to craft this?" ) try: crafting_amount_message = await self.bot.wait_for( "message", timeout=120.0, check=lambda m: m.channel.id == ctx.channel.id and m.author.id == ctx.author.id and m.content) except asyncio.TimeoutError: return await ctx.send( "Timed out on crafting confirmation - please try again later.") # Get how many they want to craft, and make sure they can do it try: user_craft_amount = int(crafting_amount_message.content) except ValueError: their_value = await commands.clean_content().convert( ctx, crafting_amount_message.content) return await ctx.send( f"I couldn't convert `{their_value}` into an integer - please try again later." ) # See if they said 0 if user_craft_amount <= 0: return await ctx.send("Alright, aborting crafting!") # Remove the right amounts from their inventory for ingredient, required_amount in ingredients.items(): if inventory[ingredient] - (required_amount * user_craft_amount) < 0: return await ctx.send( f"You don't have enough **{ingredient}** items to craft this." ) inventory[ingredient] -= (required_amount * user_craft_amount) # Alter their inventory babey lets GO async with ctx.typing(): async with self.bot.database() as db: for item, amount in inventory.items(): await db( "UPDATE user_inventories SET amount=$4 WHERE guild_id=$1 AND user_id=$2 AND item_name=$3", ctx.guild.id, ctx.author.id, item, amount) await db( """INSERT INTO user_inventories (guild_id, user_id, item_name, amount) VALUES ($1, $2, $3, $4) ON CONFLICT (guild_id, user_id, item_name) DO UPDATE SET amount=user_inventories.amount+excluded.amount""", ctx.guild.id, ctx.author.id, crafted_item_name, item_craft_amount[0]['amount_created'] * user_craft_amount) return await ctx.send( f"You've sucessfully crafted **{item_craft_amount[0]['amount_created'] * user_craft_amount:,}x {crafted_item_name}**." )
async def lower(self, ctx, *, message: commands.clean_content): message = message.lower() await ctx.send(message)
async def tts(self, ctx, *, message: commands.clean_content): await ctx.trigger_typing() tts = gTTS(text=message.lower(), lang="en") tts.save('cogs/data/out/out.wav') await ctx.send(file=discord.File('cogs/data/out/out.wav'))
async def default(self, ctx, mode, *, qry: commands.clean_content = None): """ Set a default team or league for your server's lookup commands """ # Validate mode = mode.lower() if mode not in ["league", "team"]: return await ctx.send( ':no_entry_sign: Invalid default type specified, valid types are "league" or "team"' ) mode = "default_team" if mode == "team" else "default_league" if qry is None: connection = await self.bot.db.acquire() record = await connection.fetchrow( """ SELecT * FROM scores_settings WHERE (guild_id) = $1 AND (default_league is NOT NULL OR default_team IS NOT NULL) """, ctx.guild.id) await self.bot.db.release(connection) if not record: return await ctx.send( f"{ctx.guild.name} does not currently have a default team or league set." ) league = record["default_league"] if record[ "default_league"] is not None else "not set." output = f"Your default league is: {league}" team = record["default_team"] if record[ "default_team"] is not None else "not set." output += "\n" + team return await ctx.send(output) if qry.lower() == "none": # Intentionally set Null for DB entry url = None else: # Find await ctx.send(f'Searching for {qry}...', delete_after=5) fsr = await self._search(ctx, qry, mode=mode) if fsr is None: return await ctx.send( f"Couldn't find matching {mode} for {qry}, try searching for something else." ) url = fsr.link connection = await self.bot.db.acquire() async with connection.transaction(): await connection.execute( f"""INSERT INTO scores_settings (guild_id,{mode}) VALUES ($1,$2) ON CONFLICT (guild_id) DO UPDATE SET {mode} = $2 WHERE excluded.guild_id = $1 """, ctx.guild.id, url) await self.bot.db.release(connection) if qry is not None: return await ctx.send( f'Your commands will now use <{url}> as a default {mode}') else: return await ctx.send( f'Your commands will no longer use a default {mode}')