def alarm_end(alarm_time: datetime.datetime, alarm: dict, news_call: bool,
              weather_call: bool) -> None:
    """
    This function runs when an alarm has gone off. The notification and log
    dictionaries are created including the necessary alarm data. 
    If the user has checked news and weather checkboxes then news and weather information
    will be played. Covid Data Nwews will be plaayed on every alarm
    """
    # Alarm Go off notification created
    alarm_notification = ({
        'timestamp': time.strftime('%H:%M:%S'),
        'type': 'Alarm',
        'title': ' Alarm scheduled for ' + str(alarm_time) + ' has gone off.',
        'description': ''
    })
    alarm_log = ({
        'timestamp': time.strftime('%H:%M:%S'),
        'type': 'alarm',
        'description':
        'Alarm scheduled for ' + str(alarm_time) + ' has gone off.',
        'error': ''
    })
    new_notification(alarm_notification)
    info_log(alarm_log)
    tts("Alarm  " + str(alarm_time) + "has gone off")
    if news_call == True:
        get_news(True)
    if weather_call == True:
        get_weather(True)
    get_covid_data(True)
def main():
    print("Welcome to the investment information feed(iif) system!")
    print("*******************************************************")
    #print("Please select your identity:")
    #print("1) RM")
    #print("2) client")
    #iden = input()
    iden = '1'
    if iden == '1':
        ope = ''
        while ope != 'q':
            print("*******************************************************")
            print("To quit: type 'q'")
            print("Choose an operation:")
            print("1) Assets Management")
            print("2) Technical Analysis")
            print("3) Market News")
            ope = input().lower()
            if ope == '1':
                optimize_portfolio()
            elif ope == '2':
                technical_analyze()
            elif ope == '3':
                get_news()
            elif ope == 'q':
                break
            else:
                print("Please enter a valid input")
Beispiel #3
0
def get_news():
    print('\n\n[INFO] Chờ vài phút!...')

    for page in range(1, 31):
        URL = f'https://dantri.com.vn/su-kien/trang-{page}.htm'
        news.get_news(URL)

    print('\n\n[INFO] Xong!')
 def __init__(self, parent, *args, **kwargs):
     Frame.__init__(self, parent, bg='black')
     # Init a label
     newss = news.get_news()
     self.new0 = newss[0]
     self.new1 = newss[1]
     self.new2 = newss[2]
     self.meuLabel = Label(self,
                           font=('Helvetca', 18),
                           fg="white",
                           bg="black")
     self.meuLabel.pack(side=TOP, anchor=W)
     self.meuLabel2 = Label(self,
                            text=self.new1,
                            font=('Helvetca', 18),
                            fg="white",
                            bg="black")
     self.meuLabel2.pack(side=TOP, anchor=W)
     self.meuLabel3 = Label(self,
                            text=self.new2,
                            font=('Helvetca', 18),
                            fg="white",
                            bg="black")
     self.meuLabel3.pack(side=TOP, anchor=W)
     self.tick()
Beispiel #5
0
def news_page(request):
    query=request.GET.get('query')
    q,dummy =Search.objects.get_or_create(query=query,user=request.user)
    content=news.get_news(query)
    wcurl=WC.wcloud((' '.join(x['title'] + x['content_snippet'] for x in content[:7])),query)
    variables = RequestContext(request,{'user':request.user,'query':query,'content':content,'wcurl':wcurl})
    return render_to_response('twapp/news_page.html',variables)
Beispiel #6
0
def display_news(image, origin, displaysize):
    articles = news.get_news()

    draw.draw_section_header(image, settings.title_prefix, (origin[0] + settings.travel_title_indent_x, origin[1]))

    draw.draw_footer(image, origin, displaysize)    

    draw_news_headlines(image, articles, origin, displaysize)
Beispiel #7
0
def task_list():
    ans = check_login()
    if ans:
        return ans
    return render_template('task_list.html',
                           page_title="Список заданий",
                           user={"name": session['user_name']},
                           news=get_news(),
                           count=get_len())
