Example #1
0
    async def check_gm_roll(self, commands):
        """
        Checks to see if the roll is a gm roll to be seen only in secret.
        """

        gm_roll = False
        gm_commands = ["gm", "-gm", "secret"]

        for i in gm_commands:
            if i in commands:
                gm_roll = True
                commands.pop(commands.index(i))

        return commands, gm_roll
Example #2
0
    async def check_exploding(self, commands):
        """
        Checks shadowrun 5E commands to see if the dice are supposed to be
        re-rolled on 6's.
        """

        exploding = False
        exploding_commands = ["explode", "-ex", "edge", "-edge"]

        for i in exploding_commands:
            if i in commands:
                exploding = True
                commands.pop(commands.index(i))

        return commands, exploding
Example #3
0
    async def removecommand(self, ctx, name):
        """Removes a custom command with the given name"""

        # Get dict, remove given command, and write new dict
        with open("data/commands.json", "r") as f:
            commands = json.load(f)

        try:
            commands.pop(name)
        except:
            await ctx.send("No command with that name!")
            return

        with open("data/commands.json", "w") as f:
            json.dump(commands, f)

        await ctx.send(f"There is now no command for {name}")
Example #4
0
    async def check_verbose(self, commands):
        """
        Checks to see if a command is supposed to be verbose.
        commands: list[str]

            -> commands: list[str], verbose: bool
        """

        verbose = False
        verbose_commands = ['show', 'verbose', '-v']

        for i in verbose_commands:
            if i in commands:
                verbose = True
                commands.pop(commands.index(i))

        return commands, verbose
Example #5
0
    async def check_prime(self, commands):
        """
        Checks to see if 'prime' is in the commands list.

        commands: list[str]

            -> commands: list[str], prime: boolean
        """

        prime = False
        prime_commands = ['prime', '-p', 'primer']

        for i in prime_commands:
            if i in commands:
                commands.pop(commands.index(i))
                prime = True

        return commands, prime
Example #6
0
 async def cc_del(self,ctx,name):
     """Deltes a custom command for this server, requires manage server permission."""
     guildid = str(ctx.guild.id)
     commands = await self.checkGuildDict(guildid)
     if commands.pop(name,None) is None:
         await ctx.send("{} wasn't found.".format(name))
         return
     else:
         storage.write("commands",commands,path="cogs/custom/",key=guildid)
         await ctx.send("Command {} deleted!".format(name))
async def on_message(message):
    # Ignore message if this bot sent the message
    if ((message.author == client.user) or (message.author.bot)):
        return

    #if message.author.id == 206966878365679616:
        #match = re.search(r"^\!voice\s+(\d+)\s+(.+\Z)", message.content)
        #if match:
        #    await client.send_message(client.get_channel(match.group(1)), match.group(2))
        #await client.send_message(client.get_channel(279861790194532353), 'Test')
    
    # Decode newlines and other unusual characters
    def decode(text):
        return codecs.escape_decode(bytes(text, "utf-8"))[0].decode("utf-8")
    
    def encode(text):
        return codecs.escape_encode(bytes(text, "utf-8"))[0]
    
    # Replace symbols with emoji
    def emojimize(text):
        for key, value in emoji.items():
            text = text.replace(key, value)
        
        return text
    
    # Italicize all reminder text
    def fixReminderText(text):
        return re.sub(r'(\([^)]+\))', r'*\1*', text)
    
    # Search starting with
    def stdSearch(term):
        cur.execute("SELECT * FROM cards WHERE multiverseId > 0 and name LIKE '{0}' ORDER BY multiverseId ASC LIMIT 1000".format(term))
        return cur.fetchall()
    
    def startsWithSearch(term):
        cur.execute("SELECT * FROM cards WHERE multiverseId > 0 and name LIKE '{0}%' ORDER BY multiverseId ASC LIMIT 100".format(term))
        return cur.fetchall()
    
    # Search anywhere
    def anywhereSearch(term):
        cur.execute("SELECT * FROM cards WHERE multiverseId > 0 and name LIKE '%{0}%' ORDER BY multiverseId ASC LIMIT 100".format(term))
        return cur.fetchall()
    
    # Search according to Soundex
    def soundexSearch(term):
        cur.execute("SELECT * FROM cards WHERE multiverseId > 0 and name SOUNDS LIKE '{0}' ORDER BY multiverseId ASC LIMIT 100".format(term))
        return cur.fetchall()
    
    def levenshteinSearch(term):
        termRange = math.ceil(len(term) / 3) + 1
        termFloor = len(term) - termRange
        termCeil = len(term) + termRange
                
        cur.execute("SELECT name FROM cards WHERE multiverseId > 0 and CHAR_LENGTH(name) >= '{0}' and CHAR_LENGTH(name) <= '{1}' ORDER BY multiverseId DESC".format(termFloor, termCeil))
        cardsToCheck = cur.fetchall()
        bestMatch = 0.0
        matchedCard = None
                
        for card in cardsToCheck:            
            ratio = Levenshtein.ratio(term, card['name'])

            if (ratio > bestMatch):                    
                bestMatch = ratio
                matchedCard = card['name']
        
        if (bestMatch >= .65):
            return stdSearch(matchedCard)
        else:
            return stdSearch(term)
        
    # Look up the card in the MySQL database
    def getCard(card):
        # Iterate through searches to find the card
        for query in [stdSearch, startsWithSearch, anywhereSearch, soundexSearch, levenshteinSearch]:
            result = query(card)
            if result:
                printInfo = []
                lastrow = ''
        
                for row in result:
                    if ((lastrow != row['setCode']) and (result[0]['name'] == row['name'])):
                        printInfo.append(row['setCode'] + ' ' + row['rarity'].upper()[0])
                        lastrow = row['setCode']
        
                result[0]['printings'] = ', '.join(printInfo)
                return result[0]
            
        return result
    
    def getMultiverseId(card):
        cur.execute("SELECT `multiverseId` FROM cards WHERE multiverseId > 0 and name LIKE '{0}' ORDER BY multiverseId DESC LIMIT 1".format(db.escape_string(card).decode()))
        return cur.fetchone()['multiverseId']

    def getScryfallId(card):
        cur.execute("SELECT `scryfallId` FROM cards WHERE multiverseId > 0 and name LIKE '{0}' ORDER BY multiverseId DESC LIMIT 1".format(db.escape_string(card).decode()))
        return cur.fetchone()['scryfallId']
    
    def removePunctuation(text):
        return re.sub('['+string.punctuation+']', '', text)
        
    def formatCard(card):
        # Build the response with the card data
        response = '**' + card['name'] + '**'
        
        if card['manaCost']:
            response += '    ' + emojimize(card['manaCost'])
        
        response += '\n'
        response += card['type'] + '\n'
        
        if card['text']:
            response += fixReminderText(decode(emojimize(card['text'].replace('*', '★')))) + '\n'
        
        if card['flavorText']:
            response += '*' + decode(card['flavorText']) + '*\n'
        
        if card['power'] or card['toughness']:
            response += '**' + decode(card['power'].replace('*', '★')) + '/' + decode(card['toughness'].replace('*', '★')) + '**' + '\n'
        
        if card['loyalty']:
            response += '**' + card['loyalty'] + '**\n'
        
        if card['printings']:
            response += '*' + card['printings'] + '*\n'
        
        if (getMultiverseId(card['name']) >= 9999999):
            response = '||' + response + '||'
        
        return response
    
    def writedown(commands):
        # Record found cards into database
        cur.execute("""INSERT INTO queries (user, channel, query) VALUES ({0}, {1}, '{2}')""".format(message.author.id, message.channel.id, db.escape_string('|'.join(commands)).decode()))
        db.commit()
        
    # Get commands from messages, splitting on the defined delimiter
    # Always drop the first element
    commands = [segment.split(DELIMITER[1])[0] for segment in message.content.split(DELIMITER[0])]
    commands.pop(0)
    
    if (commands):
        query = []
        
        # No more than 5 cards, sorry
        del commands[5:]
        
        for command in commands:
            # advancedCommand = re.search(r"([tos]):(\S+)", command)
            # if advancedCommand:
            #     getAdvancedCard()
            
            # Strip punctuation
            retrievedCard = getCard(db.escape_string(command).decode())
            #retrievedCard['name'] = retrievedCard['name'].replace("’", "'")
            
            if retrievedCard:
                if (retrievedCard['name'] not in query):
                    query.append(retrievedCard['name'])
                    await message.channel.send(formatCard(retrievedCard))
            else:
                await message.channel.send('**No cards found.**\nPlease revise your query.')
                
        if (len(query)):
            writedown(query)

    if (message.content.find('!price') >= 0):
        # Get the card price
        cur.execute("""SELECT * FROM queries WHERE channel = {0} ORDER BY id DESC LIMIT 1""".format(message.channel.id))
        result = cur.fetchone()

        if (result == None):
            return

        resultList = result['query'].split('|')
        
        response = []
        
        # Find the image by the set and card number
        for item in resultList:
            price = json.loads(getCard(item)['prices'])
            purchase = json.loads(getCard(item)['purchaseUrls'])
            
            if (price['paper']['2019-05-26']):
                response.append(getCard(item)['name'] + ' *' + getCard(item)['setCode'] + ' ' + getCard(item)['rarity'] + '* $' + price['paper']['2019-05-26'])
                if (purchase['tcgplayer']):
                    response[-1] += '\n TCGPlayer: <' + purchase['tcgplayer'] +'>'

        await message.channel.send('\n'.join(response))


    if (message.content.find('!image') >= 0):
        # Display image for card for last query in this channel
        cur.execute("""SELECT * FROM queries WHERE channel = {0} ORDER BY id DESC LIMIT 1""".format(message.channel.id))
        result = cur.fetchone()
        
        if (result == None):
            return
        
        resultList = result['query'].split('|')
        
        response = []
        
        # Find the image by the set and card number
        for item in resultList:
            # Check if it’s a back side of a card
            side = ''
            if (getCard(item)['side'] == 'b'):
                side = '&face=back'
            
            # SPOILERS!
            if (getMultiverseId(item) >= 9999998):
                response.append('||https://api.scryfall.com/cards/' + getScryfallId(item) + '?format=image' + side + '||')
            else:
                response.append('https://api.scryfall.com/cards/' + getScryfallId(item) + '?format=image' + side)
        
        await message.channel.send('\n'.join(response))