Exemplo n.º 1
0
    async def imgur(self, *text):
        """Retrieves a picture from imgur

        imgur search [keyword] - Retrieves first hit of search query.
        imgur [subreddit section] [top or new] - Retrieves top 3 hottest or latest pictures of today for given a subreddit section, e.g. 'funny'."""
        imgurclient = ImgurClient("1fd3ef04daf8cab", "f963e574e8e3c17993c933af4f0522e1dc01e230")
        if text == ():
            rand = randint(0, 59) #60 results per generated page
            items = imgurclient.gallery_random(page=0)
            await self.bot.say(items[rand].link)
        elif text[0] == "search":
            items = imgurclient.gallery_search(" ".join(text[1:len(text)]), advanced=None, sort='time', window='all', page=0)
            if len(items) < 1:
                await self.bot.say("NI PRSLO DO REZULTATU DJOPORKO!")
            else:
                await self.bot.say(items[0].link)
        elif text[0] != ():
            try:
                if text[1] == "top":
                    imgSort = "top"
                elif text[1] == "new":
                    imgSort = "time"
                else:
                    await self.bot.say("Only top or new is a valid subcommand.")
                    return
                items = imgurclient.subreddit_gallery(text[0], sort=imgSort, window='day', page=0)
                if (len(items) < 3):
                    await self.bot.say("This subreddit section does not exist, try 'funny'")
                else:
                    await self.bot.say("{} {} {}".format(items[0].link, items[1].link, items[2].link))
            except:
                await self.bot.say("Type help imgur for details.")
Exemplo n.º 2
0
    async def imgur(self, *text):
        """Retrieves a picture from imgur

        imgur search [keyword] - Retrieves first hit of search query.
        imgur [subreddit section] [top or new] - Retrieves top 3 hottest or latest pictures of today for given a subreddit section, e.g. 'funny'."""
        imgurclient = ImgurClient("1fd3ef04daf8cab", "f963e574e8e3c17993c933af4f0522e1dc01e230")
        if text == ():
            rand = randint(0, 59) #60 results per generated page
            items = imgurclient.gallery_random(page=0)
            await self.bot.say(items[rand].link)
        elif text[0] == "search":
            items = imgurclient.gallery_search(" ".join(text[1:len(text)]), advanced=None, sort='time', window='all', page=0)
            if len(items) < 1:
                await self.bot.say("Your search terms gave no results.")
            else:
                await self.bot.say(items[0].link)
        elif text[0] != ():
            try:
                if text[1] == "top":
                    imgSort = "top"
                elif text[1] == "new":
                    imgSort = "time"
                else:
                    await self.bot.say("Only top or new is a valid subcommand.")
                    return
                items = imgurclient.subreddit_gallery(text[0], sort=imgSort, window='day', page=0)
                if (len(items) < 3):
                    await self.bot.say("This subreddit section does not exist, try 'funny'")
                else:
                    await self.bot.say("{} {} {}".format(items[0].link, items[1].link, items[2].link))
            except:
                await self.bot.say("Type help imgur for details.")
Exemplo n.º 3
0
def _imgur_search(conf, query="", filetype='gif', random_result=False):
    ''' returns an image from imgur '''

    # basic api client setup
    client_id = conf['imgur_client_id']
    client_secret = conf['imgur_client_secret']
    client = ImgurClient(client_id, client_secret)

    # get the image url for an imgur album
    def _get_direct_url(url):

        scrape_start = '<link rel="image_src"'
        scrape_end = '"/>'

        request = urllib.request.Request(url)
        result = urllib.request.urlopen(request)
        charset = result.info().get_content_charset()
        html = result.read().decode(charset)

        direct_url = html[html.find(scrape_start):]
        direct_url = direct_url[direct_url.find('href="') +
                                len('href="'):direct_url.find(scrape_end)]

        return direct_url

    # handle random
    if random_result:
        gifs = []

        for item in client.gallery_random():
            if item.is_album:
                direct_url = _get_direct_url(item.link)

            else:
                direct_url = item.link

            if '.gif' in direct_url:
                gifs.append(direct_url)

        return random.choice(gifs)

    # handle queries
    else:
        query = query.split(' ')
        advanced_dict = {'q_all': query, 'q_type': filetype}
        item = random.choice(client.gallery_search("", advanced=advanced_dict))

        if item.is_album:
            return _get_direct_url(item.link)

        else:
            return item.link
Exemplo n.º 4
0
def _imgur_search(conf, query="", filetype='gif', random_result=False):
    ''' returns an image from imgur '''

    # basic api client setup
    client_id      = conf['imgur_client_id']
    client_secret  = conf['imgur_client_secret']
    client         = ImgurClient(client_id, client_secret)

    # get the image url for an imgur album
    def _get_direct_url(url):

        scrape_start = '<link rel="image_src"'
        scrape_end   = '"/>'

        request      = urllib.request.Request(url)
        result       = urllib.request.urlopen(request)
        charset      = result.info().get_content_charset()
        html         = result.read().decode(charset)

        direct_url   = html[html.find(scrape_start):]
        direct_url   = direct_url[direct_url.find('href="') + len('href="'):direct_url.find(scrape_end)]

        return direct_url

    # handle random
    if random_result:
        gifs = []

        for item in client.gallery_random():        
            if item.is_album:
                direct_url = _get_direct_url(item.link)
        
            else:
                direct_url = item.link
        
            if '.gif' in direct_url:
                gifs.append(direct_url)
        
        return random.choice(gifs)


    # handle queries
    else:
        query = query.split(' ')    
        advanced_dict = {'q_all':query, 'q_type':filetype}    
        item = random.choice(client.gallery_search("", advanced=advanced_dict))
    
        if item.is_album:    
            return _get_direct_url(item.link)
    
        else:    
            return item.link
