Using Slack RTM API with Django 2.0 - python

I am a beginner to the Django framework and I am building a Django app that uses the Slack RTM API.
I have a coded a program in python that performs the OAuth authentication process like so :
def initialize():
url="https://slack.com/api/rtm.connect"
payload={"token":"xxx"}
r=requests.post(url,payload)
res=json.loads(r.text)
url1=res['url']
ws = create_connection(url1)
return ws
My Requirement:
The stream of events I receive (from my slack channel that my slack app is added to) is processed to filter out events of the type - message ,then match the message with a regex pattern and then store the matched string in a database.
As a stand alone python program I am receiving the stream of events from my channel.
My questions:
How do I successfully integrate this code to Django so that I can
fulfill my requirement?
Do I put the code in templates/views? What is the
recommended method to process this stream of data?

def initialize():
url = "https://slack.com/api/rtm.connect"
r = requests.get(url, params={'token': '<YOUR TOKEN>'})
res = r.json()
url1=res['url']
ws = create_connection(url1) #Note: There is no function called create_connnection() so it will raise an error
return ws
if you read the API web methods, you see :
Preferred HTTP method: GET
See here: Slack rtm.connect method
look at the comment, and thats the right code, see the differences between this code and yours.
basically to get JSON from a request don't use json.loads because this search your local computer not the request
use r.json() so it call the json you got from r.
Note that r.text will return raw text output so when you want to get url it will not be identified, with r.json you can call the object url as stated about
Hope this help.
and please could you tell us more what you wanna do with this in view ? because template is a directory which contains all the HTML files which you don't need to work with.
but why views.py ?

Related

Posting a message in Symphony from Python

I'm trying to send a message from Symphony using Python.
https://developers.symphony.com/restapi/reference#create-message-v4
I found this page but I don't really know how to use it ( There's a cURL and a post url .. ) and I don't understand how I can use requests in this context ( still a beginner in API ).
Can someone help me to figure out how I can use this page to send a message from Python.
Thank you
You have to pass some required things in headers and use multipart/from-data content-type.
If you know about the postman then first with that and pass required headers.
files ={"message":"<messageML>Hello world!</messageML>"}
headers={
"sessionToken": "SESSION_TOKEN",
"keyManagerToken": "KEY_MANAGER_TOKEN"
}
requests.post("https://YOUR-AGENT-URL.symphony.com/agent/v4/stream/:sid/message/create", files=files,headers=headers)
https://github.com/finos/symphony-bdk-python/blob/main/examples has alot of examples on how to use symphony sdk. From python you don't want to use the api. This is the simple code to send a message from a bot. If you do not have a bot set up yet, follow https://docs.developers.symphony.com/building-bots-on-symphony/configuration/configure-your-bot-for-bdk-2.0-for-python NOTE you will need an admin user to follow these steps.
from symphony.bdk.core.config.loader import BdkConfigLoader
from symphony.bdk.core.symphony_bdk import SymphonyBdk
config = BdkConfigLoader.load_from_file("config.yaml")
async with SymphonyBdk(config) as bdk:
streams = bdk.streams()
messages = bdk.messages()
user_id = 123 # this can be found by clicking on a profile and copy profile link eg symphony://?userId=31123123123
stream = await streams.create_im_or_mim([user_id])
await messages.send_message(stream.id, f"<messageML>Message you want to send</messageML>")

How can I use the output of a python script as RASA’s input instead of the usual user input?

I am currently using RASA and developed a working chatbot. One part of my project is to use a speech-to-text recognition, and I wrote a working code in Python that returns the text said by the user.
I want to use that text for RASA’s input, instead of writing like usual.
I saw there was something to do with the inputs channels, but I only saw input that are other webservices and couldn’t figure it out for using just a local script.
Thank you for any advice,
LM
You can try rasa REST API for this purpose. Make sure that you have action_endpoint url in endpoints.yml. Normally it is
url: "http://localhost:5055/webhook"
Then make sure your rasa bot is up and if htere are any custom actions, start that server as well.
After starting your webhook, you can simple call
http://localhost:5005/webhooks/rest/webhook
and in the payload you have to put below payload
messagePayload = {
sender: 'default',
message: 'Your message is here'
}
and finally add httpheader content type as application/json like below
'Content-Type': 'application/json'
Now your bot will work fine.
tldr;
If you are using request in your python for api calls, you can try below code.
import requests
API_ENDPOINT = "http://localhost:5005/webhooks/rest/webhook"
messagePayload = {
sender: 'default',
message: 'Your message is here'
}
r = requests.post(url = API_ENDPOINT, data = messagePayload)
How about just using Rest API that is already present in the library.
For this, you just need to fill the query parameter, which you can do with your script, rather than writing a custom Input Channel.

How to programmatically delete an email from list of bounced emails?

