本文整理汇总了Python中DatabaseHandler类的典型用法代码示例。如果您正苦于以下问题:Python DatabaseHandler类的具体用法?Python DatabaseHandler怎么用?Python DatabaseHandler使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了DatabaseHandler类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: buildMangaReplyWithAuthor
def buildMangaReplyWithAuthor(searchText, authorName, message, isExpanded, blockTracking=False):
try:
ani = Anilist.getMangaWithAuthor(searchText, authorName)
mal = None
mu = None
ap = None
if ani:
mal = MAL.getMangaCloseToDescription(searchText, ani['description'])
ap = AniP.getMangaURL(ani['title_english'], authorName)
else:
ap = AniP.getMangaURL(searchText, authorName)
mu = MU.getMangaWithAuthor(searchText, authorName)
if ani:
try:
titleToAdd = ''
if mal is not None:
titleToAdd = mal['title']
else:
titleToAdd = ani['title_english']
if not blockTracking:
DatabaseHandler.addRequest(titleToAdd, 'Manga', message.author.id, message.server.id)
except:
traceback.print_exc()
pass
return CommentBuilder.buildMangaComment(isExpanded, mal, ani, mu, ap)
except Exception as e:
traceback.print_exc()
return None
示例2: buildMangaReplyWithAuthor
def buildMangaReplyWithAuthor(searchText, authorName, isExpanded, baseComment, blockTracking=False):
try:
ani = Anilist.getMangaWithAuthor(searchText, authorName)
mal = None
mu = None
ap = None
if ani:
mal = MAL.getMangaCloseToDescription(searchText, ani['description'])
ap = AniP.getMangaURL(ani['title_english'], authorName)
else:
ap = AniP.getMangaURL(searchText, authorName)
mu = MU.getMangaWithAuthor(searchText, authorName)
if ani:
try:
titleToAdd = ''
if mal is not None:
titleToAdd = mal['title']
else:
titleToAdd = ani['title_english']
if (str(baseComment.subreddit).lower is not 'nihilate') and (str(baseComment.subreddit).lower is not 'roboragi') and not blockTracking:
DatabaseHandler.addRequest(titleToAdd, 'Manga', baseComment.author.name, baseComment.subreddit)
except:
traceback.print_exc()
pass
return CommentBuilder.buildMangaComment(isExpanded, mal, ani, mu, ap)
except Exception as e:
traceback.print_exc()
return None
示例3: on_message
async def on_message(message):
print('Message recieved')
#Is the message valid (i.e. it's not made by Discordoragi and I haven't seen it already). If no, try to add it to the "already seen pile" and skip to the next message. If yes, keep going.
if not (DiscordoragiSearch.isValidMessage(message)):
try:
if not (DatabaseHandler.messageExists(message.id)):
DatabaseHandler.addMessage(message.id, message.author.id, message.server.id, False)
except Exception:
traceback.print_exc()
pass
else:
await process_message(message)
示例4: run
def run(self):
try:
print("Starting stream")
commentStream = praw.helpers.comment_stream(self.reddit, self.subredditList, limit=1000, verbosity=0)
for comment in commentStream:
if ((time.time() - self.updateTime) > Config.tcgUpdateInterval * 60 * 60):
DatabaseHandler.updateTCGCardlist()
self.updateTime = time.time()
if ((time.time() - self.submissionsLastProcessed) > Config.submissionProcessingInterval * 60 * 60):
self.submissionProcessor.processSubmissions(100)
self.submissionsLastProcessed = time.time()
#print("Found comment")
#If we've already seen this comment, ignore it
if DatabaseHandler.commentExists(comment.id):
continue
#If the post has been deleted, getting the author will return an error
try:
author = comment.author.name
except Exception as e:
continue
#If this is one of our own comments, ignore it
if (author == 'YugiohLinkBot'):
continue
reply = self.requestHandler.buildResponse(comment.body)
try:
if reply:
cards = re.findall('\[\*\*(.+?)\*\*\]\(', reply)
for card in cards:
DatabaseHandler.addRequest(card, author, comment.subreddit)
if("VENT THREAD" in comment.link_title):
reply = self.submissionProcessor.convertCase(True, reply)
elif("happiness thread" in comment.link_title):
reply = self.submissionProcessor.convertCase(False, reply)
DatabaseHandler.addComment(comment.id, author, comment.subreddit, True)
comment.reply(reply)
print("Comment made.\n")
else:
if ('{' in comment.body and '}' in comment.body):
print('')
DatabaseHandler.addComment(comment.id, author, comment.subreddit, False)
except Exception as e:
print("Reddit probably broke when replying:" + str(e) + '\n')
except Exception as e:
print("Error with comment stream: " + str(e))
traceback.print_exc()
示例5: buildMangaReply
def buildMangaReply(searchText, isExpanded, baseComment):
try:
#Basic breakdown:
#If Anilist finds something, use it to find the MAL version.
#If hits either MAL or Ani, use it to find the MU version.
#If it hits either, add it to the request-tracking DB.
ani = Anilist.getMangaDetails(searchText)
mal = None
mu = None
if not (ani is None):
mal = MAL.getMangaDetails(ani['title_romaji'])
else:
mal = MAL.getMangaDetails(searchText)
if not (mal is None):
ani = Anilist.getMangaDetails(mal['title'])
if (ani is not None) or (mal is not None):
try:
titleToAdd = ''
if mal is not None:
titleToAdd = mal['title']
mu = MU.getMangaURL(mal['title'])
else:
titleToAdd = ani['title_english']
mu = MU.getMangaURL(ani['title_romaji'])
if (str(baseComment.subreddit).lower is not 'nihilate') and (str(baseComment.subreddit).lower is not 'roboragi'):
DatabaseHandler.addRequest(titleToAdd, 'Manga', baseComment.author.name, baseComment.subreddit)
except:
traceback.print_exc()
pass
if ani is not None:
if ani['adult'] is True:
print("NSFW ENTRY")
mal = None
ani = None
mu = None
return CommentBuilder.buildMangaComment(isExpanded, mal, ani, mu)
except Exception as e:
traceback.print_exc()
return None
示例6: isValidComment
def isValidComment(comment, reddit):
try:
if (DatabaseHandler.commentExists(comment.id)):
return False
try:
if (comment.author.name == USERNAME):
DatabaseHandler.addComment(comment.id, comment.author.name, comment.subreddit, False)
return False
except:
pass
return True
except:
traceback.print_exc()
return False
示例7: isValidMessage
def isValidMessage(message):
try:
if (DatabaseHandler.messageExists(message.id)):
return False
try:
if (message.author.name == USERNAME):
DatabaseHandler.addMessage(message.id, message.author.id, message.server.id, False)
return False
except:
pass
return True
except:
traceback.print_exc()
return False
示例8: isValidSubmission
def isValidSubmission(submission):
try:
if (DatabaseHandler.commentExists(submission.id)):
return False
try:
if (submission.author.name == 'Roboragi'):
DatabaseHandler.addComment(submission.id, submission.author.name, submission.subreddit, False)
return False
except:
pass
return True
except:
traceback.print_exc()
return False
示例9: __init__
def __init__(self, consumer_key, consumer_secret, access_key, access_secret, database, server):
self.consumer_key = consumer_key
self.consumer_secret = consumer_secret
self.access_key = access_key
self.access_secret = access_secret
self.database = database
self.server = server
self.db_users = DatabaseHandler(self.database, self.server)
示例10: StoreUser
class StoreUser(object):
def __init__(self, consumer_key, consumer_secret, access_key, access_secret, database, server):
self.consumer_key = consumer_key
self.consumer_secret = consumer_secret
self.access_key = access_key
self.access_secret = access_secret
self.database = database
self.server = server
self.db_users = DatabaseHandler(self.database, self.server)
def save_user(self, username):
d = '{"_id": "' + username + '", "num_tweets": 1, "harvested": "true" }'
try:
user = json.loads(d)
self.db_users.save(user)
except couchdb.http.ResourceConflict:
user = self.db_users.get_row(user['_id'])
user['num_tweets'] += 1
self.db_users.save(user)
def exists(self, username):
try:
user = self.db_users.get_row(username)
if user is None:
return False
else:
return True
except:
return False
示例11: formatCardData
def formatCardData(card, isExpanded):
if isExpanded:
requestStats = DatabaseHandler.getStats(card['name'])
if card['cardtype'].lower() == 'monster':
return MONSTER_CARD_TEMPLATE_EXPANDED.format(
name = '[**{}**]'.format(card['name']),
image = '({})'.format(card['image']) if card['image'] else '(http://i.imgur.com/paNkvJ5.jpg)',
wikia = '[Wikia]({})'.format(card['wikia']),
infosyntax = ', ' if card['pricedata'] else '',
pricedata = '[($)]({})'.format(card['pricedata']) if card['pricedata'] else '',
leveltype = '{}: '.format(card['leveltype']),
level = '{}, '.format(card['level']),
cardtype = 'Category: {}, '.format(card['cardtype'].title()),
types = 'Type: {}, '.format(' / '.join(str(i[1]) for i in enumerate(card['types']))),
attribute = 'Attribute: {}'.format(card['attribute'].upper()),
text = '>{}'.format(card['text']),
att = '>ATK: {}, '.format(card['att']),
defn = 'DEF: {}'.format(card['def']),
stats = 'Stats: {total} requests - {percentage}% of all requests'.format(
total=requestStats['total'],
percentage=str(round(requestStats['totalAsPercentage'],2))))
else:
return SPELL_CARD_TEMPLATE_EXPANDED.format(
name = '[**{}**]'.format(card['name']),
image = '({})'.format(card['image']) if card['image'] else '(http://i.imgur.com/paNkvJ5.jpg)',
wikia = '[Wikia]({})'.format(card['wikia']),
infosyntax = ', ' if card['pricedata'] else '',
pricedata = '[($)]({})'.format(card['pricedata']) if card['pricedata'] else '',
cardtype = 'Category: {}, '.format(card['cardtype'].title()),
cardproperty = 'Property: {}'.format(card['property']),
text = '>{}'.format(card['text']),
stats = 'Stats: {total} requests - {percentage}% of all requests'.format(
total=requestStats['total'],
percentage=str(round(requestStats['totalAsPercentage'],2))))
else:
if card['cardtype'].lower() == 'monster':
return MONSTER_CARD_TEMPLATE_NORMAL.format(
name = '[**{}**]'.format(card['name']),
image = '({})'.format(card['image']) if card['image'] else '(http://i.imgur.com/paNkvJ5.jpg)',
wikia = '[Wikia]({})'.format(card['wikia']),
infosyntax = ', ' if card['pricedata'] else '',
pricedata = '[($)]({})'.format(card['pricedata']) if card['pricedata'] else '')
else:
return SPELL_CARD_TEMPLATE_NORMAL.format(
name = '[**{}**]'.format(card['name']),
image = '({})'.format(card['image']) if card['image'] else '(http://i.imgur.com/paNkvJ5.jpg)',
wikia = '[Wikia]({})'.format(card['wikia']),
infosyntax = ', ' if card['pricedata'] else '',
pricedata = '[($)]({})'.format(card['pricedata']) if card['pricedata'] else '')
示例12: start
def start():
print('Starting comment stream:')
last_checked_pms = time.time()
#This opens a constant stream of comments. It will loop until there's a major error (usually this means the Reddit access token needs refreshing)
comment_stream = praw.helpers.comment_stream(reddit, SUBREDDITLIST, limit=250, verbosity=0)
for comment in comment_stream:
# check if it's time to check the PMs
if (time.time() - last_checked_pms) > TIME_BETWEEN_PM_CHECKS:
process_pms()
last_checked_pms = time.time()
#Is the comment valid (i.e. it's not made by Roboragi and I haven't seen it already). If no, try to add it to the "already seen pile" and skip to the next comment. If yes, keep going.
if not (Search.isValidComment(comment, reddit)):
try:
if not (DatabaseHandler.commentExists(comment.id)):
DatabaseHandler.addComment(comment.id, comment.author.name, comment.subreddit, False)
except:
pass
continue
process_comment(comment)
示例13: process_pms
def process_pms():
for msg in reddit.get_unread(limit=None):
if (msg.subject == 'username mention'):
if (('{' and '}') in msg.body) or (('<' and '>') in msg.body):
try:
if str(msg.subreddit).lower() in exiled:
print('Edit request from exiled subreddit: ' + str(msg.subreddit) + '\n')
msg.mark_as_read()
continue
mentionedComment = reddit.get_info(thing_id=msg.name)
mentionedComment.refresh()
if not (DatabaseHandler.commentExists(mentionedComment.id)):
if str(mentionedComment.subreddit).lower() in Config.subredditlist:
continue
replies = mentionedComment.replies
ownComments = []
commentToEdit = None
for reply in replies:
if (reply.author.name == 'Roboragi'):
ownComments.append(reply)
for comment in ownComments:
if 'http://www.reddit.com/r/Roboragi/wiki/index' in comment.body:
commentToEdit = comment
commentReply = process_comment(mentionedComment, True)
try:
if (commentReply):
if commentToEdit:
commentToEdit.edit(commentReply)
print('Comment edited.\n')
else:
mentionedComment.reply(commentReply)
print('Comment made.\n')
except praw.errors.Forbidden:
print('Edit equest from banned subreddit: ' + str(msg.subreddit) + '\n')
msg.mark_as_read()
except Exception as e:
print(e)
示例14: processSubmissions
def processSubmissions(self, num):
subreddits = self.reddit.get_subreddit(self.subredditList)
for submission in subreddits.get_new(limit=num):
#If we've already seen this submission, ignore it
if DatabaseHandler.commentExists(submission.id):
continue
#If the post has been deleted, getting the author will return an error
try:
author = submission.author.name
except Exception as e:
continue
#If this is one of our own submissions, ignore it
if (author == 'YugiohLinkBot'):
continue
reply = self.requestHandler.buildResponse(submission.selftext)
try:
if reply:
cards = re.findall('\[\*\*(.+?)\*\*\]\(', reply)
for card in cards:
DatabaseHandler.addRequest(card, author, submission.subreddit)
if("VENT THREAD" in submission.title):
reply = self.convertCase(True, reply)
elif("happiness thread" in submission.title):
reply = self.convertCase(False, reply)
DatabaseHandler.addComment(submission.id, author, submission.subreddit, True)
submission.add_comment(reply)
print("Comment made.\n")
else:
if ('{' in submission.selftext and '}' in submission.selftext):
print('')
DatabaseHandler.addComment(submission.id, author, submission.subreddit, False)
except Exception as e:
traceback.print_exc()
print("Reddit probably broke when replying:" + str(e) + '\n')
示例15: buildMangaReply
def buildMangaReply(searchText, isExpanded, baseComment, blockTracking=False):
try:
ani = None
mal = None
mu = None
ap = None
try:
sqlCur.execute('SELECT dbLinks FROM synonyms WHERE type = "Manga" and lower(name) = ?', [searchText.lower()])
except sqlite3.Error as e:
print(e)
alternateLinks = sqlCur.fetchone()
if (alternateLinks):
synonym = json.loads(alternateLinks[0])
if (synonym['mal']):
mal = MAL.getMangaDetails(synonym['mal'])
if (synonym['ani']):
ani = Anilist.getMangaDetails(synonym['ani'])
if (synonym['mu']):
mu = MU.getMangaURL(synonym['mu'])
if (synonym['ap']):
ap = AniP.getMangaURL(synonym['ap'])
else:
#Basic breakdown:
#If Anilist finds something, use it to find the MAL version.
#If hits either MAL or Ani, use it to find the MU version.
#If it hits either, add it to the request-tracking DB.
ani = Anilist.getMangaDetails(searchText)
if not (ani is None):
mal = MAL.getMangaDetails(ani['title_romaji'])
else:
mal = MAL.getMangaDetails(searchText)
if not (mal is None):
ani = Anilist.getMangaDetails(mal['title'])
#----- Finally... -----#
if ani or mal:
try:
titleToAdd = ''
if mal:
titleToAdd = mal['title']
else:
titleToAdd = ani['title_english']
if not alternateLinks:
#MU stuff
if mal:
mu = MU.getMangaURL(mal['title'])
else:
mu = MU.getMangaURL(ani['title_romaji'])
#Do the anime-planet stuff
if mal and not ap:
if mal['title'] and not ap:
ap = AniP.getMangaURL(mal['title'])
if mal['english'] and not ap:
ap = AniP.getMangaURL(mal['english'])
if mal['synonyms'] and not ap:
for synonym in mal['synonyms']:
if ap:
break
ap = AniP.getMangaURL(synonym)
if ani and not ap:
if ani['title_english'] and not ap:
ap = AniP.getMangaURL(ani['title_english'])
if ani['title_romaji'] and not ap:
ap = AniP.getMangaURL(ani['title_romaji'])
if ani['synonyms'] and not ap:
for synonym in ani['synonyms']:
if ap:
break
ap = AniP.getMangaURL(synonym)
if (str(baseComment.subreddit).lower is not 'nihilate') and (str(baseComment.subreddit).lower is not 'roboragi') and not blockTracking:
DatabaseHandler.addRequest(titleToAdd, 'Manga', baseComment.author.name, baseComment.subreddit)
except:
traceback.print_exc()
pass
if ani is not None:
if ani['adult'] is True:
mal = None
ani = None
mu = None
ap = None
return CommentBuilder.buildMangaComment(isExpanded, mal, ani, mu, ap)
except Exception as e:
traceback.print_exc()
return None