Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
# Written by Gareth Halfacree
import RPi.GPIO as GPIO
from twython import Twython
import datetime
api_token = 'InsertTokenHere'
api_secret = 'InsertSecretHere'
access_token = 'InsertOAuthTokenHere'
access_token_secret = 'InsertOAuthSecretHere'
GPIO.setmode(GPIO.BCM)
GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP)
twitter = Twython(api_token, api_secret, access_token, access_token_secret)
while True:
try:
print "Waiting for doorbell..."
GPIO.wait_for_edge(23, GPIO.FALLING)
print "Doorbell detected, sending direct message."
twitter.send_direct_message(screen_name="ghalfacree", text="DING-DONG at %s" %datetime.datetime.now())
except KeyboardInterrupt:
GPIO.cleanup()
schedule_df = pd.read_csv(schedule_csv)
schedule_date = schedule_df[(schedule_df['GAME_ID'] == int(game_id))]
home = schedule_date['HOME'].item()
away = schedule_date['AWAY'].item()
### establish common filepaths
livefeed_file = files_root + 'livefeed.json'
### post charts to Twitter
APP_KEY = twitter_credentials.APP_KEY
APP_SECRET = twitter_credentials.APP_SECRET
OAUTH_TOKEN = twitter_credentials.OAUTH_TOKEN
OAUTH_TOKEN_SECRET = twitter_credentials.OAUTH_TOKEN_SECRET
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
shots_all = open(charts_teams + 'shots_scatter.png', 'rb')
shots_5v5 = open(charts_teams + 'shots_scatter_5v5.png', 'rb')
shots_PP_away = open(charts_teams + 'shots_scatter_pp_away.png', 'rb')
shots_PP_home = open(charts_teams + 'shots_scatter_pp_home.png', 'rb')
with open(livefeed_file) as livefeed_json:
livefeed_data = json.load(livefeed_json)
period = livefeed_data["liveData"]["linescore"]["currentPeriod"]
status = livefeed_data["liveData"]["linescore"]["currentPeriodTimeRemaining"]
minutes_gone = int()
seconds_gone = int()
regulation_time_gone = str()
ot_time_gone = str()
import json
from twython import Twython
# Credentials setup
# Loads in 'creds.json' values as a dictionary
with open('creds.json') as f:
credentials = json.loads(f.read())
# Sets config values from the config file
CONSUMER_KEY = credentials["consumer_key"]
CONSUMER_SECRET = credentials["consumer_secret"]
ACCESS_TOKEN_KEY = credentials["access_token_key"]
ACCESS_TOKEN_SECRET = credentials["access_token_secret"]
# Create the Twython Twitter client using our credentials
twitter = Twython(CONSUMER_KEY, CONSUMER_SECRET,
ACCESS_TOKEN_KEY, ACCESS_TOKEN_SECRET)
# Sample random tweets
potential_tweets = [
'This is my first tweet with Sparrow by @fmc_sea - https://github.com/fernando-mc/sparrow',
'Wow! Isn\'t Sparrow by @fmc_sea just the coolest! https://github.com/fernando-mc/sparrow',
'Jeez! Everyone should learn about AWS Lambda and Twitter Bots from @fmc_sea'
]
def send_tweet(tweet_text):
"""Sends a tweet to Twitter"""
twitter.update_status(status = tweet_text)
def handler(event,context):
"""Sends random tweet from list of potential tweets"""
send_tweet(random.choice(potential_tweets))
def get_twitter(app_key=None, app_secret=None, search='python', location='', **kwargs):
"""Location may be specified with a string name or latitude, longitude, radius"""
if not app_key:
from settings_secret import TWITTER_API_KEY as app_key
if not app_secret:
from settings_secret import TWITTER_API_SECRET as app_secret
twitter = Twython(app_key, app_secret, oauth_version=2)
return Twython(app_key, access_token=twitter.obtain_access_token())
@api.route('/get_twitter_oauth_token', methods=['GET'])
@login_required
def get_twitter_oauth_token():
twitter = Twython(app.config['TWITTER_API_KEY'],app.config['TWITTER_API_SECRET'])
auth = twitter.get_authentication_tokens(callback_url=request.url_root+'twitter_callback')
session['oauth_token'] = auth['oauth_token']
session['oauth_token_secret'] = auth['oauth_token_secret']
return jsonify({'url':auth['auth_url']})
import datetime
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.ticker import EngFormatter, PercentFormatter
import requests
import pandas as pd
from twython import Twython
APP_KEY = os.environ['APP_KEY']
APP_SECRET = os.environ['APP_SECRET']
OAUTH_TOKEN = os.environ['OAUTH_TOKEN']
OAUTH_TOKEN_SECRET = os.environ['OAUTH_TOKEN_SECRET']
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
# home_timeline = twitter.get_home_timeline(tweet_mode='extended')
# latest_crypto_tweet_id = [x for x in home_timeline if '#CryptoCurrency prices' in x['full_text']][0]['id']
resp = requests.get('https://api.coinmarketcap.com/v2/ticker/?limit=20')
global_crypto = requests.get('https://api.coinmarketcap.com/v2/global/')
total_market_cap = global_crypto.json()['data']['quotes']['USD']['total_market_cap']
timestamp = resp.json()['metadata']['timestamp']
timestamp = pd.to_datetime(resp.json()['metadata']['timestamp'], unit='s')
df_raw = pd.DataFrame.from_dict(resp.json()['data'], orient='index').reset_index(drop=True)
quotes = pd.DataFrame.from_records([x['USD'] for x in df_raw['quotes']])
df = pd.concat([df_raw, quotes], axis=1)
df['pct_of_tot_mkt_cap'] = df['market_cap'] / total_market_cap
from twython import Twython
from auth import (
consumer_key,
consumer_secret,
access_token,
access_token_secret
)
twitter = Twython(
consumer_key,
consumer_secret,
access_token,
access_token_secret
)
message = "Hello World!"
twitter.update_status(status=message)
print("Tweeted: " + message)
except IOError as e:
e.message = 'Cannot find or access rules file "%s"' % args.config
raise
try:
# Saved application state
app_state = load_app_state(args.state)
state_lock = threading.Lock()
def save_state():
with state_lock:
save_app_state(args.state, app_state)
# Twitter client, and handles and keywords to monitor
twitter_handles, twitter_keywords = set(), set()
twitter_client = twython.Twython(**config.twitter)
# Exchanges
exchanges = {}
for name, creds in config.exchanges.items():
exchanges[name] = Exchange(creds)
# Accounts
accounts: Dict[str, Account] = {}
account_states = app_state.accounts
for name, acct in config.accounts.items():
rules = []
for r in acct['rules']:
rule = Rule(r)
twitter_handles.update(rule.handles)
twitter_keywords.update(rule.keywords)
rules.append(rule)
def main():
logging.basicConfig(level=logging.INFO)
predictor_words, food_words = get_words()
queries = make_twitter_queries(predictor_words, food_words)
coords = get_coords()
twitter = Twython(APP_KEY, APP_SECRET, oauth_version=2)
access_token = twitter.obtain_access_token()
twitter = Twython(APP_KEY, access_token=access_token)
logging.info('Loading previous state')
tweets = []
try:
with open('state.pickle', 'r+b') as f:
state = pickle.load(f)
except:
state = {}
logging.info('Downloading new tweets')
for lat, lng in coords:
for query in queries:
print 'QUERY:',query
try:
#!/usr/bin/env python3
### REQUIRED IMPORT
import time, sys, psutil, subprocess, shutil, os, random
from datetime import timedelta, datetime
from apscheduler.schedulers.background import BackgroundScheduler
from twython import Twython, TwythonError, TwythonStreamer
#### Twitter Credentials & accounts
API_KEY = 'Consumer Key (API Key)'
API_SECRET = 'Consumer Secret (API Secret)'
ACCESS_TOKEN = 'Access Token'
ACCESS_TOKEN_SECRET = 'Access Token Secret'
BOT, MASTER = 'bot', 'utilisateur'
api = Twython(API_KEY,API_SECRET,ACCESS_TOKEN,ACCESS_TOKEN_SECRET)
#### Path variables
with open('twitterbot.log', 'w+'): pass
LOG = 'twitterbot.log'
OSSEC_LOG = '/var/ossec/logs/alerts/alerts.log'
#### Scheduler : daily tweets & log remover
def delete_tweets():
user_timeline = api.get_user_timeline(screen_name=BOT, count=100)
for tweets in user_timeline:
api.destroy_status(id=tweets['id_str'])
def delete_log():
open(LOG, 'w').close()
def check_intrusions(level=10):