Exemple #1
0
def flistchar(uri, phenny):
    if hasattr(phenny.config, 'f_list_account') and hasattr(phenny.config, 'f_list_password') :
        ticketuri = 'https://www.f-list.net/json/getApiTicket.php'
        ticketquery = {'account' : phenny.config.f_list_account, 'password' : phenny.config.f_list_password}
        ticketjson = web.post(ticketuri, ticketquery)
        
        ticketstr = str(ticketjson)
        ticketdict = ast.literal_eval(ticketstr)
        ticket = ticketdict['ticket']
        
        urilist = uri.split('/')
        urlcharname = urilist[4]
        urlcharname = web.unquote(urlcharname)
        charuri = 'https://www.f-list.net/json/api/character-get.php'
        charquery = {'name' : urlcharname}
        charjson = web.post(charuri, charquery)
        
        charstr = str(charjson)
        chardict = ast.literal_eval(charstr)
        try:
            charname = chardict['character']['name']
        except:
            errname = chardict['error']
        
        try:
            titlestr = 'Error - ' + errname
        except UnboundLocalError:
            titlestr = '\002\00312,01F-List\017 - ' + charname
        
        
        return titlestr
    else:
        return
Exemple #2
0
def trudysSurprise(session):
    global times

    key = "trudy"
    timeExpiry = times.get(key)

    if timeExpiry == None or time.time() > timeExpiry:
        response = web.get(session, Constants.NEO_TRUDYS)

        postFields = {"action": "beginroll"}
        web.post(session, Constants.NEO_TRUDYS_SPIN, postFields,
                 Constants.NEO_TRUDYS)
        time.sleep(
            11
        )  # Sleeps because when you spin the wheel you must wait for it to stop before collecting prize

        postFields = {"action": "prizeclaimed"}
        web.post(session, Constants.NEO_TRUDYS_SPIN, postFields,
                 Constants.NEO_TRUDYS)

        print("Spun Trudy's Surprise Wheel")

        times[key] = timestamp.endOfDay()

        file = open('times.pkl', 'wb')
        pickle.dump(times, file)
        file.close()
Exemple #3
0
def loop():
    global pirepID
    while True:
        if config.useFSUIPC == True: track.beginTrack()
        try:
            if config.useFSUIPC == True: track.posUpdate()

            exportdata = {
                "lat": read('lat'),
                "lon": read('lon'),
                "heading": read('heading'),
                "altitude": read('altitude'),
                "vs": read('vs'),
                "gs": read('gs')
            }
            exportdata = {"positions": [exportdata]}

            exportdata = json.dumps(exportdata)

            web.post(
                config.website + '/api/pireps/' + pirepID + '/acars/position',
                exportdata)
        except Exception as e:
            tk.messagebox.showerror("xACARS Error - Update Loop", e)

        time.sleep(5)

        if stop == True:
            break
Exemple #4
0
def sign_out(me: uri.URI):
    """Sign the user out by revoking the token."""
    access_token = tx.auth_client.get_guest(me)["access_token"]
    web.post(
        tx.user.session["token_endpoint"],
        data={
            "action": "revoke",
            "token": access_token
        },
    )
Exemple #5
0
def lines(phenny, input):
    """.lines <nickname> (<today/yesterday/YYYYMMDD>) - Returns the number of lines a user posted on a specific date."""

    if input.group(2):
        info = input.group(2).split(" ")

        if len(info) == 1:
            nickname = info[0]
            date = "today"
        elif len(info) == 2:
            nickname = info[0]
            date = info[1]
        else:
            phenny.reply(".lines <nickname> (<today/yesterday/YYYYMMDD>) - Returns the number of lines a user posted on a specific date.")
            return

    else:
        nickname = input.nick
        date = "today"

    try:
        req = web.post("http://linx.li/vtluuglines", {'nickname': nickname, 'date': date, 'sender': input.nick, 'channel': input.sender, 'api_key': phenny.config.linx_api_key})
    except (HTTPError, IOError):
        raise GrumbleError("THE INTERNET IS F*****G BROKEN. Please try again later.")

    phenny.reply(req)
    def __search(self,
                 item,
                 max_searches,
                 criteria="exact",
                 min_price=0,
                 max_price=999999):
        new_search = ItemSearch(item)
        for i in range(max_searches):
            self.searches += 1
            if self.__shopwizard_ban == False:
                referer = "http://www.neopets.com/market.phtml?type=wizard"
                postFields = {
                    "type": "process_wizard",
                    "feedset": 0,
                    "shopwizard": item,
                    "table": "shop",
                    "criteria": criteria,
                    "min_price": min_price,
                    "max_price": max_price
                }

                search_results_page_source = web.post(
                    self.session, Constants.NEO_SHOP_WIZARD, postFields,
                    referer)
                self.__check_shopwizard_ban(search_results_page_source)
                new_search.add_shops(
                    self.__parse_search(search_results_page_source, item))

        return new_search
Exemple #7
0
    def _poster(self, category='', page=0):
        """
        Makes POST to tinychat's server and gets json data as response.

        :param category: The room category. e.g `all`, `most-gifted` or `near-you`.
        :type category: str
        :param page: The page number.
        :type page: int
        :return: json data or None.
        :rtype: dict | None
        """
        if self._csrf_token != '':
            header = {'X-Requested-With': 'XMLHttpRequest'}

            post_data = {
                '_token': self._csrf_token,
                'category': category,
                'page': str(page)
            }

            response = web.post(url=self.post_url,
                                post_data=post_data,
                                header=header,
                                json=True)
            if response.error is None:
                return response.json
        return None
Exemple #8
0
def foodvote(phenny, input):
    """.foodvote"""
    if not input.group(2) or not input.group(3):
        return phenny.reply("You need to specify a place and time, as in "\
                ".foodvote hokie haus 18:45")

    key = input.group(4) or input.sender
    postdata = {
        'user': input.nick,
        'restaurant': input.group(2),
        'start': input.group(3),
        'key': key.strip(),
    }
    postdata['sig'] = _sign_vote(phenny.config.foodforus_api_key, postdata)

    try:
        req = web.post(API_URL + '/vote', postdata)
        data = json.loads(req)
    except (HTTPError, IOError):
        raise GrumbleError("Uh oh, I couldn't contact foodforus. HOW WILL WE "\
                "EAT NOW‽")

    if 'error' in data:
        phenny.reply(data['error'])
    else:
        phenny.reply("Your vote has been recorded.")
