• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python irc.assembleFormattedText函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中twisted.words.protocols.irc.assembleFormattedText函数的典型用法代码示例。如果您正苦于以下问题:Python assembleFormattedText函数的具体用法?Python assembleFormattedText怎么用?Python assembleFormattedText使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了assembleFormattedText函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: urbandictionary_lookup

 def urbandictionary_lookup(self, channel, nick, msg, args):
     query = args['query']
     try:
         r = requests.get(API_URL % query)
         r.raise_for_status()
     except requests.exceptions.HTTPError:
         self.bot.msg(channel, 'No results for %s' % query)
         return False
     data = r.json()
     if 'result_type' in data:
         if data['result_type'] == "no_results":
             self.bot.msg('No results for %s' % query)
             return False
         else:
             definition = data['list'][0]
             word = definition['word'].encode('UTF-8')
             def_text = definition['definition'].encode('UTF-8')
             permalink = definition['permalink'].encode('UTF-8')
             formatted_msg = assembleFormattedText(A.bold[word])
             formatted_msg += assembleFormattedText(A.normal[": "])
             formatted_msg += def_text.split('\r\n')[0]
             formatted_msg += assembleFormattedText(A.bold[" See more: "])
             formatted_msg += assembleFormattedText(A.normal[permalink])
             self.bot.msg(channel, formatted_msg)
     else:
         self.bot.msg(channel, 'No results for %s' % query)
         return False
开发者ID:twexler,项目名称:diatribe,代码行数:27,代码来源:urbandictionary.py


示例2: execute

    def execute(self, message):
        """
        @type message: IRCMessage
        """

        subString = self._mangleEscapes(message.Parameters)

        try:
            segments = list(self._parseSubcommandTree(subString))
        except UnbalancedBracesException as e:
            red = assembleFormattedText(A.bold[A.fg.lightRed['']])
            normal = assembleFormattedText(A.normal[''])
            error = subString[:e.column] + red + subString[e.column] + normal + subString[e.column+1:]
            error = self._unmangleEscapes(error, False)
            return [IRCResponse(ResponseType.Say, u"Sub Error: {}".format(e.message), message.ReplyTo),
                    IRCResponse(ResponseType.Say, error, message.ReplyTo)]

        prevLevel = -1
        responseStack = []
        extraVars = {}
        metadata = {}

        for segment in segments:
            (level, command, start, end) = segment

            # We've finished executing subcommands at the previous depth,
            # so replace subcommands with their output at the current depth
            if level < prevLevel:
                command = self._substituteResponses(command, responseStack, level, extraVars, start)

            # Replace any extraVars in the command
            for var, value in iteritems(extraVars):
                command = re.sub(r'\$\b{}\b'.format(re.escape(var)), u'{}'.format(value), command)

            # Build a new message out of this segment
            inputMessage = IRCMessage(message.Type, message.User.String, message.Channel,
                                      self.bot.commandChar + command.lstrip(),
                                      self.bot,
                                      metadata=metadata)

            # Execute the constructed message
            if inputMessage.Command.lower() in self.bot.moduleHandler.mappedTriggers:
                response = self.bot.moduleHandler.mappedTriggers[inputMessage.Command.lower()].execute(inputMessage)
                """@type : IRCResponse"""
            else:
                return IRCResponse(ResponseType.Say,
                                   u"'{}' is not a recognized command trigger".format(inputMessage.Command),
                                   message.ReplyTo)

            # Push the response onto the stack
            responseStack.append((level, response.Response, start, end))
            # Update the extraVars dict
            extraVars.update(response.ExtraVars)
            metadata = self._recursiveMerge(metadata, response.Metadata)

            prevLevel = level

        responseString = self._substituteResponses(subString, responseStack, -1, extraVars, -1)
        responseString = self._unmangleEscapes(responseString)
        return IRCResponse(ResponseType.Say, responseString, message.ReplyTo, extraVars=extraVars, metadata=metadata)
开发者ID:MatthewCox,项目名称:PyMoronBot,代码行数:60,代码来源:Sub.py


示例3: _guess

    def _guess(self, message):
        """
        @type message: IRCMessage
        @rtype: IRCResponse
        """
        channel = message.ReplyTo.lower()
        if channel not in self.gameStates:
            return IRCResponse(ResponseType.Say,
                               u'[Hangman] no game running, use {}hangman start to begin!'.format(self.bot.commandChar),
                               message.ReplyTo)

        responses = []
        gs = self.gameStates[channel]

        guess = message.Parameters.lower()
        # single letter
        if len(guess) == 1:
            try:
                correct = gs.guessLetter(guess)
            except (AlreadyGuessedException,
                    InvalidCharacterException) as e:
                return self._exceptionFormatter(e, message.ReplyTo)
        # whole phrase
        else:
            try:
                correct = gs.guessPhrase(guess)
            except (WrongPhraseLengthException,
                    PhraseMismatchesGuessesException,
                    PhraseUsesKnownBadLettersException) as e:
                return self._exceptionFormatter(e, message.ReplyTo)

        user = message.User.Name
        # split the username with a zero-width space
        # hopefully this kills client highlighting on nick mentions
        #user = user[:1] + u'\u200b' + user[1:]
        # try a tiny arrow instead, some clients actually render zero-width spaces
        colUser = user[:1] + u'\u034e' + user[1:]
        if correct:
            colUser = assembleFormattedText(A.normal[A.fg.green[colUser]])
        else:
            colUser = assembleFormattedText(A.normal[A.fg.red[colUser]])
        responses.append(IRCResponse(ResponseType.Say,
                                     u'{} - {}'.format(gs.render(), colUser),
                                     message.ReplyTo))

        if gs.finished:
            if correct:
                responses.append(IRCResponse(ResponseType.Say,
                                             u'[Hangman] Congratulations {}!'.format(user),
                                             message.ReplyTo))
            else:
                responses.append(IRCResponse(ResponseType.Say,
                                             u'[Hangman] {} blew up the bomb! The {} was {}'.format(user,
                                                                                                    gs.wOrP(),
                                                                                                    gs.phrase),
                                             message.ReplyTo))
            self._stop(message, suppressMessage=True)

        return responses
开发者ID:MatthewCox,项目名称:PyMoronBot,代码行数:59,代码来源:Hangman.py


示例4: _renderGuesses

 def _renderGuesses(self):
     colouredGuesses = []
     for g in self.guesses:
         if g in self.phrase:
             colouredGuesses.append(assembleFormattedText(A.bold[A.fg.green[g]]))
         else:
             colouredGuesses.append(assembleFormattedText(A.fg.red[g]))
     reset = assembleFormattedText(A.normal[''])
     return u'[{}{}]'.format(u''.join(colouredGuesses), reset)
开发者ID:MatthewCox,项目名称:PyMoronBot,代码行数:9,代码来源:Hangman.py


示例5: whoresponse

    def whoresponse(self, channel):
        who_users = communicator.handleWho(self, channel)

        if len(who_users) > 0:
            return [irc.assembleFormattedText(
                irc.attributes.bold[irc.attributes.underline["List of relayed users on ", channel]]),
                "  ".join(who_users),
                irc.assembleFormattedText(irc.attributes.bold[irc.attributes.underline[
                    "END List of relayed users on ", channel]])]
        return None
开发者ID:tslocum,项目名称:RelayBot,代码行数:10,代码来源:relaybot.py


