Can i use twitter api for select poll votes ? is there any methods in tweepy? - python-3.x

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.

Related

How do I change my Slack bot icon in python?

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.

Can MechanicalSoup log into page requiring SAML Auth?

I'm trying to download some files from behind a SSO (Single Sign-On) site. It seems to be SAML authenticated, that's where I'm stuck. Once authenticated I'll be able to perform API requests that return JSON, so no need to interpret/scrape.
Not really sure how to deal with that in mechanicalsoup (and relatively unfamiliar with web-programming in general), help would be much appreciated.
Here's what I've got so far:
import mechanicalsoup
from getpass import getpass
import json
login_url = ...
br = mechanicalsoup.StatefulBrowser()
response = br.open(login_url)
if verbose: print(response)
# provide the username + password
br.select_form('form[id="loginForm"]')
print(br.get_current_form().print_summary()) # Just to see what's there.
br['UserName'] = input('Email: ')
br['Password'] = getpass()
response = br.submit_selected().text
if verbose: print(response)
At this point I get a page telling me javascript is disabled and that I must click submit to continue. So I do:
br.select_form()
response = br.submit_selected().text
if verbose: print(response)
That's where I get a complaint about state information being lost.
Output:
<h2>State information lost</h2>
State information lost, and no way to restart the request<h3>Suggestions for resolving this problem:</h3><ul><li>Go back to the previous page and try again.</li><li>Close the web browser, and try again.</li></ul><h3>This error may be caused by:</h3><ul><li>Using the back and forward buttons in the web browser.</li><li>Opened the web browser with tabs saved from the previous session.</li><li>Cookies may be disabled in the web browser.</li></ul>
The only hits I've found on scraping behind SAML logins are all going with a selenium approach (and sometimes dropping down to requests).
Is this possible with mechanicalsoup?
My situation turned out to require Javascript for login. My original question about getting into SAML auth was not the true environment. So this question has not truly been answered.
Thanks to #Daniel Hemberger for helping me figure that out in the comments.
In this situation MechanicalSoup is not the correct tool (due to Javascript) and I ended up using selenium to get through authenication then using requests.

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/

Subscribe to Kodi's JSONRPC notification

I am trying to build a simple python script to control kodi from my linux machine. I can get the basic method calls to work and get the gist of how things are but when it comes to 'listening' for notifications such as Application.OnVolumeChanged, Player.OnPlay, etc., I have no idea where to start from, how to subscribe to these notifications.
The best knowledge I have is that notifications can be subscribed using websockets or TCP and the following piece of code I could piece together,
import asyncio
import websockets
from jsonrpcclient.websockets_client import WebSocketsClient
async def main():
async with websockets.connect('ws://192.168.1.104:9000') as ws:
response = await WebSocketsClient(ws).request('Application.OnVolumeChanged')
print(response)
asyncio.get_event_loop().run_until_complete(main())
One immediate thing I can notice with above code is authorization details aren't being sent to kodi. Apart from that, I have no clue where to go from here (and if this is indeed the right direction).
Any help will be appreciated!
API reference page I have been following - JSON RPC API v8

Handling parallel REST post requests

I have created my own REST service based on the examples from "Domino Sample REST Service Feature" from 901v00_11.20141217-1000 version of XPages Extension Library.
As far as I understand the design of the library each REST request will be run in its own thread on the server. This approach does not allow to handle parallel POST requests to the same document.
I have not found any examples in XPages Extension Library which would handle post requests as transactions on the server, i.e. which would block the server resource for the whole request processing time and would put put next requests in the queue?
Can anybody point to the source code of the service which would allow to handle parallel requests?
The skeleton for my post request processing function is this
#POST
#Path(PATH_SEPARATOR + MyURL)
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Response myPost(
String requestEntity,
#Context final UriInfo uriInfo)
{
LogMgr.traceEntry(this, "myPost");
RestContext.verifyUserContext();
String myJson = ... // Process post
Response response = buildResponse(myJson);
LogMgr.traceExit(this, "myPost", "OK");
return response;
}
And I would like to implement something like this
// Start transaction
String myJson = ... // Process post
// Stop transaction
Is there a way to do it in Java?
I suppose you could use document locking in traditional Notes/Domino context - and synchronized in Java :-)
Have you tried any of these? I cannot see why they should not work.
/John
I agree with John. You can use document locking to prevent simultaneous updates to the same document. You might also want to consider some changes to the definition of your REST API.
First, you imply you are using POST to update an existing document. Usually, POST is used to create a new resource. Consider using PUT instead of POST.
Second, even with document locking, you still might want to check for version conflicts. For example, let's say a client reads version 2 of a document and then attempts to update it. Meanwhile, another client has already updated the document to version 3. Many REST APIs use HTTP ETags to handle such version conflicts.

Resources