Python - Slack outgoing webhook to Telegram - python

I'm working on a webhook that sends Telegrams messages to Slack and Slack messages to Telegram; right now I can send Telegram messages to Slack but I can't send from Slack to Telegram because I don't know how to get the data. As the Slack documentation states, the data sent on the POST request is like this:
token=XXXXXXXXXXXXXXXXXX
team_id=T0001
team_domain=example
channel_id=C2147483705
channel_name=test
timestamp=1355517523.000005
user_id=U2147483697
user_name=Steve
text=googlebot: What is the air-speed velocity of an unladen swallow?
trigger_word=googlebot:
The content type is application/x-www-form-urlencoded
From that data I want to get the user_name and text
On my Flask code I don't have nothing because I don't know how to receive that data or how can I see it on the console so I could try to extract it and send it to Telegram, this is the only thing that I have for the Slack webhook just because I wanted to see if it was working, I think that these lines of code are not relevant right now:
#app.route("/" + SLACK, methods=['POST'])
def slack_handler():
if request.method == "POST":
return "POST"
And that's my problem; how can I receive, store that data? if I should explain more my issue please let me know and thanks for any help.

As long as your slack webhook is configured appropriately you should be able to treat it like a form. The following should work-
from flask import Flask, request
slack_webhook = your_webhook_here
#app.route('/slack', methods=['POST'])
def slack():
if request.form.get('token') == slack_webhook:
channel = request.form.get('channel')
username = request.form.get('username')
return "Channel: " + channel + "Username: " + username
else:
return "None found"
Read this post for more on this-
realpython.com

Related

Discord - Send messages from a channel to my website in real time

I currently have a python/django platform and a discord community. On my discord server there is a channel "announcements". I would just like that when a message is published in this channel, it goes up to my website in real time. This is in order to convert it into a notification.
Currently I managed to upload the messages from the channel to my site in a simple way but not in real time:
def discord_get_last_message_id():
message_id = 0
try:
message_id = Notification.objects.latest('id').discord_message_id
except:
pass
return message_id
def get_channel_messages():
#load last id discord message in DB
last_message_id = discord_get_last_message_id()
#Base route
route = "/channels/"+ DISCORD_CHANNEL_ANNONCES_ID +"/messages"
#if first time to DB, load just one item
if last_message_id == 0:
add = "?limit=1"
else:
add = "?after="+last_message_id
route = route + add
data,error_message = request_discord('GET',route)
print(data)
def request_discord(method,url_access,body={}):
data =''
#Call token
error_message = ''
access_token = discord_get_token()
#Call request
headers = {'Authorization': access_token}
body = body
if method=="GET":
result = requests.get(DISCORD_BASE_URI + url_access, headers=headers)
else:
result = requests.post(DISCORD_BASE_URI + url_access, headers=headers,data=body)
#Check result
if result.status_code != 200 and result.status_code != 201:
error_message = "Impossible de d'obtenir un resultat erreur: " + str(result.status_code)
else:
data = result.json()
return data,error_message
def discord_get_token():
return DISCORD_ANNONCES_CHANNEL_TOKEN
I'm trying to understand how discord websockets work but I have the impression that it's made to communicate with a bot only.
My question is, which way should I go to get the messages from my discord channel to my website in real time? Do I have to go through a bot?
NOTE: the goal is to get his messages to make notifications on my platform.
Thanks for your answers !
To answer your question:
My question is, which way should I go to get the messages from my discord channel to my website in real time? Do I have to go through a bot?
The best way would be to use a bot. This is the simplest, yet best way to do accomplish what you want. You could use a on_message event to get messages when they are sent. Then you could use that message and update your website. An example of how to do this is:
#bot.event
async def on_message(message):
message_content = message.content
return
You can do whatever you want with message_content. For your purpose you might want to store it in a database.
For the website side, you could use JavaScript to get the messages from the DB and update the HTML accordingly.

How do you send a typing bubble to FB messenger via Flask and pymessenger?