示例6: FollowKickstarter

    def FollowKickstarter(self, ksID, message):
        webPage = WebUtils.fetchURL('https://www.kickstarter.com/projects/{0}/'.format(ksID))

        soup = BeautifulSoup(webPage.body)

        data = []

        title = soup.find(class_='title')
        if title is not None:
            creator = soup.find(id='name')
            if creator is not None:
                data.append(assembleFormattedText(A.normal['{0}', A.fg.gray[' by '], '{1}']).format(title.h2.text.strip(), creator.text.strip()))
            else:
                data.append(title.h2.text.strip())

        stats = soup.find(id='stats')

        backerCount = stats.find(id='backers_count')
        if backerCount is not None:
            data.append('Backers: {0:,}'.format(int(backerCount['data-backers-count'])))

        pledged = stats.find(id='pledged')
        if pledged is not None:
            if float(pledged['data-percent-raised']) >= 1.0:
                percentageString = A.fg.green['({3:,.0f}% funded)']
            else:
                percentageString = A.fg.red['({3:,.0f}% funded)']
                
            pledgedString = assembleFormattedText(A.normal['Pledged: {0:,.0f}', A.fg.gray['/'], '{1:,.0f} {2} ', percentageString])
            data.append(pledgedString.format(float(pledged['data-pledged']),
                                             float(pledged['data-goal']),
                                             pledged.data['data-currency'],
                                             float(pledged['data-percent-raised']) * 100))

        findState = soup.find(id='main_content')
        if 'Project-state-canceled' in findState['class']:
            data.append(assembleFormattedText(A.normal[A.fg.red['Cancelled']]))
            
        elif 'Project-state-failed' in findState['class']:
            data.append(assembleFormattedText(A.normal[A.fg.red['Failed']]))

        elif 'Project-state-successful' in findState['class']:
                data.append(assembleFormattedText(A.normal[A.fg.green['Successful']]))

        elif 'Project-state-live' in findState['class']:
            duration = stats.find(id='project_duration_data')

            if duration is not None:
                remaining = float(duration['data-hours-remaining'])
                days = math.floor(remaining/24)
                hours = remaining/24 - days

                data.append('Duration: {0:.0f} days {1:.1f} hours to go'.format(days, hours))

        return IRCResponse(ResponseType.Say, self.graySplitter.join(data), message.ReplyTo)
开发者ID:HubbeKing,项目名称:PyMoronBot,代码行数:55,代码来源:URLFollow.py


示例7: stock

def stock(bot, args, sender, source):
    try:
        resp = yql(args[0])
    except:
        bot.reply(source, sender, "Couldn't get stock data: {}".format(sys.exc_info()[0]))
        raise

    if resp["count"] == 0:
        bot.reply(source, sender, assembleFormattedText(
            A.normal["Couldn't find the ticker symbol ", A.bold[args[0]]]
        ))
        return

    quote = resp["results"]["quote"]

    if quote["LastTradePriceOnly"] is None:
        bot.reply(source, sender, assembleFormattedText(
            A.normal["Couldn't find the ticker symbol ", A.bold[args[0]]]
        ))
        return

    change = float(quote["Change"])
    price = float(quote["LastTradePriceOnly"])
    name = quote["Name"]

    if price == 0 and change == 0:
        # Company is dead
        bot.reply(source, sender, assembleFormattedText(
            A.normal[A.bold[name], " is no longer trading."]
        ))
        return

    color = A.fg.gray

    percent = (change / (price - change)) * 100

    if change > 0:
        color = A.fg.green
        change = "+{}".format(change)
    elif change < 0:
        color = A.fg.lightRed

    bot.reply(source, sender, assembleFormattedText(
        A.normal[
            A.bold[name], " (",  A.bold[quote["Symbol"]], "): ",
            str(price), " ", color["{} ({:.2f}%)".format(change, percent)]
        ]
    ))
开发者ID:w4,项目名称:belle,代码行数:48,代码来源:stock.py


示例8: execute

    def execute(self, message):
        """
        @type message: IRCMessage
        """
        if len(message.ParameterList) != 1:
            return IRCResponse(ResponseType.Say, self.help, message.ReplyTo)

        subreddit = message.ParameterList[0].lower()

        url = "https://api.imgur.com/3/gallery/r/{}/time/all/{}"
        url = url.format(subreddit, random.randint(0, 100))
        response = WebUtils.fetchURL(url, self.headers)
        jsonResponse = json.loads(response.body)
        images = jsonResponse['data']

        if not images:
            return IRCResponse(ResponseType.Say,
                               "The subreddit '{}' doesn't seem to have any images posted to it (or it doesn't exist!)"
                               .format(subreddit),
                               message.ReplyTo)

        image = random.choice(images)

        data = []
        if image['title'] is not None:
            data.append(image['title'])
        if image['nsfw']:
            data.append(u'\x034\x02NSFW!\x0F')
        if image['animated']:
            data.append(u'\x032\x02Animated!\x0F')
        data.append(image['link'])

        graySplitter = assembleFormattedText(A.normal[' ', A.fg.gray['|'], ' '])
        return IRCResponse(ResponseType.Say, graySplitter.join(data), message.ReplyTo)
开发者ID:DotsTheHero,项目名称:PyMoronBot,代码行数:34,代码来源:RedditImage.py


示例9: FollowTwitter

    def FollowTwitter(self, tweeter, tweetID):
        url = 'https://twitter.com/{}/status/{}'.format(tweeter, tweetID)
        webPage = self.bot.moduleHandler.runActionUntilValue('fetch-url', url)

        soup = BeautifulSoup(webPage.body, 'lxml')

        tweet = soup.find(class_='permalink-tweet')
        
        user = tweet.find(class_='username').text

        tweetText = tweet.find(class_='tweet-text')
        
        tweetTimeText = tweet.find(class_='client-and-actions').text.strip()
        try:
            tweetTimeText = time.strftime('%Y/%m/%d %H:%M', time.strptime(tweetTimeText, '%I:%M %p - %d %b %Y'))
        except ValueError:
            pass
        tweetTimeText = re.sub(r'[\r\n\s]+', u' ', tweetTimeText)

        links = tweetText.find_all('a', {'data-expanded-url': True})
        for link in links:
            link.string = ' ' + link['data-expanded-url']

        embeddedLinks = tweetText.find_all('a', {'data-pre-embedded': 'true'})
        for link in embeddedLinks:
            link.string = ' ' + link['href']

        text = string.unescapeXHTML(tweetText.text)
        text = re.sub('[\r\n]+', self.graySplitter, text)

        formatString = str(assembleFormattedText(A.normal[A.fg.gray['[{0}]'], A.bold[' {1}:'], ' {2}']))

        return formatString.format(tweetTimeText, user, text), url
开发者ID:MatthewCox,项目名称:PyMoronBot,代码行数:33,代码来源:URLFollow.py


示例10: applyColorFormat

 def applyColorFormat(self, *msg, **kwargs):
     """put some nice colors on the message"""
     colors = kwargs.get('colors')
     toAssemble = []
     log.debug(msg)
     log.debug(colors)
     msg = [m.encode('utf-8') for m in msg]
     if not colors or len(colors) != len(msg):
         log.debug("no colors")
         for m in msg:
             log.debug(m)
             log.debug(type(m))
             toAssemble.append(irc.attributes.fg.gray[m])
     else:
         log.debug("colors!")
         for m, c in zip(msg, colors):
             log.debug(m)
             log.debug(c)
             if not c:
                 log.debug("no c")
                 toAssemble.append(irc.attributes.fg.gray[m])
             else:
                 log.debug("using special color")
                 log.debug(c)
                 toAssemble.append(c[m])
     return irc.assembleFormattedText(irc.attributes.normal[toAssemble])
开发者ID:aa-m-sa,项目名称:boxbot,代码行数:26,代码来源:boxbot.py


