How do I change my Slack bot icon in python? - python-3.x

I'm very (very) novice at playing with the Slack api - so be gentle and use short words. So far I have managed to set up a simple system that can post to our Slack channel. All well and good, but the icon associated with the posts is the default. How do I go about setting a different icon or even one I create myself?
Here is the basic code (snagged from a tutorial listed on teh Slack api dev site):
import requests
import json
url = 'https://slack.com/api/chat.postMessage'
token = 'xoxb-00000000000etc'
headers = {'Content-Type': 'application/json', 'Authorization': 'Bearer {0}'.format(token)}
def send_message(message_text):
message = {'channel': '#channel_name', 'text': message_text}
requests.post(url, headers=headers, data=json.dumps(message))
send_message('beep boop - this is the OMS bot calling')
Many thanks...

To set the icon image for your message you can simple provide the property icon_url with a URL to an image.
Example:
message = {'channel': '#channel_name', 'text': message_text, 'icon_url': 'https://img.icons8.com/emoji/96/000000/penguin--v2.png'}
You can see all available properties on the official documentation page for the API method chat.postMessage.
Since you said you very a beginner allow me to make two additional suggestions.
1 - The offical Slack library
There is an official Slack library for Python which makes thinks much easier, e.g. you don't need to deal with the requests library and HTTP headers. You find it here: https://github.com/slackapi/python-slackclient
2 - Slack token in environment variables
For security reasons it is good practice to put your slack token in an environment variable. That way you also can check in your code into github etc.
Updated example
Here is your example with the two suggested improvements:
import slack
import os
client = slack.WebClient(token=os.environ['SLACK_TOKEN'])
response = client.chat_postMessage(
channel='general',
text='beep boop - this is the OMS bot calling',
icon_url='https://img.icons8.com/emoji/96/000000/penguin--v2.png'
)

When passing icon_url or icon_emoji to a bot, remember that the scope chat:write.customize is required. Otherwise it will have no effect.

Related

PRIVACY Card API Authorization

I have recently been working with API's but I am stuck on one thing and it's been holding me back for a few days.
I am trying to work with Privacy's API and I do not understand the Authentication/Authorization process. When I enter the url in a browser I get the error "message": "Please provide API key in Authorization header", even when I use the correct format of Authorization. I also get an error when I make a request in Python. The format I'm using for the url is https://api.privacy.com/v1/card "Authorization: api-key:".
If someone could explain how to work this or simply give an example of how I would make a request through Python3. The API information is in the link below.
Thank you in advance.
https://developer.privacy.com/docs
This is the code I am using in Python. After I run this I receive a 401 status code.
import requests
headers={'Authorization': 'api-key:200e6036-6894-xxxx-xxxx-xxxx'}
url = 'https://api.privacy.com/v1/card'
r = requests.get(url)
print("Status code:", r.status_code)
You need to add the authentication header to the get call. It isn't enough to include it in a header variable. You need to provide those headers to requests
import requests
response = requests.get('https://api.privacy.com/v1/card', headers={'Authorization': 'api-key 65a9566c-XXXXXXXXXXXX'})
print(response.json())

Can't call any methods made available by FBO.gov's web API

I'm trying to get data from fbo.gov, which is a government website where they post contracts that vendors can bid in. They have a document containing ways of accessing information on the site through SOAP requests, which is what I'm trying to do. Although all of the examples in that document are in PHP, I am trying to make my requests in Python, because I've never done anything with PHP before.
To make the SOAP requests in Python, I'm using zeep.
Right now, I can successfully authenticate myself through HTTP, but no matter what method I try to call, I always get the same error: This user has an inactive agency.
Here is the code I'm using to send the request
from requests import Session
from requests.auth import HTTPBasicAuth
import zeep
from zeep.transports import Transport
test = "https://fbo-test.symplicity.com"
prod = "https://fbo.gov"
session = Session()
session.auth = HTTPBasicAuth("sample_username", "sample_password")
client = zeep.Client(f"{test}/ws/fbo_api.php?wsdl", transport=Transport(session=session))
dictionary = {"notice_type": "PRESOL"}
print(client.service.getList(data=dictionary))
I realize this is a long shot, but what could be causing this error? I can't find anything even remotely related to the error anywhere on the internet.
Per the Federal Service Desk:
The FBO API is only available for government user accounts.
Some of the FBO data is available at: ftp://ftp.fbo.gov
Currently, FBO is in the process of moving to SAM, and will have a public API once the move is complete. The new API is under development, with the latest specification at: https://open.gsa.gov/api/get-opportunities-public-api/
FBO.GOV has been retired as of 11/12/2019 along with the ftp.fbo.gov bulk download, use the following instead,
https://open.gsa.gov/api/sam-entity-extracts-api/

Can i use twitter api for select poll votes ? is there any methods in tweepy?