I am working on a GAE(Google App Engine) based python app and which have sendgrid python SDK(v3.2.10) integrated into it. What I am trying do is right now that whenever sendgrid pushes an event webhook of type "bounce" I want to delete that bounced email from the list of bounced emails present on sendgrid.
I have already gone through the documentation provided on the official site. First I tried to delete email address using SDK and it worked fine on localhost. But after deploying it to the live server it just doesn't do anything and falls in the exception clause.
Code snippet:
try:
send_grid_client = sendgrid.SendGridAPIClient(apikey=SENDGRID_API_KEY)
data = {"emails": [email.strip()]}
delete_response = send_grid_client.client.suppression.bounces.delete(
request_body=data)
except Exception as exception:
logging.info('Exception is: {}'.format(exception))
pass
As it did not work as expected, I am now trying to do the same using REST API.
Code snippet:
import requests
data = {"emails": [email]}
headers = {"Authorization": "Bearer {}".format(SENDGRID_API_KEY)}
delete_response = requests.delete("https://api.sendgrid.com/v3/suppression/bounces", data=json.dumps(data), headers=headers)
logging.info(delete_response)
logging.info(delete_response.status_code)
logging.info(delete_response.text)
Now, sendgrid API is continuously returning error 400 with message {"errors":[{"field":null,"message":"emails or delete_all params required"}]}. I simply could not figure out how to overcome this issue. Maybe I am missing how to pass request body in the delete function but, I could not figure it out.
I just figured out the issue.
It's the SendGrid API docs here which causes confusion as it is not mentioned clearly that they have a different way of calling the same endpoint when you want to delete a single email address or list of emails.
For a single email, it needs to be passed in the URL i.e. https://api.sendgrid.com/v3/suppression/bounces/{email_address}
For a list of emails, the list needs to be passed in the body of the delete request. i.e. it will look like this {"emails": [email_address_1, email_address_1, ...]}
As in the question above a single email was meant to be deleted and it was being passed as {"emails": [email_address_1]} in the delete request. Sendgrid API was not able to digest this info and was throwing an error. The email address was to be passed in the URL.
This issue has been resolved. But, I wonder why Sendgrid API was not able to digest this info {"emails": [email_address_1]}. Why they have a hard assumption that list will always have elements greater than one in it.

Instagram API using Python

I am currently using Instagram API in the sandbox mode using Python's python-instagram library. Now, I have an application and its associated client id, client secret and access token, and one connected sandbox user.
Earlier today, I was experimenting with the users/search endpoint. First, I directly used their endpoint URL to send a request:
https://api.instagram.com/v1/users/search?q=XXXX&access_token=<my_access_token>
where XXXX is the connected sandbox user of my Instagram application. This is the generated response:
{"meta":{"code":200},"data":[{"username":"XXXX","bio":"Twitter: #XXXX","website":"","profile_picture":"https:a.jpg","full_name":"XXXX XXXX","id":"22222222"}]}
Now, I tried using the python-instagram library to send request to the same endpoint as follows:
from instagram.client import InstagramAPI
access_token = <my_access_token>
api = InstagramAPI(client_secret='aaaa', access_token = access_token[0])
usr = api.user_search('XXXX')
print usr
However, this is the response I get in this case:
[User: XXXX]
Why is it that I get different responses when I try to call the same endpoint using the direct URL and the Python library?
What python-instagram is doing is that it will take the raw JSON response you get when you issue an HTTP request, and map it to python objects.
When you issue a print usr, you are printing a User object that's in a list, so you see a string which is [User: XXXX].
You can find the model they use for the User object here. It actually directly maps the fields from the Json to get attributes.
Try the following code to retrieve a username and id:
my_usr = usr[0]
print 'User id is', my_usr.id, 'and name is ', my_usr.username

Insufficient permissions when trying to create a Quizlet set

I am trying to create a set on Quizlet.com, using its API found here: https://quizlet.com/api/2.0/docs/sets#add
Here is my code of a set I am trying to create:
import requests
quizkey = my_client_id
authcode = my_secret_code # I'm not sure if I need this or not
data = {"client_id":quizkey, "whitespace":1, "title":"my-api-set",
"lang_terms":"it", "lang_definitions":"en",
"terms":['uno','due'], "definitions":["one","two"]}
apiPrefix = "https://api.quizlet.com/2.0/sets"
r = requests.post(url=apiPrefix, params=data)
print r.text
The response is:
{
"http_code": 401,
"error": "invalid_scope",
"error_title": "Not Allowed",
"error_description": "You do not have sufficient permissions to perform the requested action."
}
I also tried "access_token":authcode instead of "client_id":quizkey, but this resulted in the error: "You do not have sufficient permissions to perform the requested action."
How can I fix this and not get a 401 error?
Alright so 3 and a half years later (!!) I've looked into this again and here's what I've discovered.
To add a set you need an access token - this is different to the client_id (what I call quizkey in my code), and to be quite honest I don't remember what authcode in my code is.
This token is obtained by going through the user authentication flow. To summarise it:
Send a POST request to https://quizlet.com/authorize like so:
https://quizlet.com/authorize?response_type=code&client_id=MY_CLIENT_ID&scope=read&state=RANDOM_STRING
Keep the response_type as code, replace client_id with your client_id, keep the scope as read, and state can be anything
I believe this requires human intervention because you're literally authorising your own account? Not sure of another way...
You'll receive a response back with a code
Let's call this RESPONSE_CODE for now
Send a POST request to https://api.quizlet.com/oauth/token, specifying 4 mandatory parameters:
grant_type="authorization_code" (this never changes)
code=RESPONSE_CODE
redirect_uri=https://yourredirecturi.com (this can be found at your personal API dashboard)
client ID and secret token separated by a colon and then base64-encoded (the user authentication flow link above tells you what this is if you don't want to do any of the encoding)
You'll receive the access_token from this API call
Now you can use that access_token in your call to create a set like I've done above (just replace "client_id":quizkey with "access_token":access_token)
You will need to authenticate in order to make sets. This link gives an overview:
https://quizlet.com/api/2.0/docs/making_api_calls
And this one provides details about the authentication process:
https://quizlet.com/api/2.0/docs/authorization_code_flow

Categories