Exemplo n.º 5
0
    async def imgur(self, *text):
        """Retrieves a picture from imgur

        imgur search [keyword] - Retrieves first hit of search query.
        imgur [subreddit section] [top or new] - Retrieves top 3 hottest or latest pictures of today for given a subreddit section, e.g. 'funny'."""
        imgurclient = ImgurClient("1fd3ef04daf8cab",
                                  "f963e574e8e3c17993c933af4f0522e1dc01e230")
        if text == ():
            rand = randint(0, 59)  #60 results per generated page
            items = imgurclient.gallery_random(page=0)
            #colour = ''.join([randchoice('0123456789ABCDEF') for x in range(6)])
            #colour = int(colour, 16)
            #embed=discord.Embed(colour=discord.Colour(value=colour))
            #embed.set_author(name="Imgur", icon_url=self.bot.user.avatar_url)
            #embed.set_image(url=items[rand].link)
            #await self.bot.say(embed=embed)
            await self.bot.say(items[rand].link)
        elif text[0] == "search":
            items = imgurclient.gallery_search(" ".join(text[1:len(text)]),
                                               advanced=None,
                                               sort='time',
                                               window='all',
                                               page=0)
            if len(items) < 1:
                await self.bot.say("Your search terms gave no results.")
            else:
                await self.bot.say(items[0].link)
        elif text[0] != ():
            try:
                if text[1] == "top":
                    imgSort = "top"
                elif text[1] == "new":
                    imgSort = "time"
                else:
                    await self.bot.say("Only top or new is a valid subcommand."
                                       )
                    return
                items = imgurclient.subreddit_gallery(text[0],
                                                      sort=imgSort,
                                                      window='day',
                                                      page=0)
                if (len(items) < 3):
                    await self.bot.say(
                        "This subreddit section does not exist, try 'funny'")
                else:
                    await self.bot.say("{} {} {}".format(
                        items[0].link, items[1].link, items[2].link))
            except:
                pass
Exemplo n.º 6
0
Arquivo: imgur.py Projeto: tleecsm/BtR
class imgurCommand:
    """
    imgurCommand
    Class that contains the initialization and runtime logic for imgur command
    """
    def __init__(self):
        """
        __init__
        Creates the class variables needed for the client
        Additionally stores the client for access in a class variable
        """
        self.clientId = 'ebae683a1f7ca07'
        self.clientSecret = 'c49e4fcb78b0cbe92481c1778a38cb884f9af584'
        self.imgurClient = ImgurClient(self.clientId, self.clientSecret)

    async def imgur(self, discordClient, message):
        """
        imgur
        Main execution logic for the imgur command
        Leverages the imgurClient to fetch image requests from the user
        Image request terms fetched from message content
        """
        #Start by stripping the imgur command off the message
        #messageContent will contain the search request from the user
        messageContent = message.content[7:]
        gallery = self.imgurClient.gallery_search(messageContent,
                                                  sort='best',
                                                  page=0)
        if len(gallery) < 1:
            #There are no images in the gallery
            #Return an error message
            imgurError = 'I couldn\'t find anything with that tag!'
            await discordClient.send_message(message.channel, imgurError)
            return
        image = random.choice(gallery)
        await discordClient.send_message(message.channel, image.link)

    async def imgurRandom(self, discordClient, message):
        """
        imgurRandom
        Fetches a random imgur post
        Returns it in a message to the user's channel
        """
        #Fetch a random gallery and pull a random image from the gallery
        gallery = self.imgurClient.gallery_random()
        await discordClient.send_message(message.channel, gallery[0].link)
Exemplo n.º 7
0
def main():
    config = {}
    with open("config.json") as config_f:
        config = json.load(config_f)

    temp_dir = tempfile.mkdtemp()
    print temp_dir

    imgur_client = ImgurClient(config["client_id"], config["client_secret"])

    random_image_list = []
    gets = 0

    while not random_image_list and gets <= MAX_GETS:
        random_image_list = [ i for i in imgur_client.gallery_random() if not i.is_album \
                              and not i.nsfw \
                              and not i.animated \
                              and (i.width/float(i.height)) >= 1.5 \
                              and (i.width/float(i.height)) <= 1.8]
        gets += 1

    if gets > MAX_GETS:
        raise SystemExit("Failed to get image list after %d gets! :(" % MAX_GETS)

    random.shuffle(random_image_list)
    random_image = random_image_list[0]
    random_image_get = requests.get("https://imgur.com/%s.png" % random_image.id)
    random_image_content = random_image_get.content

    imgur_f_path = os.path.join(temp_dir, "imgur.png")
    with open(imgur_f_path, "w") as imgur_f:
        imgur_f.write(random_image_content)

    imgur_pil = PIL.Image.open(imgur_f_path)
    fib_pil = PIL.Image.open("1280px-Fibonacci_spiral_34.svg.png")
    fib_pil = fib_pil.resize((random_image.width, random_image.height), PIL.Image.ANTIALIAS)

    imgur_pil.paste(fib_pil, (0, 0), fib_pil)
    imgur_pil.show()
