本文整理汇总了Python中willie.web.get函数的典型用法代码示例。如果您正苦于以下问题:Python get函数的具体用法?Python get怎么用?Python get使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: osu_beatmap
def osu_beatmap(bot, trigger):
data = '?k=%s&%s=%s' % (bot.config.osu.api_key, str(trigger.group(1)), str(trigger.group(2)))
#bot.say(url)
raw = web.get('https://osu.ppy.sh/api/get_beatmaps' + data)
topscore = None
if trigger.group(1) == 'b':
rawscore = web.get('https://osu.ppy.sh/api/get_scores' + data)
topscore = json.loads(rawscore)[0]
response = json.loads(raw)
if not response[0]:
bot.say('[' + color('osu!', u'13') + '] ' + ' Invalid link')
return
beatmap = response[0]
m, s = divmod(int(beatmap['total_length']), 60)
output = [
'[', color('osu!', u'13'), '] ',
beatmap['artist'],
' - ',
beatmap['title'],
' (Mapped by ',
beatmap['creator'],
') | ',
str(m), 'm, ', str(s), 's',
' | ',
beatmap['version'],
' | Difficulty: ',
beatmap['difficultyrating'],
' | ',
beatmap['bpm'],
' BPM'
]
if topscore:
output += (' | High Score: ' + topscore['score'] + ' (' + topscore['rank'] + ') - ' + topscore['username'])
bot.say(''.join(output))
开发者ID:Inari-Whitebear,项目名称:inumuta-modules,代码行数:34,代码来源:osu.py
示例2: radio
def radio(bot, trigger):
""" Radio functions, valid parameters: on, off, song, now, next, soon, stats. """
global checkSongs, current_song, radioURL
if not radioURL:
if not hasattr(bot.config, "radio"):
bot.say("Radio module not configured")
return
else:
radioURL = bot.config.radio.url + "%s?sid=" + bot.config.radio.sid
try:
args = trigger.group(2).lower().split(" ")
except AttributeError:
bot.say("Usage: .radio (next|now|off|on|song|soon|stats)")
return
if args[0] == "on":
if bot.privileges[trigger.sender][trigger.nick] < OP:
return
if checkSongs != 0:
return bot.reply("Radio data checking is already on.")
if not getAPI(bot, trigger):
checkSongs = 0
return bot.say("Radio data checking not enabled.")
checkSongs = 10
while checkSongs:
last = current_song
try:
current_song = web.get(radioURL % "currentsong")
nextsong = web.get(radioURL % "nextsong")
except Exception as e:
checkSongs -= 1
if checkSongs == 0:
bot.debug(__file__, "Exception while trying to get periodic radio data: %s" % e, "warning")
bot.say("The radio is not responding to the song request.")
bot.say("Turning off radio data checking.")
break
if not current_song == last:
if not current_song:
csong = "The radio is currently offline."
else:
csong = "Now Playing: " + current_song
if nextsong and current_song:
bot.say(csong + " | Coming Up: " + nextsong)
else:
bot.say(csong)
sleep(5)
elif args[0] == "off":
if bot.privileges[trigger.sender][trigger.nick] < OP:
return
if checkSongs == 0:
bot.reply("Radio data checking is already off.")
return
checkSongs = 0
current_song = ""
bot.reply("Turning off radio data checking.")
elif args[0] == "song" or args[0] == "now":
currentSong(bot, trigger)
elif args[0] == "next" or args[0] == "soon":
nextSong(bot, trigger)
elif args[0] == "stats":
getAPI(bot, trigger)
开发者ID:roidelapluie,项目名称:willie,代码行数:60,代码来源:radio.py
示例3: radio
def radio(bot, trigger):
""" Radio functions, valid parameters: on, off, song, now, next, soon, stats. """
global checkSongs, current_song, radioURL
if not radioURL:
if not hasattr(bot.config, 'radio'):
bot.say('Radio module not configured')
return
else:
radioURL = bot.config.radio.url + '%s?sid=' + bot.config.radio.sid
try:
args = trigger.group(2).lower().split(' ')
except AttributeError:
bot.say('Usage: .radio (next|now|off|on|song|soon|stats)')
return
if args[0] == 'on':
if bot.privileges[trigger.sender][trigger.nick] < OP:
return
if checkSongs != 0:
return bot.reply('Radio data checking is already on.')
if not getAPI(bot, trigger):
checkSongs = 0
return bot.say('Radio data checking not enabled.')
checkSongs = 10
while checkSongs:
last = current_song
try:
current_song = web.get(radioURL % 'currentsong')
nextsong = web.get(radioURL % 'nextsong')
except Exception as e:
checkSongs -= 1
if checkSongs == 0:
bot.debug(__file__, 'Exception while trying to get periodic radio data: %s' % e, 'warning')
bot.say('The radio is not responding to the song request.')
bot.say('Turning off radio data checking.')
break
if not current_song == last:
if not current_song:
csong = 'The radio is currently offline.'
else:
csong = 'Now Playing: ' + current_song
if nextsong and current_song:
bot.say(csong + ' | Coming Up: ' + nextsong)
else:
bot.say(csong)
sleep(5)
elif args[0] == 'off':
if bot.privileges[trigger.sender][trigger.nick] < OP:
return
if checkSongs == 0:
bot.reply('Radio data checking is already off.')
return
checkSongs = 0
current_song = ''
bot.reply('Turning off radio data checking.')
elif args[0] == 'song' or args[0] == 'now':
currentSong(bot, trigger)
elif args[0] == 'next' or args[0] == 'soon':
nextSong(bot, trigger)
elif args[0] == 'stats':
getAPI(bot, trigger)
开发者ID:StevenPine,项目名称:willie,代码行数:60,代码来源:radio.py
示例4: lastfm
def lastfm(willie, trigger):
user = trigger.group(2)
apikey = str(willie.config.lastfm.apikey)
if not (user and user != ''):
if trigger.nick in willie.db.preferences:
user = willie.db.preferences.get(trigger.nick, 'lastfm_user')
if not user:
willie.reply("Invalid username given or no username set. Use .fmset to set a username.")
return
#username variable prepared for insertion into REST string
quoted_user = web.quote(user)
#json formatted output for recent track
recent_page = web.get("http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=%s&api_key=%s&format=json" % (quoted_user, apikey))
recent_track = json.loads(recent_page)['recenttracks']['track'][0]
#artist and track name pulled from recent_track
quoted_artist = web.quote(recent_track['artist']['#text'])
quoted_track = web.quote(recent_track['name'])
#json formatted track info
trackinfo_page = web.get("http://ws.audioscrobbler.com/2.0/?method=track.getInfo&artist=%s&track=%s&username=%s&api_key=%s&format=json" % (quoted_artist, quoted_track, quoted_user, apikey))
#track playcount and loved stats
trackinfo = json.loads(trackinfo_page)['track']
try:
playcount = trackinfo['userplaycount']
except KeyError:
playcount = "unknown"
loved = int(trackinfo['userloved'])
try:
if loved > 0:
willie.say('\x035' + u'\u2665' +'\x03 %s - %s - (%s plays)' % (recent_track['artist']['#text'], recent_track['name'], playcount))
else:
willie.say(u'\u266A' + ' %s - %s (%s plays)' % (recent_track['artist']['#text'], recent_track['name'], playcount))
except KeyError:
willie.say("Couldn't find any recent tracks")
开发者ID:Gseoa,项目名称:willie-modules,代码行数:34,代码来源:lastfm.py
示例5: search
def search(title):
response = '[{}]'
if is_integer(title.strip()):
response = web.get('https://mal-api.test.ramblingahoge.net/anime/'+web.quote(title), verify_ssl=False)
return json.loads('['+response+']')
else:
response = web.get('https://mal-api.test.ramblingahoge.net/anime/search?q='+web.quote(title), verify_ssl=False)
return json.loads(response)
开发者ID:meew0,项目名称:inumuta-modules,代码行数:8,代码来源:mal.py
示例6: github_repo
def github_repo(bot, trigger, match=None):
match = match or trigger
repo = match.group(2) or match.group(1)
if repo.lower() == "status":
current = json.loads(web.get("https://status.github.com/api/status.json"))
lastcomm = json.loads(web.get("https://status.github.com/api/last-message.json"))
status = current["status"]
if status == "major":
status = "\x02\x034Broken\x03\x02"
elif status == "minor":
status = "\x02\x037Shakey\x03\x02"
elif status == "good":
status = "\x02\x033Online\x03\x02"
lstatus = lastcomm["status"]
if lstatus == "major":
lstatus = "\x02\x034Broken\x03\x02"
elif lstatus == "minor":
lstatus = "\x02\x037Shakey\x03\x02"
elif lstatus == "good":
lstatus = "\x02\x033Online\x03\x02"
timezone = get_timezone(bot.db, bot.config, None, trigger.nick)
if not timezone:
timezone = "UTC"
lastcomm["created_on"] = format_time(
bot.db, bot.config, timezone, trigger.nick, trigger.sender, from_utc(lastcomm["created_on"])
)
return bot.say(
"[Github] Current Status: "
+ status
+ " | Last Message: "
+ lstatus
+ ": "
+ lastcomm["body"]
+ " ("
+ lastcomm["created_on"]
+ ")"
)
elif repo.lower() == "rate-limit":
return bot.say(fetch_api_endpoint(bot, "https://api.github.com/rate_limit"))
if "/" not in repo:
repo = trigger.nick.strip() + "/" + repo
URL = "https://api.github.com/repos/%s" % (repo.strip())
fmt_response(bot, trigger, URL)
开发者ID:andrejsavikin,项目名称:inumuta-modules,代码行数:50,代码来源:github.py
示例7: get_content
def get_content(phrase, mode, period = "day"):
subreddit = phrase.lower()
if " " in phrase:
subreddit_find_string = phrase.replace(" ", "+")
if not resolved_subreddit.has_key(subreddit_find_string):
url = json.loads(web.get("http://www.reddit.com/subreddits/search.json?q={0}".format(subreddit_find_string)))
result = [x['data']['display_name'] for x in url['data']['children'] if x.has_key('data') and x['data'].has_key('display_name') and x['data']['subreddit_type'] != "private"]
if len(result) > 0:
subreddit = result[0].lower()
resolved_subreddit[subreddit_find_string] = subreddit
else:
return "I looked for a public subreddit matching that phrase but didn't find one.", None
else:
subreddit = resolved_subreddit[subreddit_find_string]
if not last_seen.has_key(subreddit):
last_seen[subreddit] = {}
url = "http://www.reddit.com/r/{0}/search.json?q=site%3Aimgur.com&restrict_sr=on&sort={1}&t={2}".format(subreddit, mode, period)
get = web.get(url, timeout=5)
try:
array = json.loads(get)
except ValueError:
return "{0} doesn't look like a subreddit to me.".format(subreddit), subreddit
if 'error' in array:
if array['error'] == 404:
return "{0} isn\'t a real subreddit.".format(subreddit), subreddit
elif array['error'] == 403:
return "{0} is a private subreddit.".format(subreddit), subreddit
else:
return "Unknown error. Whoops."
else:
links = []
iterator = 0
if 'children' in array['data'] and len(array['data']['children']) > 0:
while (len(links) < 10) and (iterator < len(array)):
for child in array['data']['children']:
iterator = iterator + 1
if child['data']['domain'] == 'i.imgur.com':
if 'over_18' in child['data']:
id = child['data']['id']
if last_seen[subreddit].has_key(id):
child['data']['lastseen'] = last_seen[subreddit][id]
else:
child['data']['lastseen'] = 0
links.append(child['data'])
return links, subreddit
开发者ID:jcrza,项目名称:imgurbot,代码行数:49,代码来源:imgurbot.py
示例8: show_bug
def show_bug(willie, trigger):
"""Show information about a Bugzilla bug."""
domain = trigger.group(1)
if domain not in willie.config.bugzilla.get_list('domains'):
return
url = 'https://%s%sctype=xml&%s' % trigger.groups()
data = web.get(url)
bug = etree.fromstring(data).find('bug')
message = ('[BUGZILLA] %s | Product: %s | Component: %s | Version: %s | ' +
'Importance: %s | Status: %s | Assigned to: %s | ' +
'Reported: %s | Modified: %s')
if bug.find('resolution') is not None:
status = bug.find('bug_status').text + ' ' + bug.find('resolution').text
else:
status = bug.find('bug_status').text
message = message % (
bug.find('short_desc').text, bug.find('product').text,
bug.find('component').text, bug.find('version').text,
(bug.find('priority').text + ' ' + bug.find('bug_severity').text),
status, bug.find('assigned_to').text, bug.find('creation_ts').text,
bug.find('delta_ts').text)
willie.say(message)
开发者ID:WireShout,项目名称:willie,代码行数:25,代码来源:bugzilla.py
示例9: show_bug
def show_bug(bot, trigger, match=None, bug_url=None):
"""Show information about a Bugzilla bug."""
if bug_url is None:
print(match, trigger)
match = match or trigger
domain = match.group(1)
if domain not in bot.config.bugzilla.get_list('domains'):
return
url = 'https://%s%sctype=xml&%s' % match.groups()
else:
url = bug_url
print(url)
data = web.get(url)
bug = etree.fromstring(data).find('bug')
if bug.get('error'):
bot.reply("That bug id is sketchy, man.")
return
message = ('[BUGZILLA] %s | Product: %s | Component: %s | Version: %s | ' +
'Importance: %s | Status: %s | Assigned to: %s | ' +
'Reported: %s | Modified: %s')
resolution = bug.find('resolution')
if resolution is not None and resolution.text:
status = bug.find('bug_status').text + ' ' + resolution.text
else:
status = bug.find('bug_status').text
message = message % (
bug.find('short_desc').text, bug.find('product').text,
bug.find('component').text, bug.find('version').text,
(bug.find('priority').text + ' ' + bug.find('bug_severity').text),
status, bug.find('assigned_to').text, bug.find('creation_ts').text,
bug.find('delta_ts').text)
bot.say(message)
开发者ID:miketaylr,项目名称:willie,代码行数:35,代码来源:bugzilla.py
示例10: fetch_video_info
def fetch_video_info(bot, id):
"""Retrieves video metadata from YouTube"""
url = INFO_URL.format(get_api_key(bot), id)
raw, headers = web.get(url, return_headers=True)
if headers['_http_status'] == 403:
bot.say(u'[YouTube Search] Access denied. Check that your API key is '
u'configured to allow access to your IP address.')
return
try:
result = json.loads(raw)
except ValueError as e:
raise YouTubeError(u'Failed to decode: ' + raw)
if 'error' in result:
raise YouTubeError(result['error']['message'])
if len(result['items']) == 0:
raise YouTubeError('YouTube API returned empty result')
video = result['items'][0]
info = {
'title': video['snippet']['title'],
# 'uploader': video['snippet']['channelTitle'],
# 'uploaded': convert_date(video['snippet']['publishedAt']),
'duration': convert_duration(video['contentDetails']['duration']),
'views': video['statistics']['viewCount'],
# 'comments': video['statistics']['commentCount'],
# 'likes': video['statistics']['likeCount'],
# 'dislikes': video['statistics']['dislikeCount'],
'link': 'https://youtu.be/' + video['id']
}
return info
开发者ID:madprops,项目名称:willie-modules,代码行数:35,代码来源:youtube.py
示例11: bing_search
def bing_search(query, lang='en-GB'):
query = web.quote(query)
base = 'http://www.bing.com/search?mkt=%s&q=' % lang
bytes = web.get(base + query)
m = r_bing.search(bytes)
if m:
return m.group(1)
开发者ID:atti92,项目名称:AtiBot,代码行数:7,代码来源:search.py
示例12: show_bug
def show_bug(bot, trigger, match=None):
"""Show information about a Bugzilla bug."""
match = match or trigger
domain = match.group(1)
if not bot.config.has_section('bugzilla') or domain not in bot.config.bugzilla.get_list('domains'):
return
url = 'https://%s%sctype=xml&%s' % match.groups()
data = web.get(url, dont_decode=True)
bug = etree.fromstring(data).find('bug')
message = ('[BUGZILLA] %s | Product: %s | Component: %s | Version: %s | ' +
'Importance: %s | Status: %s | Assigned to: %s | ' +
'Reported: %s | Modified: %s')
resolution = bug.find('resolution')
if resolution is not None and resolution.text:
status = bug.find('bug_status').text + ' ' + resolution.text
else:
status = bug.find('bug_status').text
message = message % (
bug.find('short_desc').text, bug.find('product').text,
bug.find('component').text, bug.find('version').text,
(bug.find('priority').text + ' ' + bug.find('bug_severity').text),
status, bug.find('assigned_to').text, bug.find('creation_ts').text,
bug.find('delta_ts').text)
bot.say(message)
开发者ID:Cadair,项目名称:willie,代码行数:27,代码来源:bugzilla.py
示例13: amazon_url
def amazon_url(bot, trigger):
item = html.fromstring(web.get(trigger.group(1)))
try:
title = item.xpath("//span[@id='productTitle']/text()")[0]
except:
title = item.xpath("//span[@id='btAsinTitle']/text()")[0]
try:
price = item.xpath("//span[@id='priceblock_ourprice']/text()")[0]
except:
try:
price = item.xpath("//span[@id='priceblock_saleprice']/text()")[0]
except:
try:
price = item.xpath("//b[@class='priceLarge']/text()")[0]
except:
price = "$?"
try:
rating = item.xpath("//div[@id='avgRating']/span/text()")[0].strip()
except:
rating = item.xpath("//div[@class='gry txtnormal acrRating']/text()")[0].strip()
try:
breadcrumb = ' '.join(item.xpath("//li[@class='breadcrumb']")[0].text_content().split())
except:
breadcrumb = "Unknown"
star_count = round(float(rating.split(' ')[0]), 0)
stars = ''
for x in xrange(0, int(star_count)):
stars += u'\u2605'
for y in xrange(int(star_count), 5):
stars += u'\u2606'
out = ['[Amazon]', title, '|', breadcrumb, '|', stars, '|', price]
bot.say(' '.join(out))
开发者ID:Inari-Whitebear,项目名称:inumuta-modules,代码行数:34,代码来源:amazon.py
示例14: wa
def wa(bot, trigger):
"""Wolfram Alpha calculator"""
if not trigger.group(2):
return bot.reply("No search term.")
query = trigger.group(2)
uri = 'http://tumbolia.appspot.com/wa/'
try:
answer = web.get(uri + web.quote(query.replace('+', '%2B')), 45)
except timeout as e:
return bot.say('[WOLFRAM ERROR] Request timed out')
if answer:
answer = answer.decode('string_escape')
answer = HTMLParser.HTMLParser().unescape(answer)
# This might not work if there are more than one instance of escaped
# unicode chars But so far I haven't seen any examples of such output
# examples from Wolfram Alpha
match = re.search('\\\:([0-9A-Fa-f]{4})', answer)
if match is not None:
char_code = match.group(1)
char = unichr(int(char_code, 16))
answer = answer.replace('\:' + char_code, char)
waOutputArray = string.split(answer, ";")
if(len(waOutputArray) < 2):
if(answer.strip() == "Couldn't grab results from json stringified precioussss."):
# Answer isn't given in an IRC-able format, just link to it.
bot.say('[WOLFRAM]Couldn\'t display answer, try http://www.wolframalpha.com/input/?i=' + query.replace(' ', '+'))
else:
bot.say('[WOLFRAM ERROR]' + answer)
else:
bot.say('[WOLFRAM] ' + waOutputArray[0] + " = "
+ waOutputArray[1])
waOutputArray = []
else:
bot.reply('Sorry, no result.')
开发者ID:DanUgore,项目名称:willie,代码行数:35,代码来源:calc.py
示例15: etymology
def etymology(word):
# @@ <nsh> sbp, would it be possible to have a flag for .ety to get 2nd/etc
# entries? - http://swhack.com/logs/2006-07-19#T15-05-29
if len(word) > 25:
raise ValueError("Word too long: %s[...]" % word[:10])
word = {'axe': 'ax/axe'}.get(word, word)
bytes = web.get(etyuri % word)
definitions = r_definition.findall(bytes)
if not definitions:
return None
defn = text(definitions[0])
m = r_sentence.match(defn)
if not m:
return None
sentence = m.group(0)
maxlength = 275
if len(sentence) > maxlength:
sentence = sentence[:maxlength]
words = sentence[:-5].split(' ')
words.pop()
sentence = ' '.join(words) + ' [...]'
sentence = '"' + sentence.replace('"', "'") + '"'
return sentence + ' - ' + (etyuri % word)
开发者ID:BOFHers,项目名称:willie,代码行数:29,代码来源:etymology.py
示例16: ytsearch
def ytsearch(bot, trigger):
"""
.youtube <query> - Search YouTube
"""
if not trigger.group(2):
return
uri = 'https://www.googleapis.com/youtube/v3/search?part=snippet&type=video&q=' + trigger.group(2)
raw = web.get(uri + '&key=' + bot.config.google.public_key)
vid = json.loads(raw)['items'][0]['id']['videoId']
uri = 'https://www.googleapis.com/youtube/v3/videos?id=' + vid + '&part=contentDetails,snippet,statistics'
video_info = ytget(bot, trigger, uri)
if video_info is None:
return
message = ('[YT Search]' +
' Title: ' + video_info['snippet']['title'] +
' | Uploader: ' + video_info['snippet']['channelTitle'] +
' | Uploaded: ' + video_info['snippet']['publishedAt'] +
' | Duration: ' + video_info['contentDetails']['duration'] +
' | Views: ' + video_info['statistics']['viewCount'] +
' | Comments: ' + video_info['statistics']['commentCount'] +
' | ' + color(video_info['statistics']['likeCount'] + '+', colors.GREEN) +
' | ' + color(video_info['statistics']['dislikeCount'] + '-', colors.RED) +
' | Link: https://youtu.be/' + video_info['id'])
bot.say(message)
开发者ID:Inari-Whitebear,项目名称:inumuta-modules,代码行数:26,代码来源:youtube.py
示例17: get_def
def get_def(path, num=0):
url = UD_URL + path
try:
resp = json.loads(web.get(url))
except UnicodeError:
definition = ('ENGLISH MOTHERFUCKER, DO YOU SPEAK IT?')
return definition
nom = num + 1
try:
word = path[12:]
except:
pass
if path.startswith("define?term=") and resp['result_type'] == 'no_results':
definition = 'Definition %s not found!' % (word)
else:
try:
item = resp['list'][num]['definition'].encode('utf8')
thumbsup = resp['list'][num]['thumbs_up']
thumbsdown = resp['list'][num]['thumbs_down']
points = str(int(thumbsup) - int(thumbsdown))
total_nom = len(resp['list'])
definition = ""
if path == "random":
word = resp['list'][num]['word'].encode('utf8')
definition = 'Word: ' + str(word) + ' | '
definition = definition + 'Definition: ' + str(item)[1:].replace("\n", "") + " | Number: " + str(nom) + '/' + str(total_nom) + ' | Points: ' + points + ' (03' + str(thumbsup) + '|05' + str(thumbsdown) + ')'
except IndexError:
definition = ('Definition entry %s does'
'not exist for \'%s\'.' % (nom, word))
return definition
开发者ID:shamazar,项目名称:willie-modules,代码行数:30,代码来源:ud.py
示例18: horrible
def horrible(bot, trigger):
"""
.horrible [show] - View the latest HorribleSubs releases for any given show
"""
latest = False
query = trigger.group(2)
if not query:
latest = True
url = 'http://horriblesubs.info/lib/search.php?value={}'
if latest:
url = 'http://horriblesubs.info/lib/latest.php'
soup = BeautifulSoup(web.get(url.format(query)), 'lxml')
ep = soup.find_all('div', {'class': 'episode'})
if len(ep) > 0:
for epi in ep:
episode = ''.join([x for x in epi.contents if isinstance(x, NavigableString)])
resblock = epi.find_all('div', {'class': 'linkful resolution-block'})
resolutions = []
links = []
for res in resblock:
links.extend([link.find('a')['href'] for link in res.find_all('span', {'class': 'ind-link'}) if 'Torrent' in link.text])
resolutions.append(res.find('a', {'href': '#'}).text)
bot.say('Latest: {} | Resolutions: {} | Download: {} ({})'.format(episode, ', '.join(resolutions), links[-1], resolutions[-1]))
return
bot.say('[Horrible] No results found')
开发者ID:Inari-Whitebear,项目名称:inumuta-modules,代码行数:30,代码来源:horrible.py
示例19: info
def info(genre, title):
if ".mp3" not in title:
title = title + ".mp3"
genre = urllib.unquote(genre)
title = urllib.unquote(title)
request = web.get("http://jpv.everythingisawesome.us/api/v1/song/" + genre + "/" + title)
return json.loads(request)
开发者ID:pierg75,项目名称:inumuta-modules,代码行数:7,代码来源:jpv.py
示例20: checkSchedule
def checkSchedule(bot):
print("Checking for new schedule...")
bytes = web.get(handmadeScheduleURI)
reader = csv.DictReader(bytes.split("\n"), ["date", "time", "description"])
result = ""
for row in reader:
rowSplit = row["date"].split("-")
date = arrow.now().replace(year=int(rowSplit[0]), month=int(rowSplit[1]), day=int(rowSplit[2]))
#date = arrow.get(date, defaultTz)
streams = getStreamsOnDay(date)
time,flag = dateParser.parseDT(row["time"], sourceTime=date.datetime)
time = arrow.get(time, defaultTz)
off_day = row["description"] == "off"
for stream in streams: ## Don't worry, this is usually 1 element long (if it's not, we have some refactoring to do elsewhere!)
if(off_day):
#kill the stream
StreamEpisode.delete(getID(stream))
pass
if(abs(stream.start - time) > timedelta(0)):
#print("%s now at %s (was %s), " % (time.strftime("%b %d %Y"), time.strftime("%I:%M%p"), stream._get_start().strftime("%I:%M%p")))
scheduleStream(time)
result += "%s now at %s (was %s), " % (time.strftime("%b %d %Y"), time.strftime("%I:%M%p"), stream._get_start().strftime("%I:%M%p"))
#print(date, streams)
if (len(streams) == 0 and off_day == False):
#print("No stream on %s, added one at %s" % (time.strftime("%b %d %Y"), time.strftime("%I:%M%p")))
scheduleStream(time)
result += time.strftime("%b %d %Y at %I:%M%p %Z") + ", "
if (len(result) > 0):
result = result[:-2]
for channel in bot.channels:
#bot.msg(channel, "Updated the stream schedule: %s" % result)
pass
开发者ID:Chronister,项目名称:hmh_bot,代码行数:33,代码来源:handmade_stream.py
注:本文中的willie.web.get函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论