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 ;)
Related
So, i have this code:
import os
from twilio.rest import Client
xml=f'''
<Response>
<Say language="ru-RU">Здравствуйте, пожалуйста введите код для подтверждения.</Say>
</Response>'''
account_sid = ('AC274461ad47988c753424a3c8735dbcc1')
auth_token =('8ac88e8d5bce419ae3b5cbac4fc255f9')
client = Client(account_sid, auth_token)
call = client.calls.create( twiml=xml,
to='+375336412273',
from_='+12318247004',
)
print(call.sid)
I want to put in xml, that way, so i could put result of (what user typed in) in variable.
I want to do it only with python and twilio.rest, on twilio site i only found how to do it with flask, url and twiml.
Twilio developer evangelist here.
In order to be able to run interactive phone calls, there needs to be a way for your application to give instructions to Twilio, receive responses and then give further instructions. The instructions are the TwiML that you send to Twilio, but the way that Twilio communicates things back to you, like the result of what a user typed during a <Gather>, is via webhooks. Webhooks are HTTP requests from Twilio that include data about the call, like user input, in the body of the request.
To use that data and provide Twilio with further TwiML instructions your application needs to be able to receive HTTP requests and respond with an HTTP response containing the TwiML.
There are example in the Twilio documentation using Flask because Flask is a good way to receive and respond to HTTP requests in Python. You could build an application without a framework like Flask, but you would still need to be able to receive an incoming HTTP request and respond to it.
I have a small script that sends text messages with Twilio using Python.
This is my code:
import os
from twilio.rest import Client
account_sid = os.environ.get('TWILIO_ACCOUNT_SID')
auth_token = os.environ.get('TWILIO_AUTH_TOKEN')
client = Client(account_sid, auth_token)
cell_number = os.environ.get('CELL_PHONE_NUMBER')
text_message = input("Enter a message to send: ")
send_message = client.messages.create(from_=os.environ.get('TWILIO_PHONE_NUMBER'),
to=cell_number,
body=text_message
print(send_message)
And this is the response I get back:
<Twilio.Api.V2010.MessageInstance account_sid=MY_ACCOUNT_SID sid=SMc5e8f335198144b4b3c7f401af511f11>
I was wondering what the best way was to validate that the message was actually sent in code.
I thought of doing something like this:
if send_message:
print("Message sent.")
else:
print("Message not sent.")
And I was just wondering if there was a better way to do that.
I understand that this is a relatively old question and you might have figured out a way to achieve the desired behavior, but just wanted to post my thoughts so that it may help other learners like me in the future.
So basically, twilio provides developers with a functionality of webhooks using which the status of messages can be tracked. You will have to provide an extra parameter while creating the message wherein you will have to pass the callback url pointing to a server which will be logging the status of the sent messages.
When your python script sends a SMS by doing a POST request to twilio server, twilio will send the status of the message to the callback URL as a parameter by making a post or a get request.
This document describes how to achieve the above behavior with the help of example code snippets. In case you used another method to track the status of the messages, let us know so that it will help the community.
Is it possible to set up this simple bot, using an incoming webhook, but send the message as a DM (not a #mention) to specific user(s)?
My guess is no. But then how could I achieve this?
Right now, the message is just sent into the room in which the bot was added and I can't see anything on DMs in the messaging docs.
You can currently achieve this very easily in Slack by setting up a so called bot user and using their chat.postMessage but I would like to do this in Google Hangouts Chat instead.
from httplib2 import Http
from json import dumps
#
# Hangouts Chat incoming webhook quickstart
#
def main():
url = '<INCOMING-WEBHOOK-URL>'
bot_message = {
'text' : 'Hello from Python script!'}
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()
As of now you would need their Space ID or webhook url in order to DM the user privately whether you use a webhook (like you did) or REST API. Unless you have this Space ID/Webhook you cannot message a user. One way of getting it, is to ask the user for their spaceID and store it. Either way, Google API hasn't given a way to retrieve a different Space ID then the current one you are talking inside of. This means, a bot can only message users its interacted with at some point.
The current Space ID value can be retrieved from the event JSON (event['space']['name']) and then using messages.create to send a new message to the user
service.spaces().messages().create( parent = spaceName, body = response).execute()
OR it can be retrieved from the url https://chat.google.com/dm/ --> space ID is here <---
Google has not released any way of generating your own spaceID for a specific user.
EDIT: In order to get the webhook url. See below:
then copy and paste the webhook url into your code above.
NOTICE: If you need, this webhook url can be manufactured using the usual url for google chat with their space ID as mentioned above and a key and access token in this format: https://chat.googleapis.com/v1/spaces/< space ID >/messages?key=A< key goes here > &token=< access token here >
For info on how to get a key and access token, read the documentation provided here: https://developers.google.com/identity/protocols/OAuth2
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'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