I want to use twitter api for poll votes using tweepy is there any methods to implement this?
I tried doing api.update_status("poll_1"[1112227775552223333]) but its not working.
No. The poll API is private and is not available to anyone apart from Twitter's own apps.
There are no plans to open this to the public - https://twittercommunity.com/t/poll-support/78235
The other answer is incorrect. There is a way, it's just the JSON data you get back is quite unwieldy (I have plans to build a tweepy addon to make this easier). The way to get it with Python 3.x is through requests. Don't worry though, it's only a line or so of code. As you can see in this link, we can indeed get back twitter poll data. Here's a code snippet:
import requests, json, OAuth1
# provided by a Twitter dev account
auth = OAuth1(my_key, my_secret_key, my_access_token, my_secret_access_token)
tweet_ids_string = "12345678,123456790,09886654333"
# for more expansions see the link above
data_url = f'https://api.twitter.com/2/tweets?ids={tweet_ids_string}&expansions=attachments.poll_ids&poll.fields=duration_minutes,end_datetime,options,voting_status'
response = requests.get(get_data_url, auth=auth)
response_json = response.json() # then you can get all sorts of data from here
Beware though, the Twitter polls API isn't lightning fast, so there might be several seconds of a delay between a poll getting voted on and the request JSON changing.

How to receive/access headers of the POST request and 'User Properties' from Data Factory task in Azure Function app

I'm still new to Azure, so please bear with me if this is a newbie question.
I created a task in Azure Data Factory that will invoke a Http-triggered Python function (Consumption plan). The settings and user properties of that task is as shown below:
and here
The function itself is as shown below:
Q1: I'd like to know how to read/access the headers of the POST request in the Python function ('run.py' in the screenshot above). For now, I could only access the body of the HTTP request by using os.environ['req'].
Q2: I'd also like to know if it's possible to access 'User Properties' in the 'run.py' assuming that I run the task in the Data Factory (the first and second screenshot). If so, how would I do that.
The existing resources (e.g., 1 and 2) that I could find online don't tell me yet. Any advice/tip would be greatly appreciated. Thank you in advance!
I finally figured it out and am sharing what I found below so that it helps everyone out there wondering the same thing as i did.
This is the code I wrote in Python Function App to access the body and the request headers.
import os
import json
# This is how I'm currently reading the **body of the POST request**
postreqdata = json.loads(open(os.environ['req']).read())
# This is how we should read **a header of the POST request**;
# here 'excelSourcePath' is one of the header names.
postreqdata['header1'] = os.environ['REQ_HEADERS_EXCELSOURCEPATH']
# 'User Properties' is just for monitoring purpose
# https://social.msdn.microsoft.com/Forums/en-US/8692cd00-307b-4204-a547-bed2030cb762/adfv2-user-property-setting?forum=AzureDataFactory
response = open(os.environ['res'], 'w')
response.write(json.dumps({'This is what I see from POST request now':postreqdata}))
response.close()
Hope this is helpful.

Send emails through gmail using flask-mail

I have a simple CRUD webapp set up in Python/Flask, when one particular function is activated (approving a request) I'd like to send an email notification to the user, but for all I've tried I can't get the email to send through my code.
Here is my config file with all the relevant environment variables set (inside of a Config object):
MAIL_SERVER = 'smtp.gmail.com'
MAIL_PORT=465
MAIL_USE_SSL=True
MAIL_USERNAME = '**#gmail.com'
MAIL_PASSWORD = '**'
I have also tried calling app.config.update(those values) in my app/init.py file. Here is the current code to do so
mail = Mail()
def create_app(config_name):
app = Flask(__name__, instance_relative_config=True)
app.config.from_object(app_config[config_name])
app.config.from_pyfile('./config.py')
app.config.update(
MAIL_SERVER='smtp.gmail.com',
MAIL_PORT=465,
MAIL_USE_SSL=True,
MAIL_USE_TLS=False,
MAIL_USERNAME = '**#gmail.com',
MAIL_PASSWORD = '**')
mail.init_app(app)
And finally here is the code where I actually attempt to send the email:
msg = Message(html=html, sender='**#gmail.com', subject='Your Reservation for %s' % reservation.item.name, recipients=['**'])
mail.send(msg)
Additionally, it currently fails silently and I don't know how to even view what error is happening. Any help is much appreciated!
My suggestion in the comments was indeed the answer to the question.
Enabling "Less Secure Apps" in the Google Account settings was the necessary step to fix the hangup the OP was experiencing. This link from Google's support page walks you through how to enable this option.
I think, you should switch your sending protocol to TLS
this is sample from my project
MAIL_SERVER='smtp.gmail.com',
MAIL_PORT=587,
MAIL_USE_TLS=True,
MAIL_USERNAME = '**#gmail.com',
MAIL_PASSWORD = '**'
for me this works very well.
Now that Google is removing the less-secure app access feature due to security reasons, the best way to get around this is to use Sendgrid. They provide 100 free emails per day forever. You can register your same Gmail address as a single sender in SendGrid. Generate an API key and use it in your flask app to send emails.
For reference: Sending Emails from Python Flask Applications With Twilio SendGrid

Resources