Exemple #9
0
    def _create_task(self):
        """
        Create a captcha solving task.
        """
        log.info('creating anti-captcha task.')

        post_data = {
            'clientKey': self._api_key,
            'task': {
                'type': 'NoCaptchaTaskProxyless',
                'websiteURL': self._page_url,
                'websiteKey': self._site_key
            }
        }

        url = 'https://api.anti-captcha.com/createTask'

        pr = web.post(url=url, json=post_data, as_json=True)

        if len(pr.errors) > 0:
            log.error(pr.errors)
        else:
            if pr.json['errorId'] > 0:
                if pr.json['errorId'] == 10:
                    raise NoFundsError('no funds for `%s`' % self._api_key)
                else:
                    raise AntiCaptchaApiError(**pr.json)
            else:
                self._task_id = pr.json['taskId']
                log.debug('anti-captcha task id: %s' % self._task_id)
                return self._task_waiter()
Exemple #10
0
def withdraw(session, amount):

    response = web.get(session, Constants.NEO_BANK)
    bankBalance = getBankBalance(response)

    #withdraw
    if amount <= bankBalance and amount != 0:
        postFields = {"type": "withdraw", "amount": amount}
        web.post(session, Constants.NEO_BANK_INTEREST, postFields,
                 Constants.NEO_BANK)
        return True

    #insufficient funds
    else:
        print("Insufficient Funds")
        return False
Exemple #11
0
def authorize_sign_in(state, code, flow):
    """Complete the authorization and return the response."""
    if state != tx.user.session["state"]:
        raise web.BadRequest("bad state")
    if flow == "profile":
        endpoint = tx.user.session["authorization_endpoint"]
    elif flow == "token":
        endpoint = tx.user.session["token_endpoint"]
    else:
        raise web.BadRequest("only `profile` and `token` flows supported")
    response = web.post(
        endpoint,
        headers={
            "Accept": "application/json"
        },
        data={
            "grant_type": "authorization_code",
            "code": code,
            "client_id": tx.user.session["client_id"],
            "redirect_uri": tx.user.session["redirect_uri"],
            "code_verifier": tx.user.session["code_verifier"],
        },
    ).json
    create_guest(tx.db, response)
    return response
Exemple #12
0
def lines(phenny, input):
    """.lines <nickname> (<today/yesterday/YYYYMMDD>) - Returns the number of lines a user posted on a specific date."""

    if input.group(2):
        info = input.group(2).split(" ")

        if len(info) == 1:
            nickname = info[0]
            date = "today"
        elif len(info) == 2:
            nickname = info[0]
            date = info[1]
        else:
            phenny.reply(
                ".lines <nickname> (<today/yesterday/YYYYMMDD>) - Returns the number of lines a user posted on a specific date."
            )
            return

    else:
        nickname = input.nick
        date = "today"

    try:
        req = web.post("http://linx.li/vtluuglines", {
            'nickname': nickname,
            'date': date,
            'sender': input.nick
        })
    except (HTTPError, IOError):
        raise GrumbleError(
            "THE INTERNET IS F*****G BROKEN. Please try again later.")

    phenny.reply(req)
Exemple #13
0
def foodvote(phenny, input):
    """.foodvote"""
    if not input.group(2) or not input.group(3):
        return phenny.reply("You need to specify a place and time, as in "\
                ".foodvote hokie haus 18:45")

    key = input.group(4) or input.sender
    postdata = {
        'user': input.nick,
        'restaurant': input.group(2),
        'start': input.group(3),
        'key': key.strip(),
    }
    postdata['sig'] = _sign_vote(phenny.config.foodforus_api_key, postdata)

    try:
        req = web.post(API_URL + '/vote', postdata)
        data = json.loads(req)
    except:
        raise GrumbleError("Uh oh, I couldn't contact foodforus. HOW WILL WE "\
                "EAT NOW‽")

    if 'error' in data:
        phenny.reply(data['error'])
    else:
        phenny.reply("Your vote has been recorded.")
 def _shorten(self, link):
     # We can utilitze git.io to shorten *.github.com links
     l, code = web.post("https://git.io/create", {"url": link})
     if code != 200:
         return None
     l = str(l, "utf-8")
     if " " in l:  # spaces means there was an error :(
         return None
     return "https://git.io/" + l
Exemple #15
0
 def __sedex(self, codigo):
     parametros = {'P_ITEMCODE': '',
                   'P_LINGUA' : '001', 
                   'P_TESTE': '',
                   'P_TIPO': '001',
                   'P_COD_UNI': codigo,
                   'Z_ACTION': 'Pesquisar'}
     uri = 'http://websro.correios.com.br/sro_bin/txect01$.QueryList'
     return web.post(uri, parametros)
Exemple #16
0
 def _shorten(self, link):
     # We can utilitze git.io to shorten *.github.com links
     l, code = web.post("https://git.io/create", {'url': link})
     if code != 200:
         return None
     l = str(l, 'utf-8')
     if ' ' in l:  # spaces means there was an error :(
         return None
     return "https://git.io/" + l
Exemple #17
0
def buy_stock(session, times):
    key = "stocks"

    timeExpiry = times.get(key)

    if timeExpiry == None or time.time() > timeExpiry:

        shares = 1000
        ticker, price = __get_cheapest_stock(session)

        if ticker is not None:
            funds = True

            source = web.get(session, Constants.NEO_STOCK_BUY + ticker)
            balance = bank.getOnHandBalance(source)

            # Not enough nps get money from bank
            if balance < shares * price:
                funds = bank.withdraw(session, shares * price - balance)

            # If we have enough then buy the stocks
            if funds:
                soup = BeautifulSoup(source, "html.parser")
                ref = soup.find("input", {"name": "_ref_ck"})["value"]

                postFields = {
                    "_ref_ck": ref,
                    "type": "buy",
                    "ticker_symbol": ticker,
                    "amount_shares": shares
                }
                web.post(session, Constants.NEO_STOCK_BUY_PROCESS, postFields,
                         Constants.NEO_STOCK_BUY + ticker)
                print("Bought " + str(shares) + " of " + ticker + "!")

                times[key] = timestamp.endOfDay()

                file = open('times.pkl', 'wb')
                pickle.dump(times, file)
                file.close()

        else:
            print("No stocks currently trading below 20np")
            times[key] = timestamp.end_of_hour()
