Send messages to Twilio Flex - python

Just to try to give you an idea of what we are trying to do: we have a Python system that works like a chatbot, answering some questions automatically, but there comes a time when we need to send the contact to the service one by one, and we need to use Python to open the conversation in Flex
I tried many ways to send messages to a chat on Flex, but as I said previously we just able to create a chat no send messages into it, better saying, we’re able to send the messages but they don’t appear on Flex’s chat interface (that’s weird). I tried 1) using the normal way via API, 2) creating a Runtime function (the same result than via API, just creating a chat but no messages appearing), 3) I tried applying Twilio Sync, and also 4) I tried using Twilio Proxy directly.
I can get the sid for all objects created and see the chat created on Flex interface, but I can't see the messages sent to this chat on Flex's UI.
event = {
'from': 'phone_number_from',
'to': 'flex_phone_number',
'body': 'Testing'
}
attrs = get_channel_attrs(event.get('from'))
channel = get_or_create_chat_channel(event.get('from'), event.get('to'), attrs)
print('Channel created: %s' % channel.sid)
task = get_or_create_ongoing_tasks(event.get('from'), channel.sid)
print('Task created: %s' % task.sid)
message = send_message(channel=channel, from_=event.get('from'), body=event.get('body'))
print('Message created: %s' % message.sid)
-----------------------
Channel created: CH99b4831f********************
Task created: WTe8eee516********************
Message created: IM08884be42********************

You may need to set additional attributes for the chat task to appear in Flex. Here is an example of Taskrouter attributes through the web chat and through SMS in Taskrouter. These tasks both appear in Flex.
Web chat:
{"channelSid":"CHc7221e1c8ac04b4d9f45xxxxxxxxxxxx","name":"Jane","channelType":"web"}
SMS:
{"channelSid":"CH86818963afed4d769fb3xxxxxxxxxxxx","endpoint":"sms","identity":"+15555555555","name":"+15555555555","title":"SMS request"}

Aaron, I am having similar issue and was trying to have a look at Flex Create Chat function but it is not there. When I click "create a function" and filter by flex product only blan function template is provided which will generate this function code:
exports.handler = function(context, event, callback) {
let twiml = new Twilio.twiml.VoiceResponse();
// twiml.say("Hello World");
callback(null, twiml);
};

Related

SocketIO to emit to a particular user (without using separate room for every client)

I am trying to develop a web application that supports a long task at the backend. I am using flask-socketio package on my server along with celery. My workflow is following :
When a client opens the Html page -- I initiate a socket connection to the server which creates a uid for the user and emits it back.
Now once the user posts a request for the long task -- I schedule it using celery and once finished I need to emit it to the user who posted the request. (I stored the relevant userid in post request)
I have looked at #Miguels's answer for 39423646/flask-socketio-emit-to-specific-user which creates a separate room for each user and then broadcasts the message on that room. But I wanted to ask if there is some other simpler way to do this since it seems inefficient or forced way to do this.
I also came across the nodejs solution (how-to-send-a-message-to-a-particular-client-with-socket-io) which I felt to be a more natural way to accomplish this. Is there a similar solution in python-socketio too?
Update: After some more search I came across the following solution on a github gist. According to this -- ** flash-socketIO already puts all clients in the separate room given by request.sid **.
I would still wish to discuss other ways to do this. Specifically if the site traffic is quite high -- wouldn't it lead to too many rooms?
Update (2): my current (working) server code which makes use of rooms. This is borrowed and modified from flask-SocketIO celery example
#celery.task(bind=True)
def long_task(self, userid, url):
# LONG TASK
time.sleep(10)
# meta = some result
post(url, json=meta)
# It seems i can't directly emit from celery function so I mimic a post request and emit from that function
return meta
#app.route('/longtask', methods=['POST'])
def longtask():
userid = request.json['userid']
task = long_task.delay(elementid, userid, url_for('event', _external=True))
return jsonify({}), 202
#socketio.on('connect', namespace='/custom')
def events_connect():
userid = str(uuid.uuid4())
session['userid'] = userid
current_app.clients[userid] = request.sid
emit('userid', {'userid': userid})
#app.route('/event/', methods=['POST'])
def event():
userid = request.json['userid']
data = request.json
roomid = app.clients.get(userid)
socketio.emit('celerystatus', data, namespace='/custom', room=roomid)
return 'ok'
You don't have to create any rooms to address an individual user. Just set the to argument to the sid of the user you want to address:
emit('my event', my_data, to=user_sid)
The sid value that is assigned to each user is given to you in the connect event handler as request.sid.
You can make a room for every separate user. And you can emit to a particular room which user you want to share the message.
io.to(user.room).emit('specific-user', { message });
Here mean to separate user room that you need to define a room id to a chat room like a chat application (one-to-one-communication).
Room id can be concatinate of own id and user id which you want to send a message for a unique room id for each user.

