I'm your News Buddy.
bot
A virtual environment is a tool that helps to keep dependencies required by different projects separate by creating isolated python virtual environments for them.
python -m venv myvenv
After running above command, a folder named myvenv will get created in your project folder. Activate the virtual environment by running following command:
pip install python-telegram-bot
import logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',level=logging.INFO)
logger = logging.getLogger(__name__)
updater = Updater(TOKEN)
dp = updater.dispatcher
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", _help))
dp.add_handler(MessageHandler(Filters.text, echo_text))
dp.add_handler(MessageHandler(Filters.sticker, echo_sticker))
dp.add_error_handler(error)
pip install flask
# create telegram bot object
bot = Bot(TOKEN)
# set webhook for telegram bot
bot.set_webhook("https://protected-fjord-75558.herokuapp.com/" + TOKEN)
@app.route(f'/{TOKEN}', methods=['GET', 'POST'])
def webhook():
"""webhook view which receives updates from telegram"""
# create update object from json-format request data
update = Update.de_json(request.get_json(), bot)
# process update
dispatcher.process_update(update)
return "ok"
ngrok is a free tool that allows us to tunnel from a public URL to our application running locally.
./ngrok http 8443
Login into dialogflow console
Create a new agent or import a pre-built agent
From settings page of agent, open the service account of your project in Google Cloud Console
Create a new service account for your project. Download private key for the service account in a JSON file
```python
pip install dialogflow
import dialogflow_v2 as dialogflow
dialogflow_session_client = dialogflow.SessionsClient()
PROJECT_ID = “newsbot-xsfd”
```python
def detect_intent_from_text(text, session_id, language_code='en'):
session = dialogflow_session_client.session_path(PROJECT_ID, session_id)
text_input = dialogflow.types.TextInput(text=text, language_code=language_code)
query_input = dialogflow.types.QueryInput(text=text_input)
response = dialogflow_session_client.detect_intent(session=session, query_input=query_input)
return response.query_result
response = detect_intent_from_text("show me sports news from india in hindi", 12345)
response.intent.display_name
get_news
dict(response.parameters)
{'geo-country': 'India', 'language': 'Hindi', 'topic': 'Sports'}
from gnewsclient import gnewsclient
client = gnewsclient.NewsClient()
def get_reply(query, chat_id):
response = detect_intent_from_text(query, chat_id)
if response.intent.display_name == 'get_news':
return "get_news", dict(response.parameters)
else:
return "small_talk", response.fulfillment_text
pip install gnewsclient
client.location = 'India'
client.language = 'Hindi'
client.topic = 'Sports'
client.get_config()
{'language': 'Hindi', 'location': 'India', 'topic': 'Sports'}
client.get_news()
`[{‘link’: ‘https://news.google.com/__i/rss/rd/articles/CBMijwFodHRwczovL3d3dy5hYWp0YWsuaW4vc3Bv.........?oc=5‘,
‘media’: None,
‘title’: “विराट कोहली के समर्थन में उतरे सलमान बट्ट, माइकल वॉन की ऐसे की ‘बेइज्जती’ - Aaj Tak”},
{‘link’: ‘https://news.google.com/__i/rss/rd/articles/CBMigwFodHRwczovL3d3dy5saXZlaGluZHVzdGFuLm........?oc=5‘,
‘media’: None,
‘title’: ‘दिल्ली: मर्डर केस में पहलवान सुशील कुमार के खिलाफ गैर जमानती वारंट जारी - Hindustan’},
{‘link’: ‘https://news.google.com/__i/rss/rd/articles/CBMipwFodHRwczovL3d3dy5qYWdyYW4uY29tL2Nya..........?oc=5‘,
‘media’: None,
‘title’: ‘भुवनेश्वर कुमार ने टेस्ट नहीं खेलने की खबर को नकारा, कहा- तीनों फॉर्मेट में चयन के लिए उपलब्ध हूं - दैनिक जागरण’}]`
def fetch_news(parameters):
client.language = parameters.get('language')
client.location = parameters.get('geo-country')
client.topic = parameters.get('topic')
return client.get_news()[:5]
def news(bot, update):
bot.send_message(chat_id=update.message.chat_id, text="Choose a category",
reply_markup=ReplyKeyboardMarkup(keyboard=topics_keyboard, one_time_keyboard=True))
topics_keyboard = [
['Top Stories', 'World', 'Nation'],
['Business', 'Technology', 'Entertainment'],
['Sports', 'Science', 'Health']
]
web gunicorn app:app
Also, install gunicorn
in your virtual environment:
pip install gunicorn
To specify a particular version of Python via your app’s runtime.txt
python-3.9.5
Contains all 3rd party libraries required by your app.
Simply do:
pip freeze > requirements.txt
to generate a requirements.txt file.
.gitignore file specifies patterns which are used to exclude certain files in your working directory from your Git history.
myvenv/
*.pyc
Setup Git repository Download
Initialize a new git repository in your project folder.
git init
Add all untracked files to git repository by:
git add .
Commit the changes to git repository by:
git commit -m "YOUR_COMMIT_MESSAGE_HERE"
Create a new heroku account
Download Heroku CLI.
Create a new Heroku app.
heroku create <your-app-name>
Edit app.py
and set webhook URL as your Heroku app’s URL
bot.set_webhook("https://protected-fjord-75558.herokuapp.com/" + TOKEN)
Finally, you are ready to deploy your app by pushing your local git repository to the remote heroku app’s git repository by:
git push heroku master
To check the logs of your heroku app:
heroku logs