示例11: FollowTwitter

    def FollowTwitter(self, tweeter, tweetID, message):
        webPage = WebUtils.fetchURL('https://twitter.com/{0}/status/{1}'.format(tweeter, tweetID))

        soup = BeautifulSoup(webPage.body)

        tweet = soup.find(class_='permalink-tweet')
        
        user = tweet.find(class_='username').text

        tweetText = tweet.find(class_='tweet-text')
        
        tweetTimeText = tweet.find(class_='client-and-actions').text.strip()
        try:
            tweetTimeText = time.strftime('%Y/%m/%d %H:%M', time.strptime(tweetTimeText, '%I:%M %p - %d %b %Y'))
        except ValueError:
            pass

        links = tweetText.find_all('a', {'data-expanded-url': True})
        for link in links:
            link.string = ' ' + link['data-expanded-url']

        embeddedLinks = tweetText.find_all('a', {'data-pre-embedded': 'true'})
        for link in embeddedLinks:
            link.string = ' ' + link['href']

        text = StringUtils.unescapeXHTML(tweetText.text)
        text = re.sub('[\r\n]+', self.graySplitter, text)

        formatString = unicode(assembleFormattedText(A.normal[A.fg.gray['[{0}]'], A.bold[' {1}:'], ' {2}']))

        return IRCResponse(ResponseType.Say,
                           formatString.format(tweetTimeText, user, text),
                           message.ReplyTo,
                           {'urlfollowURL': 'https://twitter.com/{}/status/{}'.format(tweeter, tweetID)})
开发者ID:Heufneutje,项目名称:PyMoronBot,代码行数:34,代码来源:URLFollow.py


示例12: wolfram

def wolfram(bot, args, sender, source):
    query = args[0].strip()

    key = "wolfram:{}".format(query.lower())

    if dave.config.redis.exists(key):
        bot.reply(source, sender, dave.config.redis.get(key).decode('utf-8'))
        dave.config.redis.setex(key, 60, dave.config.redis.get(key))
        return

    if query:
        client = wolframalpha.Client(dave.config.config["api_keys"]["wolfram"])
        res = client.query(query)

        pods = list(res.pods)

        if len(pods) > 0:
            resultpod = next(res.results)
            result = resultpod.text

            if "image" in pods[0].text:
                result = resultpod.img

            if len(result) > 500:
                result = result[:497] + "..."

            res = assembleFormattedText(A.normal[A.bold[pods[0].text],
                                        ": {}".format(result)])
            dave.config.redis.setex(key, 60, res)
            bot.reply(source, sender, res)
开发者ID:w4,项目名称:belle,代码行数:30,代码来源:wolfram.py


示例13: FollowTwitter

    def FollowTwitter(self, tweeter, tweetID, message):
        webPage = WebUtils.fetchURL('https://twitter.com/{0}/status/{1}'.format(tweeter, tweetID))

        soup = BeautifulSoup(webPage.body)

        tweet = soup.find(class_='permalink-tweet')
        
        user = tweet.find(class_='username').text

        tweetText = tweet.find(class_='tweet-text')

        links = tweetText.find_all('a', {'data-expanded-url': True})
        for link in links:
            link.string = link['data-expanded-url']

        embeddedLinks = tweetText.find_all('a', {'data-pre-embedded': 'true'})
        for link in embeddedLinks:
            link.string = link['href']

        text = StringUtils.unescapeXHTML(tweetText.text)
        text = re.sub('[\r\n]+', self.graySplitter, text)

        formatString = unicode(assembleFormattedText(A.normal[A.bold['{0}:'], ' {1}']))

        return IRCResponse(ResponseType.Say, formatString.format(user, text), message.ReplyTo)
开发者ID:ekimekim,项目名称:PyMoronBot,代码行数:25,代码来源:URLFollow.py


