Amazing-Python-Scripts
54 строки · 1.5 Кб
1import io2import os3import sys4from contextlib import contextmanager5
6import newsapi7from gtts import gTTS8from pydub import AudioSegment9from pydub.playback import play10
11more_news = True12article_number = 013
14
15def fetch_news() -> dict:16query = input("What do you want to hear about? ")17return newsapi.get_everything(q=query)18
19
20# To play audio text-to-speech during execution
21def speak(text: str):22with io.BytesIO() as f:23gTTS(text=text, lang='en').write_to_fp(f)24f.seek(0)25audio = AudioSegment.from_file(f, format="mp3")26play(audio)27
28
29if __name__ == '__main__':30with open("api_key.txt", "r") as file:31api_key = file.readline()32newsapi = newsapi.NewsApiClient(api_key=api_key)33
34headlines = fetch_news()35while more_news:36article_number += 137try:38print()39article = headlines["articles"][article_number]40print(article["title"], "-", article["source"]["name"])41speak(article["title"])42print(article["description"])43speak(article["description"])44print("Continue reading on this URL:", article["source"]["name"])45except IndexError:46speak(47"It looks as there are no more news on this topic. Why not search something else? "48)49except KeyboardInterrupt:50break51if article_number == 10:52article_number = 053if input("Want to hear more news? [y/n] ") != "y":54more_news = False55