def confirm_email(hashid, key): # If post is in pending state and email key is correct, convert to published # and update post.datetime to utcnow() so it'll show on top of the stack # This function expects key to be email_verify_key, not edit_key like the others post = JobPost.query.filter_by(hashid=hashid).first() if post is None: abort(404) elif post.status == POSTSTATUS.REJECTED: abort(410) elif post.status in [POSTSTATUS.CONFIRMED, POSTSTATUS.REVIEWED]: flash("This job listing has already been confirmed and published", "interactive") return redirect(url_for('jobdetail', hashid=post.hashid), code=302) elif post.status == POSTSTATUS.DRAFT: # This should not happen. The user doesn't have this URL until they # pass the confirm form return redirect(url_for('confirm', hashid=post.hashid), code=302) elif post.status == POSTSTATUS.PENDING: if key != post.email_verify_key: abort(403) else: post.email_verified = True post.status = POSTSTATUS.CONFIRMED post.datetime = datetime.utcnow() db.session.commit() if app.config['TWITTER_ENABLED']: tweet(post.headline, url_for('jobdetail', hashid=post.hashid, _external=True), post.location) flash("Congratulations! Your job listing has been published", "interactive") return redirect(url_for('jobdetail', hashid=post.hashid), code=302)
def on_detection(): if is_pi: try: camera.capture('./img.jpg') except: print("Failed to caputre image") try: if (tweeting): try: tweet(location + ' spotted:', './img.jpg') print('Tweeted ./img.jpg with the caption: \'I spotted: \'') except: print("Failed to tweet") fname = (str(time.time()) + '.jpg') download_url = fs.add('images/' + fname, fname, './img.jpg') print('Image download URL:' + download_url) try: db.push( '/spottings', { 'image': download_url, 'confirmed': False, 'time': fname[:-4], 'location': location }) except: print("Failed to push to db") except IOError: print( "./img.jpg cannot be parsed/detected; does the file exist & is it a jpg?" )
def main(data: Dict) -> None: if 'tweet_create_events' in data: for event in data['tweet_create_events']: text = event['text'] user_id = event['user']['id_str'] screen_name = event['user']['screen_name'] name = event['user']['name'] status_id = event['id_str'] if screen_name == BOTSCREENNAME: continue if re.match('(^RT |^QT |.* RT |.* QT ).*', text): continue message = execute(text, user_id, screen_name, name, True) if message is not None: twitter.tweet(message[:140], status_id) if 'direct_message_events' in data: for event in [event for event in data['direct_message_events'] if event['type'] == 'message_create']: text = '@tipkotone ' + event['message_create']['message_data']['text'] user_id = event['message_create']['sender_id'] screen_name = data['users'][user_id]['screen_name'] name = data['users'][user_id]['name'] if screen_name == BOTSCREENNAME: continue message = execute(text, user_id, screen_name, name, False) if message is not None: twitter.dm(message, user_id)
def main(): db = Database() for grade in GRADE_NAMES: get_url = BASE_URL + grade + '/' try: req = urllib.request.Request(get_url, None, { 'Authorization': AUTH_TOKEN }) with urllib.request.urlopen(req) as res: links = get_links(res.read()) except Exception as e: print(e) continue for link in links: req = urllib.request.Request(link[0], None, { 'Authorization': AUTH_TOKEN }) with urllib.request.urlopen(req) as res: cur_upd = res.headers['last-modified'] old_upd = db.get_last_update(link[0]) if old_upd == None: twitter.tweet(NEW_PAGE_TPL.format(grade=GRADE_NAMES[grade], title=link[1])) elif old_upd != cur_upd: twitter.tweet(UPD_PAGE_TPL.format(grade=GRADE_NAMES[grade], title=link[1])) db.set_last_update(link[0], cur_upd)
def main(message=None, pattern_id=None, in_reply_to_status_id=None, destroy_wait=None): if not message: message = msggen(pattern_id) if message: tweet(message, in_reply_to_status_id=in_reply_to_status_id, destroy_wait=destroy_wait) else: print '(no message)'
def main(): for batch in new_batches(): json_url = batch['url'].strip('/') + '.json' batch_info = json.loads(urllib.urlopen(json_url).read()) name = format_name(batch['awardee']) msg = "%s newspaper pages were just loaded from %s %s" % \ (batch_info['page_count'], name, batch['url']) twitter.tweet(msg) time.sleep(5)
def take_picture_and_tweet(): with picamera.PiCamera() as camera: camera.start_preview() timestamp = datetime.now().isoformat() img = '/home/pi/twitter/%s.jpg' % timestamp message = choice(messages) camera.annotate_text = message camera.capture(img) camera.stop_preview() twitter.tweet(message, img)
def broadcast(from_number, message): print('message: ', message) numbers = find_numbers() print('found numbers:', numbers) send_messages(numbers, message) tweet(message) facebook_group_post(message) metadata, found = identify_event_metadata(from_number) if not found: return 'Broadcast successful but unknown Patron' save_event(message, from_number, metadata) return 'Broadcast successful!'
def tweet_hadith(): collection, book, hadith_no = get_hadith_track() hadith_source = "http://askhadith.herokuapp.com" full_hadith_source = "https://askhadith.herokuapp.com" hadith_link = f"{full_hadith_source}/b/{collection}/{book}/{hadith_no}" resp = requests.get(f"{hadith_source}/api/{collection}/{book}/{hadith_no}") if resp.json(): hadith = Hadith(**resp.json()) hadith.hadith_link = hadith_link tweet(hadith) post_on_page(hadith) update_hadith_track(collection, book, hadith_no)
def main(argv): if len(argv) > 1: # for testing date = datetime.datetime.strptime(argv[1], '%m/%d/%Y') else: today = datetime.date.today() date = datetime.date(today.year-100, today.month, today.day) headlines = [] for page in front_pages(date): headlines.extend(blocks(page)) headlines.sort(tweetability) msg = twitter_msg(headlines[0], date) twitter.tweet(msg)
def tweetit(update, context): allowlist = get_allowlist() if update.message.from_user['username'] in allowlist: response_message = "Tweeting: "+update.message.text twitter.tweet(update.message.text) context.bot.send_message( chat_id=update.effective_chat.id, text=response_message ) else: response_message = "You are not in the allowlist" context.bot.send_message( chat_id=update.effective_chat.id, text=response_message )
def verify(arrobas): clock = time.monotonic() qtde_tweets = 0 qtde_arrobas = 0 for arroba in arrobas: urls = [] qtde_arrobas += 1 #print(str(qtde_arrobas) + " - criando lista de links para... " + arroba) lista_antiga = database.recupera_ids(arroba) urls += [ "https://twitter.com/" + arroba + "/status/" + str(id[0]) for id in lista_antiga ] #print("Verificando status dos links...") if len(urls) > 20: urlss = split(urls, int(len(urls) / 20)) else: urlss = [urls] for urls in urlss: qtde_tweets_arroba = 0 time.sleep(5) try: requests = [grequests.get(url) for url in urls] responses = grequests.map(requests, exception_handler=exception_handler) # print(len(responses)) for resp in responses: if resp.status_code == 404: id, tweet, handle, archive_url, creation_date = database.retrieve_tweet( resp.url) if len(tweet + handle) > 1: if (qtde_tweets_arroba == 0): status = twitter.tweet_start(handle) #print(tweet) #print(handle) #print(resp.url) #print(archive_url) status = twitter.tweet(handle, tweet, archive_url, creation_date, id, status) qtde_tweets += 1 qtde_tweets_arroba += 1 database.update_tweet(id) resp.close() except Exception as E: print("erro... em alguma url") print(E) time.sleep(300) twitter.tweet_end(timedelta(seconds=time.monotonic() - clock), qtde_tweets)
def confirm_email(hashid, key): # If post is in pending state and email key is correct, convert to published # and update post.datetime to utcnow() so it'll show on top of the stack # This function expects key to be email_verify_key, not edit_key like the others post = JobPost.query.filter_by(hashid=hashid).first() if post is None: abort(404) elif post.status == POSTSTATUS.REJECTED: abort(410) elif post.status in [POSTSTATUS.CONFIRMED, POSTSTATUS.REVIEWED]: flash("This job listing has already been confirmed and published", "interactive") return redirect(url_for('jobdetail', hashid=post.hashid), code=302) elif post.status == POSTSTATUS.DRAFT: # This should not happen. The user doesn't have this URL until they # pass the confirm form return redirect(url_for('confirm', hashid=post.hashid), code=302) elif post.status == POSTSTATUS.PENDING: if key != post.email_verify_key: abort(403) else: if app.config.get('THROTTLE_LIMIT', 0) > 0: post_count = JobPost.query.filter(JobPost.email_domain == post.email_domain).filter( JobPost.status > POSTSTATUS.PENDING).filter( JobPost.datetime > datetime.utcnow() - timedelta(days=1)).count() if post_count > app.config['THROTTLE_LIMIT']: flash(u"We've received too many listings from %s in the last 24 hours. Please try again in a few hours. " "If you believe this to be an error, please email us at %s." % (post.email_domain, app.config['SUPPORT_EMAIL']), category='info') return redirect(url_for('index')) post.email_verified = True post.status = POSTSTATUS.CONFIRMED post.datetime = datetime.utcnow() db.session.commit() if app.config['TWITTER_ENABLED']: try: tweet(post.headline, url_for('jobdetail', hashid=post.hashid, _external=True), post.location) flash("Congratulations! Your job listing has been published and tweeted", "interactive") except: # FIXME: Catch-all flash("Congratulations! Your job listing has been published " "(Twitter was not reachable for tweeting)", "interactive") else: flash("Congratulations! Your job listing has been published", "interactive") return redirect(url_for('jobdetail', hashid=post.hashid), code=302)
def main(): for u in users.get(): comp = compliment.get() success, err = twitter.tweet(comp, u) if not success: print(f'Failed to send tweet: {err}') continue print(f'Tweeted compliment: {comp}. For user: {u}')
def updateCourse(course): log.log("Updating %s" % str(course)) url = "https://registrar.princeton.edu/course-offerings/course_details.xml?courseid={}&term={}".format(course.number, TERM) html = urllib2.urlopen(url).read() soup = BeautifulSoup(html) rows = soup.find_all('tr')[1:] for row in rows: fields = row.find_all('td') classNumber = fields[0].get_text().strip() if not classNumber: continue theclass, created = Class.objects.get_or_create(number=classNumber, course=course) theclass.title = fields[1].get_text().strip() theclass.time = fields[2].get_text().strip().replace("\n", "") theclass.days = fields[3].get_text().strip().replace("\n", "") raw = fields[5].get_text().replace("\n","").replace(" ","") sindex = raw.find("Enrolled:") eindex = raw.find("Limit:") theclass.enroll = int(raw[sindex+9:eindex]) theclass.max = int(raw[eindex+6:] or 1000) isClosed = fields[6].get_text().strip() == "Closed" if not isClosed: freeSpots = theclass.max - theclass.enroll try: # don't tweet "P99" if theclass.title != "P99": twitter.tweet("%s has %d open spot(s)." % (str(theclass), freeSpots)) except Exception: pass log.log("Class %s is now open!" % str(classNumber)) for subscription in Subscription.objects.filter(theclass=theclass, active=True): log.log("Sending subscription %s." % str(subscription)) subscription.sendNotification() subscription.active = False subscription.save() theclass.isClosed = isClosed theclass.save()
def publish(): publog = [] hero = Comic.hero() if hero.published: print("Nothing to see here!") return publog.append("We're publishing a comic! Hooray!") publog.append(str(hero)) hero.published = True # this should trigger a cache-clear and re-order operation hero.save() hero = Comic.hero() assert(hero.order > 0) # send hero e-mail to subscribers subscribers = EmailSubscriber.subscribers() mails = [] for subscriber in subscribers: try: publog.append("Sending comic to {}".format(subscriber.email)) subscriber.send_promo_email(hero) except SpamSpamSpamSpam: publog.append("\tCan't send: SPAM limit!") except Exception as e: publog.append(e) # tweet hero tweet twitter_message = hero.twitter_message() publog.append("\n") publog.append("Tweeting: {}".format(twitter_message)) try: tweet(twitter_message) except Exception as e: publog.append(e) # send printed report to admin mail_admins(subject="Published!", message="\n".join(publog)) return
def updateCourse(course): log.log("Updating %s" % str(course)) url = "https://registrar.princeton.edu/course-offerings/course_details.xml?courseid={}&term={}".format(course.number, TERM) html = urllib2.urlopen(url).read() soup = BeautifulSoup(html) rows = soup.find_all('tr')[1:] for row in rows: fields = row.find_all('td') classNumber = fields[0].get_text().strip() if not classNumber: continue theclass, created = Class.objects.get_or_create(number=classNumber, course=course) theclass.title = fields[1].get_text().strip() theclass.time = fields[2].get_text().strip().replace("\n", "") theclass.days = fields[3].get_text().strip().replace("\n", "") raw = fields[5].get_text().replace("\n","").replace(" ","") sindex = raw.find("Enrolled:") eindex = raw.find("Limit:") theclass.enroll = int(raw[sindex+9:eindex]) theclass.max = int(raw[eindex+6:] or 1000) isClosed = fields[6].get_text().strip() == "Closed" if not isClosed: freeSpots = theclass.max - theclass.enroll try: twitter.tweet("%s has %d open spot(s)." % (str(theclass), freeSpots)) except Exception: pass log.log("Class %s is now open!" % str(classNumber)) for subscription in Subscription.objects.filter(theclass=theclass, active=True): log.log("Sending subscription %s." % str(subscription)) subscription.sendNotification() subscription.active = False subscription.save() theclass.isClosed = isClosed theclass.save()
def on_message(ws,message): obj = json.loads(message) if obj['userID'] in checkusers and obj['status'] == 4: problem = str(obj['problemID']) print(message) if obj['lessonID'] != "": problem = obj['lessonID'] + "_" + problem tweet_text = '[AOJ] ' + obj['userID'] + ' solved \'' + obj['problemTitle'] + '\' http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=' + problem make_histogram(histogram_filename,problem,obj['runID'],obj['lang'],obj['cputime'],obj['memory'],obj['code']) media_id = twitter.upload_image(histogram_filename) status = twitter.tweet({"status": tweet_text,"media_ids": media_id})
def pokemon_found(pokemon): # get name pokename = _str(pokemon["name"]).lower() # check array if not pushbullet_client: return elif wanted_pokemon != None and not pokename in wanted_pokemon: return elif wanted_pokemon == None and unwanted_pokemon != None and pokename in unwanted_pokemon: return # notify print "[+] Notifier found pokemon:", pokename #http://maps.google.com/maps/place/<place_lat>,<place_long>/@<map_center_lat>,<map_center_long>,<zoom_level>z latLon = '{},{}'.format(repr(pokemon["lat"]), repr(pokemon["lng"])) google_maps_link = 'http://maps.google.com/maps/place/{}/@{},{}z'.format(latLon, latLon, 20) disappear_time = convert_timestamp(pokemon['disappear_time']) bot_id = os.environ['BOT_ID'] groupme_message = 'A wild {} appeared at {} and will be available until {}.'.format(_str(pokemon['name']), google_maps_link, disappear_time) groupme.send_message(groupme_message, bot_id) twitter.tweet(groupme_message)
def news_list(driver): # ページOPEN driver.get("https://football-tribe.com/japan/news/") contents = {} # ニュース一覧ページからurlとテキストを取得 for element in driver.find_elements_by_class_name( 'tribe-thumbnails-wrapper'): result = element.find_element_by_tag_name('a') url = result.get_attribute("href") # ニュースの配信日時を取得 # 日付フォーマットを変換(2019.09.26. 10:59 am 形式) post_date = element.find_element_by_class_name('post-date').text post = post_date.replace("Posted on: ", "") post_time = datetime.strptime(post, '%Y.%m.%d. %I:%M %p') # 1時間前のタイムスタンプを取得 last_date = datetime.now() + timedelta(hours=-1) # 直近1時間以内に配信されたニュースのみツイート if last_date.timestamp() < post_time.timestamp(): twitter.tweet(url) else: continue return contents
def script(self, sc, year): if year <= self.currentYear: event = getEventFromYear(year) currentIteration = db.get_current_iteration() tweet_id = tweet(event['text']) db.add_event(currentIteration, event['date'], event['text'], tweet_id) # Increment year for next iteration self.start(year + 1) else: # End of this world iteration db.create_new_iteration() currentIteration = db.get_current_iteration() tweet('World is over.') time.sleep(1) tweet('Generating new world.') time.sleep(5) tweet('World #' + str(current_iteration.number) + ' operational.') udpate_name(current_iteration.number) self.start()
def Twitter_share(): data = request.form sentence = data['sentence'] source = data['source'] twitter.tweet(sentence, source) return redirect(request.referrer, code=302)
if newTweets != []: emailSubject = "@%s Bot Status Update" % twitterHandle emailBody += "%s new Tweets left in database:\n\n%s" % (len(newTweets), "\n".join(newTweets)) logger.info("%s new tweets were retrieved." % len(newTweets)) else: emailSubject = "@%s DATABASE ERROR" % twitterHandle.upper() emailBody += "No new tweets left in database! Add more ASAP!" logger.error("No new tweets left in database!") nextTweet = newTweets[0] logger.debug("Set next tweet to \'%s\'" % nextTweet) logger.debug("Sending annual email to %s..." % emailRecipient) print "Sending annual email to %s" % emailRecipient sendMail(emailRecipient, emailSubject, emailBody) #sleeping until the closest hour given in the list sleepUntilNextAction(tweetTimes) #these are for debugging #print "sleeping" #sleep(30) #emailRecipient is needed because if there is a tweet error, it will send to that email logger.info("Tweeting...") twitter.tweet(nextTweet, twitterHandle, emailRecipient) logger.info("Adding Tweet to pasttweets.txt...") tweetRetriever.writeToPastTweets(nextTweet, pastTweetsFile)
""" This is importing a function named `tweet` from a file that we unfortunately don't have access to change. You use it like so: >>> tweet("Hello this is my tweet") If the function cannot connect to Twitter, the function will raise a `CommunicationError` If the message is too long, the function will raise a `MessageTooLongError` """ from twitter import ( tweet, MessageTooLongError, CommunicationError, ) message = input("What would you like to tweet? ") # Your code here try: tweet(message) except CommunicationError: print("An error occurred attempting to connect to Twitter. Please try again!") except MessageTooLongError as err: print("Your message is too long {}".format(err))
def tweet(): """Tweet sentence to twitter.""" status = request.form['sentence'] twitter.tweet(status) return redirect('/')
def tweet(): '''Posts a status update to the @AdamChain Twitter account.''' status_update = request.form.get('sentence') twitter.tweet(status_update) return redirect(url_for('index'))
#! /usr/bin/python from twitter import user, tweet, follow user = user() user.cleanAll() tweet = tweet() follow = follow() user.addUser("ich") user.addUser("du") user.addUser("er") follow.follows("du", "ich") follow.follows("er", "ich") users = user.getAllUsers() for u in users : print u tweet.addTweet("ich", None, "ein neuer tweet") print "tweets von ich" tweets = tweet.getTweetsForUser("ich") for t in tweets : print t print "followers von ich" followers = follow.getFollowersOfUser("ich") for f in followers : print f
def takePhotoAndUpload(status): takenPhotoName = gopro.takePhotoAndDownload() return twitter.tweet(status, takenPhotoName)
shotDelay = allDayRet[1] # moved the following to after the targetTime so the folders will have the correct date if i start it the night before shot_date = datetime.now().strftime("%Y-%m-%d") shot_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") date_folder = "/tlPython/timelapse/images/" + shot_date makeFolders() tp.takePictures(numPics, shotDelay) tp.getPictures(image_location) msgL3 = "stopped shooting at " + now() tp.resizeImages(image_location, resize_location) # resize from a to b movName = tp.makeVid(resize_location, shot_date) # where to find source images tp.makeGif(resize_location, shot_date) print "movName = " + str(movName) msgL4 = "processing finished " + now() msg = msg12 + "\n" + msgL3 + "\n" + msgL4 + "\n" + str( numPics) + " pictures taken" twitter.tweet(msg, movName) # os.chdir(date_folder) os.chdir(date_folder + "/" + folderNumber) f = open("stats.txt", "w+") f.write(msg) f.close() oled.clear()
async def processCommand(message, commandPrefix, client): command = message.content[1:] #the message without the commandPrefix if command == "help": helpMessage = "" for x in commands: helpMessage += x + "\n\n" await message.channel.send(helpMessage) elif command == "ping": await message.channel.send("pong") elif command == "register": await marbleManager.register(message.author, message.channel) elif command == "profile": await marbleManager.getCollection(message.author, message.channel) elif command.split()[0] == "coinflip": parts = command.split() if len(parts) == 2: if not parts[1].isdigit(): await message.channel.send( "You didn't specify a number correctly dumbo.") else: #good to go await marbleManager.coinflip(message.author, message.channel, int(parts[1])) else: await message.channel.send( "coinflip should have 2 parts seperated by a space dumbo.") elif command.split()[0] == "leaderboard" or command.split()[0] == "lb": parts = command.split() if len(parts) == 2: await marbleManager.leaderboard(message.author, message.channel, parts[1], client) elif len(parts) == 1: await marbleManager.leaderboard(message.author, message.channel, "marbles", client) else: await message.channel.send( "leaderboard should have 2 parts seperated by a space dumbo.") elif command.split()[0] == "give": parts = command.split() if len(parts) == 3: if parts[1].isdigit(): await marbleManager.give(message.author, message.channel, int(parts[1]), message.mentions[0]) elif parts[2].isdigit(): await marbleManager.give(message.author, message.channel, int(parts[2]), message.mentions[0]) else: await message.channel.send( "You didn't specify a number correctly dumbo.") else: await message.channel.send("give should have 3 parts.") elif command.split()[0] == "cooltext": userInput = command[len(command.split()[0]) + 1:] output = "" for x in range(len(userInput), 0, -1): blah = " " * x + userInput[x:len(userInput) - x] if userInput[x:len(userInput) - x] != "": output += blah + "\n" for x in range(len(userInput)): blah = " " * x + userInput[x:len(userInput) - x] if userInput[x:len(userInput) - x] != "": output += blah + "\n" await message.channel.send("```\n" + output + "```") elif command.split()[0] == "tweet": userInput = command[len(command.split()[0]) + 1:] tweet(userInput) await message.channel.send("https://twitter.com/onsclom") else: await message.channel.send("Command not recognized. " + commandPrefix + "help to see commands.")
def start_new_world(self): # End current iteration db.create_new_iteration() self.reset() current_iteration = db.get_current_iteration() udpate_name(current_iteration.number) # Get explosion gif gif = get_explosion_gif() # Tweet about end of world tweet('World\'s destruction initiated.') time.sleep(1) tweet('3.') time.sleep(1) tweet('2.') time.sleep(1) tweet('1.') time.sleep(2) tweet('Booom ! ' + gif['url']) time.sleep(5) tweet('Generating new world.') time.sleep(5) tweet('World #' + str(current_iteration.number) + ' operational.') # start again self.start()
if __name__ == '__main__': from database import TweetBotParams from database import TweetBotQueue import twitter import sys languages = [sys.argv[1]] for language in languages: first = True previous_status = None status_list = TweetBotQueue.select( TweetBotQueue, TweetBotParams).join(TweetBotParams).where( (TweetBotQueue.param.lang == language) & (TweetBotParams.period_day == sys.argv[2]) & (TweetBotQueue.bot_flag == False)).order_by( TweetBotQueue.trend_type.asc()) for status in status_list: previous_status = twitter.tweet(status, previous_status, first) first = False status.bot_flag = True status.save() # if (len(status_list) > 0): # last_tweet = TweetBotParams.select().where((TweetBotParams.slug == 'end') & # (TweetBotParams.lang == language)).get() # twitter.end_thread(last_tweet, previous_status)
def broadcast(self): message = 'My rectangle is {} by {}'.format(self.width, self.height) tweet(message)
def tweet(): status = request.form['sentence'] twitter.tweet(status) return redirect('/')
import twitter twitter.tweet('sup', '/photoZeroPython/timelapse/images/2018-10-19/1/2018-10-19.mp4')
def tweet(): status = request.form['quote'] twitter.tweet(status) return redirect('/')
def get_tweets(): return jsonify(twitter.tweet())
import TweetGenerator import CorpusGenerator import twitter #scrape twitter and nyt, and add in with other trump texts CorpusGenerator.CorpusGenerator() #generate tweet using ngram/markov chain tweet_maker = TweetGenerator.TweetGenerator("corpus.txt") trump_tweet = tweet_maker.generate_tweet() #tweet out the trump tweet twitter = twitter.TwitterAPI() twitter.tweet(trump_tweet)
def say(message_uc, in_reply_to_status_id=None, dry_run=False): if len(message_uc) > 140: message_uc = message_uc[:139] + u'…' twitter.tweet(message_uc, in_reply_to_status_id=in_reply_to_status_id, dry_run=dry_run) print '!!', message_uc.encode('utf-8')
async def on_message(message): channel = message.channel print(pf("") + str(message.author) + ": " + message.content) if message.author == client.user: return global whitelist if whitelist == True and not str(message.author) in auth: await channel.send("Sorry, I may only talk to authorized users.") return check_user(str(message.author.id), str(message.author)) if message.content.startswith(".") and str(message.author) in admins: if message.content.lower().split(" ")[0] == ".stop": await channel.send("`" + pf("i") + "Client logout called." + "`") status("I will be inaccessible for a while. Sorry!") await client.logout() elif message.content.lower().split(" ")[0] == ".ping": await channel.send("`" + pf("i") + "Pong!" + "`") elif message.content.lower().split(" ")[0] == ".i": print(pf("i") + "Message ignored.") elif message.content.lower().split(" ")[0] == ".api": await channel.send("`" + pf("i") + discord.__version__ + "`") elif message.content.lower().split(" ")[0] == ".reload": load() await channel.send("`" + pf("i") + "Data successfully reloaded." + "`") elif message.content.lower().split(" ")[0] == ".coinflip": await channel.send("`" + pf("Coinflip") + "Result: " + coinflip() + "`") elif message.content.lower().split(" ")[0] == ".twitter": if message.content.lower().split(" ")[1] == "on": enable_twitter = True await channel.send("`" + pf("i") + "Twitter successfully enabled." + "`") elif message.content.lower().split(" ")[1] == "off": enable_twitter = False await channel.send("`" + pf("i") + "Twitter successfully disabled." + "`") else: await channel.send("`" + pf("i") + "enable_twitter = " + str(enable_twitter) + "`") elif message.content.lower().split(" ")[0] == ".tweet": twitter.tweet(message.content[7:]) await channel.send("`" + pf("Tweet") + "Twitter status update called." + "`") elif message.content.lower().split(" ")[0] == ".whitelist": if message.content.lower().split(" ")[1] == "on": whitelist = True await channel.send("`" + pf("i") + "Whitelist successfully enabled." + "`") elif message.content.lower().split(" ")[1] == "off": whitelist = False await channel.send("`" + pf("i") + "Whitelist successfully disabled." + "`") else: await channel.send("`" + pf("i") + "auth = " + str(auth) + "`") else: await channel.send("`" + pf("e") + "Invalid command." + "`") elif message.content.lower() == "hello!": await channel.send("Hi there!") elif message.content.lower() == "flip a coin!": await channel.send("Sure, just a second.") time.sleep(random.randrange(1, 4)) await channel.send("It landed " + coinflip() + "!") else: await channel.send(ai(message))
import twitter import sys if not twitter.tweet("テストツイートです"): print("Failed to tweet") sys.exit(1)
def nearest_point(plane): pd = "{} -> nearest {} ".format(get_time(plane["closest_time"]), plane['icoa']) for item in [ 'closest_miles', 'flight', 'tail', 'track', 'alt_baro', 'Owner', 'Manufacturer', 'plane', 'route' ]: if item in plane: if item in {'closest_miles', 'track'}: pd = pd + " {:>7.2f} ".format(plane[item]) elif item in {'flight', 'tail', 'alt_baro'}: pd = pd + "{0:7} ".format(plane[item]) else: pd = pd + " {:<} ".format(plane[item]) try: sqldb.insert_data((time.time(), plane["flight"], plane["icoa"], plane["tail"], plane['plane'], plane["alt_baro"], plane["track"], plane["closest_miles"], plane["closest_lat"], plane["closest_lon"])) except: pass name = '' if 'tail' in plane: name = plane['tail'] else: name = 'unknown' if 'alt_baro' not in plane: plane["alt_baro"] = "0" kml_text = kml_doc(plane['closest_lon'], plane['closest_lat'], -1.9591988377888176, 50.835736602072664, plane["alt_baro"], name, plane['closest_miles'], plane["tracks"]) #redo_miles = Haversine() with open("kmls/{}.kml".format(name), "w") as f: f.write(kml_text) f.close() if 'expired' in plane: pd = pd + ' expired ' linelen = 145 pd = pd[0:linelen] if len(pd) < 145: pd = pd + " " * (linelen - len(pd)) place = get_place(plane['closest_lat'], plane['closest_lon']) plane['reported'] = 1 if 'miles' in plane: if plane['miles'] < TWEET_RADIUS: tweet(pd) pd = pd + " : " + place loggit(pd, BOTH, GREEN_TEXT) txt = "plane overhead " if 'Owner' in plane: txt = txt + " " + plane['Owner'] m = int(plane['miles']) if 'alt_baro' in plane: if plane['alt_baro'] != 'ground': h = math.floor(int(plane['alt_baro']) / 100) if h > 9: txt = txt + " at " + str(h / 10) + " thousand feet" else: txt = txt + " at " + str(h) + " hundred feet" else: txt = txt + " on ground" txt = txt + " distance {:>1.1f} miles".format(m) say.speak(txt) else: pd = pd + " : " + place if 'plane' in plane: if 'DA42' in plane['plane']: loggit(pd, BOTH, YELLOW_TEXT) else: loggit(pd, BOTH, CYAN_TEXT) #loggit("{}".format(plane["tracks"].get_values()),BOTH,CYAN_TEXT) else: pd = pd + " " + json.dumps(plane) loggit(pd, BOTH, CYAN_TEXT)
def status(message): if enable_twitter == True: print(pf("Twitter") + twitter.tweet(message))
def tweet(comment, lastComment): twitter.tweet(comment, lastComment)
def awslambda_handler(event, context): message = trigrams.generate_random_sentence() return twitter.tweet(message)