def _connect_reddit():
if _config is None:
error("Can't connect to reddit without a config")
return None
return praw.Reddit(client_id=_config.r_oauth_key, client_secret=_config.r_oauth_secret,
username=_config.r_username, password=_config.r_password,
user_agent=_config.useragent,
check_for_updates=False)
python类Reddit()的实例源码
def __init__(self):
useragent = "CryoChecker 1.0"
self.r = praw.Reddit('CryoChecker', user_agent = useragent)
self.subreddit = self.r.subreddit("thecryopodtohell")
def authenticate():
log("Authenticating...")
reddit = praw.Reddit(username=USERNAME,
password=PASSWORD,
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
user_agent="StandardsBot v1.2 for reddit. /u/Nokeo08")
log("Authenticated as {}".format(reddit.user.me()))
return reddit
def loginReddit():
global r
r = praw.Reddit(client_id=obot.client_id,
client_secret=obot.client_secret,
user_agent=obot.user_agent,
username=obot.username,
password=obot.password)
def parse_reddit_comments():
import sys
import praw
import tools.settings
from datetime import datetime
username = settings.getOwner()
r = praw.Reddit(settings.getRedditToken())
user = r.get_redditor(username)
for comment in user.get_comments(limit = None):
body = comment.body.encode('utf-8').strip()
if is_valid_message(body):
yield body, datetime.fromtimestamp(comment.created).year
def reportKarma(username):
import praw
r = praw.Reddit(settings.getRedditToken())
try:
user = r.get_redditor(username)
message = "<https://www.reddit.com/user/{}|{}> has {} comment karma and {} link karma.".format(username, username, user.comment_karma, user.link_karma)
except:
return "User _{}_ does not exit (or Reddit is down).".format(username)
return message
def authenticate():
print('Authenticating...\n')
reddit = praw.Reddit('animal-facts-bot', user_agent='/u/AnimalFactsBot')
print('Authenticated as {}\n'.format(reddit.user.me()))
return reddit
def __init__(self, bot):
super().__init__(bot)
logger.info('Reddit cog created!')
self.praw = praw.Reddit(**bot.cfg['credentials']['reddit'])
self.update_interval = UPDATE_INTERVAL
self.fuzz_interval = FUZZ_INTERVAL
self.feed_task = bot.loop.create_task(self.post_to_feeds())
def __unload(self):
logger.info('Reddit cog unloading, cancelling feed task...')
self.feed_task.cancel()
def post_to_feeds(self):
# guilds aren't available until the bot is ready, and this task begins before the bot
# is ready. so let's wait for it to be ready before updating feeds
await self.bot.wait_until_ready()
logger.debug('Bot is ready, proceeding to Reddit feed update loop...')
while True:
# sleep up here so we don't update immediately
# wait the main sleep interval
await asyncio.sleep(self.update_interval)
logger.debug('Going to update all feeds...')
# fetch all feeds, and update them all
feeds = await self.bot.pgpool.fetch('SELECT * FROM reddit_feeds')
# enumerate through all feeds
for idx, feed in enumerate(feeds):
logger.debug('Updating feed {}/{}!'.format(idx + 1, len(feeds)))
# wait a minute or two to prevent rate limiting (doesn't really help but w/e)
await asyncio.sleep(random.random() + self.fuzz_interval)
# update the feed
await self.update_feed(feed)
logger.debug('Updated.')
def reddit(self, ctx):
"""
This command group contains all commands related to Reddit feeds.
Feeds will be updated every 30 minutes. Both self and link posts will be posted to the channel. NSFW posts will
only be posted if the channel that the bot is posting in is NSFW. Stickied posts are never posted.
"""
pass
def setup(bot):
if 'reddit' not in bot.cfg['credentials']:
logger.warning('Not adding Reddit cog, not present in configuration!')
return
bot.add_cog(Reddit(bot))
def connect_reddit(self):
"""
Returns a praw connection object
"""
seconds = int(1 * 3000)
if hasattr(self.conf.reddit, 'last_refresh') and self.conf.reddit.last_refresh + seconds > int(time.mktime(time.gmtime())):
lg.debug("< CointipBot::connect_reddit(): to connect to reddit(): DONE (skipping)")
return self.reddit
lg.debug('CointipBot::connect_reddit(): connecting to Reddit via OAuth2...')
client_auth = requests.auth.HTTPBasicAuth(self.conf.reddit.auth.id, self.conf.reddit.auth.secret)
post_data = {"grant_type": "password", "username": self.conf.reddit.auth.user, "password": self.conf.reddit.auth.password}
conn = praw.Reddit(user_agent = self.conf.reddit.auth.user, api_request_delay=1.0)
conn.set_oauth_app_info(client_id=self.conf.reddit.auth.id,
client_secret=self.conf.reddit.auth.secret,
redirect_uri=self.conf.reddit.auth.redirect)
while True:
response = requests.post("https://ssl.reddit.com/api/v1/access_token", auth=client_auth, data=post_data)
r_info = json.loads(response.content)
lg.debug(r_info)
if (response.status_code == 200):
self.conf.reddit.access_token = r_info['access_token']
conn.set_access_credentials(set(['edit','identity','privatemessages','read','submit','vote', 'creddits']),r_info['access_token'])
print "Access Granted"
self.conf.reddit.last_refresh = int(time.mktime(time.gmtime()))
lg.info("CointipBot::connect_reddit(): logged in to Reddit as %s", self.conf.reddit.auth.user)
return conn
else:
print "Sleeping..."
time.sleep(10)
pass
# conn.login(self.conf.reddit.auth.user, self.conf.reddit.auth.password)
def setup():
return praw.Reddit(client_id=config['client_id'],
client_secret=config['client_secret'],
user_agent=config['user_agent']
)
def __init__(self, stream=True):
self.auth = helpers.reddit_auth()
self.api = praw.Reddit(**self.auth)
self.stream = stream
def send_private_message(self, title, content):
reddit = praw.Reddit(config.bot_name)
reddit.redditor(self.username).message(title, content)
def __init__(self):
self.reddit = praw.Reddit(config.bot_name)
def authenticate_api():
reddit = praw.Reddit(client_id=REDDIT['CLIENT_ID'],
client_secret=REDDIT['CLIENT_SECRET'],
user_agent=REDDIT['USER_AGENT'])
return reddit
def get_reddit_submissions(subreddit):
# Connect to Kafka
producer = KafkaProducer(bootstrap_servers='kafka:9092')
# Reddit API
reddit = authenticate_api()
submissions = 0
try:
for submission in reddit.subreddit(subreddit).new():
sub = format_submission(submission)
if submissions > 1000:
break
msg = producer.send('data', json.dumps(sub).encode('utf-8'))
submissions += 1
print(submissions)
with open('test.jsonl', 'a') as f:
f.write(json.dumps(sub)+'\n')
# Flush kafka producer
producer.flush()
except Exception as e:
with open('Errors.txt', 'a') as f:
f.write(str(type(e))+'\n')
f.write(str(e)+'\n')
# Flush kafka producer
producer.flush()
return subreddit