Beispiel #8
0
def main():
    filename = '../expo/assets/articles.json'
    articles = news.get_news()
    for article in articles:
        article['score'] = analyze.analyze(article['text'])

    articles.sort(key=lambda x: x['score'], reverse=True)
    with open(filename, 'w') as file:
        json.dump(articles, file)
def compile_and_send():
    var_dicts = dict()
    var_dicts['date'] = get_date()
    var_dicts['wod'] = get_sp_wod()
    var_dicts['readings'] = get_today_reading()
    var_dicts['trends'] = twitter_trending(2514815)
    var_dicts['articles'] = get_news()
    var_dicts['weather'] = get_today_weather("22003")
    send_email(var_dicts)
Beispiel #10
0
def callback_picked_quickreply(payload, event):
    sender_id = event.sender_id
    if payload == 'news_hello':
        smart_object = qr.get_news_quick_reply()
        page.send(recipient_id=sender_id,
                  message='Choose any one of these sources:',
                  quick_replies=smart_object)
    else:
        news_obj = news.get_news(payload)
        page.send(sender_id, Template.Generic(news_obj))
Beispiel #11
0
def init_window():
    """窗口线程"""
    width = config.get('root', 'width')
    height = config.get('root', 'height')
    origin_x, origin_y = config.get('root', 'x'), config.get('root', 'y')
    root.overrideredirect(True)
    root.attributes('-alpha', config.get('root', 'alpha'))
    root.geometry('%sx%s+%s+%s' % (width, height, origin_x, origin_y))
    canvas = Tkinter.Canvas(root)
    canvas.configure(width=width)
    canvas.configure(height=height)
    canvas.configure(bg='black')
    canvas.configure(highlightthickness=0)
    canvas.pack()
    x, y = 0, 0

    def move(event):
        global x, y
        new_x = (event.x - x) + root.winfo_x()
        new_y = (event.y - y) + root.winfo_y()
        root.geometry('%sx%s+%d+%d' % (width, height, new_x, new_y))

    def button_1(event):
        global x, y
        x, y = event.x, event.y

    canvas.bind('<B1-Motion>', move)
    canvas.bind('<Button-1>', button_1)
    init_news(canvas)

    button = Tkinter.Button(canvas,
                            text="close",
                            command=close_window,
                            anchor=Tkinter.W)
    button.configure(width=10,
                     activebackground="#000000",
                     background="#000000",
                     fg="white",
                     relief=Tkinter.FLAT)
    button.pack(side=Tkinter.BOTTOM)
    news.get_news()
    root.mainloop()
Beispiel #12
0
def news_stock_analyzer(stock_ticker):
    stock_score = 0
    stock_score += nc.sentiment_analyzer(news.get_news(stock_ticker))
    print(stock_ticker, "news score:", stock_score)
    if stock_score >= 0.35 and stock_ticker not in all_active_positions.keys():
        alpaca.create_order(stock_ticker, 1)  #todo: calculate order amount
        active_positions_to_check[stock_ticker] = sdg.get_current_stock_data(
            stock_ticker)['Close']
        all_active_positions[stock_ticker] = sdg.get_current_stock_data(
            stock_ticker)['Close']
        print("Based on News analysis, buying", stock_ticker)
Beispiel #13
0
def home():
    """
    This function is responsible for fetching a list of alarms, current
    weather, latest news and lates covid data. This data is
    fetched to be displayed on the main page.
    Whenever the html page refreshes news , weather and covid information
    is also fetched.
    """
    favicon = 'static\images\logo.ico'
    #False parameter is provide here so each time  news , weather
    #and covid info. is fetched it doesnt get played by text_to_speech
    get_news(False)
    get_weather(False)
    get_covid_data(False)
    title = "Smart Alarm Clock"
    alarm_list = get_alarms()
    notification_list = update_notifications()
    return render_template('home.html',
                           alarm_list=alarm_list,
                           notification_list=notification_list,
                           favicon=favicon,
                           title=title)
Beispiel #14
0
def news():
    data_frame = get_news()
    data_frame = data_frame.drop(columns=['Datetime'])
    info = []
    objects = {}
    for i in range(data_frame.shape[0]):
        objects['Headlines'] = data_frame['Headlines'][i]
        objects['Publisher'] = data_frame['Publisher'][i]
        objects['Links'] = data_frame['Links'][i]
        objects['Hours'] = data_frame['Hours'][i]
        info.append(objects)
        objects = {}
    return jsonify({'data': info}), 200
