本文整理汇总了Python中reddit.Reddit类的典型用法代码示例。如果您正苦于以下问题:Python Reddit类的具体用法?Python Reddit怎么用?Python Reddit使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Reddit类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_mark_as_read
def test_mark_as_read(self):
oth = Reddit(USER_AGENT)
oth.login('PyApiTestUser3', '1111')
# pylint: disable-msg=E1101
msg = six_next(oth.user.get_unread(limit=1))
msg.mark_as_read()
self.assertTrue(msg not in oth.user.get_unread(limit=5))
示例2: test_mark_multiple_as_read
def test_mark_multiple_as_read(self):
oth = Reddit(USER_AGENT)
oth.login('PyApiTestUser3', '1111')
messages = list(oth.user.get_unread(limit=2))
self.assertEqual(2, len(messages))
self.r.user.mark_as_read(messages)
unread = oth.user.get_unread(limit=5)
for msg in messages:
self.assertTrue(msg not in unread)
示例3: test_mark_as_unread
def test_mark_as_unread(self):
oth = Reddit(USER_AGENT)
oth.login('PyApiTestUser3', '1111')
found = None
for msg in oth.user.get_inbox():
if not msg.new:
found = msg
msg.mark_as_unread()
break
else:
self.fail('Could not find a read message.')
self.assertTrue(found in oth.user.get_unread())
示例4: parse
def parse(ignore_duty=True, ignore_resolutions=True):
govfeed = feedparser.parse('http://www.govtrack.us/events/events.rss?'
'feeds=misc%3Aintroducedbills')
r = Reddit(user_agent='WatchingCongress/1.0')
r.login('FuturistBot', '<BOTPASS>')
for entry in govfeed.entries:
if not entry['guid'].find('guid'):
logging.info("Couldn't find GUID")
continue
if not entry['title']:
logging.info("No title for bill: {0}".format(entry['guid']))
continue
if house_collection.find_one({'guid': entry['guid']}):
logging.info("Already created story: {0}".format(entry['title']))
continue
if ignore_duty and 'duty' in entry['title'] and 'temporar' in entry['title']:
logging.info("Ignored boring bill: {0}".format(entry['title']))
continue
if ignore_resolutions and '.Res' in entry['title']:
logging.info("Ignored resolution: {0}".format(entry['title']))
continue
record = {
'title': entry['title'],
'description': entry['description'],
'link': entry['link'],
'guid': entry['guid'],
}
bill_number = entry['title'].split(':')[0]
try:
news_stories = find_news_stories(bill_number)
except Exception as e:
news_stories = []
logging.error("Couldn't parse Google News: {}".format(unicode(e)))
try:
text = template.render(description=entry['description'],
link=entry['link'],
news_stories=news_stories)
r.submit('futuristparty', entry['title'], text=text)
house_collection.insert(record)
logging.info("Created story: {0}".format(entry['title']))
except Exception as e:
logging.error("Exception occured: {0}".format(unicode(e)))
time.sleep(2)
示例5: test_mark_multiple_as_read
def test_mark_multiple_as_read(self):
oth = Reddit(USER_AGENT)
oth.login('PyApiTestUser3', '1111')
messages = []
for msg in oth.user.get_unread(limit=None):
if msg.author != oth.user.name:
messages.append(msg)
if len(messages) >= 2:
return
self.assertEqual(2, len(messages))
self.r.user.mark_as_read(messages)
unread = oth.user.get_unread(limit=5)
for msg in messages:
self.assertTrue(msg not in unread)
示例6: run
def run(self, host, port):
self.reddit = Reddit(creds.key, creds.secret, creds.username, creds.password, creds.redirect_uri)
self.reddit.updateToken()
self.reddit.testAccess()
sleeptime = 0
while True:
if sleeptime > 10:
time.sleep(10)
elif sleeptime > 1:
time.sleep(1)
# Connect to host:port, get the fp
fp = self.connect(host, port)
# Send hostname of client over initially
hostname = socket.getfqdn()
fp.write(hostname+'\n')
fp.flush()
if debug:
print 'Sent hostname'
# Recv all the urls
reqlist = []
newline = False
while True:
line = fp.readline()
line = line.strip()
if line != '':
reqlist.append(line.split(','))
else:
if newline == True:
break
newline = True
fp.flush()
print host+' >> '+str(reqlist)
# See if any urls were sent, close if zero
if len(reqlist) == 0:
if debug:
print 'No requests'
self.close()
sleeptime += 1
continue
sleeptime = 0
if debug:
print 'Downloading requests'
# Download all the urls otherwise
self.download_data(reqlist)
# targzip the data
targz = self.targz()
# Send the data
targz_fp = open(targz, 'rb')
targz_data = targz_fp.read()
fp.write(targz_data)
fp.flush()
print host+' << archive.tar.gz'
self.close()
self.cleanup()
示例7: __init__
class QReddit:
def __init__(self):
self.r = Reddit()
(self.options, args) = self.parseArguments()
if(len(args) < 1):
print "Please specify type of action (textpost, linkpost, viewsub, createuser)"
return
self.action = args[0]
if(self.options.username and self.options.password):
self.user = {"username":self.options.username, "password":self.options.password}
else:
try:
self.user = self.getUser()
except IOError:
print "No user was specified through --user and --password but could not find 'user.json'. Please either use createuser or use --user and --password."
sys.exit()
def parseArguments(self):
parser = optparse.OptionParser()
parser.add_option("-s", "--subreddit", help="Specify subreddit", dest="subreddit")
parser.add_option("-t", "--title", help="Specify title", dest="title")
parser.add_option("-b", "--body", help="Specify post body (for text post)", dest="body")
parser.add_option("-l", "--link", help="Specify post link (for link post)", dest="link")
parser.add_option("-u", "--user", help="Specify username", dest="username")
parser.add_option("-p", "--pass", help="Specify password", dest="password")
parser.add_option("-L", "--limit", help="Limit results (for view)", type="int", dest="limit")
parser.add_option("-i", "--postid", help="Specify post ID", dest="postid")
return parser.parse_args()
def performAction(self):
if(self.action == "textpost"):
self.r.doTextPost(self.options, self.user)
if(self.action == "linkpost"):
self.r.doLinkPost(self.options, self.user)
if(self.action == "viewsub"):
self.r.doViewsub(self.options)
if(self.action == "viewpost"):
self.r.doViewpost(self.options)
if(self.action == "createuser"):
self.createUser(self.options.username, self.options.password)
def getUser(self):
try:
with open("user.json") as f:
user = json.load(f)
except IOError:
raise e
return user
def createUser(self, username, password):
with open("user.json", "w") as f:
json.dump({"username":username, "password":password}, f)
示例8: main
def main():
level = 0
# Read program arguments
for arg in sys.argv[1:]:
(param, value) = arg.split('=')
if param == '--level':
level = int(value)
path = os.path.dirname(os.path.realpath(__file__))
loggingConf = open('{0}/configs/logging.yml'.format(path), 'r')
logging.config.dictConfig(yaml.load(loggingConf))
loggingConf.close()
logger = logging.getLogger(LOGGER)
logger.info('Program started')
config = configparser.ConfigParser()
config.read('{0}/configs/bot.ini'.format(path))
username = config['Reddit']['username']
password = config['Reddit']['password']
user_agent = config['Reddit']['user-agent']
dry_run = config['Bot'].getboolean('dry-run')
if dry_run:
logger.info('Running in dry run mode. Nothing will be commited')
reddit = Reddit(username, password, user_agent, dry_run)
history = History('{0}/{1}'.format(path, DATABASE))
news = News()
if level == 0:
level = int(config['Bot']['level'])
news_items = news.get_news_items(level)
for item in news_items:
url = item[0]
title = item[1]
degree = item[2]
if not history.has_link_been_posted(url):
history.add_link_as_posted(url, dry_run)
if not reddit.post_link(get_redirect_url(url), title):
continue
break
logger.info('Program done')
示例9: test_report
def test_report(self):
# login as new user to report submission
oth = Reddit(USER_AGENT)
oth.login('PyApiTestUser3', '1111')
subreddit = oth.get_subreddit(self.sr)
submission = None
for submission in subreddit.get_new_by_date():
if not submission.hidden:
break
if not submission or submission.hidden:
self.fail('Could not find a non-reported submission.')
submission.report()
# check if submission was reported
for report in self.r.get_subreddit(self.sr).get_reports():
if report.id == submission.id:
break
else:
self.fail('Could not find reported submission.')
示例10: parse
def parse():
govfeed = feedparser.parse('http://www.govtrack.us/events/events.rss?'
'feeds=misc%3Aintroducedbills')
r = Reddit(user_agent='WatchingCongress/1.0')
r.login('congressbot', '<BOTPASS>')
for entry in govfeed.entries:
if not entry['guid'].find('guid'):
logging.info("Couldn't find GUID")
continue
if not entry['title']:
logging.info("No title for bill: {}".format(entry['guid']))
continue
if house_collection.find_one({'guid': entry['guid']}):
logging.info("Already created story: {}".format(entry['title']))
continue
if 'duty' in entry['title'] and 'temporar' in entry['title']:
logging.info("Ignored boring bill: {}".format(entry['title']))
continue
if '.Res' in entry['title']:
logging.info("Ignored resolution: {}".format(entry['title']))
continue
record = {
'title': entry['title'],
'description': entry['description'],
'link': entry['link'],
'guid': entry['guid'],
}
try:
text = template.render(description=entry['description'],
link=entry['link'])
r.submit('watchingcongress', entry['title'], text=text)
house_collection.insert(record)
logging.info("Created story: {}".format(entry['title']))
except Exception as e:
logging.error("Exception occured: {}".format(unicode(e)))
time.sleep(2)
示例11: main
def main(subreddit):
print "Subreddit :", subreddit
rsub = url_data("http://www.reddit.com/r/%s/new/.json?sort=new"%subreddit, json=True)
children = rsub['data']['children']
r = Reddit(USERNAME, PASSWORD)
session = r.login()
f = open('history.txt', 'r')
history = f.read()
f.close()
for child in children:
is_self = child['data']['is_self']
thread_id = child['data']['name']
print thread_id
if thread_id in history:
print "Thread: %s already in history"%thread_id
pass
else:
if not is_self:
img_url = child['data']['url']
thread_id = child['data']['name']
repost = karmadecay(img_url)
if repost:
text = form_comment(repost)
r_resp = r.post(session, thread_id, text)
if r_resp != None:
error = r_resp['json']['errors']
delay = find_digit(error[0][1])
print "waiting: %s seconds" %delay*60
time.sleep(delay*60)
r.post(session, thread_id, text)
f = open('history.txt', 'a')
f.write("\n%s"%thread_id)
print text
f.close()
time.sleep(1)
print "Comment Posted:", thread_id
else:
pass
else:
pass
print "Finished"
return
示例12: __init__
def __init__(self, subreddit, site, verbosity):
self.reddit = Reddit(str(self), site)
self.subreddit = self.reddit.get_subreddit(subreddit)
self.verbosity = verbosity
self.submissions = []
self.comments = []
self.submitters = defaultdict(list)
self.commenters = defaultdict(list)
self.min_date = 0
self.max_date = time.time() - DAYS_IN_SECONDS * 3
self.prev_srs = None
# Config
self.reddit.config.comment_limit = -1 # Fetch max comments possible
self.reddit.config.comment_sort = 'top'
示例13: __init__
def __init__(self, file):
# Initialize the Bot
super().__init__(file)
self.update_time = datetime.now()
# Load the configurations.
with open(file, 'r') as y:
# Load the configs
config = yaml.load(y)
# Grab the database filename from the configs.
self.dbfile = config['database']
# Create a Reddit object to handle the Reddit-specific tasks.
self.reddit = Reddit(self.dbfile)
示例14: authenticate
def authenticate(self, username, password, request=None):
try:
reddit = Reddit(user_agent=USER_AGENT)
reddit.login(username, password)
r_user = reddit.user
except urllib2.URLError:
log.warning("Could not reach reddit. Is it down?")
r_user = None
except InvalidUserPass:
log.Info(_('User "%s" tried to login without valid credentials')%username)
return None
except urllib2.HTTPError as e:
log.Info(_('User "%s" tried to login without valid credentials')%username)
return None
try:
db_user = User.objects.get(username__iexact=username)
if not r_user and not db_user.check_password(password):
return None
if not db_user.is_active: #instead of deleting users, disable them.
return None
except User.DoesNotExist:
#Rules for Joining
if r_user and r_user.comment_karma >= JOIN_MIN_COMMENT_KARMA \
and r_user.link_karma >= JOIN_MIN_LINK_KARMA \
and (datetime.now() - datetime.utcfromtimestamp(r_user.created_utc)) >= JOIN_MIN_MEMBER_TIME:
db_user = User(username=username, is_active=True)
else:
return None
db_user.set_password(password) # Hash and store password for offline logins
db_user.backend = self.__class__.__name__
db_user.save()
return db_user
示例15: ShowerThoughtBot
class ShowerThoughtBot(Bot):
def __init__(self, file):
# Initialize the Bot
super().__init__(file)
self.update_time = datetime.now()
# Load the configurations.
with open(file, 'r') as y:
# Load the configs
config = yaml.load(y)
# Grab the database filename from the configs.
self.dbfile = config['database']
# Create a Reddit object to handle the Reddit-specific tasks.
self.reddit = Reddit(self.dbfile)
def parse_message(self, msg, chan, fromNick):
# logger.debug("parse_message starting with msg " + msg)
if msg.find("PING :") != -1:
self.ping()
elif (msg.find(":hello {}".format(self.nick)) != -1 or
msg.find(":hello, {}".format(self.nick)) != -1 or
msg.find(":hi {}".format(self.nick)) != -1):
logger.info(msg)
self.hello(chan, fromNick)
elif (msg.find(":!showerthought") != -1 or
msg.find(":{}: thought".format(self.nick)) != -1 or
msg.find(":!stb thought") != -1):
logger.info(msg)
self.print_shower_thought(chan, fromNick)
elif (msg.find(":{}: help".format(self.nick)) != -1 or
msg.find(":!stb help") != -1):
logger.info(msg)
self.print_help(chan)
elif (msg.find(":!stb source") != -1 or
msg.find(":{}: source".format(self.nick)) != -1):
logger.info(msg)
self.print_source_link(chan)
elif msg.find(":{}: updatedb".format(self.nick)) != -1:
if not fromNick == 'mlane':
self.send_message(chan, "Don't tell me what to do!")
else:
self.send_message(chan, "Pulling in some thoughts.")
self.update_database(False)
elif msg.find(":{}: shruggie".format(self.nick)) != -1:
logger.debug("trying to print shruggie")
self.print_shruggie(chan)
else:
logger.info(msg)
return
def print_source_link(self, chan):
self.send_message(chan, "ShowerThoughtBot is by Mike Lane, "
"https://github.com/mikelane/ShowerThoughtBot")
self.send_message(chan, "Feel free to fork or report issues.")
def print_help(self, chan):
lines = []
lines.append("I respond to {}: $command or !stb command".format(
self.nick))
lines.append("$command = [help|thought|source]")
lines.append("Get a shower thought with !showerthought.")
lines.append("More to come...")
lines.append("[email protected] for bugs.")
for line in lines:
self.send_message(chan, line)
def print_shower_thought(self, chan, nick):
# #self.db_lock.acquire()
db = DBAdapter(self.dbfile)
thought = db.get_random_thought()
self.send_message(chan, "okay {}: \"{}\" -{}\r\n".format(
nick, thought[1], thought[2]))
def print_shruggie(self, chan):
self.send_message(chan, "\udcc2\udcaf\_("
"\udce3\udc83\udc84)_/\udcc2\udcaf")
def update_database(self, Scheduled=True):
if Scheduled:
now = datetime.now()
duration = now - self.update_time
duration = int(duration.total_seconds())
if duration >= 86400:
logger.info('Updating database on schedule.')
self.update_time = now
#self.db_lock.acquire()
self.reddit.get_daily_top()
#self.db_lock.release()
else:
self.reddit.get_daily_top()
#.........这里部分代码省略.........