Guest User

Untitled

a guest
Sep 7th, 2017
31
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.42 KB | None | 0 0
  1. import requests
  2. import requests.auth
  3. import sys
  4. import time
  5. import os
  6. import random
  7. from pprint import pprint
  8. import pyrebase
  9. import datetime
  10.  
  11. # variables #
  12. print('setting variables')
  13. id = 'YdSbzhqDbT6kRw'
  14. secret = 'ZCCKeZEYE2a5CnbEqTisPk0VZOo'
  15. userAgent = 'motobebot 1.0'
  16. user = 'motoBeBot'
  17. password = 'z0mg7812'
  18. waiting = 60
  19. url = 'https://www.reddit.com/r/YourBotTestingGround/comments/.json'
  20.  
  21.  
  22.  
  23. headers = {'User-agent': userAgent}
  24. print('variables set')
  25.  
  26. config = {
  27.     'apiKey':
  28.     'authDomain':
  29.     'databaseURL':
  30.     'storageBucket':
  31. }
  32.  
  33. fb = pyrebase.initialize_app(config)
  34. db = fb.database()
  35.  
  36. # functions #
  37.  
  38. class Token:
  39.  
  40.     def __init__(self):
  41.         self.files = []
  42.  
  43.     def __enter__(self):
  44.         print('getting token')
  45.         client_auth = requests.auth.HTTPBasicAuth(id, secret)  # id and secret
  46.         post_data = {'grant_type': 'password', 'username': user, 'password': password, 'scope': 'submit identity'}  # post data to request access token
  47.         headers = {'User-agent': userAgent}  # user agent header
  48.         r = requests.post('https://www.reddit.com/api/v1/access_token', auth=client_auth, data=post_data, headers=headers)
  49.         msg = r.json()
  50.         print('token received')
  51.         self.accessToken = msg['access_token']
  52.         return self
  53.  
  54.     def __exit__(self, exc_type, exc_value, traceback):
  55.         print('revoking token')
  56.         headers = {'User-agent': userAgent}
  57.         post_data = {'token': self.accessToken, 'token_type_hint': 'access_token'}
  58.         client_auth = requests.auth.HTTPBasicAuth(id, secret)
  59.         r = requests.post('https://www.reddit.com/api/v1/revoke_token', auth=client_auth, data=post_data, headers=headers)
  60.         print('token revoked')
  61.  
  62.  
  63. def reply(commentId, text):
  64.  
  65.     with Token() as token:
  66.         headers = {'Authorization': 'bearer ' + token.accessToken, 'User-Agent': user}
  67.         post_data = {'thing_id': 't1_' + commentId, 'api_type': 'json', 'text': text}
  68.         r = requests.post('https://oauth.reddit.com/api/comment', headers=headers, data=post_data)
  69.  
  70.  
  71. class Events:
  72.  
  73.     def __init__(self, database):
  74.         self.db = database
  75.  
  76.     def getEvents(self):
  77.         events = self.db.child('events').order_by_key().get()
  78.         data = events.val()
  79.         print(data)
  80.         text = '''event|date\n:--|:--'''
  81.         for key in data:
  82.             eventD, eventM, eventY = map(int, data[key]['date'].split('/'))
  83.             eventDate = datetime.datetime(eventY, eventM, eventD)
  84.             if eventDate < datetime.datetime.now():
  85.                 text += '\n~~' + data[key]['name'] + '~~|~~' + data[key]['date']+'~~'
  86.             else:
  87.                 text += '\n'+data[key]['name']+'|'+data[key]['date']
  88.         return text
  89.  
  90.     def saveEvent(self, eventId, eventName, date):
  91.         data = {'name': eventName, 'date': date}
  92.         self.db.child('events').child(eventId).set(data)
  93.  
  94.  
  95. class Comment:
  96.  
  97.     def __init__(self, url):
  98.         self.url = url
  99.  
  100.     def getComment(self):
  101.         print('getting latest comment')
  102.         headers = {'User-agent': userAgent}
  103.         self.url += '?limit=1'
  104.         r = requests.get(self.url, headers=headers)
  105.         rJson = r.json()
  106.         data = rJson['data']['children']
  107.  
  108.         msg = data[0]
  109.         comment = msg['data']['body']
  110.         self.parseComment(comment)
  111.         self.commentId = msg['data']['id']
  112.         self.linkUrl = msg['data']['link_url']
  113.  
  114.     def parseComment(self, command):
  115.         self.command = command
  116.         if len(command) > 4:
  117.             self.commandSplit = command.split(' ')
  118.             if len(self.commandSplit) >= 1:
  119.                 self.botCommand = self.commandSplit[0]
  120.             if len(self.commandSplit) >= 2:
  121.                 self.botAction = self.commandSplit[1]
  122.             if len(self.commandSplit) >= 3:
  123.                 self.eventName = self.commandSplit[2]
  124.             if len(self.commandSplit) >= 4:
  125.                 self.eventDate = self.commandSplit[3]
  126.             if len(self.commandSplit) >= 5:
  127.                 self.eventTime = self.commandSplit[4]
  128.  
  129. class bot:
  130.  
  131.     def __init__(self, url, database):
  132.         self.url = url
  133.         self.events = Events(database)
  134.  
  135.     def loop(self):
  136.         comment = Comment(self.url)
  137.  
  138.         while True:
  139.             comment.getComment()
  140.  
  141.             if comment.botCommand == '!bot':
  142.                 print(comment.command)
  143.  
  144.                 if comment.botAction == 'roll20':
  145.                     rng = random.randint(1, 20)
  146.                     reply(comment.commentId, 'rolling d20, the result is %s' % str(rng))
  147.  
  148.                 elif comment.botAction == 'create':
  149.                     if len(comment.commandSplit) >= 4 and '/' in comment.eventDate:
  150.                         dateD, dateM, dateY = map(int, comment.eventDate.split('/'))
  151.                         eventId = dateD+(dateM*100)+(dateY*10000)
  152.                         date = date.strftim('%d/%m/%Y')
  153.  
  154.                         Events.saveEvent(self.events, eventId, comment.eventName, comment.eventDate)
  155.                     else:
  156.                         print('wrong comment format')
  157.  
  158.                 elif comment.botAction == 'list':
  159.                     text = self.events.getEvents()
  160.                     reply(comment.commentId, text)
  161.             else:
  162.                 print('no comment the bot can use')
  163.             print('trying again in %i seconds' % waiting)
  164.  
  165.             time.sleep(waiting)
  166.  
  167. bot(url, db).loop()
Add Comment
Please, Sign In to add comment