Beispiel #15
0
def generate_news_embed(query_string):
    total_news_data = get_news(query_string)
    embed_var = Embed(title=f"{query_string} News", color=16736330)
    for i, news in enumerate(total_news_data[:-1]):
        # only include the first sentence of the article for brevity
        description = news['description'].split(".")[0]
        provider_date = f"*{news['provider']['name']} | {format_date(news['datePublished'])}*"
        embed_var.add_field(name=f"{i + 1}. **{news['title']}**",  
                            value=f"[{description}]({news['url']})" + '\n' + '\n' + provider_date + '\n' + '\n',
                            inline=True)
    embed_var.set_footer(text="From ContextualWeb News")

    return embed_var
Beispiel #16
0
    def send_news(self, event):
        send_text = tn.get_news(self.log)
        send_phno = self.phno.GetLineText(0)

        try:
            sms.sms_send(send_phno, send_text)
        except:
            self.log.AppendText(
                'Error Occured. Ensure the following:\n1. The mobile should be registered and properly entered.\n2. Check proper internet connectivity\n3. The text may be too large\n\nIf problem persists, we regret and please contact admin.\n'
            )
        else:
            self.log.AppendText('News succesfully sent to :' + send_phno)
        finally:
            self.log.AppendText('\n\n' + 'Buzzer v1.0'.center(50, '=') +
                                '\n\n')
Beispiel #17
0
def bot_talking(message):
    bot.send_chat_action(message.chat.id, action='typing')
    if weather.is_weather(message.text.lower()):
        bot.send_message(message.chat.id,
                         weather.get_weather(message.text.lower()))
    elif news.is_news(message.text.lower()):
        bot.send_message(message.chat.id, news.get_news(message.text.lower()))
    elif schedule.is_schedule(message.text.lower()):
        result = schedule.get_schedule(message.text.upper())
        if isinstance(result, str):
            bot.send_message(message.chat.id, result)
        else:
            bot.send_photo(message.chat.id, caption='Держи!', photo=result)
    else:
        bot.send_message(message.chat.id,
                         smart_talking.get_smart_talking(message.text))
Beispiel #18
0
def update_to_site():

	news_list = os.listdir(config.WAIT_PUBLISH_DIR)
	
	
	for file_name in news_list:

		news = news_service.get_news(config.WAIT_PUBLISH_DIR,file_name)
		
		title = news.get("title")
		article = news.get("article")

		post = PostNew(driver)
		post.set_title(title)
		post.set_html_content(article)
		post.save()
		
		news_service.remove(config.WAIT_PUBLISH_DIR,file_name)
Beispiel #19
0
def get_news_summaries(concepts):
    texts = [concept['text'] for concept in concepts]
    query = " ".join(texts)
    news = get_news(query)['results']

    print("Got news, summarizing...")
    news_summaries = []
    for news_article in news:
        news_article['title'], news_article['text'] = get_agolo_summary(
            news_article['url'])
        if news_article['title']:
            news_summaries.append(news_article)

    print("Got summaries")

    print('----------------------')

    return news_summaries
def calculate(url):
    """
    Calculates text similarity.

    Parameters
    ----------
    url: string
        The url to check for similarity

    Returns
    ----------
    float
        Percentage of similarity

    """
    article = Article(url)
    article.download()
    article.parse()

    source_article_body = article.text
    source_article_headline = article.title

    kw = keywords.extract(source_article_body, limit=5)
    try:
        news_articles = news.get_news(' '.join(kw))['articles']
    except NewsAPIException as e:
        return 0.0
    length = 5 if len(news_articles) > 5 else len(news_articles)

    body = []
    headlines = []
    for i in range(length):
        article = Article(news_articles[i]['url'])
        article.download()
        article.parse()
        body.append(article.text)
        headlines.append(article.title)

    body_sim = text_similarity.cosine_similarity(body, source_article_body)
    headline_sim = text_similarity.cosine_similarity(headlines,
                                                     source_article_headline)

    return (body_sim + headline_sim) / 2 * 100
