项目作者: swagatobag2000

项目描述 :
I'm your News Buddy.
高级语言: Python
项目地址: git://github.com/swagatobag2000/python-telegram-bot.git
创建时间: 2021-05-16T05:30:03Z
项目社区:https://github.com/swagatobag2000/python-telegram-bot

开源协议:

下载


python-telegram-bot

Screenshots


How to make python-telegram-bot

1. Registering a Telegram Bot

  • Choose a bot name and then choose a username for your bot. It must end in bot
  • Like : newsbuddy_bot
  • Then the bot will be created

2. Setup a Python Virtual Environment

A virtual environment is a tool that helps to keep dependencies required by different projects separate by creating isolated python virtual environments for them.

  • Create a Project Folder and run following command to create a new virtual environment inside your project folder:
  1. 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:

    • For ubuntu and mac users:

      1. source myvenv/bin/activate
      • For windows users:

        1. myvenv\Scripts\activate

        3. Install required Python Packages:

  1. pip install python-telegram-bot

4. Start Coding

  • Enable Logging
  1. import logging
  2. logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',level=logging.INFO)
  3. logger = logging.getLogger(__name__)
  • Create Updater
  1. updater = Updater(TOKEN)
  • Create Dispatcher
  1. dp = updater.dispatcher
  • Add handlers
  1. dp.add_handler(CommandHandler("start", start))
  2. dp.add_handler(CommandHandler("help", _help))
  3. dp.add_handler(MessageHandler(Filters.text, echo_text))
  4. dp.add_handler(MessageHandler(Filters.sticker, echo_sticker))
  5. dp.add_error_handler(error)

5. Setting up a server

  • Install Flask
  1. pip install flask
  • Setup Webhook
  1. # create telegram bot object
  2. bot = Bot(TOKEN)
  3. # set webhook for telegram bot
  4. bot.set_webhook("https://protected-fjord-75558.herokuapp.com/" + TOKEN)
  • Create view to handle webhooks
  1. @app.route(f'/{TOKEN}', methods=['GET', 'POST'])
  2. def webhook():
  3. """webhook view which receives updates from telegram"""
  4. # create update object from json-format request data
  5. update = Update.de_json(request.get_json(), bot)
  6. # process update
  7. dispatcher.process_update(update)
  8. return "ok"
  • Generate Public URL for Webhook using ngrok.io

ngrok is a free tool that allows us to tunnel from a public URL to our application running locally.

  • Download ngrok
  • Unzip it.
  • Run ngrok from command line (from the location where executable is stored)
  • Ports currently supported for Webhooks: 443, 80, 88, 8443
    1. ./ngrok http 8443
  • Copy the HTTPS Forwarding URL

5. Introduction to Dialogflow

  • 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

  • Install Python Client for Dialogflow
  • dialogflow-python-client
    1. pip install dialogflow
    ```python

    in utils.py

    import os
    os.environ[“GOOGLE_APPLICATION_CREDENTIALS”] = ‘client.json’

    Original address can be given or client.json should be present in same directory

    client.json is the key file downloaded from google cloud console

import dialogflow_v2 as dialogflow
dialogflow_session_client = dialogflow.SessionsClient()
PROJECT_ID = “newsbot-xsfd”

This Project id can be found in settings page of agent

  1. ```python
  2. def detect_intent_from_text(text, session_id, language_code='en'):
  3. session = dialogflow_session_client.session_path(PROJECT_ID, session_id)
  4. text_input = dialogflow.types.TextInput(text=text, language_code=language_code)
  5. query_input = dialogflow.types.QueryInput(text=text_input)
  6. response = dialogflow_session_client.detect_intent(session=session, query_input=query_input)
  7. return response.query_result
  8. response = detect_intent_from_text("show me sports news from india in hindi", 12345)
  1. response.intent.display_name

:arrow_forward: get_news

  1. dict(response.parameters)

:arrow_forward: {'geo-country': 'India', 'language': 'Hindi', 'topic': 'Sports'}

6. Integrating dialogflow to telegram bot

  1. from gnewsclient import gnewsclient
  2. client = gnewsclient.NewsClient()
  3. def get_reply(query, chat_id):
  4. response = detect_intent_from_text(query, chat_id)
  5. if response.intent.display_name == 'get_news':
  6. return "get_news", dict(response.parameters)
  7. else:
  8. return "small_talk", response.fulfillment_text
  • News Source
  1. pip install gnewsclient
  1. client.location = 'India'
  2. client.language = 'Hindi'
  3. client.topic = 'Sports'
  1. client.get_config()

:arrow_forward: {'language': 'Hindi', 'location': 'India', 'topic': 'Sports'}

  1. client.get_news()

:arrow_forward:
`[{‘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’: ‘भुवनेश्वर कुमार ने टेस्ट नहीं खेलने की खबर को नकारा, कहा- तीनों फॉर्मेट में चयन के लिए उपलब्ध हूं - दैनिक जागरण’}]`

  • Integrating gnewsclient in telegram bot
  1. def fetch_news(parameters):
  2. client.language = parameters.get('language')
  3. client.location = parameters.get('geo-country')
  4. client.topic = parameters.get('topic')
  5. return client.get_news()[:5]

7. Custom Keyboard Reply Markup

  1. def news(bot, update):
  2. bot.send_message(chat_id=update.message.chat_id, text="Choose a category",
  3. reply_markup=ReplyKeyboardMarkup(keyboard=topics_keyboard, one_time_keyboard=True))
  • A keyboard is provided as a list of lists (consider it like a table)
  1. topics_keyboard = [
  2. ['Top Stories', 'World', 'Nation'],
  3. ['Business', 'Technology', 'Entertainment'],
  4. ['Sports', 'Science', 'Health']
  5. ]

8. Create some new files for Heroku deployment

  • Procfile : A Procfile is a mechanism for declaring what commands are run by your application’s dynos on the Heroku platform.
  1. web gunicorn app:app

Also, install gunicorn in your virtual environment:

  1. pip install gunicorn
  • runtime.txt

To specify a particular version of Python via your app’s runtime.txt

  1. python-3.9.5
  • requirements.txt

Contains all 3rd party libraries required by your app.

Simply do:

  1. pip freeze > requirements.txt

to generate a requirements.txt file.

  • .gitignore

.gitignore file specifies patterns which are used to exclude certain files in your working directory from your Git history.

  1. myvenv/
  2. *.pyc

9. Now, its time to create a Heroku app!

  • Setup Git repository Download

    • Initialize a new git repository in your project folder.

      1. git init
    • Add all untracked files to git repository by:

      1. git add .
    • Commit the changes to git repository by:

      1. git commit -m "YOUR_COMMIT_MESSAGE_HERE"
  • Create a new heroku account

  • Download Heroku CLI.

  • Create a new Heroku app.

    1. heroku create <your-app-name>
  • Edit app.py and set webhook URL as your Heroku app’s URL

  1. 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:

    1. git push heroku master
  • To check the logs of your heroku app:

    1. heroku logs