Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
'''Saves a message to deliver to someone later'''
dbConn = sqlite.connect(dbName)
cursor = dbConn.cursor()
sender = event.source().split("!")[0]
sendee = args.split()[0].lower() # To whom should the message be delivered
if sendee == "me" or sendee == "myself":
sendee = sender
channel = event.target()
message = " ".join(args.split()[1:])
if len(message.split(" in ")) > 1:
message = " ".join(message.split(" in ")[:-1])
# Parse the time to deliver the message (if any)
deliver = args.split(" in ")[-1]
p = pdt.Calendar(pdc.Constants()) # Use parsedatetime module to easily handle human date formatting
deliver = p.parse(deliver)
if deliver[1] == 0: # Tried to parse an invalid time (i.e., we can't parse "stuff")
deliver = None
else:
deliver = deliver[0]
deliver = "%d-%d-%d %d:%d:%d" % (deliver[0], deliver[1], deliver[2], deliver[3], deliver[4], deliver[5]) # Format the deliver into a string for toEpoch()
deliver = epochTools.toEpoch(deliver, format="%Y-%m-%d %H:%M:%S") # deliverstamp for DB storage
cursor.execute("insert into tell (sender, sendee, channel, message, deliver, sent) values (?, ?, ?, ?, ?, ?)", (sender, sendee, channel, message, deliver, time.time()))
connection.privmsg(event.target(), "Will do!")
dbConn.commit()
@classmethod
def parseTime(cls, view, target):
"""Parses Natural Language time strings using parsedatetime library."""
target = target.lower()
for matchKey in cls.textMatches:
#natural language time string found
if ((cls.textMatches[matchKey]).lower()).startswith(target):
cal = parsedatetime.Calendar()
(timeVar, invalidFlag) = cal.parse(matchKey)
#invalidFlag = 0 implies no date/time
#invalidFlag = 1 implies only date, no time
if invalidFlag != 0 and invalidFlag != 1:
timeVar = pim.shortTimeFormat.format(view, datetime(*timeVar[:5]))
matchKey = cls.textMatches[matchKey]+ " - %s" %timeVar
yield matchKey
else:
cal = parsedatetime.Calendar()
(timeVar, invalidFlag) = cal.parse(target)
#invalidFlag = 0 implies no date/time
#invalidFlag = 1 implies only date, no time
if invalidFlag != 0 and invalidFlag != 1:
match = pim.shortTimeFormat.format(view, datetime(*timeVar[:5]))
if unicode(match).lower() !=target:
yield match
datetime => datetime
str => datetime
"""
if isinstance(epoch, bool) or isinstance(epoch, datetime):
return epoch
elif epoch == 'True':
return True
elif epoch == 'False':
return False
try:
return datetime.strptime(epoch, self.DATE_FORMAT)
except ValueError:
pass
parser = parsedatetime.Calendar(Constants())
time_tupple = parser.parse(epoch) # 'yesterday' => (time.struct_time, int)
if not time_tupple[1]:
raise NotConfigured('Could not parse epoch: %s' % epoch)
time_struct = time_tupple[0] #=> time.struct_time(tm_year=2012, tm_mon=4, tm_mday=7, tm_hour=22, tm_min=8, tm_sec=6, tm_wday=5, tm_yday=98, tm_isdst=-1)
return datetime(*time_struct[:6]) #=> datetime.datetime(2012, 4, 7, 22, 8, 6)
def parsedate(s):
import parsedatetime.parsedatetime as pdt
p = pdt.Calendar()
if s == '--':
return None
return datetime.date(*p.parse(s)[0][0:3])
def natural_parser(date_time, settings):
"""
This is a bit clever. We've found a python lib that can translate
"""
# This is a list of the error codes and matching formats that will be used
# depending on what is returned by the parser
format_map = {
1: get_date_format(settings),
2: get_time_format(settings),
3: get_full_format(settings)
}
# remove the first character and send attempt to translate it
date_time_to_parse = date_time[1:-1]
cal = parsedatetime.Calendar()
date_time_parsed = cal.parseDT(date_time_to_parse)
# This parser handily sends back an error code, just in case
error_code = date_time_parsed[1]
if error_code == 0:
raise ValueError
else:
return date_time_parsed[0], format_map[error_code]
def save_to_db(self):
"""
Saves the permalink comment, the time, and the message to the DB
"""
cal = pdt.Calendar()
try:
holdTime = cal.parse(self._storeTime, datetime.now(timezone('UTC')))
except ValueError, OverflowError:
# year too long
holdTime = cal.parse("9999-12-31")
if holdTime[1] == 0:
# default time
holdTime = cal.parse("1 day", datetime.now(timezone('UTC')))
self._replyMessage = "**Defaulted to one day.**\n\n"
# Converting time
#9999/12/31 HH/MM/SS
self._replyDate = time.strftime('%Y-%m-%d %H:%M:%S', holdTime[0])
cmd = "INSERT INTO message_date (permalink, message, new_date, origin_date, userID) VALUES (%s, %s, %s, %s, %s)"
self._addToDB.cursor.execute(cmd, (
self.comment.permalink.encode('utf-8'),
self._messageInput.encode('utf-8'),
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
# Connect to the db
db = dataset.connect(DATABASE_URL)
print('DATABASE_URL=%s' % DATABASE_URL)
table = db['reminders']
# Twitter client
auth = tweepy.OAuthHandler(TWITTER_KEY, TWITTER_SECRET)
auth.set_access_token(TWITTER_TOKEN, TWITTER_TOKEN_SECRET)
api = tweepy.API(auth)
# parsedatetime object
cal = pdt.Calendar()
def now():
"""Get the current time in UTC."""
ts = cal.parse('now', datetime.now(timezone(DEFAULT_TZ)))[0]
return time.strftime(REMINDER_TIME_FORMAT, ts)
def search_db():
'''Returns a list of all rows from db that we can remind right now.'''
now_ts = now()
result = db.query(('select * from reminders '
'where sent_tweet_id = \'\''
'and reminder_time::timestamp < \'%s\'::timestamp;' % now_ts))
logging.info('search_db: %d results for time %s' % (
def parse(s):
"""
Parse the string using parsedatetime and format it to the current timezone
"""
return TZ.localize(datetime(*tuple(pdt.Calendar(pdc.Constants()).parse(s)[0])[:7]))