示例14: _stringifyTweet

    def _stringifyTweet(self, tweet):
        """
        turn a tweet object into a nice string for us to send to IRC
        @type tweet: dict[str, T/str]
        """
        retweet = None
        # get the original tweet if this is a retweet
        if 'retweeted_status' in tweet:
            retweet = tweet
            tweet = retweet['retweeted_status']

        tweetText = StringUtils.unescapeXHTML(tweet['text'])
        tweetText = re.sub('[\r\n]+', StringUtils.graySplitter, tweetText)
        for url in tweet['entities']['urls']:
            tweetText = tweetText.replace(url['url'], url['expanded_url'])

        timestamp = parser.parse(tweet['created_at'])
        timeString = timestamp.strftime('%A, %Y-%m-%d %H:%M:%S %Z')
        delta = datetime.datetime.utcnow() - timestamp.replace(tzinfo=None)
        deltaString = StringUtils.deltaTimeToString(delta)
        tweetText = u'{} (tweeted {}, {} ago)'.format(tweetText, timeString, deltaString)

        if retweet is None:
            user = tweet['user']['screen_name']
        else:
            user = retweet['user']['screen_name']
            tweetText = 'RT {}: {}'.format(tweet['user']['screen_name'], tweetText)
            
        link = u'https://twitter.com/{}/status/{}'.format(tweet['user']['screen_name'], tweet['id_str'])
        link = WebUtils.shortenGoogl(link)

        formatString = unicode(assembleFormattedText(A.normal[A.bold['@{0}>'], ' {1} {2}']))
        newTweet = formatString.format(user, tweetText, link)
        return newTweet
开发者ID:DotsTheHero,项目名称:PyMoronBot,代码行数:34,代码来源:Twitter.py


示例15: execute

    def execute(self, message):
        """
        @type message: IRCMessage
        """
        if len(message.ParameterList) == 0 or len(message.ParameterList) > 2:
            return IRCResponse(ResponseType.Say, self.help(None), message.ReplyTo)

        if not self.imgurClientID:
            return IRCResponse(ResponseType.Say,
                               u'[imgur client ID not found]',
                               message.ReplyTo)

        subreddit = message.ParameterList[0].lower()
        if len(message.ParameterList) == 2:
            try:
                if len(message.ParameterList[1]) < 20:
                    topRange = int(message.ParameterList[1])
                else:
                    raise ValueError
                if topRange < 0:
                    raise ValueError
            except ValueError:
                return IRCResponse(ResponseType.Say, "The range should be a positive integer!", message.ReplyTo)
        else:
            topRange = 100

        url = "https://api.imgur.com/3/gallery/r/{}/time/all/{}"
        url = url.format(subreddit, random.randint(0, topRange))
        try:
            response = self.bot.moduleHandler.runActionUntilValue('fetch-url', url, extraHeaders=self.headers)
            jsonResponse = json.loads(response.body)
        except json.JSONDecodeError:
            return IRCResponse(ResponseType.Say,
                               "[The imgur API doesn't appear to be responding correctly]",
                               message.ReplyTo)

        images = jsonResponse['data']

        if not images:
            return IRCResponse(ResponseType.Say,
                               "The subreddit '{}' doesn't seem to have any images posted to it (or it doesn't exist!)"
                               .format(subreddit),
                               message.ReplyTo)

        image = random.choice(images)

        data = []
        if 'title' in image and image['title'] is not None:
            data.append(image['title'])
        if 'nsfw' in image and image['nsfw']:
            data.append(u'\x034\x02NSFW!\x0F')
        if 'animated' in image and image['animated']:
            data.append(u'\x032\x02Animated!\x0F')
        if 'gifv' in image:
            data.append(image['gifv'])
        else:
            data.append(image['link'])

        graySplitter = assembleFormattedText(A.normal[' ', A.fg.gray['|'], ' '])
        return IRCResponse(ResponseType.Say, graySplitter.join(data), message.ReplyTo)
开发者ID:MatthewCox,项目名称:PyMoronBot,代码行数:60,代码来源:RedditImage.py


示例16: link_parse