Exemplo n.º 8
0
class Client(BaseNamespace):
    def initialize(self):
        """Secondary __init__ created for the SocketIO_client instantiation method
        """
        self.voteskips = []
        self.response = {}
        self.route = {}
        self.userlist = []
        self.poll = []
        self.media = []
        self.init = False
        self.question = None
        self.jumble = None
        self.imgur = None

    def config(self, config):
        if 'response' in config:
            self.response = config['response']
        if 'route' in config:
            self.route = config['route']
        if all(k in config for k in ('channel', 'username', 'password')):
            self.login(config['channel'], config['username'],
                       config['password'])
        if 'tmdbapi' in config:
            tmdb.API_KEY = config['tmdbapi']
        if 'giphyapi' in config:
            self.giphy = giphypop.Giphy(api_key=config['giphyapi'])
        if 'timeout' in config:
            self.timeout = config['timeout']
        if 'cost' in config:
            self.cost = config['cost']
        if 'imgur' in config:
            self.imgur = ImgurClient(config['imgur']['client_id'],
                                     config['imgur']['client_secret'])

    def login(self, channel, username, password):
        """Simple login to the websocket. Emits the params to the
        websocket.

        Args:
            channel (str): Channel to join on login
            username (str): Username of account to login
            password (str): Password of account to control
        """
        self.username = username
        self.channel = channel
        self.emit('initChannelCallbacks')
        self.emit('joinChannel', {'name': channel})
        self.emit('login', {'name': username, 'pw': password})

    def chat_voteskip(self, msg, *args):
        """An example of executing arbitrary messages through chat.
        Stores all media in `media`. Flags the skips.
        """
        msg.to = msg.username
        self.emit('voteskip', {})

    def pm_kill(self, msg, *args):
        if (msg.username == 'zim'):
            exit()

    def chat_give(self, msg, *args):
        omsg = msg
        omsg.body = 'test'
        if (len(args) > 0):
            wFrom = Wallet(msg.username)
            to = args[0][0]
            amt = int(args[0][1])
            if amt <= 0 or (to == msg.username):
                omsg.to = msg.username
                omsg.body = 'Bruh, really?'
            elif (wFrom.balance < amt):
                omsg.to = msg.username
                omsg.body = 'Give: Insufficient funds.'
            else:
                wTo = Wallet(to)
                wFrom.transaction(-amt)
                wTo.transaction(amt)
                omsg.body = '{} gave {} {} squids!'.format(
                    msg.username, to, amt)
        else:
            omsg.body = 'The syntax is !give <username> <amount>'
            omsg.to = msg.username
        self.sendmsg(omsg)

    def chat_help(self, msg, *args):
        msg.to = msg.username
        meth = dir(self)
        lst = []
        for cmd in meth:
            if 'chat_' in cmd:
                lst.append(cmd[5:])
        msg.body = "This is an experimental feature, some of these may not work.\n"
        msg.body += ', '.join(lst)
        self.sendmsg(msg)

    def getUser(self, name):
        for usr in self.userlist:
            if 'name' in usr and name in usr['name']:
                return usr

    def x_imgur(self, msg, *args):
        if (args[0]):
            search = self.imgur.gallery_search(' '.join(args[0]),
                                               window='all',
                                               sort='time',
                                               page=0)
        else:
            search = self.imgur.gallery_random()
        if len(search) > 0:
            item = random.choice(search)
            if item.is_album:
                choice = random.choice(self.imgur.get_album_images(item.id))
                choice = choice.link
            else:
                choice = item.link
        else:
            out = 'There were no results for that request.'
        self.emit('pm', {'msg': out, 'meta': {}, 'to': msg.to})

    def chat_giphy(self, msg, *args):
        if (args[0]):
            x = self.giphy.search(' '.join(args[0]), rating='pg-13')
            for y in x:
                out = y.media_url + '.pic'
                self.sendmsg(out)
                return
            out = 'There were no PG-13 results for that request.'
            self.sendmsg(out)

    def chat_slots(self, msg, *args):
        if (args[0]):
            wallet = Wallet(msg.username)
            timer = Timer(msg.username, 'slots')
            cost = 0
            if args[0][0].isdigit():
                cost = -abs(int(args[0][0]))
            else:
                self.sendmsg('Please place a numeric bet.')
                return

            chk = timer.check(self.timeout['slots'])
            if (not chk['ready']):
                timetil = chk['timetil'] / 60
                self.sendmsg('Try again in {} minute(s).'.format(timetil))
                return
            else:
                cost = abs(int(args[0][0]))
                if wallet.balance >= cost:
                    wallet.transaction(-cost)
                    serverWallet = Wallet('{{server}}')
                    lst = [0] * 5 + [1] * 5 + [2] * 5 + [3] * 5 + [4] * 2 + [5]
                    x, y, z = random.choices(lst, k=3)
                    prizemsg = ":botchat3:"
                    translate = ['♥', '♣', '♠', '♪', '♀', '♦']
                    prizemsg = "| {} | {} | {} |\n".format(
                        translate[x], translate[y], translate[z])

                    if 5 in (x, y, z) and (x == y == z):
                        cost = serverWallet.balance
                        wallet.transaction(cost)
                        serverWallet.transaction(-abs(serverWallet.balance))
                        prizemsg += '{} hit the jackpot! They have earned {} squids!'.format(
                            msg.username, cost)
                    elif (x == y == z) and max(x, y, z) < 4:
                        wallet.transaction(cost * 3)
                        prizemsg += '{} matches 3 (three) fruits! [3x] Multiplyer (Bal: {})'.format(
                            msg.username, wallet.balance)
                    elif 5 in (x, y, z) and len({x, y, z}) == 2:
                        wallet.transaction(cost * 2)
                        prizemsg += '{} got a diamond and two matches. [2x] (Bal: {})'.format(
                            msg.username, wallet.balance)
                    elif 5 in (x, y, z) and len({x, y, z}) == 3:
                        wallet.transaction(cost)
                        prizemsg += '{} breaks even with 1 (one) diamond. [1x] (Bal: {})'.format(
                            msg.username, wallet.balance)
                    elif len({x, y, z}) == 2:
                        wallet.transaction(2 * cost)
                        prizemsg += '{} matches 2! [2x] Multiplyer (Bal: {})'.format(
                            msg.username, wallet.balance)
                    else:
                        serverWallet.transaction(cost)
                        prizemsg += '{}, better luck next time. (Bal: {})'.format(
                            msg.username, wallet.balance)
                    self.sendmsg(prizemsg)
                    timer.setTimer()
                else:
                    msg.to = msg.username
                    msg.body = 'Slots: Insufficient funds.'
                    self.sendmsg(msg)

    def chat_trivia(self, msg, *args):
        if not self.question:
            r = req.get('https://opentdb.com/api.php?amount=1')
            self.question = r.json()['results'][0]
            sub = 'True/False' if any(s in self.question['correct_answer']
                                      for s in ('True', 'False')) else None
            body = '{}(Category: {}) {}'.format(
                '[' + sub + ']' if sub else '', self.question['category'],
                html.unescape(self.question['question']))
            self.sendmsg(body)
        else:
            sub = 'True/False' if any(s in self.question['correct_answer']
                                      for s in ('True', 'False')) else None
            body = '{}(Category: {}) {}'.format(
                '[' + sub + ']' if sub else '', self.question['category'],
                html.unescape(self.question['question']))
            self.sendmsg(body)
        if (self.question['type'] == 'multiple'):
            choices = self.question['incorrect_answers']
            choices.append(self.question['correct_answer'])
            random.shuffle(choices)
        #    self.sendmsg("Choices: {}".format(html.unescape(','.join(choices))))

    def chat_nq(self, msg, *args):
        w = Wallet(msg.username)
        if (w.balance >= 100):
            w.transaction(-100)
            self.question = None
            self.sendmsg('{} spent 100 squids to skip the question.\
                    ({})'.format(msg.username, w.balance))

    def chat_a(self, msg, *args):
        if (len(args[0]) > 0):
            ans = html.unescape(' '.join(args[0]).lower())
            if (html.unescape(
                    self.question['correct_answer'].lower().rstrip().lstrip())
                    == ans):
                w = Wallet(msg.username)
                w.transaction(100)
                self.sendmsg('{} got it right! (100 Squids)'.format(
                    msg.username))
                self.question = None
        else:
            return

    def chat_hint(self, msg, *args):
        if self.question:
            body = ' '.join([
                ''.join(random.sample(word, len(word))) for word in
                html.unescape(self.question['correct_answer']).split()
            ])
            self.sendmsg(body)

    def chat_love(self, msg, *args):
        data = {'msg': 'No love.'}
        if args[0]:
            args = args[0]
        to = args[0] if len(args) > 0 else self.username
        frm = args[1] if len(args) > 1 else msg.username
        if (msg.username in self.response):
            data['msg'] = self.response[msg.username].format(to, frm)
        else:
            data['msg'] = random.choice(self.response['generic']).format(
                to, frm)

        self.sendmsg(Msg(data))

    def chat_squids(self, msg, *args):
        wallet = Wallet(msg.username)
        self.sendmsg(
            Msg({
                'body':
                '{0} has {1} squids.'.format(msg.username, wallet.balance)
            }))

    def chat_skin(self, msg, *args):
        search = tmdb.Search()
        body = 'No sexual parental guide found'
        if len(args) > 0:
            response = search.movie(query=' '.join(args[0]))
            if search.results:
                mid = search.results[0]['id']
                movie = tmdb.Movies(mid)
                info = movie.info()
                if 'imdb_id' in info:
                    t = req.get('https://www.imdb.com/title/' +
                                info['imdb_id'] + '/parentalguide')
                    advise = Soup(t.content).find('section',
                                                  id='advisory-nudity')
                    if advise:
                        body = ''
                        items = advise.find_all('li', 'ipl-zebra-list__item')
                        for item in items:
                            body += item.contents[0].strip().replace(
                                '\n', '.').replace('-', ' ')
        msg.body = '/sp ' + body
        self.sendmsg(msg)

    def chat_trailers(self, msg, *args):
        search = tmdb.Search()
        vids = {}
        msg.to = msg.username
        regex = re.compile('[^a-zA-Z ]')
        for movie in self.poll:
            movie = movie.replace('.', ' ')
            movie = regex.sub('', movie)
            response = search.movie(query=movie)
            if search.results:
                mid = search.results[0]['id']
            else:
                break
            movie = tmdb.Movies(mid)
            videos = movie.videos()
            for video in videos:
                if 'results' in videos:
                    for t in videos['results']:
                        if t['type'] == 'Trailer':
                            vids[search.results[0]['title']] = t['key']
        for title, vid in vids.items():
            msg.body = title + ': http://youtube.com/watch?v=' + vid
            self.sendmsg(msg)
            for user in self.userlist:
                if (user['name'].lower() == msg.username.lower()
                        and user['rank'] > 1):
                    if any(t['key'] in s for s in self.media):
                        msg.body = title + ' already exists in queue.'
                        self.sendmsg(msg)
                    else:
                        self.queue(vid, True)

    def pm_debug(self, msg, *args):
        if msg.username == 'zim':
            msg.to = 'zim'
            for x in self.media:
                msg.body = ''.join(x)
                self.sendmsg(msg)

    def chat_choose(self, msg, *args):
        if args[0]:
            msg.body = random.choice(args[0])
            self.sendmsg(msg)

    def chat_fuck(self, msg, *args):
        args = args[0]
        fmsg = f**k.random(from_=msg.username)
        if len(args) > 0:
            fmsg = f**k.random(from_=msg.username, name=args[0])
        data = Msg({'msg': fmsg.text})
        self.sendmsg(data)
        return True

    def chat_rate(self, msg, *args):
        """TODO: If the socket app does not support media, allow this to wait
        for a callback; this will let users rate functionality?
        (SCOPE CREEP)"""
        if (len(args) > 0):
            msg.to = msg.username
            msg.body = 'Thank you for rating, wzrd will be pleased!'
            self.sendmsg(msg)

    def chat_j(self, msg, *args):
        if (len(args[0]) > 0 and self.jumble):
            if ' '.join(args[0]).lower() == self.jumble:
                msg.body = "{} solved the jumble: {}. (50 squids)".format(
                    msg.username, self.jumble)
                wallet = Wallet(msg.username)
                wallet.transaction(50)
                self.jumble = None
                self.sendmsg(msg)
            else:
                pass

    def chat_jumble(self, msg, *args):
        """Attempts to solve an anagram based on letters parsed from handle_msg
        Requests calls based on the arguments and the whole Msg.

        Args:
            match (str): The anagram which has been parsed from the Msg
            to be solved to an english word
        """
        if self.jumble:
            msg.body = ''.join(random.sample(self.jumble, len(self.jumble)))
        else:
            word_site = "https://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-type=text/plain"
            r = req.get(word_site)
            self.jumble = random.choice(r.text.splitlines()).lower()
            msg.body = ''.join(random.sample(self.jumble, len(self.jumble)))
        self.sendmsg(msg)

    def chat_handout(self, msg, *args):
        amt = random.randint(1, 100)
        wallet = Wallet(msg.username)
        timer = Timer(msg.username, 'handout')
        chk = timer.check(self.timeout['handout'])
        if (chk['ready']):
            wallet.transaction(amt)
            timer.setTimer()
        else:
            timetil = chk['timetil'] / 60
            self.sendmsg('Try again in {} minute(s).'.format(timetil))
            return
        balance = wallet.balance
        if (balance):
            self.sendmsg('Here'
                         's {} squids. {} has {} squids!'.format(
                             amt, msg.username, balance))
        return

    def qryCur(self, qry):
        self.currencyCur.execute(qry)
        res = self.currencyCur.fetchone()
        self.currencyConn.commit()
        return res

    def chat_catboy(self, msg, *args):
        self.sendmsg(':catfap:')

    def chat_auto(self, msg, *args):
        if (msg.username == 'catboy'):
            if random.random() < 0.02:
                self.sendmsg('Meow')

    def sendmsg(self, msg):
        if (isinstance(msg, str)):
            self.emit('chatMsg', {'msg': msg})
        elif (msg.to):
            self.emit('pm', {'msg': msg.body, 'meta': {}, 'to': msg.to})
        else:
            self.emit('chatMsg', {'msg': msg.body, 'meta': msg.meta})
        log.debug(msg)

    def queue(self, url, after=False):
        data = {"id": url, "type": "yt", "pos": "next", "temp": True}
        self.emit('queue', data)
        self.media.append(url)

    def sendadminmsg(self, msg):
        msg = {'username': None, 'rank': 0}
        for y in self.userlist:
            if (not y['meta']['afk']):
                if (msg['rank'] < y['rank']):
                    msg['username'] = y['name']
                    msg['rank'] = y['rank']

    @check_init
    def jackpot_announce(self):
        timeout = 15 * 60
        if ('jackpot' in self.timeout):
            timeout = self.timeout['jackpot']
        t = threading.Timer(timeout, self.jackpot_announce)
        t.daemon = True
        t.start()
        serverWallet = Wallet('{{server}}')
        self.sendmsg('Current jackpot is: {} squids!'.format(
            serverWallet.balance))
        p = random.random()
        if p < 0.0002:
            bal = serverWallet.balance
            amt = random.randint(int(bal / len(str(bal))), int(bal / 2))
            user = random.choice(self.userlist)['name']
            serverWallet.transaction(-amt)
            userWallet = Wallet(user)
            userWallet.transaction(amt)
            self.sendmsg(
                'The accountant made a mistake and {} got {} squids!'.format(
                    user, amt))

    @run_async
    @check_init
    def handle_msg(self, msg):
        chatlog.info(msg)
        ret = False
        cmd = ''
        cnt = False
        if (self.route):
            for user in self.route:
                if (msg.username == user):
                    for func in self.route[user]:
                        match = msg.search_body(self.route[user][func])
                        if (match):
                            dir_cmd = func
                            args = match
                            cnt = True
        if (msg.text.startswith('!') and msg.username):
            cmd = msg.text.split()
            dir_cmd = cmd[0][1:]
            args = cmd[1:]
            cnt = True
        if (cnt):
            call = 'chat_' + dir_cmd
            if (msg.to):  # It's a PM
                call = 'pm_' + dir_cmd
            try:
                func = getattr(self, call.lower())
                if callable(func):
                    if (dir_cmd in self.cost):
                        wallet = Wallet(msg.username)
                        if (wallet.balance < self.cost[dir_cmd]):
                            self.sendmsg(
                                '{0} costs {1} squids. {2} has {3}'.format(
                                    dir_cmd, self.cost[dir_cmd], msg.username,
                                    wallet.balance))
                            return
                        else:
                            wallet.transaction(-self.cost[dir_cmd])
                            self.sendmsg(
                                Msg({
                                    'to':
                                    msg.username,
                                    'body':
                                    'You spent {0} squids on {1}'.format(
                                        self.cost[dir_cmd], dir_cmd)
                                }))

                    log.info('%s : %s' % (func.__name__, msg))
                    ret = func(msg, args)
            except Exception as e:
                log.error('Exception[%s]: %s' % (e, msg))
                exc_type, exc_obj, exc_tb = sys.exc_info()
                fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
                log.error(exc_type, fname, exc_tb.tb_lineno)
        return ret

    @run_async
    def on_chatMsg(self, omsg):
        msg = Msg(omsg)
        self.handle_msg(msg)

    def on_changeMedia(self, *args):
        try:
            self.media.remove(args[0]['id'])
        except Exception as e:
            return

    def on_newPoll(self, *args):
        self.poll = []
        for poll in args:
            if 'options' in poll:
                for opt in poll['options']:
                    self.poll.append(opt)

    def on_userlist(self, *args):
        self.userlist = args[0]
        self.userlist.append({'name': self.username})
        self.init = True

    def on_queue(self, *args):
        for arg in args:
            for media in arg:
                if 'media' in media:
                    if media['media']['id'] not in self.media:
                        self.media.append(media['media']['id'])

    def on_pm(self, omsg):
        msg = Msg(omsg)
        self.handle_msg(msg)

    def on_userLeave(self, *args):
        self.userlist[:] = [
            d for d in self.userlist if d['name'] != args[0]['name']
        ]

    def on_addUser(self, *args):
        self.userlist.append(args[0])

    def on_connect(self):
        log.info('[Connected]')

    def on_disconnect(self):
        raise Exception('disconnected')

    def on_login(self, *args):
        self.jackpot_announce()
        if (not args[0]['success']):
            log.error(args[0]['error'])
            raise SystemExit

    def on_event(self, *args):
        pass

    def on_emoteList(self, *args):
        pass

    def on_channelCSSJS(self, *args):
        pass

    def on_setMotd(self, *args):
        pass

    def on_setPlaylistMeta(self, *args):
        pass

    def on_playlist(self, *args):
        for arg in args:
            for media in arg:
                if 'media' in media:
                    if media['media']['id'] not in self.media:
                        self.media.append(media['media']['id'])
        log.info('Playlist Loaded')

    def on_channelOpts(self, *args):
        pass

    def on_mediaUpdate(self, *args):
        pass