Beispiel #21
0
 def test_get_new_three(self):
     """Testing NEWS"""
     EXPECTED_ARTICLES = [
         Article("Test_Title", "CBS News", "this is a description",
                 "CBS News", "image.jpg", "a time", "link to article")
     ]
     with mock.patch("requests.get", mock_news_request_one):
         articles = get_news(1)
         for i in range(0, len(articles)):
             article = articles[i]
             expected_article = EXPECTED_ARTICLES[i]
             self.assertEqual(article.title, expected_article.title)
             self.assertEqual(article.author, expected_article.author)
             self.assertEqual(article.description,
                              expected_article.description)
             self.assertEqual(article.source, expected_article.source)
             self.assertEqual(article.image, expected_article.image)
             self.assertEqual(article.publishDate,
                              expected_article.publishDate)
             self.assertEqual(article.url, expected_article.url)
Beispiel #22
0
def home():
    if not ('logined' in session) or session['logined'] == False:
        return render_template('login.html', page_title="Авторизация")
    if not ('user_name' in session):
        session['user_name'] = 'admin'
    try:
        user = user_get(session['email'])
    except:
        user = {
            "name": "admin",
            "abilities":
            "JavaScript, PHP, Java, Python, Ruby, Java, Node.js, etc.",
            "finished_tasks": 13,
            "created_tasks": 37
        }
    return render_template('index.html',
                           page_title="Лента",
                           user=user,
                           news=get_news(),
                           count=get_len())
Beispiel #23
0
 def news_displayer(self):
     refreshtime = 60
     # clear screen
     os.system('bw_tool -I -a 94 -D /dev/i2c-1 -w 10:0')
     # set contrast 
     os.system('bw_tool -I -a 94 -D /dev/i2c-1 -w 12:000f')
     # set brightness
     os.system('bw_tool -I -a 94 -D /dev/i2c-1 -w 13:0080')
     while 1:
        	t = get_news()
        	print(t[0])
        	print(t[1])
        	# clear screen
        	os.system('bw_tool -I -a 94 -D /dev/i2c-1 -w 10:0')
        	# write first line
        	os.system('bw_tool -I -a 94 -D /dev/i2c-1 -t {}'.format(t[0]))
        	# set cursor to new line
        	os.system('bw_tool -I -a 94 -D /dev/i2c-1 -w 11:20')
        	# print weather data
        	os.system('bw_tool -I -a 94 -D /dev/i2c-1 -t {}'.format(t[1]))
        	time.sleep(refreshtime)
def get_top_tweets(user):
    tweets = get_tweets("from:" + user)
    news = get_news()

    scored_tweets = []
    for tweet in tweets:
        news.insert(0, tweet.text)
        vect = TfidfVectorizer(min_df=1)
        tfidf = vect.fit_transform(news)
        vectors = (tfidf * tfidf.T).A
        scores_list = vectors.tolist()[0]
        tweet.set_score(sum(scores_list))
        news.pop(0)
        scored_tweets.append(tweet)
    sorted_tweets = sorted(scored_tweets)
    top_ten_scored_tweet_ids = {}
    tweet_count = min(10, len(sorted_tweets))
    for i in range(tweet_count):
        if sorted_tweets[i].score > 1.5:
            top_ten_scored_tweet_ids[str(i)] = sorted_tweets[i].id
    return top_ten_scored_tweet_ids
Beispiel #25
0
def postnews():
    post_data = request.get_json()
    query = post_data['headline']
    data_frame = get_news()
    text = data_frame['Headlines']
    text = text.tolist()
    abstract_vectors = []
    abstract_vectors = generate_embeddings(text, word_embeddings, data_frame)
    result = cosine_sim(query, word_embeddings, abstract_vectors, data_frame)
    result = result.drop(columns=['Datetime', 'Cosine'])
    l = []
    info = []
    objects = {}
    l = result.index.values
    for i in range(9):
        objects['Links'] = result['Links'][l[i]]
        objects['Headlines'] = result['Headlines'][l[i]]
        objects['Publisher'] = result['Publisher'][l[i]]
        objects['Hours'] = result['Hours'][l[i]]
        info.append(objects)
        objects = {}
    return jsonify({'data': info}), 200