I'm building a chatbot deployed via FB messenger. According to FB documentation, you have to send this post request to the messenger platform. I send a string representation of the payload using json.dumps. However, I never see the typing bubble and only get the actual response message from the bot. Here is the pertinent code from the Flask app.
#app.route('/', methods=['GET', 'POST'])
def receive_message():
global tag, latest_message
if request.method == 'GET':
# Before allowing people to message your bot Facebook has implemented a verify token
# that confirms all requests that your bot receives came from Facebook.
token_sent = request.args.get("hub.verify_token")
return verify_fb_token(token_sent)
# If the request was not GET, it must be POSTand we can just proceed with sending a message
# back to user
else:
# get whatever message a user sent the bot
output = request.get_json()
for event in output['entry']:
messaging = event['messaging']
for message in messaging:
if message.get('message'):
# Facebook Messenger ID for user so we know where to send response back to
recipient_id = message['sender']['id']
typing_payload = json.dumps({"recipient":{"id":recipient_id}, "sender_action":"typing_on"})
bot.send_raw(typing_payload)
time.sleep(3)
if message['message'].get('text'):
response_sent_text = send(message['message'].get('text'))
send_message(recipient_id, response_sent_text)
latest_message = response_sent_text
return "Message Processed"
You can use Pymessenger wrapper. Just import it, create an instance and pass your FB_TOKEN and wrap your actions. Remember when sending action, Facebook doc state that you must only pass the recipient_id and action and call the method separate from the response.
set action to "typing_on" in your method.
NB: Your method is incorrect because you are mixing sender_id and recipient_id
from pymessenger import Bot
bot = Bot(<FB_ACCESS_TOKEN>)
def send_typing_bubble(sender_id, recipient_id, action, response_sent_text):
bot.send_action(sender_id, action)
bot.send_text_message(sender_id, response_sent_text)
After your create the method you can just call send_typing_bubble() inside your webhook receive_message() method
if messaging_event.get('message'):
#your code here
send_typing_bubble(sender_id, recipient_id, action,
response_sent_text)

How to do a "typing_on" post with pymessenger to FB messenger?

I'm trying to set my chatbot to display a typing bubble before sending the user the response so that it's more human like. I followed the documentation but am still getting instant responses from the bot with no typing bubble. As per the documentation I am using this sender action:
{"recipient":{"id":recipient_id}, "sender_action":"typing_on"}
And to put it in context, here is how I'm using it in the flask app:
#app.route('/', methods=['GET', 'POST'])
def receive_message():
global tag, latest_message
if request.method == 'GET':
# Before allowing people to message your bot Facebook has implemented a verify token
# that confirms all requests that your bot receives came from Facebook.
token_sent = request.args.get("hub.verify_token")
return verify_fb_token(token_sent)
# If the request was not GET, it must be POSTand we can just proceed with sending a message
# back to user
else:
# get whatever message a user sent the bot
output = request.get_json()
for event in output['entry']:
messaging = event['messaging']
for message in messaging:
if message.get('message'):
# Facebook Messenger ID for user so we know where to send response back to
recipient_id = message['sender']['id']
if message['message'].get('text'):
response_sent_text = send(message['message'].get('text'))
send_message(recipient_id, response_sent_text)
latest_message = response_sent_text
return "Message Processed"
def send_message(recipient_id, response):
# sends user the text message provided via input response parameter
typing_payload = {"recipient":{"id":recipient_id}, "sender_action":"typing_on"}
bot.send_raw(typing_payload)
print(bot.send_raw(typing_payload))
bot.send_text_message(recipient_id, response)
return "success"
Any ideas would be much appreciated!
You should pass a string representation of the payload (not a dictionary).
try doing something like this:
import json
...
def send_message(recipient_id, response):
# sends user the text message provided via input response parameter
typing_payload = json.dumps({"recipient":{"id":recipient_id}, "sender_action":"typing_on"})
bot.send_raw(typing_payload)
print(bot.send_raw(typing_payload))
bot.send_text_message(recipient_id, response)
return "success"
Also it's best practice to send these indicators upon receiving message (to show the typing indicator while processing), as opposed to directly before sending message.