Exemple #18
0
def get_title(phenny, url, channel):
    """ Have linx retrieve the (augmented) title """
    try:
        return web.post("https://linx.li/vtluuggettitle", {
            'url': url,
            'channel': channel,
            'api_key': phenny.config.linx_api_key
        })
    except:
        return
Exemple #19
0
def loop():
    global pirepID
    while True:
        track.beginTrack()

        lat, lon, hdg, vs, alt, gs = track.posUpdate()
        try:
            exportdata = {"lat": lat,"lon": lon,"heading": hdg,"altitude": alt,"vs": vs,"gs": gs}
            exportdata = {"positions": [exportdata]}

            exportdata = json.dumps(exportdata)
            
            web.post(config.website + '/api/pireps/' + pirepID + '/acars/position', exportdata)
        except Exception as e:
            tk.messagebox.showerror("xACARS Error - Update Loop", e)

        time.sleep(5)

        if stop == True:
            break
Exemple #20
0
def collectInterest(session, times):
    key = "interest"

    timeExpiry = times.get(key)

    if timeExpiry == None or time.time() > timeExpiry:
        #Future edit check if interest has been collected
        #Return interest collected
        web.get(session, Constants.NEO_BANK, Constants.NEO_HOMEPAGE)

        #send POST to collect interest
        postFields = {"type": "interest"}
        web.post(session, Constants.NEO_BANK_INTEREST, postFields,
                 Constants.NEO_BANK)

        print("Bank interest collected :)")
        times[key] = timestamp.endOfDay()

        file = open('times.pkl', 'wb')
        pickle.dump(times, file)
        file.close()
Exemple #21
0
def issue(phenny, input):
    """ .issue <owner>/<repository> <title> - create a new GitHub issue """

    if not is_up(gh_uri):
        return phenny.reply('Sorry, GitHub is down.')

    # check if GitHub auth token is available in default.py
    try:
        oauth_token = phenny.config.gh_oauth_token
    except AttributeError:
        return phenny.reply(
            'GitHub authentication token needs to first be set in the configuration file (default.py)'
        )

    # check input validity
    if not input.group(1):
        return phenny.reply(invalidmsg)

    content = ''.join(input.group(1)).strip()
    ghpath = content.split()[0].split('/')

    # check whether likely in an owner/repository combo format
    if len(ghpath) != 2:
        return phenny.reply(invalidmsg)

    owner = ghpath[0]
    repo = ghpath[1]

    if owner not in allowed_owners:
        return phenny.reply('Begiak cannot create an issue there.')

    title = ' '.join(content.split()[1:]).strip()
    if len(title) < 1:
        return phenny.reply(invalidmsg)

    # build and post HTTP request
    req_url = '{}/repos/{}/{}/issues'.format(gh_uri, owner, repo)
    req_headers = {'Authorization': 'token {}'.format(oauth_token)}
    req_body = json.dumps({
        "title": title,
        "body": default_desc.format(input.nick)
    })

    try:
        req_str = post(req_url, req_body, req_headers)
        req_json = json.loads(req_str)
        phenny.reply(
            'Issue created. You should add a description at {}'.format(
                req_json['html_url']))
    except HTTPError:
        phenny.reply(
            'It appears that the repository you provided does not exist.')
Exemple #22
0
def adventCalendar(session):
    global times

    december = 12

    # Only execute if we're in the month of december
    if int(time.strftime("%m")) == december:
        key = "advent"
        timeExpiry = times.get(key)

        if timeExpiry == None or time.time() > timeExpiry:
            response = web.get(session, Constants.NEO_ADVENT_CALENDAR)

            web.post(session, Constants.NEO_PROCESS_ADVENT, {},
                     Constants.NEO_ADVENT_CALENDAR)

            print("Collected Advent Calendar")
            times[key] = timestamp.endOfDay()

            file = open('times.pkl', 'wb')
            pickle.dump(times, file)
            file.close()
Exemple #23
0
def deposit(session, amount):
    response = web.get(session, Constants.NEO_BANK)
    onHandBalance = getOnHandBalance(response)

    #send POST to deposit
    if onHandBalance >= amount and amount != 0:
        postFields = {"type": "deposit", "amount": amount}
        source = web.post(session, Constants.NEO_BANK_INTEREST, postFields,
                          Constants.NEO_BANK)

    else:
        print("You don't have " + str(amount) + " to deposit!")

    return onHandBalance
Exemple #24
0
 def FreeDict(self, tipo, palavra, palavra_exata, resultados):
     parametros = {'search': palavra,
                   'exact' : palavra_exata, 
                   'max': resultados}
     if tipo == 'enpt':
         parametros['from'] = 'English'
         parametros['to']   = 'Portugese'
         parametros['fname']= 'eng2por1'
     else:
         parametros['to']   = 'English'
         parametros['from'] = 'Portugese'
         parametros['fname']= 'eng2por2'
     parametros['back'] = 'por.html'
     return web.post('http://www.freedict.com/onldict/onldict.php', parametros)
Exemple #25
0
def short(phenny, input):
    """.short <url> - Shorten a URL."""

    url = input.group(2)
    if not url:
        phenny.reply("No URL provided. CAN I HAS?")
        return

    try:
        req = web.post("http://vtlu.ug/vtluug", {'lurl': url})
    except (HTTPError, IOError):
        raise GrumbleError("THE INTERNET IS F*****G BROKEN. Please try again later.")

    phenny.reply(req)
Exemple #26
0
def message_join(jenni, input): 
	'''This will send the message waiting for the user to them when they join the channel'''
	### Matt Meinwald and Michael Yanovich
	channel = input.bytes

	tellee = input.nick
	if tellee == jenni.nick: return

	if not os.path.exists(jenni.tell_filename): 
		return
	
	reminders = []
	remkeys = list(reversed(sorted(jenni.reminders.keys())))
	for remkey in remkeys: 
		if not remkey.endswith('*') or remkey.endswith(':'): 
			if tellee.lower() == remkey: 
				reminders.extend(getReminders(jenni, channel, remkey, tellee))
		elif tellee.lower().startswith(remkey.rstrip('*:')): 
			reminders.extend(getReminders(jenni, channel, remkey, tellee))

	for line in reminders[:maximum]: 
		jenni.say(line)
		
	if reminders[maximum:]:
		try:
			if origin.sender in lispchannels:
				chan = origin.sender
			else: chan = 'None'
			
			result = web.post('http://paste.lisp.org/submit',
				{'channel': chan,
				'username': jenni.nick,
				'title': 'Further Messages for %s' % tellee,
				'colorize': 'None',
				'text': '\n'.join(reminders[maximum:]) + '\n',
				'captcha': 'lisp',
				'captchaid': 'bdf447484f62a3e8b23816f9acee79d9'
				}
			)
			uris = re.findall('http://paste.lisp.org/display/\d+', result)
			uri = list(reversed(uris)).pop()
			if not origin.sender in lispchannels:
				message = '%s: see %s for further messages' % (tellee, uri)
				jenni.say(message)
		except:
			error = '[Sorry, some messages were elided and lost...]'
			jenni.say(error)

	if len(jenni.reminders.keys()) != remkeys: 
		dumpReminders(jenni.tell_filename, jenni.reminders) # @@ tell
Exemple #27
0
def posted(phenny, input):
    """.posted <message> - Checks if <message> has already been posted."""

    message = input.group(2)
    if not message:
        phenny.say(".posted <message> - Checks if <message> has already been posted.")
        return

    try:
        req = web.post("http://linx.li/vtluugposted", {'message': message, 'sender': input.nick, 'channel': input.sender, 'api_key': phenny.config.linx_api_key})
    except (HTTPError, IOError):
        raise GrumbleError("THE INTERNET IS F*****G BROKEN. Please try again later.")

    phenny.reply(req)
Exemple #28
0
def message(phenny, input): 
   if not input.sender.startswith('#'): return

   tellee = input.nick
   channel = input.sender

   if not os: return
   if not os.path.exists(phenny.tell_filename): 
      return

   reminders = []
   remkeys = list(reversed(sorted(phenny.reminders.keys())))
   for remkey in remkeys: 
      if not remkey.endswith('*') or remkey.endswith(':'): 
         if tellee.lower() == remkey: 
            reminders.extend(getReminders(phenny, channel, remkey, tellee))
      elif tellee.lower().startswith(remkey.rstrip('*:')): 
         reminders.extend(getReminders(phenny, channel, remkey, tellee))

   for line in reminders[:maximum]: 
      phenny.msg(tellee, line)

   if reminders[maximum:]: 
      try: 
         if origin.sender in lispchannels: 
            chan = origin.sender
         else: chan = 'None'

         result = web.post('http://paste.lisp.org/submit', 
            {'channel': chan, 
             'username': phenny.nick, 
             'title': 'Further Messages for %s' % tellee, 
             'colorize': 'None', 
             'text': '\n'.join(reminders[maximum:]) + '\n', 
             'captcha': 'lisp', 
             'captchaid': 'bdf447484f62a3e8b23816f9acee79d9'
            }
         )
         uris = re.findall('http://paste.lisp.org/display/\d+', result)
         uri = list(reversed(uris)).pop()
         if not origin.sender in lispchannels: 
            message = '%s: see %s for further messages' % (tellee, uri)
            phenny.msg(tellee, message)
      except: 
         error = '[Sorry, some messages were elided and lost...]'
         phenny.msg(tellee, error)

   if len(phenny.reminders.keys()) != remkeys: 
      dumpReminders(phenny.tell_filename, phenny.reminders) # @@ tell
Exemple #29
0
def flistchar(uri, phenny):
    if hasattr(phenny.config, 'f_list_account') and hasattr(
            phenny.config, 'f_list_password'):
        ticketuri = 'https://www.f-list.net/json/getApiTicket.php'
        ticketquery = {
            'account': phenny.config.f_list_account,
            'password': phenny.config.f_list_password
        }
        ticketjson = web.post(ticketuri, ticketquery)

        ticketstr = str(ticketjson)
        ticketdict = ast.literal_eval(ticketstr)
        ticket = ticketdict['ticket']

        urilist = uri.split('/')
        urlcharname = urilist[4]
        urlcharname = web.unquote(urlcharname)
        charuri = 'https://www.f-list.net/json/api/character-get.php'
        charquery = {'name': urlcharname}
        charjson = web.post(charuri, charquery)

        charstr = str(charjson)
        chardict = ast.literal_eval(charstr)
        try:
            charname = chardict['character']['name']
        except:
            errname = chardict['error']

        try:
            titlestr = 'Error - ' + errname
        except UnboundLocalError:
            titlestr = '\002\00312,01F-List\017 - ' + charname

        return titlestr
    else:
        return
Exemple #30
0
def short(phenny, input):
    """.short <url> - Shorten a URL."""

    url = input.group(2)
    if not url:
        phenny.reply("No URL provided. CAN I HAS?")
        return

    try:
        req = web.post("http://vtlu.ug/vtluug", {'lurl': url})
    except (HTTPError, IOError):
        raise GrumbleError(
            "THE INTERNET IS F*****G BROKEN. Please try again later.")

    phenny.reply(req)
Exemple #31
0
def message(phenny, input): 
   if not input.sender.startswith('#'): return

   tellee = input.nick
   channel = input.sender

   if not os.path.exists(phenny.tell_filename): 
      return

   reminders = []
   remkeys = list(reversed(sorted(phenny.reminders.keys())))
   for remkey in remkeys: 
      if not remkey.endswith('*') or remkey.endswith(':'): 
         if tellee.lower() == remkey: 
            reminders.extend(getReminders(phenny, channel, remkey, tellee))
      elif tellee.lower().startswith(remkey.rstrip('*:')): 
         reminders.extend(getReminders(phenny, channel, remkey, tellee))

   for line in reminders[:maximum]: 
      phenny.say(line)

   if reminders[maximum:]: 
      try: 
         if origin.sender in lispchannels: 
            chan = origin.sender
         else: chan = 'None'

         result = web.post('http://paste.lisp.org/submit', 
            {'channel': chan, 
             'username': phenny.nick, 
             'title': 'Further Messages for %s' % tellee, 
             'colorize': 'None', 
             'text': '\n'.join(reminders[maximum:]) + '\n', 
             'captcha': 'lisp', 
             'captchaid': 'bdf447484f62a3e8b23816f9acee79d9'
            }
         )
         uris = re.findall('http://paste.lisp.org/display/\d+', result)
         uri = list(reversed(uris)).pop()
         if not origin.sender in lispchannels: 
            message = '%s: see %s for further messages' % (tellee, uri)
            phenny.say(message)
      except: 
         error = '[Sorry, some messages were elided and lost...]'
         phenny.say(error)

   if len(phenny.reminders.keys()) != remkeys: 
      dumpReminders(phenny.tell_filename, phenny.reminders) # @@ tell
def activecollab_request(self, command, args={}, data={}):
    """docstring for activecollab_request"""
    url = self.config.activecollab_url
    url += "?path_info=%s" % command
    args['token'] = self.config.activecollab_key
    args['format'] = 'json'
    for (key, value) in args.items():
        url += "&%s=%s" % (key, value)
    if len(data) > 0:
        bytes = web.post(url, data)
        js = json.loads(bytes)
        return js
    else:        
        bytes = web.get(url)
        js = json.loads(bytes)
        return js
Exemple #33
0
def paste(text, title="", format='text'):
   global pastebin_key

   response = web.post("http://pastebin.com/api/api_post.php", {
      'api_option': 'paste',
      'api_dev_key': pastebin_key,
      'api_paste_code': text.encode('utf-8'),
      'api_paste_private': '1',
      'api_paste_name': title.encode('utf-8'),
      'api_paste_expire_date': '1D',
      'api_paste_format': format
   })

   if len(response) > 200: raise IOError("Pastebin is not responding correctly")

   return response
Exemple #34
0
def issue(phenny, input):
    """ .issue <owner>/<repository> <title> - create a new GitHub issue """    
 
    if not is_up(gh_uri):
        return phenny.reply('Sorry, GitHub is down.')
	
    # check if GitHub auth token is available in default.py
    try:
        oauth_token = phenny.config.gh_oauth_token
    except AttributeError:
        return phenny.reply('GitHub authentication token needs to first be set in the configuration file (default.py)')
		
    # check input validity
    if not input.group(1):
        return phenny.reply(invalidmsg)

    content = ''.join(input.group(1)).strip()
    ghpath = content.split()[0].split('/')
        
    # check whether likely in an owner/repository combo format
    if len(ghpath) != 2:
        return phenny.reply(invalidmsg)

    owner = ghpath[0]
    repo = ghpath[1]

    if owner not in allowed_owners:
        return phenny.reply('Begiak cannot create an issue there.')

    title = ' '.join(content.split()[1:]).strip()
    if len(title) < 1:
        return phenny.reply(invalidmsg)

    # build and post HTTP request
    req_url = '{}/repos/{}/{}/issues'.format(gh_uri, owner, repo)
    req_headers = {'Authorization': 'token {}'.format(oauth_token)}
    req_body = json.dumps({
        "title": title,
        "body": default_desc.format(input.nick)
    })

    try:
        req_str = post(req_url, req_body, req_headers)
        req_json = json.loads(req_str)
        phenny.reply('Issue created. You can add a description at {}'.format(req_json['html_url']))
    except HTTPError:
        phenny.reply('It appears that the repository you provided does not exist.')
Exemple #35
0
    def balance(self):
        """
        Get the balance for an API key.

        :return: The balance of an API key
        :rtype: int | float
        """
        post_data = {'clientKey': self._api_key}
        url = 'https://api.anti-captcha.com/getBalance'
        pr = web.post(url=url, json=post_data, as_json=True)

        if len(pr.errors) > 0:
            log.error(pr.errors)
        else:
            if pr.json['errorId'] > 0:
                raise AntiCaptchaApiError(**pr.json)
            else:
                return pr.json['balance']
Exemple #36
0
    def _task_result(self):
        """
        Get the task result.
        """
        post_data = {'clientKey': self._api_key, 'taskId': self._task_id}

        url = 'https://api.anti-captcha.com/getTaskResult'

        pr = web.post(url=url, json=post_data, as_json=True)

        if len(pr.errors) > 0:
            log.error(pr.errors)
        else:
            if pr.json['errorId'] > 0:
                raise AntiCaptchaApiError(**pr.json)
            else:
                log.debug('task result: %s' % pr.json)
                return pr.json
Exemple #37
0
def linx(phenny, input, short=False):
    """.linx <url> - Upload a remote URL to linx.li."""

    url = input.group(2)
    if not url:
        phenny.reply("No URL provided. CAN I HAS?")
        return

    try:
        req = web.post("http://linx.li/vtluug", {'url': url, 'short': short, 'api_key': phenny.config.linx_api_key})
    except (HTTPError, IOError):
        raise GrumbleError("THE INTERNET IS F*****G BROKEN. Please try again later.")

    data = json.loads(req)
    if len(data) <= 0 or not data['success']:
        phenny.reply('Sorry, upload failed.')
        return

    phenny.reply(data['url'])
Exemple #38
0
def linx(phenny, input, short=False):
    """.linx <url> - Upload a remote URL to linx.li."""

    url = input.group(2)
    if not url:
        phenny.reply("No URL provided. CAN I HAS?")
        return

    try:
        req = web.post("https://linx.li/upload/remote", {'url': url, 'short': short, 'api_key': phenny.config.linx_api_key})
    except (web.HTTPError, web.ConnectionError):
        raise GrumbleError("Couldn't reach linx.li")

    data = json.loads(req)
    if len(data) <= 0 or not data['success']:
        phenny.reply('Sorry, upload failed.')
        return

    phenny.reply(data['url'])
Exemple #39
0
def omelette(session):
    global times
    key = "omelette"
    timeExpiry = times.get(key)

    if timeExpiry == None or time.time() > timeExpiry:
        response = web.get(session, Constants.NEO_OMELETTE)
        postFields = {"type": "get_omelette"}

        source = web.post(session, Constants.NEO_OMELETTE, postFields,
                          Constants.NEO_OMELETTE)

        print("Collected an omelette")

        times[key] = timestamp.endOfDay()

        file = open(r'times.pkl', 'wb')
        pickle.dump(times, file)
        file.close()
