Advertisement
Guest User

Lvbot2.X

a guest
Feb 24th, 2016
210
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.42 KB | None | 0 0
  1. import urllib, urllib2, sys, pycurl, time, random
  2. from BeautifulSoup import BeautifulSoup
  3.  
  4. #Post a notice. Source for 'posted from', replyTo represents message ID you're replying to.
  5. #Leave replyTo blank if not a reply.
  6. def postNotice(message, source, replyTo):
  7.     global username, password
  8.     try:
  9.         c = pycurl.Curl()
  10.         dataArray = {'status':message, 'source':source, 'in_reply_to_status_id':replyTo}
  11.         data = urllib.urlencode(dataArray)
  12.         c.setopt(pycurl.HTTPHEADER, ['User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64; rv:31.0) Gecko/20100101 Firefox/31.'])
  13.         c.setopt(pycurl.POST, True)
  14.         c.setopt(pycurl.WRITEFUNCTION, lambda x: None)
  15.         c.setopt(pycurl.USERPWD, str(username)+':'+str(password))
  16.         c.setopt(pycurl.URL, 'http://rainbowdash.net/api/statuses/update.xml')
  17.         c.setopt(pycurl.POSTFIELDS, data)
  18.         text = c.perform()
  19.         c.close()
  20.         return None
  21.     except Exception as e:
  22.         print e
  23.         sys.exit()
  24.        
  25. #Check how many posts a user has made.
  26. def getNoticeCount(userLink):
  27.     try:
  28.         request = urllib2.Request(userLink, headers={'User-Agent':'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:31.0) Gecko/20100101 Firefox/31.'})
  29.         response = urllib2.urlopen(request)
  30.         data = response.read()
  31.         soup = BeautifulSoup(data)
  32.         count = int(soup.findAll('dl', attrs={'class':'entity_notices'})[0].find('dd').text)
  33.         return count
  34.     except Exception as e:
  35.         print 'You screwed something up.'
  36.         print e
  37.         sys.exit()
  38.        
  39. #Gets HTML for the timeline RSS feed.
  40. def getTimeline():
  41.     try:
  42.         request = urllib2.Request('http://rainbowdash.net/api/statuses/public_timeline.rss', headers={'User-Agent':'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:31.0) Gecko/20100101 Firefox/31.'})
  43.         response = urllib2.urlopen(request)
  44.         data = response.read()
  45.         return data
  46.     except Exception:
  47.         time.sleep(10)
  48.     try:
  49.     request = urllib2.Request('http://rainbowdash.net/api/statuses/public_timeline.rss', headers={'User-Agent':'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:31.0) Gecko/20100101 Firefox/31.'})
  50.         response = urllib2.urlopen(request)
  51.         data = response.read()
  52.         return data
  53.     except Exception as e:
  54.         print 'Could not get timeline. Check site status or tell the programmer he\'s horrible.'
  55.         print 'Send him this, if you do:'
  56.         print e
  57.         sys.exit()
  58.  
  59. #Gets a list of messages, (noticeID, username) format, and returns it.
  60. def getStatuses():
  61.     statusList = []
  62.     soup = BeautifulSoup(getTimeline())
  63.     try:
  64.         for i in soup.findAll('item'):
  65.             username = str(i.find('title').text.split(':')[0])
  66.         message = (i.find('title').text.split(':')[1]).encode('ascii', 'ignore')
  67.             noticeID = int(str(i.find('guid').text).split('/')[-1])
  68.             statusList.append((noticeID, username, message))
  69.     except Exception as e:
  70.         print 'Could not parse statuses. Tell the programmer he\'s horrible.'
  71.         print 'Send him this, too:'
  72.         print e
  73.         sys.exit()
  74.     return statusList
  75.  
  76. #Processes a congratulatory message by checking their page,
  77. #and getting the correct message to respond to.
  78. #Otherwise it may respond to the wrong message if someone posts multiple times in a few seconds.
  79. #Also handles if their messages were deleted, reducing their count since last checked.
  80. def processCongratulate(user, number):
  81.     url = 'http://rainbowdash.net/'+str(user)+'/rss'
  82.     request = urllib2.Request(url, headers={'User-Agent':'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:31.0) Gecko/20100101 Firefox/31.'})
  83.     response = urllib2.urlopen(request)
  84.     data = response.read()
  85.     soup = BeautifulSoup(data)
  86.     currentCount = getNoticeCount('http://rainbowdash.net/'+str(user))
  87.     targetNotice = (currentCount - number)
  88.     if(targetNotice >= 0):
  89.         replyTo = int(str(soup.findAll('item')[targetNotice].attrs[0][1]).split('/')[-1])
  90.         return replyTo
  91.     else:
  92.         userLink = 'http://rainbowdash.net/' + str(user)
  93.         userDict[str(user)] = getNoticeCount(userLink)
  94.         return None
  95.  
  96. #Congratulates people for every 100,000th message it sees on the timeline.
  97. def specialCongratulate(user, number):
  98.     global specialMessages
  99.     postNotice(random.choice(specialMessages) % (user, number), 'Bot Lounge', number)
  100.     return None
  101.  
  102. #Congratulates people for every 1,000th message they've posted.
  103. def normalCongratulate(user, number, replyTo):
  104.     global normalMessages, redMessages
  105.     replyTo = processCongratulate(user, number)
  106.     if not replyTo:
  107.         return None
  108.     if(str(user) == 'redenchilada'):
  109.         postNotice(random.choice(redMessages) % (user, number), 'Excited Bot Lounge', replyTo)
  110.     else:
  111.         postNotice(random.choice(normalMessages) % (user, number), 'Bot Lounge', replyTo)
  112.     return None
  113.  
  114. #Adds a user to userDict with their post count.
  115. def newUserDict(user, replyTo):
  116.     global userDict, welcomeNew
  117.     userLink = 'http://rainbowdash.net/' + str(user)
  118.     userDict[str(user)] = getNoticeCount(userLink)
  119.     print 'Added ' + str(user) + ' to userDict. Post count: ' + str(userDict[str(user)])
  120.     if(userDict[str(user)] % 1000 == 0):
  121.         normalCongratulate(user, userDict[str(user)], replyTo)
  122.     elif(userDict[str(user)] == 1 and welcomeNew == 'y'):
  123.         welcomeNewUser(str(user), replyTo)
  124.     return None
  125.  
  126. #Increments a user's post count in userDict rather than checking their profile each time.
  127. def updateUserDict(user, replyTo):
  128.     global userDict
  129.     userDict[str(user)] += 1
  130.     if(userDict[str(user)] % 1000 == 0 and userDict[str(user)] != 0):
  131.         normalCongratulate(user, userDict[str(user)], replyTo)
  132.     print str(user) + ' posted. New count: ' + str(userDict[str(user)])
  133.     return None
  134.  
  135. #Gets newest post from the timeline and returns its ID.
  136. def newestNoticeID():
  137.     newNoticeID = 0
  138.     statusList = getStatuses()
  139.     for i in statusList:
  140.         if(i[0] > newNoticeID):
  141.             newNoticeID = i[0]
  142.     return newNoticeID
  143.  
  144. #Runs checks on each status it hasn't seen before.
  145. #Knows if it's seen a message before based on the message's ID.
  146. #Higher ID, newer post.
  147. def findNewStatus():
  148.     global currentNoticeID, userDict, modList
  149.     newMessage = False
  150.     newNoticeID = currentNoticeID
  151.     statusList = getStatuses()
  152.     for i in statusList:
  153.         if(i[0] > currentNoticeID):
  154.         if('@lvbot welcoming on' in i[2] and i[1] in modList):
  155.         welcomeponyOn(i[1], i[0])
  156.         elif('@lvbot welcoming off' in i[2] and i[1] in modList):
  157.             welcomeponyOff(i[1], i[0])
  158.             if(i[1] in userDict):
  159.                 updateUserDict(i[1], i[0])
  160.             elif(i[1] not in userDict):
  161.         print 'Adding ' + str(i[1]) + ' to userDict.'
  162.                 newUserDict(i[1], i[0])
  163.             newMessage = True
  164.             if(i[0] > newNoticeID):
  165.                 newNoticeID = i[0]
  166.         if(i[0] % 100000 == 0 and i[0] > currentNoticeID):
  167.             specialCongratulate(i[1], i[0])
  168.     currentNoticeID = newNoticeID
  169.     return newMessage
  170.  
  171. #Turns welcomepony on/off
  172. def welcomeponyOn(username, replyTo):
  173.     global welcomeNew
  174.     postNotice('@'+str(username)+' understood! Turning welcomepony function on.', 'Welcomepony function on', replyTo)
  175.     welcomeNew = 'y'
  176.  
  177. def welcomeponyOff(username, replyTo):
  178.     global welcomeNew
  179.     postNotice('@'+str(username)+' understood! Turning welcomepony function off.', 'Welcomepony function off', replyTo)
  180.     welcomeNew = 'n'
  181.  
  182. #Welcomes new users to be better than WelcomePony
  183. def welcomeNewUser(user, replyTo):
  184.     global welcomeMessages
  185.     postNotice(random.choice(welcomeMessages) % user, 'Bot Lounge', replyTo)
  186.  
  187. #currentNoticeID represents the most recent notice it read,
  188. #userDict stores how many posts each user has.
  189. #Special and normal messages for when people reach a 100,000th RDN message,
  190. #or 1,000th personal message respectively.
  191. welcomeMessages = ['@%s Welcome to RDN! I\'m a bot, but don\'t tell anybody.']
  192. specialMessages = ['@%s Wow. That was RDN\'s %sth dash. That\'s a bunch.',
  193.                    '@%s You made RDN\'s %sth dash. Wow...']
  194. normalMessages = ['@%s Wow, you reached your %sth message. Wow, wow, wow.',
  195.                   '@%s Whoah. %s posts? That\'s about how many times you\'ve posted here. Amazing coincidence.',
  196.                   '@%s Nice job. You reached your %sth post. I wish I had that many.',
  197.                   '@%s Astounding. %s posts. That\'s maybe a hundredth of how many times whats-his-name cried when he played the game [i]To The Moon[/i].']
  198. redMessages = ['@%s Red, you just reached your %sth post.',
  199.                '@%s You know what, Red? You just hit %s posts. How does it feel?',
  200.                '@%s Red, hey, listen, hey, listen, Red, listen, you just hit %s posts.']
  201. currentNoticeID = newestNoticeID()
  202. modList = ['lvbot', 'thelastgherkin', 'cabal', 'scoot', 'mushi', 'northernnarwhal', 'theyurityphoon', 'razzleberry']
  203. userDict = {'username':'int'}
  204. username = str(raw_input('Bot username: '))
  205. password = str(raw_input('Bot password: '))
  206. welcomeNew = str(raw_input('Turn on welcoming function? y/n\n'))
  207. wait = 6
  208. findNewStatus()
  209. while(1):
  210.     try:
  211.         print "Checking..."
  212.         newMessage = findNewStatus()
  213.         if(wait <= 38 and not newMessage):
  214.             wait += 2
  215.         elif(newMessage):
  216.             wait = 6
  217.         time.sleep(wait)
  218.     except Exception as e:
  219.         print 'The programmer must suck.'
  220.         print e
  221.         sys.exit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement