I'm trying to make a Twitter bot that selects a quote from a list of quotes I give it to Tweet every 2 hours. I keep having a syntax error when I try to define the Tweet daily function and I'm not exactly sure what's wrong. I'm a beginner in coding so if it's obvious, I apologize; it's my first time doing this. I already had success in having the app Tweet with the api.update_status() command but I'm not sure how to have select from the list I'm creating. I did import random, time, from datetime, import datetime, timedelta as well as tweepy and everything else successfully.
random.choices(tweets)
last_tweeted = datetime.now()-timedelta(hours=2), random.choices(tweets)
tweets = ['insert, list, of tweets, I am adding']
where python says I have a syntax code
def tweet_daily(api, last_tweeted, random.choices(tweets):
if last_tweeted < datetime.now()-timedelta(hours=2):
logger.info(f"Tweeted {tweets, random.choices} at {datetime.now().strftime('%m/%d/%Y at %H:%M:%S')}")
return datetime.now()
else:
return last_tweeted
api.update_status('tweets(random.choice)')`
You're missing a close parenthesis in the function definition:
def tweet_daily(api, last_tweeted, random.choices(tweets):
I'm trying to schedule a "job" at a time picked by user input. When trying to input the time I get a "Invalid Time format" error.
I'm a beginner and am thinking it has to do with how to work with time in python. Any guidance is greatly appreciated.
import schedule
h = what_hour()
m = what_min()
schedule.every().day.at("h:m").do(single_alarm_sound)
Try:
schedule.every().day.at(f"{h}:{m}").do(single_alarm_sound)
More on f-string formatting here: https://realpython.com/python-f-strings/
It's a very nice feature, where you can inject variables, etc right into the string.
I've been trying to make an application in python and I'm new to python.
Well, what I actually want to do is that . I want the feedparser to read the values from an RSS of a website... say reddit... and then I want to make that output as a stringand pass the value further to my code... my code right now..
import feedparser
import webbrowser
feed = feedparser.parse('http://www.reddit.com/.rss')
print feed['entries'][1]['title']
print feed['entries'][1]['link']
It is working right now.. it parses the feed and I get the output I want... Now, I want to use the "link" from the "print feed['entries'][1]['link'] " and use it in the code further...
how can I do so..? To be more specific.. I want to open that URL in my browser...
I concluded to something like this..
import feedparser
import webbrowser
feed = feedparser.parse('http://www.reddit.com/.rss')
print feed['entries'][1]['title']
print feed['entries'][1]['link']
mystring = 'feed['entries'][1]['link']'
webbrowser.open('mystring')
It is of course not working... Please Help... if you need to know anything else.. please let me know...
This is Reddit specific so it won't work on other RSS feeds but I thought this might help you.
from __future__ import print_function
import praw
r = praw.Reddit("my_cool_user_agent")
submissions = r.get_front_page()
for x in submissions:
print("Title: {0} URL: {1} Permalink: {2}".format(x, x.url, x.permalink))
print ("------------------------------------------------------------")
For Reddit there are 2 URLs that you might be interested in: the actual link that is submitted (the 'external' link... think imgur, etc) and the permalink to the Reddit post itself.
Instead of passing the feed[entries][1][link] as a string, just pass the value inside to the webbrowser.
Example -
webbrowser.open(feed['entries'][1]['link'])
I'm using: https://github.com/bitcoin-abe/bitcoin-abe to import the blockchain into a mysql DB it is almost done after 5 days. So I started looking at the data and didn't see any addresses. I know the BTC client doesn't use those, but it still would be nice to have them in another table. I was looking around at the code and found this:
def hash_to_address(version, hash):
vh = version + hash
return base58.b58encode(vh + double_sha256(vh)[:4])
In: https://github.com/bitcoin-abe/bitcoin-abe/blob/3004fe4bad6f64d4c032c735ee23bf9f052d825b/Abe/util.py
When I run a pubkey_hash through that function I don't get the expected result of an address. For example taking the following pubkey_hash: 62E907B15CBF27D5425399EBF6F0FB50EBB88F18
I should get: 1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa
But instead I get: 6GEZdxx5UiTk3U3LaLfsWwRaFAvXEpPNS5R4mqsJDXVJcTNNngTyB5i9S76MLTq
The script I created is:
import util
hash = '62E907B15CBF27D5425399EBF6F0FB50EBB88F18'
print util.hash_to_address("00", hash)
Any ideas or is there something else that would do the same correctly?
Appleman1234 pointed me in the right direction:
import util
hash = '62E907B15CBF27D5425399EBF6F0FB50EBB88F18'
hash = '00' + hash
print "Util: ", util.hash_to_address("", hash.decode('hex'))
The reason you don't get the result you expected is due to encoding.
The correct code for Python 2
import util
hash = '62e907b15cbf27d5425399ebf6f0fb50ebb88f18'
print util.hash_to_address("00".decode('hex'), hash.decode('hex'))
The correct code for Python 3
import util
import binascii
hash = '62e907b15cbf27d5425399ebf6f0fb50ebb88f18'
print util.hash_to_address(binascii.unhexlify("00"), binascii.unhexlify(hash))
The decode and unhexlify functions convert the hexadecimal ASCII representations into binary byte strings.
The problem you were having was that the hash of the binary string and the hash of its hexadecimal ASCII representation are two different hashs.
How do I create a GUID/UUID in Python that is platform independent? I hear there is a method using ActivePython on Windows but it's Windows only because it uses COM. Is there a method using plain Python?
The uuid module provides immutable UUID objects (the UUID class) and the functions uuid1(), uuid3(), uuid4(), uuid5() for generating version 1, 3, 4, and 5 UUIDs as specified in RFC 4122.
If all you want is a unique ID, you should probably call uuid1() or uuid4(). Note that uuid1() may compromise privacy since it creates a UUID containing the computer’s network address. uuid4() creates a random UUID.
UUID versions 6 and 7 - new Universally Unique Identifier (UUID) formats for use in modern applications and databases (draft) rfc - are available from https://pypi.org/project/uuid6/
Docs:
Python 2
Python 3
Examples (for both Python 2 and 3):
>>> import uuid
>>> # make a random UUID
>>> uuid.uuid4()
UUID('bd65600d-8669-4903-8a14-af88203add38')
>>> # Convert a UUID to a string of hex digits in standard form
>>> str(uuid.uuid4())
'f50ec0b7-f960-400d-91f0-c42a6d44e3d0'
>>> # Convert a UUID to a 32-character hexadecimal string
>>> uuid.uuid4().hex
'9fe2c4e93f654fdbb24c02b15259716c'
If you're using Python 2.5 or later, the uuid module is already included with the Python standard distribution.
Ex:
>>> import uuid
>>> uuid.uuid4()
UUID('5361a11b-615c-42bf-9bdb-e2c3790ada14')
I use GUIDs as random keys for database type operations.
The hexadecimal form, with the dashes and extra characters seem unnecessarily long to me. But I also like that strings representing hexadecimal numbers are very safe in that they do not contain characters that can cause problems in some situations such as '+','=', etc..
Instead of hexadecimal, I use a url-safe base64 string. The following does not conform to any UUID/GUID spec though (other than having the required amount of randomness).
import base64
import uuid
# get a UUID - URL safe, Base64
def get_a_uuid():
r_uuid = base64.urlsafe_b64encode(uuid.uuid4().bytes)
return r_uuid.replace('=', '')
If you need to pass UUID for a primary key for your model or unique field then below code returns the UUID object -
import uuid
uuid.uuid4()
If you need to pass UUID as a parameter for URL you can do like below code -
import uuid
str(uuid.uuid4())
If you want the hex value for a UUID you can do the below one -
import uuid
uuid.uuid4().hex
If you are making a website or app where you need to every time a unique id. It should be a string a number then UUID is a great package in python which is helping to create a unique id.
**pip install uuid**
import uuid
def get_uuid_id():
return str(uuid.uuid4())
print(get_uuid_id())
OUTPUT example: 89e5b891-cf2c-4396-8d1c-49be7f2ee02d
2019 Answer (for Windows):
If you want a permanent UUID that identifies a machine uniquely on Windows, you can use this trick: (Copied from my answer at https://stackoverflow.com/a/58416992/8874388).
from typing import Optional
import re
import subprocess
import uuid
def get_windows_uuid() -> Optional[uuid.UUID]:
try:
# Ask Windows for the device's permanent UUID. Throws if command missing/fails.
txt = subprocess.check_output("wmic csproduct get uuid").decode()
# Attempt to extract the UUID from the command's result.
match = re.search(r"\bUUID\b[\s\r\n]+([^\s\r\n]+)", txt)
if match is not None:
txt = match.group(1)
if txt is not None:
# Remove the surrounding whitespace (newlines, space, etc)
# and useless dashes etc, by only keeping hex (0-9 A-F) chars.
txt = re.sub(r"[^0-9A-Fa-f]+", "", txt)
# Ensure we have exactly 32 characters (16 bytes).
if len(txt) == 32:
return uuid.UUID(txt)
except:
pass # Silence subprocess exception.
return None
print(get_windows_uuid())
Uses Windows API to get the computer's permanent UUID, then processes the string to ensure it's a valid UUID, and lastly returns a Python object (https://docs.python.org/3/library/uuid.html) which gives you convenient ways to use the data (such as 128-bit integer, hex string, etc).
Good luck!
PS: The subprocess call could probably be replaced with ctypes directly calling Windows kernel/DLLs. But for my purposes this function is all I need. It does strong validation and produces correct results.
Run this command:
pip install uuid uuid6
And then run you can import uuid1, uuid3, uuid4 and uuid5 functions from the uuid package, and uuid6 and uuid7 functions from the uuid6 package.
An example output of calling each of these functions is as follows (except uuid3 and uuid5 which require parameters):
>>> import uuid, uuid6
>>> print(*(str(i()) for i in [uuid.uuid1, uuid.uuid4, uuid6.uuid6, uuid6.uuid7]), sep="\n")
646e934b-f20c-11ec-ad9f-54a1500ef01b
560e2227-c738-41d9-ad5a-bbed6a3bc273
1ecf20b6-46e9-634b-9e48-b2b9e6010c57
01818aa2-ec45-74e8-1f85-9d74e4846897
This function is fully configurable and generates unique uid based on the format specified
eg:- [8, 4, 4, 4, 12] , this is the format mentioned and it will generate the following uuid
LxoYNyXe-7hbQ-caJt-DSdU-PDAht56cMEWi
import random as r
def generate_uuid():
random_string = ''
random_str_seq = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
uuid_format = [8, 4, 4, 4, 12]
for n in uuid_format:
for i in range(0,n):
random_string += str(random_str_seq[r.randint(0, len(random_str_seq) - 1)])
if n != 12:
random_string += '-'
return random_string