How to send python output to telegram CHANNEL not to Group and gmail email group

Hi I have a program in python that generates results every one hour. The result can be of anything.This program will run in local machine or in the virtual private network.
I have two requirements
1. Send this python generated result to one telegram group [Group name "ourworld"](created by me) automatically without user intervention . (I have desktop telegram client running or web.telegram.org running in the same system)
Send this result to gmail group email ID.
what are the methods available to achieve this requirement .Is there any working code available to do this job .Please share the info and details.
Edit:
The Issue that i am facing :
1.created a Bot using BotFather.
2.Adding this Bot to my Group ,Here i get an error could not add an member So added the Bot as admin in the group
3.Token of the BOT noted down.
4. Trying to get ChatId
in this forum (https://web.telegram.org/#/im?p=g154513121) someone says number after p=g is the chartid ,In my case there is no
number it shows #testingname like this.
Using this approach trying to get the Chat ID https://api.telegram.org/bot738909732:AAE-2l7xAAlYHBXprK_a_bex09g9DMZbbDI/getme
so here 738909732 become a chat Id (in this case why we need seperate
call for the chart id)
here it is true as response coming! Here the chat id is the ID of the my "testingname" no chart id generated for the group.
6.Now packing the URL to see the response i am getting this error.
https://api.telegram.org/bot738909732:AAE-2l7xAAlYHBXprK_a_bex09g9DMZbbDI/sendMessage?chat_id=738909732&text=testing
the output if i run this in browser
{"ok":false,"error_code":400,"description":"Bad Request: chat not
found"} {"ok":false,"error_code":403,"description":"Forbidden: bot
can't send messages to bots"}
How to resolve this issue and make the BOT working .why i am not able to add BOT to my group that says error "Cant Add user"
How to make this telegram group working.
Note : Using BotFather BOT created
In case for sending message to telegram group the above method provided by bipin_s works where the chat_id = -xxxxxx is used.This is correct id followed by - symbol to be used.
For Posting message in the "telegram channel " a minor change needs to be done in the URL.The URL must be framed as below .
url = "https://api.telegram.org/botTokenID/sendMessage?chat_id=#yourChannelChatID&text=message"
Replace the TokenID with your BOT tokenID replace the yourChannelChatID with your channel chart id.Please note that the channel id is not negative id.
the code will look like this
import request
url = "https://api.telegram.org/botXyz:wwwwDFSJSJSAX/sendMessage?chat_id=#telechanneltesting&text=message"
requests.post(url)
Here the "message" as in the URL it will be posted in telegram channel.
How to get channel id ?
Go to https://web.telegram.org/#/im in browser ,after login now search your "channel".Now in the browser address bar you will one link like https://web.telegram.org/#/im?p=#llliopppppsssssr
p=#llliopppppsssssr after the equal symbol what comes is channel chat ID.
to send message to the telegram "group" without any user intervention , you require a telegram bot. create one using telegram bot-father. take a look at this link. also note the token while creating the bot. This method will work only for telegram Group .Telegram channel another method to be followed which MarxBabu answered below in his answers post.
import requests
# telegram url
url = "https://api.telegram.org/bot<Token>"
def send_mess(text):
params = {'chat_id':-xxxxxxx, 'text': text}
response = requests.post(url + 'sendMessage', data=params)
return response
send_mess(result_you_want_to_send)
to get the chat_id follow the steps mentioned here. note: group chat id's always starts with '-' . e.g. of group chat_id -356163873. A token and chat_id is only what you require to send message to telegram group.
for sending group emails you have to search more as i do not know much
I have it running on a Raspberry pi. You must look for botfather to get your telegram token.
import telepot
from telepot.loop import MessageLoop
telegram_token = 'xxxx:xxxxxx'
user = 4444444
bot = telepot.Bot(telegram_token)
bot.sendMessage(user, 'Hey!')
For configuring gmail I don't have something here right now...
You can send emails in python through SMTP or using the Mailgun Api
I personally prefer using Mailgun as it is easier to setup and sending an email is as easy as sending a post request to mailgun.
You can get the free version of the api and add your group email id to the sandbox (to avoid spam) and then use requests to post an email with the given api token

Google Hangouts Chat bot to send DMs via incoming webhook?

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

GAE Channel API - 400 Bad Request on disconnect

I'm working on a chat application using GAE's Channel API in Python.
I don't think I've set it up correctly. When I leave a page I get the following error message in my browser console:
http://localhost:8080/_ah/channel/dev?command=disconnect&channel=0e0acee3bd…122e0acaa86eeb-channel-1354440420-1452408747-mike|5066549580791808&client=1 400 (Bad Request)
Also, when I send chat message it sends duplicate messages, so I'm guessing users are not being properly disconnected.
I've set it up such that when user visits page, my backend code checks if they are logged in, and if so will automatically create token based on their username and the permalink ID of the page.
I then create a token, calling channel.create_channel method and pass that token as a value in the dict I include when I render my template (Jinja).
In my front-end I open the channel with the token. My on-close function is:
socket.onclose = function(){
connected = false;
}
In my app.yaml file I have included inbound_services: - channel presence.
In my backend code, I have '/_ah/channel/disconnected/'routed to a class that gets that permalink's entity instance, finds the client id from a list of connections and removes that connection from the entity.
Can you someone help me think about the Channel API the right way?

How can I send a message from a flask route to a socket using flask-socketio

I have the following scenario I would like to implement:
User surfs to our website
User enters a bitcoin address.
A websocket is created to the server, passing the address.
The server registers a callback with Blocktrail
When the callback is triggered (a payment was seen by Blocktrail) we send a message back to the browser.
The page the user is browsing is updated to show the message recieved
I'm using webhooks from the Blocktrail API to "listen" to an event, being the reception of coins on an address.
Now, when the event happens, the API does a POST to my URL. This should send a message to the browser that is connected to my server with socket.io (such as 'payment seen on blockchain')
So the question is,
How can I send a message from a route to a socket using flask-socketio
Pseudo code:
#app.route('/callback/<address>')
def callback(id):
socketio.send('payment seen on blockchain')
#socketio.on('address',address)
def socketlisten(address):
registerCallback(address)
I'm going to describe how to solve this using Flask-SocketIO beta version 1.0b1. You can also do this with the 0.6 release, but it is a bit more complicated, the 1.0 release makes addressing individual clients easier.
Each client of a socket connection gets assigned a session id that uniquely identifies it, the so called sid. Within a socket function handler, you can access it as request.sid. Also, upon connection, each client is assigned to a private room, named with the session id.
I assume the metadata that you receive with the callback allows you to identify the user. What you need is to obtain the sid of that user. Once you have it, you can send your alert to the corresponding room.
Example (with some hand-waving regarding how you attach a sid to an address):
#app.route('/callback/<address>')
def callback(address):
sid = get_sid_from_address(address)
socketio.send('payment seen on blockchain', room=sid)
#socketio.on('address')
def socketlisten(address):
associate_address_with_sid(address, request.sid)

Categories

Resources