def link_parse(bot, args, sender, source):
    matches = parse.findall(args[0])

    titles = []

    for match in matches:
        if "gfycat" in match or ".webm" in match:
            continue

        if not dave.config.redis.exists("site:{}".format(match)):
            try:
                res = get(match, timeout=3,
                          headers={'user-agent': 'irc bot (https://github.com/w4)'})
            except BaseException as e:
                log.msg("Couldn't connect to host.", e)
                return

            # sometimes requests guesses the charset wrong
            if res.encoding == 'ISO-8859-1' and not 'ISO-8859-1' in \
                    res.headers.get('Content-Type', ''):
                res.encoding = res.apparent_encoding

            try:
                soup = BeautifulSoup(res.text, "html.parser")
                title = soup.title.string

                if title is not None:
                    title = re.sub(r"(\r?\n|\r| )+",
                                   " ",
                                   title.strip())
                    title = title[:140] + (title[140:] and '...')
                    dave.config.redis.setex("site:{}".format(match), 300, title)
            except BaseException as e:
                log.msg("Failed to grab title", e)
                return
        else:
            title = str(dave.config.redis.get("site:{}".format(match)), 'utf8')

        if title is not None:
            titles.append(assembleFormattedText(A.normal[title]))

    if titles:
        # remove duplicates
        titles = list(set(titles))

        bot.msg(source, "Title: {}".format(
                        assembleFormattedText(A.normal[", "]).join(titles)))
开发者ID:w4,项目名称:belle,代码行数:47,代码来源:title.py


示例17: _fetch

 def _fetch(self, j, short, mode, label):
     r = j[mode]
     data = []
     t = A.normal[A.bold['{} {}: '.format(label, r[0]['rule']['name'])],
                  '/'.join([r[0]['stage_a']['name'], r[0]['stage_b']['name']])]
     data.append(assembleFormattedText(t))
     if not short:
         # include next maps
         now = int(time.time())
         startTime = r[1]['startTime']
         delta = startTime - now
         d = datetime.timedelta(seconds=delta)
         deltaStr = string.deltaTimeToString(d, resolution='m')
         t = A.normal[A.bold['{} {} in {}: '.format(label, r[1]['rule']['name'], deltaStr)],
                      '/'.join([r[1]['stage_a']['name'], r[1]['stage_b']['name']])]
         data.append(assembleFormattedText(t))
     return ' | '.join(data)
开发者ID:DesertBot,项目名称:DesertBot,代码行数:17,代码来源:Splatoon.py


示例18: privmsg

    def privmsg(self, user, channel, message):
        # If someone addresses the bot directly, respond in the same way.
        if channel == self.nickname:
            if message.lower().startswith("who ") and len(message.split(" ")) > 1:
                who_channel = message.split(" ")[1]
                if ("#" + who_channel) in self.ircUsers.users and who_channel not in self.ircUsers.users:
                    who_channel = "#" + who_channel
                self.sendWhoToUser(who_channel, user)
            elif (message.lower().startswith("msg ") or message.lower().startswith("m ")) and len(
                    message.split(" ")) > 2:
                msg_user = message.split(" ", 2)[1]
                msg_message = message.split(" ", 2)[2]

                if not communicator.sendmessage(self, formatUsername(msg_user),
                                                "[%s] %s" % (formatUsername(user), msg_message.strip())):
                    self.sendToUser(user, irc.assembleFormattedText(
                        irc.attributes.normal["Unable to find user ", irc.attributes.bold[
                            msg_user], " on any relayed channel."]))
            else:
                self.sendToUser(user, self.privMsgResponse)
                self.sendToUser(user, irc.assembleFormattedText(irc.attributes.normal["Say ", irc.attributes.bold[
                    "WHO ", irc.attributes.underline["#channel"]], " to see who is on ", irc.attributes.underline[
                                                                                          "#channel"], " via a separate network."]))
                self.sendToUser(user, irc.assembleFormattedText(irc.attributes.normal["Say ", irc.attributes.bold[
                    "MSG ", irc.attributes.underline["user"], " ", irc.attributes.underline[
                        "message"]], " to send a private ", irc.attributes.underline[
                                                                                          "message"], " to ",
                                                                                      irc.attributes.underline[
                                                                                          "user"], "."]))
        elif channel in self.channels:
            if message.lower().strip() in [".who", "!who", "?who", ".names", "!names", "?names", ".users", "!users",
                                           "?users"]:
                self.sendWhoToUser(channel, user)
            else:
                self.relay(channel, "[%s] %s" % (formatUsername(user), message))
                if message.startswith(self.nickname + ':'):
                    self.sayToChannel(channel,
                                      self.privMsgResponse + " -- Send a private message for more information.")
                    # For consistency, if anyone responds to the bot's response:
                    self.relay(channel, "[%s] %s" % (formatUsername(self.nickname),
                                                     self.privMsgResponse + " -- Send a private message for more information."))
