def post_comments_to_mapillary(entries):
global mapillary_client_id
global mapillary_access_token
global user_agent
global time_out
for e in entries:
msg = "This image was mentioned on OpenStreetMap at https://www.openstreetmap.org/" + e.osmtype + "/" + e.osmid + " by user '" + e.osmuser + "'. Message generated by https://github.com/ltog/mapillary-osm-usage-notification-bot ."
url = "https://a.mapillary.com/v2/im/" + e.mapillaryid + "/cm?client_id=" + mapillary_client_id
payload = {"cm": msg}
r = backoff_post(url, payload)
logging.info("Posting comment for image " + e.mapillaryid + " resulted in HTTP status " + str(r.status_code) + " and response: " + r.text)
if r.status_code == 200:
log_success(str(e))
if r.status_code == 404:
logging.warning("Entry " + str(e) + "generated HTTP error 404 for URL " + url + " . ")
log_failure(str(e))
python类org()的实例源码
def main():
# Start a session so we can have persistant cookies
# Session() >> http://docs.python-requests.org/en/latest/api/#request-sessions
session = requests.Session()
# This is the form data that the page sends when logging in
login_data = {
'username': RegisterNumber,
'password': DateofBirth,
'submit': 'id',
}
print login_data
# Authenticate
r = session.post(URL, data = login_data)
# Try accessing a page that requires you to be logged in
r = session.get('http://sdpdr.nic.in/annauniv/result')
web = QWebView()
web.load(QUrl("http://sdpdr.nic.in/annauniv/result"))
#web.show()
printer = QPrinter()
printer.setPageSize(QPrinter.A4)
printer.setOutputFormat(QPrinter.PdfFormat)
printer.setOutputFileName("result.pdf")
# convertion of page to pdf format
def printhelp():
#prints help text
printusertext('This is a script to send an email alert if APs are in invalid management subnets. The alert is')
printusertext(' sent using a SMTP server; by default Gmail. Use an automation platform like Zapier to read this email')
printusertext(' and trigger further actions.')
printusertext('')
printusertext('To run the script, enter:')
printusertext(' python checksubnets.py -k <key> -v <valid subs> [-u <user> -p <pass> -d <dest>] [-s <srv> -o <org>]')
printusertext('')
printusertext('Mandatory arguments:')
printusertext(' -k <key> : Your Meraki Dashboard API key')
printusertext(' -v <valid subs> : List of valid management subnets. Alert if management IP is not in these')
printusertext('Arguments to enable sending emails. All three must be given to send email. If omitted, print to screen:')
printusertext(' -u <user> : The username (email address) that will be used to send the alert message')
printusertext(' -p <pass> : Password for the email address where the message is sent from')
printusertext(' -d <dest> : Recipient email address')
printusertext('Optional arguments:')
printusertext(' -s <server> : Server to use for sending SMTP. If omitted, Gmail will be used')
printusertext(' -o <org> : Name of organization to be processed. If omitted, will process all organizations')
printusertext('')
printusertext('Defining subnets:')
printusertext(' Parameter "-v <valid subs>" can take subnets in the following forms:')
printusertext(' <subnet>/<mask>,<subnet>/<mask>,<subnet>/<mask> Example: -v 192.168.128.0/24,10.10.0.0/16')
printusertext(' file:<filename> Example: -v file:validsubs.txt')
printusertext(' <filename> is the name of a text file that defines the valid subnets. Enter one subnet per line')
printusertext(' in the form <subnet>/<mask>')
printusertext('')
printusertext('To make script chaining easier, all lines containing informational messages to the user')
printusertext(' start with the character @')
printusertext('')
printusertext('In Windows, use double quotes ("") to pass arguments containing spaces.')
def requests_retry_session(
retries=3,
backoff_factor=0.3,
status_forcelist=(500, 502, 504),
):
"""Opinionated wrapper that creates a requests session with a
HTTPAdapter that sets up a Retry policy that includes connection
retries.
If you do the more naive retry by simply setting a number. E.g.::
adapter = HTTPAdapter(max_retries=3)
then it will raise immediately on any connection errors.
Retrying on connection errors guards better on unpredictable networks.
From http://docs.python-requests.org/en/master/api/?highlight=retries#requests.adapters.HTTPAdapter
it says: "By default, Requests does not retry failed connections."
The backoff_factor is documented here:
https://urllib3.readthedocs.io/en/latest/reference/urllib3.util.html#urllib3.util.retry.Retry
A default of retries=3 and backoff_factor=0.3 means it will sleep like::
[0.3, 0.6, 1.2]
""" # noqa
session = requests.Session()
retry = Retry(
total=retries,
read=retries,
connect=retries,
backoff_factor=backoff_factor,
status_forcelist=status_forcelist,
)
adapter = HTTPAdapter(max_retries=retry)
session.mount('http://', adapter)
session.mount('https://', adapter)
return session
def get_page_source(self, url,
params=None,
headers=None):
"""Fetches the specified url.
Attributes:
url (str): The url of which to fetch the page source code.
params (dict, optional): Key\:Value pairs to be converted to
x-www-form-urlencoded url parameters_.
headers (dict, optional): Extra headers to be merged into
base headers for current Engine before requesting url.
Returns:
``rasp.base.Webpage`` if successful
.. _parameters: http://docs.python-requests.org/en/master/user/quickstart/#passing-parameters-in-urls
"""
if not url:
raise ValueError('url needs to be specified')
if self.callback: self.callback()
merged_headers = deepcopy(self.headers)
if isinstance(headers, dict):
merged_headers.update(headers)
response = self.session.get(
url, params=params, headers=merged_headers
)
return Webpage(
url,
source=response.text,
headers=response.headers,
response_code=response.status_code
)
def post_greeting_text(greeting_text):
""" Sets the Thread Settings Greeting Text
(/docs/messenger-platform/thread-settings/greeting-text).
:param str greeting_text: Desired Greeting Text (160 chars)
:return: `Response object <http://docs.python-requests.org/en/\
master/api/#requests.Response>`_
"""
url = TD_STS_URL + PAGE_ACCESS_TOKEN
payload = {}
payload["setting_type"] = "greeting"
payload["greeting"] = {"text": greeting_text}
response_msg = json.dumps(payload)
status = requests.post(url, headers=HEADER, data=response_msg)
return status
def post_persistent_menu(call_to_actions):
""" Sets a persistent menu on the chat
(/docs/messenger-platform/thread-settings/persistent-menu)
:param list call_to_actions: format :
>>> call_to_actions = [
{
'type': 'postback',
'title': 'About',
'payload': 'ABOUT'
},
{
'type': 'web_url',
'title': 'Google it',
'url': 'https://www.google.com',
'webview_height_ratio': 'full',
'messenger_extensions': True
},
]
:return: `Response object <http://docs.python-requests.org/en/\
master/api/#requests.Response>`_
"""
url = TD_STS_URL + PAGE_ACCESS_TOKEN
payload = {}
payload["setting_type"] = "call_to_actions"
payload["thread_state"] = "existing_thread"
payload["call_to_actions"] = call_to_actions
data = json.dumps(payload)
status = requests.post(url, headers=HEADER, data=data)
return status
def post_text_list(fbid, messages=[]):
""" Sends a serie of messages from list of text.
:param str fbid: User id to send the text list.
:param list messages: A list of messages to be sent.
:return: A list of `Response objects <http://docs.python-\
requests.org/en/master/api/#requests.Response>`_\
for every message sent.
"""
responses = []
for msg in messages:
responses.append(post_text_message(fbid=fbid, message=msg))
return responses
def post_audio_attachment(fbid, audio_url):
""" Sends an audio attachment
(/docs/messenger-platform/send-api-reference/audio-attachment)
:param str fbid: User id to send the audio.
:param str audio_url: Url of a hosted audio (10 Mb).
:return: `Response object <http://docs.python-requests.org/en/\
master/api/#requests.Response>`_
"""
return post_attachment(fbid, audio_url, 'audio')
def post_image_attachment(fbid, img_url):
""" Sends an image attachment
(/docs/messenger-platform/send-api-reference/image-attachment)
:param str fbid: User id to send the image.
:param str img_url: Url of a hosted image (jpg, png, gif).
:return: `Response object <http://docs.python-requests.org/en/\
master/api/#requests.Response>`_
"""
return post_attachment(fbid, img_url, 'image')
def post_video_attachment(fbid, video_url):
""" Sends a video attachment
(/docs/messenger-platform/send-api-reference/video-attachment)
:param str fbid: User id to send the video.
:param str video_url: Url of a hosted video.
:return: `Response object <http://docs.python-requests.org/en/\
master/api/#requests.Response>`_
"""
return post_attachment(fbid, video_url, 'video')
# Send API Quick Replies
def post_text_w_quickreplies(fbid, message, quick_replies):
""" Send text with quick replies buttons
(/docs/messenger-platform/send-api-reference/quick-replies).
:param str fbid: User id to send the quick replies menu.
:param str message: message to be displayed with the menu.
:param list quick_replies: (Max 10) format :
>>> quick_replies = [
{
"content_type": "text",
"title": "Yes!",
"payload": "USER_SAY_YES"
},
{
"content_type": "text",
"title": "Nope",
"payload": "USER_SAY_NOT"
}
]
:return: `Response object <http://docs.python-requests.org/en/\
master/api/#requests.Response>`_
"""
url = MSG_URL + PAGE_ACCESS_TOKEN
payload = {}
payload["recipient"] = {"id": fbid}
payload["message"] = {"text": message, "quick_replies": quick_replies}
data = json.dumps(payload)
status = requests.post(url, headers=HEADER, data=data)
return status
# Send API Templates
def post_button_template(fbid, text, buttons):
""" Sends a button template with the specified text and buttons
(/docs/messenger-platform/send-api-reference/button-template).
:param str fbid: User id to send the buttons.
:param str text: Message to be displayed with the buttons (320 Chars).
:param list buttons: Dict of buttons that appear as call-to-actions, \
format :
>>> buttons = [
{
'type': 'web_url',
'url': 'https://petersapparel.parseapp.com',
'title': 'Show Website'
},
{
'type': 'postback',
'title': 'Start Chatting',
'payload': 'USER_DEFINED_PAYLOAD'
}
]
:return: `Response object <http://docs.python-requests.org/en/\
master/api/#requests.Response>`_.
"""
url = MSG_URL + PAGE_ACCESS_TOKEN
data = {}
data['recipient'] = {'id': fbid}
payload = {}
payload['template_type'] = 'button'
payload['text'] = text
payload['buttons'] = buttons
attachment = {"type": 'template', "payload": payload}
data['message'] = {"attachment": attachment}
data = json.dumps(data)
status = requests.post(url, headers=HEADER, data=data)
return status
def post_call_button(fbid, text, title, phone_number):
""" Sends a call button for the specified user
(/docs/messenger-platform/send-api-reference/call-button).
:param str fbid: User id to send the call button
:param str text: Text to send with the button (Max 160 Chars).
:param str title: Button title (Max 20 Chars).
:param str phone_number: Format must have "+" prefix followed by\
the country code, area code and local number.\
For example, **+16505551234**.
:return: `Response object <http://docs.python-requests.org/en/\
master/api/#requests.Response>`_
"""
url = MSG_URL + PAGE_ACCESS_TOKEN
data = {}
data['recipient'] = {'id': fbid}
payload = {}
payload['template_type'] = 'button'
payload['text'] = text
button = {}
button['type'] = 'phone_number'
button['title'] = title
button['payload'] = phone_number
payload['buttons'] = [button]
attachment = {"type": "template", "payload": payload}
data['message'] = {"attachment": attachment}
data = json.dumps(data)
status = requests.post(url, headers=HEADER, data=data)
return status
def post_settings(greeting_text):
""" Sets the **Get Started** Button and the **Greeting Text** at once.
The payload for the **Get Started** Button will be `USER_START`.
:usage:
>>> # Create a default greeting text (160 chars limit)
>>> greeting_text = "Hello! I'm your bot!"
>>> responses = fbbotw.post_settings(
greeting_text=greeting_text
)
:param str greeting_text: Desired Greeting Text (160 chars).
:return: tuple with two `Response object <http://docs.python-requests.\
org/en/master/api/#requests.Response>`_ for the greeting \
text and start button.
"""
# Set the greeting texts
url = THREAD_SETTINGS_URL.format(access_token=PAGE_ACCESS_TOKEN)
txtpayload = {}
txtpayload['setting_type'] = 'greeting'
txtpayload['greeting'] = {'text': greeting_text}
data = json.dumps(txtpayload)
greeting_text_status = requests.post(
url, headers=HEADER, data=data
)
# Set the start button
url = MESSENGER_PROFILE_URL.format(access_token=PAGE_ACCESS_TOKEN)
btpayload = {}
btpayload['get_started'] = {'payload': 'USER_START'}
data = json.dumps(btpayload)
get_started_button_status = requests.post(
url, headers=HEADER, data=data
)
return (greeting_text_status, get_started_button_status)
def post_payment_settings(privacy_url="", public_key="", test_users=[]):
""" Sets the configuration for payment: privacy policy url,
public key or test users. At least one parameter should be passed
in this function.
:param str privacy_url: The payment_privacy_url will appear in \
our payment dialogs.
:param str public_key: The payment_public_key is used to encrypt \
sensitive payment data sent to you. (Read payment reference on the \
docs)
:param list test_users: You can add payment test users \
(user page-scoped id) so that their credit card won't be \
charged during your development.
:return: `Response object <http://docs.python-requests.org/en/\
master/api/#requests.Response>`_
:facebook docs: `/payment-settings <https://developers.facebook.\
com/docs/messenger-platform/messenger-profile/payment-settings>`_
"""
if any([privacy_url.strip(), public_key.strip(), test_users]):
url = MESSENGER_PROFILE_URL.format(access_token=PAGE_ACCESS_TOKEN)
payload = {"payment_settings": {}}
if bool(privacy_url.strip()):
payload['payment_settings']['privacy_url'] = privacy_url
if bool(public_key.strip()):
payload['payment_settings']['public_key'] = public_key
if bool(test_users):
payload['payment_settings']['testers'] = test_users
data = json.dumps(payload)
status = requests.post(url, headers=HEADER, data=data)
return status
return {"Error": "At least one parameter should be set"}
def post_target_audience(countries, audience_type="all"):
""" Set the audience who will see your bot in the Discover tab \
on Messenger.
:usage:
>>> # If you will set the audience to specific contries
>>> # The audience_type param should be set to 'custom'
>>> audience_type = "custom"
>>> countries = {
"whitelist": ["US", "UK", "CA", "BR"]
}
>>> response = fbbotw.post_target_audience(
countries=countries,
audience_type=audience_type
)
:param dict countries: Country object with whitelist/blacklist. Needs\
to be specified only when audience_type is 'custom'. Countries should \
be in list of ISO 3166 Alpha-2 codes. format:
>>> countries = {
"whitelist": ["US", "BR"]
"blacklist": []
}
:param str audience_type: ("all", "custom", "none"). Default: "all"
:return: `Response object <http://docs.python-requests.org/en/\
master/api/#requests.Response>`_
:facebook docs: `/target-audience <https://developers.facebook.\
com/docs/messenger-platform/messenger-profile/target-audience>`_
"""
url = MESSENGER_PROFILE_URL.format(access_token=PAGE_ACCESS_TOKEN)
payload = {"target_audience": {}}
payload["target_audience"]["audience_type"] = audience_type
if audience_type in ['custom', 'none']:
payload["target_audience"]["countries"] = countries
data = json.dumps(payload)
status = requests.post(url, headers=HEADER, data=data)
return status
def post_chat_extension_home_url(
url, webview_share_button="hide", in_test=True):
""" Sets the url field enabling a Chat Extension in the composer \
drawer in Messenger.
:param str url: The URL to be invoked from drawer.
:param str webview_share_button: Controls whether the share button in \
the webview is enabled. (Set to "show" or "hide")
:param bool in_test: Controls whether public users (not assigned to the \
bot or its Facebook page) can see the Chat Extension.
:return: `Response object <http://docs.python-requests.org/en/\
master/api/#requests.Response>`_
:facebook docs: `/home-url <https://developers.facebook.\
com/docs/messenger-platform/messenger-profile/home-url>`_
"""
url = MESSENGER_PROFILE_URL.format(access_token=PAGE_ACCESS_TOKEN)
payload = {"home_url": {}}
payload["home_url"]["url"] = url
payload["home_url"]["webview_height_ratio"] = "tall"
payload["home_url"]["webview_share_button"] = webview_share_button
payload["home_url"]["in_test"] = in_test
data = json.dumps(payload)
status = requests.post(url, headers=HEADER, data=data)
return status
#############################################
# Send Api Functions #
#############################################
# Send API Sender Actions
def post_sender_action(fbid, sender_action):
""" Displays/Hides the typing gif or shows mark seen on
facebook chat with user.
:usage:
>>> # Set the user you want to show action
>>> fbid = "<user page scoped id>"
>>> # To show the typing animation
>>> fbbotw.post_sender_action(
fbid=fbid, sender_action="typing_on"
)
>>> # To stop typing (Stops automatically after 20s)
>>> fbbotw.post_sender_action(
fbid=fbid, sender_action="typing_off"
)
>>> # To mark as seen
>>> fbbotw.post_sender_action(
fbid=fbid, sender_action="mark_seen"
)
:param str fbid: User id to display action.
:param str sender_action: `typing_off/typing_on/mark_seen`.
:return: `Response object <http://docs.python-requests.org/en/\
master/api/#requests.Response>`_
:facebook docs: `/sender-actions <https://developers.facebook.\
com/docs/messenger-platform/send-api-reference/sender-actions>`_
"""
url = MESSAGES_URL.format(access_token=PAGE_ACCESS_TOKEN)
payload = {}
payload['recipient'] = {'id': fbid}
payload['sender_action'] = sender_action
data = json.dumps(payload)
status = requests.post(url, headers=HEADER, data=data)
return status
# Send API Content Type
def post_text_list(fbid, messages=[]):
""" Sends a serie of messages from a list of texts. The
messages will be sent in the same order as the list items.
:usage:
>>> # Set the user fbid and the list of texts to send.
>>> fbid = "<user page scoped id>"
>>> texts = [
"Hi, Todays forecast is:",
"Morning: Sunny - 27C",
"Afternoon: Sunny - 25C",
"Night: Cloudy - 18C"
]
>>> response = fbbotw.post_text_list(
fbid=fbid,
messages=texts
)
:param str fbid: User id to send the text list.
:param list messages: A list of messages to be sent.
:return: A list of `Response objects <http://docs.python-\
requests.org/en/master/api/#requests.Response>`_\
for every message sent.
"""
responses = []
for msg in messages:
responses.append(post_text_message(fbid=fbid, message=msg))
return responses