I'm currently trying to integrate dialogflow with twilio. I want to be able to parse the voice response that my customer gives to the bot. How do I get the voice response; and send response back based on certain voice texts.
As of now; when someone calls the phone it replies Hello; then I want to be able to grab what customer replies; then respond it back appropriately. So far I am using the webhook "A call comes in".
Would this require extra library that translates voice to text? Or does twilio offer it.
import os
from twilio.rest import Client
from flask import Flask
from twilio.twiml.voice_response import VoiceResponse
app = Flask(__name__)
# using os.environ['account_sid']
#app.route('/voice', methods=["GET","POST"])
def voice():
resp = VoiceResponse()
resp.say("hello")
return str(resp)
if __name__ == "__main__":
app.run(debug=True)
What you are looking for is the voice gather command. Twilio does offer speech recognition itself with this command.
from twilio.twiml.voice_response import Gather, VoiceResponse, Say
response = VoiceResponse()
gather = Gather(input='speech dtmf', timeout=3, num_digits=1)
gather.say('Hello!')
response.append(gather)
print(response)
Documentation here -> https://www.twilio.com/docs/voice/twiml/gather
Related
I am trying to create a connection to whatsapp and my python script via Twilio, to generate automatic conversations. I follow every step in order of this link https://www.pragnakalp.com/create-whatsapp-bot-with-twilio-using-python-tutorial-with-examples/?unapproved=4864&moderation-hash=3861b2bc00104a39b5f3211076dda854#comment-4864
The problem arrays when I start a conversation with the bot, that in my ngrok port, ngrok http 5000 it says POST/ 403 Forbidden, in the section of https requests.
Before sending the message to the bot I run my python script:
from flask import Flask, request
from twilio.twiml.messaging_response import MessagingResponse
app = Flask(__name__)
##app.route("/wa")
#def wa_hello():
# return "Hello, World!"
#app.route("/wasms", methods=['POST'])
def wa_sms_reply():
"""Respond to incoming calls with a simple text message."""
# Fetch the message
msg = request.form.get('Body').lower() # Reading the message from the whatsapp
print("msg-->", msg)
resp = MessagingResponse()
reply = resp.message()
# Create reply
if msg == "hi":
reply.body("hello!")
return str(resp)
if __name__ == "__main__":
app.run(debug=True)
I tried running commands like ngrok http https://localhost:5000, turning off firewalls on my Mac, allowing my country on the Twilio´s web page, inserting config.hosts << /.*\.ngrok\.io/ in my terminal and restaring my laptop, config.hosts << "a0000000.ngrok.io" and skip_before_action :verify_authenticity_token but nothing of this work for me. The error os shown here:enter image description here
I have set up a telegram bot using webhooks in python on google cloud functions. Based on some sample code from the internet I got it to work as a simple echo-bot however the structure is very different to the bots I coded before using long polling:
# main.py
import os
import telegram
def webhook(request):
bot = telegram.Bot(token=os.environ["TELEGRAM_TOKEN"])
if request.method == "POST":
update = telegram.Update.de_json(request.get_json(force=True), bot)
chat_id = update.message.chat.id
# Reply with the same message
bot.sendMessage(chat_id=chat_id, text=update.message.text)
return "ok"
I do not understand how to add any more handlers or different functions to this, especially because cloud functions needs me to name only one function to run from the script (in this case the webhook function).
How can I convert the above logic to the one I am more familiar with below:
import os
TOKEN = "TOKEN"
PORT = int(os.environ.get('PORT', '8443'))
updater = Updater(TOKEN)
# add example handler
def start(update, context):
context.bot.send_message(chat_id=update.message.chat_id, text="Hello, I am dice bot and I will roll some tasty dice for you.")
start_handler = CommandHandler('start', start)
dispatcher.add_handler(start_handler)
# start webhook polling
updater.start_webhook(listen="0.0.0.0",
port=PORT,
url_path=TOKEN)
updater.bot.set_webhook("https://<appname>.herokuapp.com/" + TOKEN)
updater.idle()
This code has the same structure as long polling so I know how to add additional handlers. However it has two problems:
It is the code snippet from the documentation for heroku, so I do not know whether this works the same for google cloud functions
This does not produce one function I can call in cloud functions, I tried wrapping all my code above in one big function webhook and simply running that but it does not work (and does not produce an error on my google dashboard).
Any help is appreciated!
I found this github telebot repo from yukuku with the setup of a telegram bot on App Engine and the webhook implementation using python. As mentioned before you may want to use App Engine in order to implement your bot with many functions on the same main.py file.
I just tried and it's working for me.
i did that here's my snippet
from telegram import Bot,Update
from telegram.ext import CommandHandler,Dispatcher
import os
TOKEN = os.getenv('TOKEN')
bot = Bot(token=TOKEN)
dispatcher = Dispatcher(bot,None,workers=0)
def start(update,context):
context.bot.send_message(chat_id=update.effective_chat.id,text="I am a bot, you can talk to me")
dispatcher.add_handler(CommandHandler('start',start))
def main(request):
update = Update.de_json(request.get_json(force=True), bot)
dispatcher.process_update(update)
return "OK"
# below function to be used only once to set webhook url on telegram
def set_webhook(request):
global bot
global TOKEN
s = bot.setWebhook(f"{URL}/{TOKEN}") # replace your functions URL,TOKEN
if s:
return "Webhook Setup OK"
else:
return "Webhook Setup Failed"
I have a chat and I want to use webhooks to add people into it.
I have tried tagging a user that was not in the chat but that did not work
from httplib2 import Http
from json import dumps
print()
import os
os.system('clear')
#messageinput = input('Message: ')
#
# Hangouts Chat incoming webhook quickstart
#
amp = 1
while amp == 1:
def main():
url = 'https://chat.googleapis.com/v1/spaces/AAAAHDmEsoI/messages?key=AIzaSyDdI0hCZtE6vySjMm-WEfRq3CPzqKqqsHI&token=YpCZyYAzFiTmZhFgs_KLGv8A1qcNFlZLVcUMNkswMCo%3D'
bot_message = {
'text' : 'Hi <users/113438975428215985106>'}
message_headers = { 'Content-Type': 'application/json; charset=UTF-8'}
http_obj = Http()
response = http_obj.request(
uri=url,
method='POST',
headers=message_headers,
body=dumps(bot_message),
)
print(response)
if __name__ == '__main__':
main()
os.system('clear')
print('Message sent as FBI Agent!')
amp = amp + 1
The code did not work to add people
from my experience, i can tell you webhooks are not designed for that, incoming webhook is designed to send messages simply without doing complicated codes, thats the goal from incoming webhook.
and if you read the Hangouts Webhook Docs, you must've seen this:
Incoming webhooks let you send asynchronous messages into Hangouts Chat from applications that aren't bots themselves. For example, you can configure a monitoring application to notify oncall personnel on Hangouts Chat when a server goes down. Incoming webhooks serve as a quick and easy way to integrate with existing workflows such as these without the overhead of writing entire bot applications.
So what you want is not sending a message, what you want is bigger than this, so i suggest using Hangouts API which might help you.
Configure the API, get the credentials, and read the docs ;)
I'm learning python and as a project I'm trying to create a program that will recieve an SMS message, process it, and then depending on what is in that message, send back information.
I am using Twilio in python with Flask and ngrok to do all the SMS stuff, but I am still not sure how to actually receive an SMS as data that I can read and process, as there is no documentation that I can find on it. It would be great if someone could help me with this.
I already know how to receive and send SMS with Twilio, I just need to know how to get the precise message that was sent to my Twilio number.
I believe you already know how to configure Twilio to hit your endpoint when a message comes in. If you configure at Twilio for a POST request, then the data passed to you from Twilio will be in request.form.
If you take a look at Twilio's example here:
(https://www.twilio.com/docs/sms/tutorials/how-to-receive-and-reply-python)
indeed the example makes no use of the data that is coming in.
The modified code below shows some data that is available from the request (and you can write your code depending on what you'd like to do with it).
the number from where the message was sent request.form['From'],
your Twilio number request.form['To']
and the body of the message request.form['Body']
from flask import Flask, request, redirect
from twilio.twiml.messaging_response import MessagingResponse
app = Flask(__name__)
#app.route("/sms", methods=['POST'])
def sms_reply():
"""Respond to incoming calls with a simple text message."""
# Use this data in your application logic
from_number = request.form['From']
to_number = request.form['To']
body = request.form['Body']
# Start our TwiML response
resp = MessagingResponse()
# Add a message
resp.message("The Robots are coming! Head for the hills!")
return str(resp)
if __name__ == "__main__":
app.run(debug=True)
Some other parameters are also available in the request:
MessageSid
SmsSid
AccountSid
MessagingServiceSid
From
To
Body
NumMedia
Docs: (https://www.twilio.com/docs/sms/twiml#request-parameters)
Also you can find more examples if you google for "twilio blog python flask"
I am trying to setup an opening chatting message on my kik bot using Python, and can not seem to find an answer to this question. The StartChattingMessage() is what I am supposed to use to send out the first message.
Here is my code below, ideally when a user responds to your bot, you are able to send out any message by obtaining the chat_id and from_user from the JSON payload, but before the user enters in any text, I would like to display a welcome message to the user, without the user having to say anything at all. But in order to send any message at all you need a chat_id and a from_user values.
# Kik bot messenger using Python 3, Flask, Gunicorn and Jinja 2
from flask import Flask, request, Response
import os
from kik import KikApi, Configuration
from kik.messages import messages_from_json, TextMessage,StartChattingMessage, ScanDataMessage, LinkMessage, \
DeliveryReceiptMessage, ReadReceiptMessage, VideoMessage
app = Flask(__name__)
kik = KikApi("BOT_USERNAME", "BOT_API_KEY")
config = Configuration(webhook='WEBHOOK')
kik.set_configuration(config)
#app.route('/incoming', methods=['POST'])
def incoming():
if not kik.verify_signature(request.headers.get('X-Kik-Signature'), request.get_data()):
return Response(status=403)
messages = messages_from_json(request.json['messages'])
for message in messages:
kik.send_messages([
TextMessage(
to=message.from_user,
chat_id=message.chat_id,
body="Hey Welcome to my chat bot !"
)]
)
return Response(status=200)
#app.route("/", methods=['GET'])
def hello():
return "<h1> Hello Welcome To My Kik Bot Messenger, Check out my bot at #afischbacher95 </h1>"
if __name__ == "__main__":
port = int(os.environ.get("PORT", 5000))
app.run(host='0.0.0.0', port=port)