Beispiel #26
0
def handle_number(number):
    if int(number) == 1:
        x = 1
    elif int(number) == 2:
        speak_it_to_me(
            "One Six Eight Nine Seven West 73rd place, arvada colorado 80007")
    elif int(number) == 3:
        speak_it_to_me("three")
    elif int(number) == 4:
        speak_it_to_me(horoscope.get_horoscope('sagittarius'))
    elif int(number) == 5:
        speak_it_to_me(joke.get_joke())
    elif int(number) == 6:
        speak_it_to_me(news.get_news())
    elif int(number) == 7:
        speak_it_to_me("seven")
    elif int(number) == 8:
        x = 8
    elif int(number) == 9:
        speak_it_to_me(weather.get_weather())
    elif int(number) == 10:
        speak_it_to_me(get_help_message())
    else:
        speak_it_to_me(number)
Beispiel #27
0
def main():
    token = 'token'
    vk_session = vk_api.VkApi(token=token)
    vk = vk_session.get_api()
    longpoll = VkLongPoll(vk_session)

    summary = '''
Вот что я умею:
    /help - сводка по командам

    /n - новости

    /m - мем

    /w - получить сведения о погоде в Москве
    (Команды с /w пока могут не работать)
    /w <город> - погода на сегодня. Это может занять некоторое время.

    /exr - получить курсы основных валют

    /exr <XXX> - получить информацию по 1 валюте при помощи её чаркода, чем XXX и является.
    Например, получить информацию о Евро: /exr EUR
                            ↓↓↓
    /c - получить чаркоды валют

    /a - скачать прикреленные к команде аудиозаписи, это может занять некоторое время.
    
    /f <жанр> - случайный фильм с таким жанром
    /f жанры - показывает все доступные жанры
    '''

    for event in longpoll.listen():
        if event.type == VkEventType.MESSAGE_NEW and event.to_me:
            random_id = get_random_id()
            user_id = event.user_id
            msg = event.text.lower()

            kwargs = {'user_id': user_id,
                      'random_id': random_id}

            if msg in ('/help', 'начать'):
                vk.messages.send(message=summary, keyboard=enable_keyboard(),
                                 **kwargs)

            elif msg == '/n':
                vk.messages.send(message=get_news(), **kwargs)

            elif msg == '/m':
                vk.messages.send(attachment=get_meme('-157645793'),
                                 **kwargs)

            elif '/w' in msg:
                vk.messages.send(message=get_weather(msg[8:].strip()), **kwargs)

            elif '/exr' in msg:
                vk.messages.send(message=get_exchange_rate(msg[9:].strip().upper()),
                                 **kwargs)

            elif msg == '/c':
                vk.messages.send(message=get_char_codes(), **kwargs)

            elif msg == '/a':
                vk.messages.send(message=download_audio(vk, user_id),
                                 **kwargs)
            elif msg == '/f жанры':
                vk.messages.send(message=get_genre_names(), **kwargs)
            elif '/f' in msg:
                vk.messages.send(message=get_film(msg[2:].strip()), **kwargs)
            else:
                vk.messages.send(message='''Я не понимаю то, что вы написали.
                                 Отправьте /help, чтобы увидеть сводку по командам''',
                                 **kwargs)
Beispiel #28
0
 def test_get_new_four(self):
     """Testing NEWS"""
     EXPETECTED_ERROR = 'API call failed, status = 404'
     with mock.patch("requests.get", mock_news_request_two):
         error = get_news(1)
         self.assertEqual(error['Error'], EXPETECTED_ERROR)
Beispiel #29
0
 def test_get_news_one(self):
     """Testing NEWS"""
     response = get_news(0)
     self.assertEqual(response['Error'], 'Amount of articles must be > 0')