开发者ID:tslocum,项目名称:RelayBot,代码行数:41,代码来源:relaybot.py


示例19: FollowTwitch

    def FollowTwitch(self, channel, message):
        # Heavily based on Didero's DideRobot code for the same
        # https://github.com/Didero/DideRobot/blob/06629fc3c8bddf8f729ce2d27742ff999dfdd1f6/commands/urlTitleFinder.py#L37
        # TODO: other stats?
        chanData = {}
        channelOnline = False
        twitchHeaders = [('Accept', 'application/vnd.twitchtv.v2+json')]
        webPage = WebUtils.fetchURL(u'https://api.twitch.tv/kraken/streams/{0}'.format(channel), twitchHeaders)

        streamData = json.loads(webPage.body)

        if 'stream' in streamData and streamData['stream'] is not None:
            chanData = streamData['stream']['channel']
            channelOnline = True
        elif 'error' not in streamData:
            webPage = WebUtils.fetchURL(u'https://api.twitch.tv/kraken/channels/{0}'.format(channel), twitchHeaders)
            chanData = json.loads(webPage.body)

        if len(chanData) > 0:
            if channelOnline:
                channelInfo = assembleFormattedText(A.fg.green['']) + '{0}'.format(chanData['display_name']) + assembleFormattedText(A.normal[''])
            else:
                channelInfo = assembleFormattedText(A.fg.red['']) + '{0}'.format(chanData['display_name']) + assembleFormattedText(A.normal[''])
            channelInfo += u' "{0}"'.format(re.sub('[\r\n]+', self.graySplitter, chanData['status'].strip()))
            if chanData['game'] is not None:
                channelInfo += assembleFormattedText(A.normal[A.fg.gray[', playing '], '{0}'.format(chanData['game'])])
            if chanData['mature']:
                channelInfo += assembleFormattedText(A.normal[A.fg.lightRed[' [Mature]']])
            if channelOnline:
                channelInfo += assembleFormattedText(A.normal[A.fg.green[' (Live with {0:,d} viewers)'.format(streamData['stream']['viewers'])]])
            else:
                channelInfo += assembleFormattedText(A.normal[A.fg.red[' (Offline)']])

            return IRCResponse(ResponseType.Say, channelInfo, message.ReplyTo)
开发者ID:ekimekim,项目名称:PyMoronBot,代码行数:34,代码来源:URLFollow.py


示例20: current_conditions

 def current_conditions(self, channel, nick, msg, args):
     query = ' '.join(args['query'].split('  ')).lstrip()
     if 'wunderground_key' not in self.bot.plugin_config:
         logging.debug('configure weather plugin')
         self.bot.msg(channel,
                      'Weather plugin not configured')
         return False
     try:
         args = {'key': self.bot.plugin_config['wunderground_key'],
                 'query': query}
         r = requests.get(API_URL % args)
         r.raise_for_status()
         data = r.json()['current_observation']
     except:
         logging.exception('Caught exception while searching for weather')
         self.bot.msg(channel,
                      'Cannot find weather for %s' % query)
         return False
     response = assembleFormattedText(A.bold[data['display_location']['full'].encode('UTF-8')])
     response += assembleFormattedText(A.normal[" (%s): " % query])
     response += "%(weather)s, %(temperature_string)s, Humidity: %(relative_humidity)s, %(observation_time)s" % data
     self.bot.msg(channel, response.encode('UTF-8'))
开发者ID:twexler,项目名称:diatribe,代码行数:22,代码来源:weather.py



注:本文中的twisted.words.protocols.irc.assembleFormattedText函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python irc.IRCClient类代码示例发布时间:2022-05-27
下一篇:
Python xmlrpc.Proxy类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap