本文整理汇总了Python中twisted.words.protocols.irc.assembleFormattedText函数的典型用法代码示例。如果您正苦于以下问题:Python assembleFormattedText函数的具体用法?Python assembleFormattedText怎么用?Python assembleFormattedText使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了assembleFormattedText函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
示例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)
示例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
示例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)
示例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
示例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)
示例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)]
]
))
示例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)
示例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
示例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])
示例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)})
示例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)
示例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)
示例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
示例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)