Usage

Installation

To run pridar_telegram_bot, first install it using pip:

(.venv) $ pip install pyTelegramBotAPI

Deployment to Telegram

launch(message=str)

implements the API calls to Voiceflow for first message

Parameters

message – user response

Returns

response

Return type

JSON Object

 1def launch(message):
 2   """ implements the API calls to Voiceflow for first message
 3
 4   Parameters
 5   ----------
 6   message : str
 7         User response
 8
 9   Returns
10   -------
11   response : JSON object
12      API call to VoiceFlow
13   """
14   body = {"action": {"type": "launch"}}
15   response = requests.post(
16      f"https://general-runtime.voiceflow.com/state/user/"+str(message.chat.id)+"/interact",
17      json=body,
18      headers={"Authorization": VF_API_KEY},
19   )
20   return response.json()
sendMsg(message=str)

implements the API calls to Voiceflow

Parameters

message – user response

Returns

response

Return type

JSON Object

 1def sendMsg(message):
 2   """ implements the API calls to Voiceflow
 3
 4   Parameters
 5   ----------
 6   message : str
 7         User response
 8
 9   Returns
10   -------
11   response : JSON object
12      API call to VoiceFlow
13   """
14   global request_body
15   if choice:
16      for c in choices:
17            if c["name"] == message.text:
18               request_body = c
19   else:
20      request_body = {"action": {"type": "text","payload":message.text}}
21   response = requests.post(
22      f"https://general-runtime.voiceflow.com/state/user/"+str(message.chat.id)+"/interact",
23      json=request_body,
24      headers={"Authorization": VF_API_KEY},
25   )
26   return response.json()
start(message='/start')

creates first API call to VoiceFlow

Parameters

message – start message

 1@bot.message_handler(commands=["start"])
 2def start(message):
 3   """
 4   only implemented when "/start" command is received
 5   forwards the payload extracted from the response to the user
 6
 7   Parameters
 8   ----------
 9   message : str
10         User's first message
11   """
12   print("launched")
13   response = launch(message)
14   bot.send_message(message.chat.id, response[-1]["payload"]["message"])
handle_message(message=str)

forwards the payload extracted from all responses to the user after first message

Parameters

message – message

 1@bot.message_handler()
 2def handle_message(message):
 3   """
 4   forwards the payload extracted from all responses to the user after first message
 5
 6   Parameters
 7   ----------
 8   message : str
 9      user message for payload to be extracted
10   """
11   print(message.text)
12   global choice
13   global choices
14   global request_body
15   global response
16   response = sendMsg(message)
17   choice = False
18   choices = []
19
20   for resp in response:
21     if resp["type"] == "text":
22         bot.send_message(message.chat.id, resp["payload"]["message"])
23     elif resp["type"] == "choice":
24         choice = True
25         for choice in resp["payload"]["buttons"]:
26             choices.append(choice)
27             bot.send_message(message.chat.id, choice["name"])
28     elif resp["type"] == "end":
29         bot.send_message(message.chat.id, "Thanks for using our chatbot.")

Complete Implementation

Find below the complete implementation of PRIDAR Chatbot Telegram deployment.

  1"""
  2pridar_telegram_bot.py
  3======================
  4
  5Deployment of PRIDAR Chatbot from VoiceFlow to Telegram
  6
  7This program makes https requests to VoiceFlow
  8with the received messages using the VoiceFlow API key and
  9extracts the response payload to forward back to Telegram.
 10
 11Documented by Linta Rahman
 12"""
 13
 14import telebot
 15import requests
 16import os
 17
 18BOT_API_KEY = os.environ.get("TELEBOT_API_KEY")
 19VF_API_KEY = os.environ.get("VF_API_KEY")
 20bot = telebot.TeleBot(BOT_API_KEY)
 21request_body = ""
 22choice = False
 23choices = []
 24response = ""
 25
 26
 27def launch(message):
 28   """ implements the API calls to Voiceflow for first message
 29
 30   Parameters
 31   ----------
 32   message : str
 33         User response
 34
 35   Returns
 36   -------
 37   response : JSON object
 38      API call to VoiceFlow
 39   """
 40   body = {"action": {"type": "launch"}}
 41   response = requests.post(
 42      f"https://general-runtime.voiceflow.com/state/user/"+str(message.chat.id)+"/interact",
 43      json=body,
 44      headers={"Authorization": VF_API_KEY},
 45   )
 46   return response.json()
 47
 48def sendMsg(message):
 49   """ implements the API calls to Voiceflow
 50
 51   Parameters
 52   ----------
 53   message : str
 54         User response
 55
 56   Returns
 57   -------
 58   response : JSON object
 59      API call to VoiceFlow
 60   """
 61   global request_body
 62   if choice:
 63      for c in choices:
 64            if c["name"] == message.text:
 65               request_body = c
 66   else:
 67      request_body = {"action": {"type": "text","payload":message.text}}
 68   response = requests.post(
 69      f"https://general-runtime.voiceflow.com/state/user/"+str(message.chat.id)+"/interact",
 70      json=request_body,
 71      headers={"Authorization": VF_API_KEY},
 72   )
 73   return response.json()
 74
 75@bot.message_handler(commands=["start"])
 76def start(message):
 77   """
 78   only implemented when "/start" command is received
 79   forwards the payload extracted from the response to the user
 80
 81   Parameters
 82   ----------
 83   message : str
 84         User's first message
 85   """
 86   print("launched")
 87   response = launch(message)
 88   bot.send_message(message.chat.id, response[-1]["payload"]["message"])
 89
 90@bot.message_handler()
 91def handle_message(message):
 92   """
 93   forwards the payload extracted from all responses to the user after first message
 94
 95   Parameters
 96   ----------
 97   message : str
 98      user message for payload to be extracted
 99   """
100   print(message.text)
101   global choice
102   global choices
103   global request_body
104   global response
105   response = sendMsg(message)
106   choice = False
107   choices = []
108
109   for resp in response:
110      if resp["type"] == "text":
111            bot.send_message(message.chat.id, resp["payload"]["message"])
112      elif resp["type"] == "choice":
113            choice = True
114            for choice in resp["payload"]["buttons"]:
115               choices.append(choice)
116               bot.send_message(message.chat.id, choice["name"])
117      elif resp["type"] == "end":
118            bot.send_message(message.chat.id, "Thanks for using our chatbot.")
119
120
121while True:
122   try:
123      bot.polling()
124   except Exception as ex:
125      print(ex)
126      print("Bot polling failed, restarting...")
127      bot.stop_polling()
128   else:
129      bot.stop_polling()
130      break