Skip to content

Instantly share code, notes, and snippets.

@jbwhaley
Last active November 25, 2018 02:05
Show Gist options
  • Save jbwhaley/8324202 to your computer and use it in GitHub Desktop.
Save jbwhaley/8324202 to your computer and use it in GitHub Desktop.
A random number generator for Pythonista on iOS. Accepts input from either Drafts.app or via alert prompt when run from within Pythonista.
import random
import requests
import sys
import clipboard
import console
import webbrowser
# Grabs input args
numArgs = len(sys.argv)
# Accepts input from Drafts; if none present, or if script is run directly in Pythonista, prompts user to input the upper limit of the desired numeric range
if numArgs == 2:
digit = sys.argv[1]
else:
digit = console.input_alert('Input the upper limit of your range...', '(as an integer)')
digit = digit.replace(",", "")
digit = int(digit)
payload = {'num' : '1', 'min' : '1', 'max' : digit, 'col' : '1',
'base' : '10', 'format' : 'plain', 'rnd' : 'new'}
# Selects a random digit in the specified range.
try:
r = requests.get('https://www.random.org/integers/', params=payload)
num = int(r.text)
except requests.exceptions.ConnectionError:
num = random.randint(1, digit)
# Sets the output to the clipboard.
num = str(num)
clipboard.set(num)
# Sends output to Drafts, if the script was launched from there; otherwise sends output to an iOS alert.
if numArgs == 2:
url = 'drafts4://x-callback-url/create?text='
text = 'Your%20random%20number%20is%3A%20'
webbrowser.open(url + text + num)
else:
display = 'Your number' + ' (' + num + ') ' + 'has been sent to the clipboard.'
console.alert(display, 'Tap CANCEL to dismiss.')
@jbwhaley
Copy link
Author

jbwhaley commented Jan 9, 2014

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment