def process(msg): if msg.startswith('#') or msg.startswith('#'): pass elif msg == u'新生指南': return freshman.get_guidance(), "news" elif msg == u'新闻' or msg == u'体育' or msg == u'体育新闻': return news.getNews(msg), "news" elif isinstance(msg, type('string')): msg = msg.lower() msg = msg.strip() if msg == 'bbc world' or msg == 'bbc china' or msg == 'bbc' or msg == 'nba': return news.getNews(msg), "news" else: return translate.translate(msg), "text" #elif msg == u'新闻': # return news_info, "text" elif msg == u'校车' or msg == u'明天校车': return xiaoche.get_timetable(msg), "text" elif msg == u'摆渡车': return ferrybus.get_timetable(msg), "text" elif msg == u'环一' or msg == u'环1': return huanyi.get_timetable(), "text" elif msg == u'天气': return weather.weather(), "text" elif msg == u'空气': return weather.get_airquality(), "text" elif re.match(u"发状态", msg): if msg[3:]: return renren.renren_status(msg[3:]), "text" else: return u"请输入状态内容", "text" else: return u"无法处理请求,请查看使用说明\n" + help_info + report_info, "text"
def get_opinion(lang, lat, long, rad, name): search.work(str(lang), str(lat) + ',' + str(long) + ',' + str(int(rad)) + 'mi') news.getNews(name) opinion = sentiment.run_sentiment_analysis('tweets.txt') opinion += sentiment.run_sentiment_analysis('news.txt') # Check for + or - in front of opinion if opinion > 0: opinion = "+" + str(opinion) elif opinion < 0: opinion = str(opinion) else: opinion = str(opinion) # Make dictionary for send senti = [ { 'Language': lang, 'Latitude': lat, 'Longitude': long, 'Radius': rad, 'Opinion': opinion } ] logging.info("Opinion of city is: " + opinion) return jsonify(senti)
def index(): link_text, links = getNews() counter = len(link_text) return render('index.html', link=links, link_text=link_text, counter=counter)
def news(): titles, content, url, image, time = getNews() return render_template('news.html', titles=titles, content=content, url=url, image=image, time=time)
def set_text(data): opening = ( "Wake up Cian, it's {} . The sky is {} with current temperature {} . Here are some top headlines for today." ).format( str(data["current_time"]), str(data["sky"]), str(data["temp"]), ) return opening + getNews()
def get_opinion(lang, lat, long, rad, name): search.work(str(lang), str(lat) + ',' + str(long) + ',' + str(int(rad)) + 'mi') news.getNews(name) twitterOpinion = sentiment.run_sentiment_analysis('tweets.txt') newsOpinion = sentiment.run_sentiment_analysis('news.txt') visual = images.process_image_search(name) # Check for + or - in front of opinion if newsOpinion > 0: newsOpinion = "+" + str(newsOpinion) elif newsOpinion < 0: newsOpinion = str(newsOpinion) else: newsOpinion = str(newsOpinion) if twitterOpinion > 0: twitterOpinion = "+" + str(twitterOpinion) elif twitterOpinion < 0: twitterOpinion = str(twitterOpinion) else: twitterOpinion = str(twitterOpinion) # Make dictionary for send senti = [ { 'Language': lang, 'Latitude': lat, 'Longitude': long, 'Radius': rad, 'News Opinion': news, 'Twitter Opinion': twitterOpinion, 'Opinion': twitterOpinion + newsOpinion, 'Visual' : visual } ] logging.info("Opinion of city is: " + twitterOpinion + newsOpinion) return jsonify(senti)
def newsfeed(): if request.method == 'POST': publisher = request.form['publisher'] keyword = request.form['keyword'] results = nf.getNews(publisher, keyword) # Call the API and get articles if results == "none": return "No articles found!" else: return render_template('result.html', results=results[0], os=results[1]) else: # GET request, do nothing here return "Go back to the home page to search for articles!"
def stance(stance_id): #gather stance data from db data = db.stances.find_one({"stance_id":stance_id}) anti = data['anti'] rebuttal = data['rebuttal'] #use query from db to get recent news sources (list of dicts) news = getNews(data['query']) return render_template('stance.html', name=data['name'], anti_summary=anti['text'],anti_quotes=anti['quotes'],anti_pubs=anti['publications'], rebut_summary=rebuttal['text'],rebut_quotes=rebuttal['quotes'],rebut_pubs=rebuttal['publications'], ethos=data['ethos'],pathos=data['pathos'],logos=data['logos'], sources=data['sources'],news=news )
def updateNews(): global search, not_waiting image_news = Image.open("assets/Newspaper.png") image_news = image_news.resize((25, 25), Image.ANTIALIAS) image_news = image_news.convert('RGB') photo_news = ImageTk.PhotoImage(image_news) news_icon_Label1.config(image=photo_news) news_icon_Label2.config(image=photo_news) news_icon_Label3.config(image=photo_news) sources = [ "bbc-news", "espn", "cnn", "fox-sports", "marca", "the-verge", "crypto-coins-news", "engadget", "ign", "abc-news", "business-insider", "mtv-news", "national-geographic", "techradar" ] contSource = 0 while (news): if search == '': if (contSource < len(sources)): header = nw.getNews(contSource, sources) news_Label.config(text="News") event_Name_Label1.config(text=header[0]) event_Name_Label2.config(text=header[1]) event_Name_Label3.config(text=header[2]) contSource += 1 time.sleep(10) else: contSource = 0 time.sleep(10) else: display_message("Looking for " + search) result = nw.searchNews(search) news_Label.config(text="Search Results") event_Name_Label1.config(text=result[0]) event_Name_Label2.config(text=result[1]) event_Name_Label3.config(text=result[2]) search = '' time.sleep(5) not_waiting = True
def bot(): incoming_msg = request.values.get('Body', '').lower() incoming_num1 = request.values.get( 'To', '').lower() #although not necessary but still incoming_num2 = request.values.get( 'From', '').lower() #the incoming message mobile number current = str(datetime.datetime.now()) resp = MessagingResponse() msg = resp.message() completionMsg = "" #this is to store the displayed result responded = False now = datetime.datetime.now() # now = datetime.now() current_time = now.strftime("%H:%M:%S") logs = "Current Time =", current_time + incoming_num2 + "Message : " + incoming_msg print(logs) if 'bothelp' in incoming_msg: reply = "Hi I am PicoBot, How can I help you ?\n\nType 'contact' for developers contact \n\nType 'tasks' for list of available tasks" msg.body(reply) # msg.body("test msg") responded = True completionMsg = reply elif ('covidhelp' in incoming_msg): l = incoming_msg.split() reply = "" try: city = l[1] required = l[2] leads = twitter.input_triggers_spinner(city, required) print("Lead length=") print(len(leads)) for lead in leads: reply += "\n" + lead['full_text'] + "\n-----------------" except: reply = "Please put your query in given format" msg.body(reply) responded = True completionMsg = reply elif ('covidnews' in incoming_msg): l = incoming_msg.split() reply = "" try: category = l[1] news = getNews(category) newstock = news["data"] for i in range(len(newstock)): reply = news["data"][i]["title"] + "\n\n" + news["data"][i][ "content"] alink = news["data"][i]["imageUrl"] # msg.media(alink) message.send(incoming_num2, reply, [alink]) except: reply = "Please put your query in given format" msg.body(reply) responded = True completionMsg = reply elif ('covidvaccine' in incoming_msg): if ('drive' in incoming_msg): reply = cowin.states() msg.body(reply) responded = True completionMsg = reply elif ('state' in incoming_msg): l = incoming_msg.split() id = int(l[2]) reply = cowin.districts(id) # except: # reply= "Please put your query in given format" msg.body(reply) responded = True completionMsg = reply else: l = incoming_msg.split() reply = "" # try: # pincode = l[1] # date = l[2] # min_age_limit = 45 # reply = cowin.driver(pincode,date,min_age_limit) # except: # reply= "Please put your query in given format" pincode = l[1] # date = l[2] min_age_limit = 45 reply = cowin.driver(pincode) # print(reply[10]) try: msg.body(reply[:699]) except: msg.body(reply) responded = True completionMsg = reply if 'covidinfo' in incoming_msg: l = incoming_msg.split() state = 'india' if (len(l) > 1): state = "" for i in l[1:]: state += i + " " state = state[:-1] c, r, d, a = statistics.driver(state) reply = "\n✅Confirmed: " + str(c) + "\n✅Recovered: " + str( r) + "\n✅Active: " + str(a) + "\n✅Deceased: " + str(d) msg.body(reply) responded = True completionMsg = reply if 'contact' in incoming_msg: reply = "Hi I am Gauransh Soni\nSophomore @ IIT Delhi\nEmail - [email protected]\nContact No. 9462447291" msg.body(reply) responded = True completionMsg = reply if 'task' in incoming_msg: reply = "Here is a list of items I can do\n1)Type 'covidhelp <cityname> <Oxygen or Remedesivir or Plasma>' to get recent leads for asked item\n2)Type 'covidinfo <state>' to get recent statistics of covid cases in your state\n3)Type 'emergency <pincode>' to get the contact number of emergency services in your area\n4)Type 'covidvaccine <pincode>' to check availability of vaccine in your area\n5)Type 'help' to get more info" msg.body(reply) responded = True completionMsg = reply if 'quote' in incoming_msg: # return a quote r = requests.get('https://api.quotable.io/random') if r.status_code == 200: data = r.json() quote = f'{data["content"]} ({data["author"]})' else: quote = 'I could not retrieve a quote at this time, sorry.' msg.body(quote) responded = True completionMsg = quote if 'aurbhai' in incoming_msg: # return a cat pic msg.body('I love cats') msg.media('https://cataas.com/cat') responded = True completionMsg = 'https://cataas.com/cat' if 'wallpaper' in incoming_msg: l = incoming_message.split() url = l[1] try: from googlesearch import search except ImportError: print("No module named 'google' found") completionMsg = "No module named 'google' found" # to search query = url + " unsplash" for j in search(query, tld="co.in", num=1, stop=4, pause=2): if "https://unsplash.com/s/photos" in j: url = j a = urllib.request.urlopen(url, context=ctx).read() soup = bs(a, 'html.parser') L = soup.find_all('a', {'title': "Download photo"}) x = randint(1, len(L) - 1) alink = L[x].get('href') msg.media(alink) completionMsg = alink responded = True if 'unsplash' in incoming_msg: # return a cat pic msg.body('Here You Go ') un_img = 'https://source.unsplash.com/random' msg.media(un_img) responded = True completionMsg = un_img if 'spam' in incoming_msg: # spams l = incoming_msg.split() countSpam = int(l[1]) mess = " ".join(l[2:]) for i in range(countSpam): msg.body(mess) completionMsg = "Succesfully spammed" responded = True if 'dank-joke' in incoming_msg: #sends a random dank joke responseDog = requests.get( "https://sv443.net/jokeapi/v2/joke/Any?type=single") l = responseDog.json() msg.body(l['joke']) completionMsg = l['joke'] responded = True if 'dict' in incoming_msg: headersDict = { 'Authorization': 'Token e3d0b4298a9592eb23efa0419b031d2ffadc94d4', } urlForDict = 'https://owlbot.info/api/v4/dictionary/' incoming_msg = 'dict cat' l = incoming_msg.split() searchTerm = l[1] urlForDict += searchTerm response = requests.get(urlForDict, headers=headersDict) ans = response.json() pronounciation = ans['pronunciation'] defination = ans['definitions'][0]['definition'] img = ans['definitions'][0]['image_url'] example = ans['definitions'][0]['example'] returnString = "*Defination* : " + defination + "\n" + "*usage*: " + example msg.body(returnString) msg.media(img) completionMsg = "successfully sent" responded = True if 'que' in incoming_msg: import urllib.request, urllib.parse, urllib.error import xml.etree.ElementTree as ET import ssl from bs4 import BeautifulSoup as bs ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE url = ' '.join(incoming_msg.split()[1:]) try: from googlesearch import search except ImportError: print("No module named 'google' found") # to search query = url + " stackoverflow" for j in search(query, tld="co.in", num=1, stop=1, pause=2): url = j a = urllib.request.urlopen(url, context=ctx).read() soup = bs(a, 'html.parser') L = soup.find_all('div', {'class': 'post-text'}) i = L[1] msg.body(i.text) print(i.text) completionMsg = i.text responded = True if not responded: msg.body('type bothelp') completionMsg = "Job Done" row = [ current, incoming_num1[9:], incoming_num2[9:], incoming_msg, completionMsg ] f = open("output.txt", "a") if incoming_msg != "": myadd = "" for string in row: myadd += string + " " f.write(myadd + "\n") f.close() # sheet.insert_row(row,index=2) return str(resp)
fi = open(str(filename) + "-" + str(n) + ".txt", 'w') fi.write(verses.decode("UTF-8").encode("UTF-16")) if len(sys.argv) > 1: filename = sys.argv[1] else: filename = "news" cmu_reader = nltk.corpus.cmudict #print "building cmu dict..." cmu_dict = cmu_reader.dict() cmu_words = cmu_reader.words() nsents = news.getNews() nwords = [] for sent in nsents: lsent = sent.split(" ") nwords.extend(lsent) plwords = [] plwords.extend(nltk.corpus.gutenberg.words('milton-paradise.txt')[20:1000]) plwords.extend(nwords) grams = nltk.util.trigrams(plwords) bigrams = nltk.util.bigrams(plwords) cfdtri = nltk.ConditionalFreqDist([((w1,w2),w3) for (w1, w2, w3) in grams]) cfdbi = nltk.ConditionalFreqDist(bigrams) generate(filename, 1, 1000)
def on_json(self, request, source): knownSources = [val for val in source.split('+') if val in news.sources.keys()] #print(repr(knownSources)) if(len(knownSources)<=0): raise NotFound() return Response([news.getNews(knownSources)])