Exemple #40
0
def linx(phenny, input):
    """.linx <url> - Upload a URL to linx.li."""

    url = input.group(2)
    if not url:
        phenny.reply("No URL provided. CAN I HAS?")
        return

    try:
        req = web.post("http://linx.li/vtluug", {'url': url})
    except (HTTPError, IOError):
        raise GrumbleError(
            "THE INTERNET IS F*****G BROKEN. Please try again later.")

    data = json.loads(req)
    if len(data) <= 0 or not data['success']:
        phenny.reply('Sorry, upload failed.')
        return

    phenny.reply(data['url'])
Exemple #41
0
def jelly(session):
    global times
    key = "jelly"

    timeExpiry = times.get(key)

    if timeExpiry == None or time.time() > timeExpiry:
        response = web.get(session, Constants.NEO_JELLY)
        postFields = {"type": "get_jelly"}

        source = web.post(session, Constants.NEO_JELLY, postFields,
                          Constants.NEO_JELLY)

        print("Collected Jelly")

        times[key] = timestamp.endOfDay()

        file = open(r'times.pkl', 'wb')
        pickle.dump(times, file)
        file.close()
Exemple #42
0
def use_pastebin(phenny, nick, remaining_notes):
  nick_lower = nick.lower()
  try:
    combined_notes = []
    for tuple in remaining_notes:
      combined_notes.append(tuple[1].encode('utf-8'))
    result = web.post('http://pastebin.com/api/api_post.php',
      {
        'api_dev_key': 'YOUR DEV KEY HERE',
        'api_option': 'paste',
        'api_paste_code': '\n'.join(combined_notes) + '\n',
        'api_paste_name': 'Further Messages for %s' % nick_lower,
        'api_paste_private': 0,
        'api_paste_expire_date': '1M'
      }
    )
    message = 'see %s for further messages' % result
    phenny.reply(message)
  except IOError:
    phenny.say("Sorry, some messages were elided and lost...")
Exemple #43
0
def tdmbgpop(session):
    global times
    key = "tdmbgpop"

    timeExpiry = times.get(key)

    if timeExpiry == None or time.time() > timeExpiry:
        response = web.get(session, Constants.NEO_TDMBGPOP)
        postFields = {"talkto": "1"}

        source = web.post(session, Constants.NEO_TDMBGPOP, postFields,
                          Constants.NEO_TDMBGPOP)

        print("Visited TDMBGPOP")

        times[key] = timestamp.endOfDay()

        file = open(r'times.pkl', 'wb')
        pickle.dump(times, file)
        file.close()
Exemple #44
0
def message(phenny, input): 
   if not input.sender.startswith('#'): return

   tellee = input.nick
   channel = input.sender

   if not os: return
   if not os.path.exists(phenny.tell_filename): 
      return

   reminders = []
   remkeys = list(reversed(sorted(phenny.reminders.keys())))
   for remkey in remkeys: 
      if not remkey.endswith('*') or remkey.endswith(':'): 
         if tellee.lower() == remkey: 
            reminders.extend(getReminders(phenny, channel, remkey, tellee))
      elif tellee.lower().startswith(remkey.rstrip('*:')): 
         reminders.extend(getReminders(phenny, channel, remkey, tellee))

   for line in reminders[:maximum]: 
      phenny.say(line)

   if reminders[maximum:]: 
      try: 
         result = web.post('http://pastebin.com/api/api_post.php',
            {'api_dev_key': 'YOUR DEV KEY HERE',
             'api_option': 'paste',
             'api_paste_code': '\n'.join(reminders[maximum:]) + '\n',
             'api_paste_name': 'Further Messages for %s' % tellee,
             'api_paste_private': 1,
             'api_paste_expire_date': '1M'
            }
         )
         message = '%s: see %s for further messages' % (tellee, result)
         phenny.say(message)
      except IOError: 
         error = '[Sorry, some messages were elided and lost...]'
         phenny.say(error)

   if len(phenny.reminders.keys()) != remkeys: 
      dumpReminders(phenny.tell_filename, phenny.reminders) # @@ tell
Exemple #45
0
def fishing(session):
    global times
    waitTime = 13
    key = "fishing"

    timeExpiry = times.get(key)

    if timeExpiry == None or time.time() > timeExpiry:
        response = web.get(session, Constants.NEO_FISHING)
        postFields = {"go_fish": "1"}

        source = web.post(session, Constants.NEO_FISHING, postFields,
                          Constants.NEO_FISHING)

        print("Went Fishing")

        times[key] = timestamp.getTimestamp(waitTime)

        file = open(r'times.pkl', 'wb')
        pickle.dump(times, file)
        file.close()
Exemple #46
0
def healingSprings(session):
    global times
    waitTime = 0.5
    key = "springs"

    timeExpiry = times.get(key)

    if timeExpiry == None or time.time() > timeExpiry:
        response = web.get(session, Constants.NEO_SPRINGS)
        postFields = {"type": "heal"}

        source = web.post(session, Constants.NEO_SPRINGS, postFields,
                          Constants.NEO_SPRINGS)

        print("Went to healing springs")

        times[key] = timestamp.getTimestamp(waitTime)

        file = open(r'times.pkl', 'wb')
        pickle.dump(times, file)
        file.close()
Exemple #47
0
    def DicionarioPtPt(self, procura, para, completo):
        uri = 'http://www.priberam.pt/dlpo/definir_resultados.aspx'
        pag = web.post(uri, {'h_texto_pesquisa': procura})
        if pag.find('lblNaoEncontrou') == -1: 
            pag = pag[pag.find('<span id="lblDlpoPesqPalavra">'):pag.find('<!-- fim TEXTO CONTEUDOS -->')]
            pag = pag.replace('<br />', '\r\n')
            while pag.find('<') != -1:
                pag = pag[:pag.find('<')] + pag[pag.find('>')+1:]
            pag = pag.replace('\r\n', ',').replace('\t', ' ')

            while pag.find('  ') != -1:
                pag = pag.replace('  ', ' ').replace(', ', ' ').replace(',,', ' | ').replace(';,', ';')
            pag = pag.replace(';-', ' |').replace(' -:', ':').strip('| ').replace(' ,', ' ')
            pag = funcoes.codificar(pag, 'utf-8', de='iso-8859-1')
            pag = pag.replace('|', '\x02|\x02').replace(';', '; ')
            # tirar abreviaturas
            if completo:
                pag = pag.replace('2 gén.', '2 gêneros').replace    ('2 núm.', '2 números (singular e plural)')
                pag = pag.replace('adj.',   'adjectivo').replace    ('adv.',   'advérbio; adverbial')
                pag = pag.replace('art.',   'artigo').replace       ('card.',  'cardinal').replace('Lat.', 'Latim')
                pag = pag.replace('comp.',  'comparativo').replace  ('conj.',  'conjunção; conjuncional')
                pag = pag.replace('def.',   'definido').replace     ('dem.',   'demonstrativo').replace('f.', 'feminino ')
                pag = pag.replace('indef.', 'indefinido').replace   ('interj.','interjeição')
                pag = pag.replace('interr.','interrogativo').replace('int.',   'intransitivo')
                pag = pag.replace('loc.',   'locução').replace      ('m.',     'masculino ').replace('mult.',   'multiplicativo')
                pag = pag.replace('num.',   'numeral').replace      ('ord.',   'ordinal').replace  (' part.','particípio')
                pag = pag.replace('pass.',  'passado').replace      ('pess.',  'pessoa').replace  ('plu.',   'plural')
                pag = pag.replace('poss.',  'possessivo').replace   ('pref.', 'prefixo')
                pag = pag.replace('prep.',  'preposição').replace   ('pron.',  'pronome; pronominal')
                pag = pag.replace('refl.',  'reflexo').replace      ('rel.',   'relativo').replace  ('s.',   'substantivo')
                pag = pag.replace('sing.',  'singular').replace     ('suf.',   'sufixo').replace    ('sup.', 'superioridade')
                pag = pag.replace('superl.','superlativo').replace  ('tr.',    'transitivo').replace('v.',   'verbo')
            self.Bot.Say(para, pag)
        else:
            f = 'javascript:SeleccionaEntrada(&quot;'
            x = 'A palavra não foi encontrada. Algumas sugestões: '
            while pag.find(f) > -1:
                pag = pag[pag.find(f)+len(f):]
                x = x + '\x02' + pag[:pag.find('&')] + '\x02, '
            self.Bot.Say(para, x.strip(', '))
Exemple #48
0
 def doPost(self, longURL):
 	return web.post('http://metamark.net/add', {'long_url': longURL})
def rsscheck(phenny, input):
	t = time.time()
	if rssnotify["last_update"] > t-rssnotify["update_cooldown"]:
		return
	rssnotify["last_update"] = t
	print("[RssNotify]: Checking RSS Feeds...")
	start = time.time()
	allchans = excepta(phenny.bot.channels, ['##minebest'])
	feeds = [
		('https://github.com/minetest/minetest/commits/master.atom', allchans),
		('https://github.com/minetest/minetest_game/commits/master.atom', allchans),
		('https://github.com/minetest/minetestmapper/commits/master.atom', allchans),
		('https://github.com/minetest/master-server/commits/master.atom', allchans),
		('https://github.com/Uberi/MineTest-WorldEdit/commits/master.atom',  allchans),
		('https://github.com/Jeija/minetest-mod-mesecons/commits/master.atom', allchans),
		('https://github.com/sfan5/phenny/commits/master.atom', ['##minetestbot']),
		('https://github.com/sfan5/minetestbot-modules/commits/master.atom', ['##minetestbot']),
	]
	for v in range(0, len(feeds)):
		url = feeds[v][0]
		feednum = v
		options = {
			'agent': 'Mozilla/5.0 (MinetestBot)',
			'referrer': 'http://minetest.net'
		}
		feed = feedparser.parse(url, **options)
		updcnt = 0
		for feed_entry in feed.entries:
			if not feednum in rssnotify["last_updated_feeds"].keys():
				rssnotify["last_updated_feeds"][feednum] = -1
			if rssnotify["last_updated_feeds"][feednum] < to_unix_time(feed_entry.updated):
				commiter_realname = feed_entry.authors[0].name
				if commiter_realname == "":
						try:
							commiter_realname = feed_entry.authors[0].email
						except AttributeError:
							commiter_realname = "Unknown"
				try:
					commiter = feed_entry.authors[0].href.replace('https://github.com/',"")
				except AttributeError:
					commiter = commiter_realname # This will only use the realname if the nickname couldn't be obtained
				reponame = url.replace("https://github.com/","").replace("/commits/master.atom","")
				commit_hash = feed_entry.links[0].href.replace("https://github.com/" + reponame + "/commit/","")[:7]
				commit_time = feed_entry.updated
				updcnt += 1
				if rssnotify["dont_print_first_message"]:
					continue
				if rssnotify["show_commit_link"]:
					if rssnotify["use_git.io"]:
						# Side note: git.io only works with *.github.com links
						l, code = web.post("http://git.io/create", {'url': feed_entry.link})
						if code == 200:
							l = str(l, 'utf-8')
							if len(l.strip()) == 6:
								commit_link = "http://git.io/" + l
							else:
								commit_link = feed_entry.link
						else:
							commit_link = feed_entry.link
					else:
						commit_link = feed_entry.link
				else:
					commit_link = ""

				chans = []
				if feeds[v][1] == '*':
					chans = phenny.bot.channels
				elif type(feeds[v][1]) == type([]):
					chans = feeds[v][1]
				else:
					print("[RssNotify]: Something went wrong!")
				if rssnotify["logfilepath"] != "":
					lf = open(rssnotify["logfilepath"], "a")
					if commiter.lower() != commiter_realname.lower():
						lf.write("[color=#3465a4][git][/color] [color=#cc0000]%s[/color] ([color=#cc0000]%s[/color]) -> [color=#73d216]%s[/color]: [b]%s[/b] [color=#a04265]%s[/color] %s ([color=#888a85]%s[/color])\n" % (commiter, commiter_realname, reponame, feed_entry.title, commit_hash, commit_link, commit_time))
					else:
						lf.write("[color=#3465a4][git][/color] [color=#cc0000]%s[/color] -> [color=#73d216]%s[/color]: [b]%s[/b] [color=#a04265]%s[/color] %s ([color=#888a85]%s[/color])\n" % (commiter, reponame, feed_entry.title, commit_hash, commit_link, commit_time))
					lf.close()
				for ch in chans:
					if commiter.lower() != commiter_realname.lower():
						phenny.write(['PRIVMSG', ch], "\x0302[git]\x0f \x0304%s\x0f (\x0304%s\x0f) -> \x0303%s\x0f: \x02%s\x0f \x0313%s\x0f %s (\x0315%s\x0f)" % (commiter, commiter_realname, reponame, feed_entry.title, commit_hash, commit_link, commit_time))
					else:
						phenny.write(['PRIVMSG', ch], "\x0302[git]\x0f \x0304%s\x0f -> \x0303%s\x0f: \x02%s\x0f \x0313%s\x0f %s (\x0315%s\x0f)" % (commiter, reponame, feed_entry.title, commit_hash, commit_link, commit_time))
		if len(feed.entries) > 0:
			m = -1
			for i in range(0, len(feed.entries)):
				if to_unix_time(feed.entries[i].updated) > m:
					m = to_unix_time(feed.entries[i].updated)
			rssnotify["last_updated_feeds"][feednum] = m
		if updcnt > 0:
			print("[RssNotify]: Found %i RSS Update(s) for URL '%s'" % (updcnt, url))
	end = time.time()
	if rssnotify["dont_print_first_message"]:
		rssnotify["dont_print_first_message"] = False
	print("[RssNotify]: Checked " + str(len(feeds)) + " RSS Feeds in %0.3f seconds" % (end-start))
Exemple #50
0
def rexstart(phenny, input):  
  if "running" in phenny.rcwatch:
    if ".rcwatch" in input:
      phenny.say("Watch daemon is running already.") 
    return
  phenny.rcwatch["running"] = True

  #phenny.msg(channel, "Ok. Running the watch daemon.")
  annoying = False

  oldrc = None
  try:
    oldrc = yaml.load(open("oldrc.yaml", "r").read())
  except:
    oldrc = "0"

  while True:
    time.sleep(sleepytime)
    
    if "stopme" in phenny.rcwatch:
      phenny.say("Aborted the watch daemon")
      del phenny.rcwatch["stopme"]
      return

    rc = None
    try:
      rc = web.get("http://wiki.xkcd.com/wgh/api.php?action=query&format=xml&list=recentchanges&rcprop=user|comment|flags|title|ids&rclimit=20")
    except:
      phenny.rcwatch["down"]=phenny.rcwatch.get("down",0)+1
      if phenny.rcwatch["down"]==3:
        phenny.msg(channel,"The wiki %s. \o/" % (random.choice(["has gone down.", "is no more.", "is unreachable.", "has disappeared.", "- I can't find it"])))
    if not rc:
      continue
    if "down" in phenny.rcwatch:
      if phenny.rcwatch["down"]>3:
        phenny.msg(channel,"The wiki is back!")
      del phenny.rcwatch["down"]
    
    et = ET.fromstring(rc)
    if not et:
      print "No page returned."
      return   
 
    newestcurrentid = "0"

    try:
      rclist = et.find("query").find("recentchanges")
    except Exception,ex:
      print ex
      continue 
    hadthese = []
    for entry in rclist:
      rcid = entry.get("rcid")
      if rcid > newestcurrentid:
        newestcurrentid = rcid
      if rcid <= oldrc:
        continue
      typ = entry.get("type")
      title = entry.get("title")
      user = entry.get("user")
      comment = entry.get("comment")
      new = "new" in entry.keys()
      bot = "bot" in entry.keys()
      minor = "minor" in entry.keys()
      pageid = entry.get("pageid")
      revid = entry.get("revid")
      
      if pageid in hadthese:
        continue
      hadthese.append(pageid)

      show, spam = None, None

      if re_anonymous.match(user):
        try:
          page = web.get("http://wiki.xkcd.com/wgh/index.php?title=%s&action=raw" % urllib.quote(title))
          for re in re_spam:
            if re.search(comment) or re.search(title) or re.search(page):
              spam = True
        except Exception, ex:
          print "while fetching page:"
          print ex #if it doesn't work, don't bother the channel. log it though.

      if "[Shmulik]" in comment:
        spam=False
        minor=True #prevent reporting, too

      if spam:
        try:
	  #login
          #result = web.post("http://wiki.xkcd.com/wgh/api.php", {"action":"login", "lgname":"ReletBot", "lgpassword":"******", "format":"xml"})
          #result might be a fail, most frequently because we are being throttled.
          #get rollback token
          rvpage = web.post("http://wiki.xkcd.com/wgh/api.php", {"action":"query", "titles":title, "prop":"info", "intoken":"edit", "format":"xml"})
          et2 = ET.fromstring(rvpage)
	  try:
            info = et2.find("query").find("pages").find("page")
	    token = info.get("edittoken")
            rvcheck = info.get("lastrevid")
            if rvcheck != revid:
              print "Someone else seems to have reverted this spam. (%s,%s)" % (title, revid) 
	      continue
          except Exception,ex:
            print "while fetching edit token:"
            print ex
            continue

          #get a lyric comment
          comment = "[Shmulik] "
          if len(lyrics)>0:
	    annoying = False
            comment+=lyrics.pop(0)
            open("lyrics.yaml","w").write(yaml.dump(lyrics))
          else:
	    comment+="undoing the last edit, because I think it looks like spam."
          if len(lyrics)==10:
            phenny.msg(channel, "I'm running out of spam-undo-lyrics. Please send me some in a private message using the .lyrics command.")
          if len(lyrics)==0:
            if not annoying:
              phenny.msg(channel, "Oh no! I've run out of spam-undo-lyrics. Please do send me some lyrics in a private message using the .lyrics command.")
              annoying = True

          #undo spam
	  if typ=="new":
            result = web.post("http://wiki.xkcd.com/wgh/api.php", {"action":"edit", "title":title, "bot":"0", "text":"{{spam}}", "token":token, "summary":comment, "format":"xml"})
          else:
            result = web.post("http://wiki.xkcd.com/wgh/api.php", {"action":"edit", "title":title, "undo":rvcheck, "bot":"0", "token":token, "summary":comment, "format":"xml"})

        except Exception, ex:
          print "while undoing:"
          print ex #if it doesn't work, don't bother the channel. log it though.
Exemple #51
0
def get_title(phenny, url, channel):
    """ Have linx retrieve the (augmented) title """
    try:
        return web.post("http://linx.li/vtluuggettitle", {'url': url, 'channel': channel, 'api_key': phenny.config.linx_api_key})
    except:
        return