def tick(): #print(database.addMessage("sendDM.py", "online", "Script sendDM.py is still working.")) global tryCounter tryCounter = tryCounter + 1 print("Next event triggers at " + str(getNextTime(True))) pause.until(getNextTime(True)) event = database.nextEvent() if getNextTime(False) < datetime.datetime.now(): print(event) try: if (event["eventType"] == "localWeather"): print(event["location"]) sendDM(event["twitterAccount"], weather.getWeather(str(event["location"]))) database.updateEventTimeAuto(event["id"]) print("Run localWeather event #" + event["id"]) elif (event["eventType"] == "dailyStock"): #TODO Call dailyStock function print("Run dailyStock #" + event["id"]) elif (event["eventType"] == "dailyQuote"): print(int(event["twitterAccount"])) sendDM(event["twitterAccount"], getDailyQuote.get_daily_quote()) database.updateEventTimeAuto(event["id"]) print("Run daily quote #" + event["id"]) elif (event["eventType"] == "dailyWord"): sendDM(event["twitterAccount"], word.getWordOfDay()) database.updateEventTimeAuto(event["id"]) print("Run word event #" + event["id"]) elif (event["eventType"] == "remindMe"): sendDM(event["twitterAccount"], "REMINDER: " + event["message"]) database.updateEventTimeAuto(event["id"]) tryCounter = 0 database.addMessage("sendDM.py", "online", "Event #" + event["id"] + " was sent.") except Exception: exc_type, exc_value, exc_traceback = sys.exc_info() lines = traceback.format_exception(exc_type, exc_value, exc_traceback) print(lines) if tryCounter <= 3: time.sleep(10) else: database.updateEventTimeAuto(event["id"]) print("Event " + event["id"] + " failed 3 times. It was skipped.") database.addMessage( "sendDM.py", "error", "Event #" + event["id"] + " failed 3 times. It was skipped.")
def tweetGreenvilleWeather(): # Greenville, NC 27858 zipcode = "27858" # Builds the forecast string forecast = getWeather(zipcode) print(forecast) # Tweet the forecast api.update_status(status=forecast) database.addMessage("main.py", "tweets", "The weather was tweeted. " + forecast).replace( '\r', ' ').replace('\n', ' ').replace('\t', ' ')
def sendEventHelp(twitterID): sendDM( twitterID, "Types of events:\r\n\t\r\n\tLOCAL WEATHER:\r\n\t\t'!add localWeather [zipCode] [time to send weather, formatted HH:MM:SS (24 hour time). optional]'\r\n\t\tSends the local weather at the time you want (defalt 8AM).\r\n\tDAILY QUOTE:\r\n\t\t'!add dailyQuote'\r\n\t\tSends a daily quote every morning at 7AM.\r\n\tDAILY STOCK*:\r\n\t\t'!add dailyStocks [stock symbol]'\r\n\t\tSend the value of a stock everyday after the stock market cloeses (5:30PM).\r\n\tWORD OF THE DAY:\r\n\t\t'!add word'\r\n\t\tSends a daily word every morning at 9AM.\r\n\tREMIND ME:\r\n\t\t'!add remindMe' [data, formatted YYYY-MM-DD] [time, formatted HH:MM:SS] [message]\r\n\tSend you a reminder on the date and time you pick." ) print( database.addMessage("checkDMs.py", "received", "User " + twitterID + " asked for event help."))
def sendHelp(twitterID): #TODO Format real command help to fit in a DM. sendDM( twitterID, "NOTE: This Twitter bot is not finished and may be unstable. Follow @csci3030team3 to be notifyed when it is ready.\r\n\r\n'!info'\r\n\tSee a list of the events you are signed up for.\r\n'!unsub [eventID]'\r\n\tUnsubscribe from an event.\r\n'!unsubAll'\r\n\tUnsubscribe from all events\r\n'!time'\r\n\tAll times are in GTM London (5 hours before EST New York) See the server time by sending .\r\n'!add [eventType] [parameters1] [parameters2]...'\r\n\tAdd a new event." ) print( database.addMessage("checkDMs.py", "received", "User " + twitterID + " asked for help."))
def sendDM(twitterID, message): event = '{"event":{"type":"message_create","message_create":{"target":{"recipient_id":"%s"},"message_data":{"text":"%s"}}}}' % ( twitterID, twitterStringCleaner(message)) r = api.request('direct_messages/events/new', event) print(str(r.status_code) + ": " + message) print( database.addMessage("checkDMs.py", "sent", "User " + twitterID + " was sent: " + message)) time.sleep(2)
def checkDM(): # Get DMs from last 30 days. r = api.request('direct_messages/events/list') # Get list of messages that have been read. with open('messagesSent.txt') as my_file: messageID_array = my_file.readlines() print(r.status_code) if (r.status_code == 200): print(r.json()["events"]) for t in r.json()["events"]: #For each message if (str(t["id"] + "\n")) not in messageID_array: if (t["message_create"]["sender_id"] != twitterID ): ##Don't respond to messages sent by ourselve. try: dmFrom = t["message_create"]["sender_id"] dmTo = t["message_create"]["target"]["recipient_id"] dmMessage = t["message_create"]["message_data"][ "text"].encode('ascii', 'ignore').decode('ascii').lower() print(dmFrom + ": " + dmMessage) if (dmMessage[0] == '!' ): #If message starts with '!' it is a command command = dmMessage.split(" ", 1)[0].replace("!", "") print("This is a command (" + command + ")") if (command == "help"): event = dmMessage.split(" ") if (int(len((event)) < 1)): if event[1] == "eventTypes": print(event) sendEventHelp(dmFrom) else: sendHelp(dmFrom) sendEventHelp(dmFrom) else: sendHelp(dmFrom) sendEventHelp(dmFrom) elif (command == "add"): event = dmMessage.split(" ") print(event) if (event[1] == "localweather"): sendDM(dmFrom, decodeLocalWeather(event, dmFrom)) elif (event[1] == "dailyquote"): database.addDailyQuote(dmFrom) sendDM( dmFrom, "You will receive a DM of a quote everyday at 7 AM." ) elif (event[1] == "dailystocks"): #TODO sendDM(dmFrom, "Daily Stocks is not done yet.") elif (event[1] == "word"): database.addDailyWord(dmFrom) sendDM( dmFrom, "You will receive a DM of a word everyday at 9 AM." ) elif (event[1] == "remindme"): event = dmMessage.split(" ", 4) print(event) database.addRemindMe( dmFrom, event[2] + " " + event[3], twitterStringCleaner(event[4])) #sendDM(dmFrom, "You will receive a DM of a word everyday at 9 AM.") else: print( sendDM( dmFrom, "Unknown add command. Type !help for more info." )) elif (command == "unsuball"): sendDM(dmFrom, database.unsubAll(dmFrom)) elif (command == "unsub"): #TODO !unsub message = dmMessage.split(" ") event = database.getByID(message[1]) if (dmFrom == event["twitterAccount"]): sendDM(dmFrom, database.unsub(message[1])) else: sendDM( dmFrom, "You can only delete your own events.") print(event) elif (command == "info"): if (len(dmMessage.split(" ")) > 1): print(dmMessage.split(" ")[1]) sendDM( dmFrom, eventToString( database.getByID( dmMessage.split(" ")[1]))) else: yourList = "LIST OF YOUR EVENTS:" print(len(dmMessage.split(" "))) events = database.getByUsername(dmFrom) for e in events: print(eventToString(e)) yourList = yourList + "\r\n\t" + eventToString( e) sendDM(dmFrom, yourList) elif (command == "time"): whatTimeIsIt(dmFrom) else: sendDM( dmFrom, "Sorry, we do not understand the command " + command + ". Use !help for a list of commands.") database.addMessage( "checkDM.py", "error", "Unknown command: " + command) except Exception: exc_type, exc_value, exc_traceback = sys.exc_info() lines = traceback.format_exception( exc_type, exc_value, exc_traceback) e = "" for l in lines: e = e + ". " + l sendDM( dmFrom, "There was an error processing your DM. (" + twitterStringCleaner(e) + ")") database.addMessage( "checkDM.py", "error", "There was a problem processing a DMs. (" + str(r.status_code) + ")") markDMasRead(t["id"]) else: print("There was a problem getting Twitter DMs. (" + str(r.status_code) + ")") database.addMessage( "checkDM.py", "error", "There was a problem getting Twitter DMs. (" + str(r.status_code) + ")") database.addMessage("checkDM.py", "online", "Script checkDM.py is still working.")
def addMessages(chat_id): return addMessage(chat_id)
tweetSkipper = True text_file = open("alertList.txt", "a") text_file.write("\n" + entry.id) text_file.close() count_alerted += 1 ##if the item is old skip it else: ##print("[" + str(datetime.datetime.now()) +", API Test/NWSPublicAlerts_twitter.py] Alert ID " + entry.id + " has already ran and will be skipped.") count_skipped += 1 else: print( "[" + str(datetime.datetime.now()) + ", API Test/NWSPublicAlerts_twitter.py] There are no active watches, warnings or advisories" ) database.addMessage( "NWSPublicAlerts_twitter.py", "online", "Script NWSPublicAlerts_twitter.py is still working.") #print("[" + str(datetime.datetime.now()) +", API Test/NWSPublicAlerts_twitter.py] "+str(count_alerted) + " new alerts found.") #print("[" + str(datetime.datetime.now()) +", API Test/NWSPublicAlerts_twitter.py] " + str(count_skipped) + " old alerts skipped.\n") #id = weatherAlerts.entries[i].id #published = weatherAlerts.entries[i].published #title = weatherAlerts.entries[i].title #update = weatherAlerts.entries[i].update #summary = weatherAlerts.entries[i].summary #event = weatherAlerts.entries[i].cap_event #severity = weatherAlerts.entries[i].cap_severity #expires = weatherAlerts.entries[i].cap_expires #print(title)