Exemplo n.º 9
0
class Imgur:
    """The most awesome images on the internet!
    
    This plugin allows basic searching on Imgur including subreddits.
    
    Warning: Searching on subreddits cannot be easily moderated, therefore it is
    extremely easy for a user to post images from an nsfw subreddit to whatever
    channel the bot is enabled in if this plugin is enabled without modification.
    The subreddit command can be disabled by changing 'enabled=True' to 'enabled=False'
    in the plugin's main file: 'plugins/imgur.py' on line 53.
    """
    def __init__(self, bot):
        self.bot = bot
        self.client = ImgurClient(config["client_id"], config["client_secret"])
    
    @c.group(pass_context=True)
    async def imgur(self, ctx):
        """Search on Imgur!"""
        if ctx.invoked_subcommand is None:
            await self.bot.say("Zoinks! You've taken a wrong turn! Try `help imgur`.")
    
    # Helper function to actually get/post the images
    async def post_image(self, request, query=None):
        case = {
            "subreddit": lambda: self.client.subreddit_gallery(query),
            "search"   : lambda: self.client.gallery_search(query),
            "random"   : lambda: self.client.gallery_random(),
            "top"      : lambda: self.client.gallery("top"),
            "hot"      : lambda: self.client.gallery("hot"),
            "rehost"   : lambda: self.client.upload_from_url(query),
        }
        function = case.get(request, None)
        image = self.bot.loop.run_in_executor(None, function)
        while True:
            await asyncio.sleep(0.25)
            if image.done():
                image = image.result()
                break
        if request == "rehost":
            await self.bot.say(image.get("link", None))
        else:
            await self.bot.say(random.choice(image).link)

    @imgur.command(name="sub", aliases=["subreddit", "reddit", "r/"], enabled=True)
    async def imgur_subreddit(self, subreddit: str):
        """Get an image from a subreddit."""
        await self.post_image("subreddit", subreddit)

    @imgur.command(name="search")
    async def imgur_search(self, *, query: str):
        """Search Imgur for (almost) anything."""
        await self.post_image("search", query)
    
    @imgur.command(name="random")
    async def imgur_random(self):
        """One free random image."""
        await self.post_image("random")
    
    @imgur.command(name="viral")
    async def imgur_viral(self, section: str = "top"):
        """Get one of the most viral images of the day.
        
        Section may be either 'top' or 'hot' and will get an image based on that criteria."""
        section = section.lower()
        if section != "top":
            section = "hot"
        await self.post_image(section)
    
    @imgur.command(name="rehost")
    async def imgur_rehost(self, url: str):
        """Rehost an image from any link to Imgur."""
        await self.post_image("rehost", url)
Exemplo n.º 10
0
class Fun(commands.Cog):
    def __init__(self, bot):
        self.imgur_client = ImgurClient(IMGUR_CLIEND_ID, IMGUR_CLIENT_SECRET)

    @commands.command(aliases=alias("spongebob"), pass_context=True)
    @commands.cooldown(1, 3, commands.BucketType.user)
    async def spongebob(self, ctx):
        await self._blend_images(ctx=ctx,
                                 filename="spongebob1.png",
                                 attachments=ctx.message.attachments,
                                 bg_size=(399, 299),
                                 bg_coord=(97, 305))

    @commands.command(aliases=alias("ihadtogrind"), pass_context=True)
    @commands.cooldown(1, 3)
    async def ihadtogrind(self, ctx):
        await self._blend_images(
            ctx=ctx,
            filename="ihadtogrind.png",
            attachments=ctx.message.attachments,
            bg_size=(545, 531),
            bg_coord=(15, 64),
        )

    @commands.command(aliases=alias("granpatv"), pass_context=True)
    @commands.cooldown(1, 3)
    async def granpatv(self, ctx):
        await self._blend_images(
            ctx=ctx,
            filename="granpatv.png",
            attachments=ctx.message.attachments,
            bg_size=(430, 243),
            bg_coord=(45, 253),
        )

    @commands.command(aliases=alias("mrkrupp"), pass_context=True)
    @commands.cooldown(1, 3)
    async def mrkrupp(self, ctx):
        await self._blend_images(
            ctx=ctx,
            filename="mrkrupp.png",
            attachments=ctx.message.attachments,
            bg_size=(566, 418),
            bg_coord=(0, 0),
        )

    @commands.command(aliases=alias("spore"), pass_context=True)
    @commands.cooldown(1, 3)
    async def spore(self, ctx):
        await self._blend_images(
            ctx=ctx,
            filename="spore.png",
            attachments=ctx.message.attachments,
            bg_size=(1024, 1024),
            bg_coord=(0, 0),
        )

    @commands.command(aliases=alias("spywow"), pass_context=True)
    @commands.cooldown(1, 3)
    async def spywow(self, ctx):
        await self._blend_images(
            ctx=ctx,
            filename="spywow.png",
            attachments=ctx.message.attachments,
            bg_size=(600, 339),
            bg_coord=(0, 0),
        )

    @commands.command(aliases=alias("thisguy"), pass_context=True)
    @commands.cooldown(1, 3)
    async def thisguy(self, ctx):
        await self._blend_images(
            ctx=ctx,
            filename="thisguy.png",
            attachments=ctx.message.attachments,
            bg_size=(520, 451),
            bg_coord=(0, 191),
        )

    @commands.command(aliases=alias("thiswoman"), pass_context=True)
    @commands.cooldown(1, 3)
    async def thiswoman(self, ctx):
        await self._blend_images(
            ctx=ctx,
            filename="thiswoman.png",
            attachments=ctx.message.attachments,
            bg_size=(964, 467),
            bg_coord=(0, 444),
        )

    @commands.command(aliases=alias("icecream"), pass_context=True)
    @commands.cooldown(1, 3)
    async def icecream(self, ctx):
        await self._blend_images(
            ctx=ctx,
            filename="icecream.png",
            attachments=ctx.message.attachments,
            bg_size=(309, 261),
            bg_coord=(202, 250),
        )

    @commands.command(aliases=alias("obstetrician"), pass_context=True)
    @commands.cooldown(1, 3)
    async def obstetrician(self, ctx):
        await self._blend_images(
            ctx=ctx,
            filename="obstetrician.png",
            attachments=ctx.message.attachments,
            bg_size=(962, 727),
            bg_coord=(22, 13),
        )

    @commands.command(aliases=alias("anus"), pass_context=True)
    @commands.cooldown(1, 3)
    async def anus(self, ctx):
        await self._blend_images(
            ctx=ctx,
            filename="anus.png",
            attachments=ctx.message.attachments,
            bg_size=(225, 191),
            bg_coord=(0, 0),
        )

    @commands.command(aliases=alias("dream"), pass_context=True)
    @commands.cooldown(1, 3)
    async def dream(self, ctx):
        await self._blend_images(
            ctx=ctx,
            filename="dream.png",
            attachments=ctx.message.attachments,
            bg_size=(685, 450),
            bg_coord=(0, 308),
        )

    @commands.command(aliases=alias("slam"), pass_context=True)
    @commands.cooldown(1, 3)
    async def slam(self, ctx):
        await self._blend_images(
            ctx=ctx,
            filename="slam.png",
            attachments=ctx.message.attachments,
            bg_size=(315, 447),
            bg_coord=(338, 14),
        )

    @commands.command(aliases=alias("badmeme"), pass_context=True)
    @commands.cooldown(1, 3)
    async def badmeme(self, ctx):
        try:
            req = requests.get("https://api.imgflip.com/get_memes")
            await ctx.send(random.choice(req.json()["data"]["memes"])["url"])
        except Exception as err:
            print(err)

    @commands.command(aliases=alias("magic"), pass_context=True)
    @commands.cooldown(2, 5, commands.BucketType.user)
    # Forked from `NotSoBot`
    async def magic(self, ctx, scale=3):
        try:
            if scale > 10:
                await ctx.send(
                    tr("The scale argument can't be more than 10", ctx=ctx))
                scale = 1

            to_send = "Images/Temp/magic.png"
            url = await self._get_images(ctx)

            response = requests.get(url)
            img = Image.open(BytesIO(response.content))
            img.save(to_send, "PNG")
            img = image.Image(filename=to_send)

            img.liquid_rescale(width=int(img.width * 0.5),
                               height=int(img.height * 0.5),
                               delta_x=int(0.5 * scale) if scale else 1,
                               rigidity=0)

            img.liquid_rescale(width=int(img.width * 1.5),
                               height=int(img.height * 1.5),
                               delta_x=scale if scale else 2,
                               rigidity=0)
            img.save(filename=to_send)

            await ctx.send(file=discord.File(to_send))
            os.remove(to_send)
        except Exception as e:
            await ctx.send(tr("I pooped myself", ctx=ctx, err=e))

    async def _blend_images(self,
                            ctx: str,
                            filename=None,
                            attachments=None,
                            bg_size=None,
                            bg_coord=None,
                            bg_scale_x1=None,
                            bg_scale_y1=None,
                            bg_scale_x2=None,
                            bg_scale_y2=None,
                            bg_resize_w=None,
                            bg_resize_h=None):
        """
		Keyword arguments for "_blend_images" method:
		Args:
			filename       - background image path
			attachments    - attached urls, default
			bg_size        - background image width and height
			bg_coord       - background image coordinates
			bg_scale_x1    - rescale image by x1
			bg_scale_y1    - rescale image by y1
			bg_scale_x2    - rescale image by x2
			bg_scale_y2    - rescale image by y2
			bg_resize_w    - resize image width
			bg_resize_h    - resize image height
		"""

        await ctx.trigger_typing()
        to_send = "Images/Temp/{}".format(filename)

        response = await self._get_images(ctx)
        response = requests.get(response)

        foreground = os.path.join(IMAGES_TEMPLATE_PATH, filename)
        foreground = Image.open(foreground)

        background = Image.open(BytesIO(response.content))

        if 3000 in background.size:
            await ctx.send(
                tr(
                    "Image is too large ({w}x{h})",
                    ctx=ctx,
                    w=background.size[0],
                    h=background.size[1],
                ))
        else:
            background = background.resize(bg_size)

            blended = Image.new("RGBA", foreground.size)
            blended.paste(background, bg_coord)
            blended.paste(foreground, (0, 0), foreground)
            blended.save(to_send, "PNG")

            await ctx.send(file=discord.File(to_send))
            os.remove(to_send)

    @commands.command(aliases=alias("impact-meme"), pass_context=True)
    async def impact_meme(self, ctx, *string):
        # Forked from: https://github.com/Littlemansmg/Discord-Meme-Generator
        # Get image from URL
        try:
            await ctx.trigger_typing()

            to_send = "Images/Temp/meme.png"
            location = await self._get_images(ctx)
            response = requests.get(location)
            font_path = FONTS["impact"]

            if len(string):
                string_size = len(string) // 2
                top_string = " ".join(string[:string_size])
                bottom_string = " ".join(string[string_size:])

                with Image.open(BytesIO(response.content)) as img:
                    size = img.size
                    font_size = int(size[1] / 5)
                    # font = IFont.truetype(font=font_path, size=font_size)
                    font = ImageFont.truetype(font_path, font_size)
                    edit = ImageDraw.Draw(img)

                    # find biggest font size that works

                    top_text_size = font.getsize(top_string)
                    bottom_text_size = font.getsize(bottom_string)

                    while top_text_size[0] > size[0] - 20 or bottom_text_size[
                            0] > size[0] - 20:
                        font_size = font_size - 1
                        font = ImageFont.truetype(font_path, font_size)
                        top_text_size = font.getsize(top_string)
                        bottom_text_size = font.getsize(bottom_string)

                    # find top centered position for top text
                    top_text_posx = (size[0] / 2) - (top_text_size[0] / 2)
                    top_text_posy = 0
                    top_text_pos = (top_text_posx, top_text_posy)

                    # find bottom centered position for bottom text
                    bottom_text_posx = (size[0] / 2) - (bottom_text_size[0] /
                                                        2)
                    bottom_text_posy = size[1] - bottom_text_size[1] - 10
                    bottom_text_pos = (bottom_text_posx, bottom_text_posy)

                    # draw outlines
                    # there may be a better way
                    outline_range = int(font_size / 15)
                    for x in range(-outline_range, outline_range + 1):
                        for y in range(-outline_range, outline_range + 1):
                            edit.text(
                                (top_text_pos[0] + x, top_text_pos[1] + y),
                                top_string, (0, 0, 0),
                                font=font)
                            edit.text((bottom_text_pos[0] + x,
                                       bottom_text_pos[1] + y),
                                      bottom_string, (0, 0, 0),
                                      font=font)

                    edit.text(top_text_pos,
                              top_string, (255, 255, 255),
                              font=font)
                    edit.text(bottom_text_pos,
                              bottom_string, (255, 255, 255),
                              font=font)
                    img.save(to_send, "PNG")

                await ctx.send(file=discord.File(to_send))
                os.remove(to_send)
            else:
                await ctx.send(tr("Type something", ctx=ctx))
        except Exception as err:
            print(err)

    async def _get_images(self, ctx, history_limit=None, formats=None):
        if not history_limit:
            history_limit = 200

        if not formats:
            formats = ("png", "gif", "jpeg", "jpg")

        async for c in ctx.history(limit=history_limit):  # limit=10
            if len(c.attachments) > 0:
                background_url = c.attachments[0].url
                background_ext = background_url.split(".")[-1]
                return background_url if background_ext in formats else None

    @commands.command(aliases=alias("whois"), pass_context=True)
    async def whois(self, ctx, *text):
        try:
            if text is None:
                text = "гей"

            member = await self._get_members(ctx)
            member = random.choice(member)
            await ctx.send(
                tr("I think it's a {member}", ctx=ctx, member=member))

        except Exception as err:
            await ctx.send(tr("I pooped myself", ctx=ctx, err=err))

    @commands.command(aliases=alias("when"), pass_context=True)
    async def when(self, ctx):
        try:
            min_year = 1993
            max_year = datetime.datetime.now().year
            start = datetime.datetime(min_year, 1, 1)
            years = max_year - min_year + 1
            end = start + datetime.timedelta(days=365 * years)
            result = start + (end - start) * random.random()
            result = datetime.datetime.strftime(
                result, tr("It happend in '{tf}'", ctx=ctx,
                           tf="%D - %d:%m:%y"))
            await ctx.send(result)
        except Exception as err:
            await ctx.send(tr("I pooped myself", ctx=ctx, err=err))

    async def _get_members(self, ctx):
        return [i.name for i in ctx.guild.members]

    @commands.command(aliases=alias("imgur"), pass_context=True)
    @commands.cooldown(2, 5)
    async def imgur(self, ctx, text):
        if text is None:
            load = self.imgur_client.gallery_random(page=0)
        else:
            load = self.imgur_client.gallery_search(text,
                                                    advanced=None,
                                                    sort="viral",
                                                    window="all",
                                                    page=0)
        rand = random.choice(load)
        try:
            if "image/" in rand.type:
                await ctx.send(rand.link)
        except AttributeError:
            if rand.title:
                title = "**{}**\n".format(rand.title)
            else:
                title = ""
            await ctx.send("{}{}".format(title, rand.link))

    @commands.command(aliases=alias("minecraft"), pass_context=True)
    @commands.cooldown(1, 3)
    async def minecraft(self, ctx, *text):
        try:
            if len(text) == 0:
                text = "Насрал в штаны"
            else:
                text = " ".join(text)

            symbols = (
                u"абвгдеёжзийклмнопрстуфхцчшщъыьэюяАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ",
                u"abvgdeejzijklmnoprstufhzcss_y_euaABVGDEEJZIJKLMNOPRSTUFHZCSS_Y_EUA"
            )

            tr = {ord(a): ord(b) for a, b in zip(*symbols)}

            url = "https://mcgen.herokuapp.com/a.php?i=1&h=%s&t=%s" % (
                text.capitalize().translate(tr), str(
                    ctx.message.author.name).translate(tr))

            response = requests.get(url)
            image = Image.open(BytesIO(response.content))
            image.save("Images/Temp/minecraft.png", "PNG")

            await ctx.send(file=discord.File("Images/Temp/minecraft.png"))
            os.remove("Images/Temp/minecraft.png")

        except Exception as err:
            await ctx.send(tr("I pooped myself", ctx=ctx, err=err))