How to pass response from external api to dialog in watson conversation?

I'm building a weather bot using watson conversation api.
Whenever a user sends 'what is the weather of '. I get back a response with intents and entities. Now I make a call to a weather api and get a response. How do I pass this weather response back to watson dialog to be displayed?
I think that I have to send the response through context object, but how do I make the call to conversation api to pass the response?
I'm using python api.
In this case, the API Referecence from IBM official document, show one example to how send message inside Watson Conversation Service.
Check this example:
import json
from watson_developer_cloud import ConversationV1
conversation = ConversationV1(
username='{username}',
password='{password}',
version='2017-04-21'
)
# Replace with the context obtained from the initial request
context = {}
workspace_id = '25dfa8a0-0263-471b-8980-317e68c30488'
response = conversation.message(
workspace_id=workspace_id,
message_input={'text': 'Turn on the lights'},
context=context
)
print(json.dumps(response, indent=2))
In this case, to send the message from user, you can use message_input, and to send message like Watson, you can use output.
If your parameter is set to response, for example, you can use:
#Get response from Watson Conversation
responseFromWatson = conversation.message(
workspace_id=WORKSPACE_ID,
message_input={'text': command},
context=context
)
See one official example code from IBM Developers:
if intent == "schedule":
response = "Here are your upcoming events: "
attachments = calendarUsage(user, intent)
elif intent == "free_time":
response = calendarUsage(user, intent)
else:
response = responseFromWatson['output']['text'][0] //THIS SEND THE MESSAGE TO USER
slack_client.api_call("chat.postMessage", as_user=True, channel=channel, text=response,
attachments=attachments)
Use this to send:
response = responseFromWatson['output']['text'][0];
if intent == "timeWeather":
response = "The Weather today is: " +yourReturnWeather
Tutorial from IBM Developer for this project here.
This example will integrate with Slack, but you can see one good example to did what you want in this project.
See official documentation.

XMPP on Python responds to Gtalk but not to Hangouts

I was trying out a Gtalk bot using python and XMPP.
When I ping the bot using iChat application, I could receive the response back.
But when I ping using Hangouts, I am not able to receive the response message. But still I could see my message at server side logs.
# -- coding: utf-8 -
import xmpp
user="BOTUSERNAME#gmail.com"
password="PASSWORD"
server=('talk.google.com', 5223)
def message_handler(connect_object, message_node):
us = str(message_node.getFrom()).split('/')[0]
if us == 'REALUSERNAME#gmail.com':
us = us[0:4]
print str(message_node)
message = "Welcome to my first Gtalk Bot :) " + us
s= str(message_node.getBody()).replace("\n", "\t")
if s <> 'None' :
print "MESSAGE: " + s
connect_object.send(xmpp.Message( message_node.getFrom() ,message))
jid = xmpp.JID(user)
connection = xmpp.Client(jid.getDomain())
connection.connect(server)
result = connection.auth(jid.getNode(), password )
connection.RegisterHandler('message', message_handler)
connection.sendInitPresence()
while connection.Process(1):
pass
Is this something to do with gtalk moving out of XMPP support?
My Bot is still able to receive message but my Hangouts Application is not receiving response
I was able to fix the issue.
You need to add typ = 'chat' attribute to xmpp.Message
connect_object.send(xmpp.Message( message_node.getFrom() ,message, typ='chat' ))
Now my gTalkBot reponds to my message from hangouts & ichat client.
Many thanks to this stack overflow answer
If you have extended sleekxmpp.ClientXMPP, then you can ensure messages are sent to hangouts by added mtype='chat' to send_message()
bot = MyBot([...])
bot.send_message(mto=JID,mbody=MSG,mtype='chat')

Categories