Beispiel #30
0
    def run(self):
        print("Connection of %s %s" % (
            self.ip,
            self.port,
        ))
        r = self.clientsocket.recv(2048)
        data = pickle.loads(r)
        ID_user, message = data['ID_user'], data['message']
        print(ID_user, message)
        subscribe_str = r"subscribe\(([\w\"]*)\)"
        unsubscribe_str = r"unsubscribe\(([\w\"]*)\)"
        add_news_str = r"add_news\(([]\"]?http[s]?://[\w\"\.\/]*)\)"

        if (message == "help" or message == "help()"):
            self.clientsocket.send(b' ' +
                                   b'get_IDuser will give you an userId' +
                                   b' ')
            self.clientsocket.send(b'\n ')
            self.clientsocket.send(
                b' ' + b'get_subjects will give you a list of keyword' + b' ')
            self.clientsocket.send(b'\n ')
            self.clientsocket.send(
                b' ' +
                b'get_subscriptions() will return the list of your subscriptions'
                + b' ')
            self.clientsocket.send(b'\n ')
            self.clientsocket.send(
                b' ' +
                b'unsubscribe(keyword) will remove the keyword subscription' +
                b' ')
            self.clientsocket.send(b'\n ')
            self.clientsocket.send(
                b' ' +
                b'subscribe(keyword) will remove the keyword subscription' +
                b' ')
            self.clientsocket.send(b'\n ')
            self.clientsocket.send(
                b' ' +
                b'add_news(url) will add the news and its keyword from the url'
                + b' ')
            self.clientsocket.send(b'\n ')
            self.clientsocket.send(b' ' +
                                   b'get_news will give all the news for you' +
                                   b' ')
            self.clientsocket.send(b'\n ')
            self.clientsocket.send(b' ' +
                                   b'note: only tested on wikipedia url' +
                                   b' ')

        elif (message == "get_subjects" or message == "get_subjects()"):
            subjects = get_subjects()
            for sub in subjects:
                self.clientsocket.send(b' ' + sub + b' ')

        elif (message == "get_IDuser" or message == "get_IDuser()"):
            current_id = get_IDuser()
            self.clientsocket.send(str(current_id).encode('utf-8'))

        elif (message == "get_subscriptions"
              or message == "get_subscriptions()"):

            subscriptions = get_subscriptions(ID_user)
            self.clientsocket.send(b' your subcriptions: \n' + b' ')
            for sub in subscriptions:
                self.clientsocket.send(b' ' + sub + b' \n ')

        elif (message == "get_news" or message == "get_news()"):
            ID_news_adapted = get_news(ID_user)
            self.clientsocket.send(b' your adapted news: \n' + b' ')
            for id in ID_news_adapted:
                self.clientsocket.send(b' news with id:' +
                                       str(id).encode('utf-8') + b' \n ')

        elif (re.search(subscribe_str, message) != None):

            keyword = re.search(subscribe_str, message).groups()[0]
            print(ID_user, keyword.encode('utf-8'))
            subscriptions = subscribe(int(ID_user), keyword.encode('utf-8'))
            self.clientsocket.send(b'subcribed to : \n' +
                                   keyword.encode('utf-8') +
                                   b' successfully \n')

        elif (re.search(unsubscribe_str, message) != None):
            keyword = re.search(unsubscribe_str, message).groups()[0]
            print(int(ID_user).encode('utf-8'), keyword.encode('utf-8'))
            subscriptions = unsubscribe(int(ID_user), keyword.encode('utf-8'))
            self.clientsocket.send(b'unsubcribed to : \n' +
                                   keyword.encode('utf-8') +
                                   b' successfully \n')

        elif (re.search(add_news_str, message) != None):
            url = re.search(add_news_str, message).groups()[0]
            ID_news, keyword = add_news(url.strip('"'))
            publish(ID_news, keyword)
            self.clientsocket.send(b'added news from : \n' +
                                   url.encode('utf-8') + b' successfully \n')
        else:
            self.clientsocket.send(b' ' + b'Enter help to see the commands' +
                                   b'\n ')
Beispiel #31
0
def news_get():
    news_dic['news_list'] = news.get_news()
    news_dic['is_completed'] = True
Beispiel #32
0
def news():
    ret = get_news()
    return jsonify(ret)
def get_news():
    return str(json.dumps(news.get_news()))