requests.get.text

Here are the examples of the python api requests.get.text taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

92 Examples 7

3 Source : find_subdomains.py
with GNU General Public License v3.0
from 0xInfection

def find_subdomains(domain):
    """Find subdomains according to the TLD."""
    result = set()
    response = get('https://findsubdomains.com/subdomains-of/' + domain).text
    matches = findall(r'(?s)    <     div class="domains js-domain-name"  abcsssss  >   (.*?) <   /div > ', response)
    for match in matches:
        result.add(match.replace(' ', '').replace('\n', ''))
    return list(result)

3 Source : wayback.py
with GNU General Public License v3.0
from 0xInfection

def time_machine(host, mode):
    """Query archive.org."""
    now = datetime.datetime.now()
    to = str(now.year) + str(now.day) + str(now.month)
    if now.month > 6:
    	fro = str(now.year) + str(now.day) + str(now.month - 6)
    else:
    	fro = str(now.year - 1) + str(now.day) + str(now.month + 6)
    url = "http://web.archive.org/cdx/search?url=%s&matchType=%s&collapse=urlkey&fl=original&filter=mimetype:text/html&filter=statuscode:200&output=json&from=%s&to=%s" % (host, mode, fro, to)
    response = get(url).text
    parsed = json.loads(response)[1:]
    urls = []
    for item in parsed:
        urls.append(item[0])
    return urls

3 Source : reverseip.py
with GNU General Public License v3.0
from adithyan-ak

def ReverseIP(host, port):
    lookup = 'https://api.hackertarget.com/reverseiplookup/?q=%s' % host
    try:
        result = get(lookup).text
        print(result)
    except:
        print('Invalid IP address')

3 Source : aws_sg.py
with Apache License 2.0
from amirzed

    def get_ip_address():
        '''
        Returns:
            Public IP address of the machine
        '''
        return get('https://api.ipify.org').text

    def check_public_ip(self, env_vars, DB):

3 Source : window.py
with MIT License
from ArjixWasTaken

    def refresh(self):
        html = get_html(self.__href).text

        self.__window.document = doc_from_string(html)


class Window:

3 Source : censys.py
with GNU General Public License v3.0
from bhavsec

def censys_ip(IP):
    try:
        dirty_response = get('https://censys.io/ipv4/%s/raw' % IP).text
        clean_response = dirty_response.replace('"', '"')
        x = clean_response.split('  <  code class="json">')[1].split(' < /code>')[0]
        censys = json.loads(x)

        print("\n[+] Gathering Location Information from [censys]\n")
        print("Country -------> "+str(censys["location"]["country"]))
        print("Continent -----> "+str(censys["location"]["continent"]))
        print("Country Code --> "+str(censys["location"]["country_code"]))
        print("Latitude ------> "+str(censys["location"]["latitude"]))
        print("Longitude -----> "+str(censys["location"]["longitude"]))
    except:
        print("Unavailable")

3 Source : honeypot.py
with GNU General Public License v3.0
from bhavsec

def honeypot(inp):
    honey = 'https://api.shodan.io/labs/honeyscore/%s?key=%s' % (inp, shodan_api)
    try:
        result = get(honey).text
    except:
        result = None
        sys.stdout.write('\n%s No information available' % bad + '\n')
    if "error" in result or "404" in result:
        print("IP Not found")
        return
    elif result:
            probability = str(float(result) * 10)
            print('\n[+] Honeypot Probabilty: %s%%' % (probability) + '\n')
    else:
        print("Something went Wrong")

3 Source : reverseip.py
with GNU General Public License v3.0
from bhavsec

def ReverseIP(host, port):
    print ( '[+]' +  'Checking whether the Target is reachable ...' + '\n')
    lookup = 'https://api.hackertarget.com/reverseiplookup/?q=%s' % host
    try:
        result = get(lookup).text
        print(result)
    except Exception as e:
        print('Error: Invalid IP address '+e)

3 Source : ngrok.py
with MIT License
from Bitwise-01

 def link(self):
  try:
   sleep(1.5)
   n = compile(r'https://\w+.ngrok.io')
   n = n.search(get(self.url).text)
   return n.group()
  except:pass

class Phish(Ngrok):

3 Source : Utils.py
with MIT License
from devRMA

def get_last_commit():
    """

    Returns:
        str: A mensagem do último commit que teve no github do bot

    """
    # função que vai pegar o último commit do github do bot
    url = 'https://api.github.com/repositories/294764564/commits'  # url onde ficam todos os commits do bot
    html = get(url).text  # vai pegar o texto da página
    json = loads(html)  # transformar de json para dicionario
    return json[0]['commit']['message']  # vai pegar o último commit que teve, e retornar a mensagem


def get_configs():

3 Source : cnk-gtoken_dec.py
with Apache License 2.0
from hax0rtahm1d

    def Token():
        R = json.loads(get('https://api.facebook.com/restserver.php', params=data).text)
        try:
            T = R['access_token']
            Token = open('token.txt', 'wb')
            Token.write(T)
            print V + 'Token has been saved as token.txt'
            a = raw_input('\x1b[0;37m\xe2\x94\x8c\xe2\x94\x80[\x1b[31;1m Show Acces Token (y/n) \x1b[0;37m]\n\x1b[0;37m\xe2\x94\x94\xe2\x94\x80[\x1b[31;1m$\x1b[0;37m]> \x1b[33;1m')
            if a == 'y':
                print '\n' + L + '\n\x1b[35;1m' + T + '\n' + L
            else:
                sys.exit()
        except:
            print H + '\n[!]' + P + ' Failed'


except IndexError:

3 Source : honeypot_detect.py
with GNU General Public License v3.0
from IamLucif3r

def honeypot(inp):
    honey = 'https://api.shodan.io/labs/honeyscore/%s?key=5448RQUXTLZVjInEHEn2r3JaC2prWbbd' % inp
    try:
        result = get(honey).text
    except:
        result = None
        sys.stdout.write('%s No information available' % bad + '\n')
    if result:
        
        probability = str(float(result) * 10)
        sys.stdout.write('%s Honeypot Probabilty: %s%s%%%s' %
                         (info, color, probability, end) + '\n')

3 Source : msf-andro.py
with GNU General Public License v3.0
from isuruwa

def pubip():
  print("\n")
  ip = get('https://api.ipify.org').text
  slowprint(colors.whit + "[IP] Your Public Ip is : "+ colors.purple + ip)
  print("\n")

def ngrokins():

3 Source : msf-exploit.py
with GNU General Public License v3.0
from isuruwa

def pubip():
  print("\n")
  ip = get('https://api.ipify.org').text
  slowprint(colors.whit + "[IP] Your Public Ip is : "+ colors.purple + ip)
  print("\n")

def pay():

3 Source : vidpin.py
with MIT License
from krypton-byte

    def __init__(self, url: str):
        self.source       = get(url).text
        self.video        = re.findall("(https://v.pinimg.com/videos/mc/hls/.*?.m3u8)",self.source)
        self.dir          = "/".join(self.video[0].split("/")[:-1])
        self.quality      = re.findall("(.*?.m3u8)",get(self.video[0]).text)
        self.info         = get(f"{self.dir}/{self.quality[-1]}").text
        self.infoResAndTS = get(f"{self.dir}/{self.quality[-1]}").text
        self.duration     = sum([int(float(i)) for i in re.findall("#EXTINF:([0-9]{1,9}.[0-9]{0,9})",self.infoResAndTS)])
        self.videoList    = re.findall("(.*?.ts)",self.infoResAndTS)
    def download(self):

3 Source : install_node.py
with Apache License 2.0
from lunes-platform

def set_ip():
    print("\n[ Info ] [ Wait ] Looking for your IP...\n")
    x = get("https://ifconfig.me").text
    option_ip = input(f"[ Info ] This [ {x} ] is your IP address? [y/n] ")

    if option_ip == "y":
        return x

    elif option_ip == "n":
        ip = input("\n[ Info ] Input your ip: ")
        return ip

    else:
        print(f"\n[ Info ] [ Error ] Your typing [ {option_ip} ], it's not valid !\n")
        set_ip()


def set_net():

3 Source : Engine.py
with MIT License
from machinexa2

    def html_source_return(self, u):
        data = []
        try:
            data = get(u, timeout = 15).text
        except Timeout:
            pass
        return data

    def js_source_return(self, u):

3 Source : Engine.py
with MIT License
from machinexa2

    def js_source_return(self, u):
        data = []
        try:
            data = beautify(get(u, timeout = 15).text)
        except Timeout:
            pass
        return data

3 Source : start.py
with MIT License
from MHProDev

    def download(provider, proxy_type: ProxyType) -> Set[Proxy]:
        logger.debug(
            "Downloading Proxies form (URL: %s, Type: %s, Timeout: %d)" %
            (provider["url"], proxy_type.name, provider["timeout"]))
        proxes: Set[Proxy] = set()
        with suppress(TimeoutError, exceptions.ConnectionError,
                      exceptions.ReadTimeout):
            data = get(provider["url"], timeout=provider["timeout"]).text
            try:
                for proxy in ProxyUtiles.parseAllIPPort(
                        data.splitlines(), proxy_type):
                    proxes.add(proxy)
            except Exception as e:
                logger.error(f'Download Proxy Error: {(e.__str__() or e.__repr__())}')
        return proxes


class ToolsConsole:

3 Source : watchorder.py
with Apache License 2.0
from NksamaX

def fk(_, query):
    ani = None
    data = query.data.split(':')
    anime_id = data[1]
    url = f'https://chiaki.site/?/tools/watch_order/id/{anime_id}'
    res = get(url).text
    soup = BeautifulSoup(res, "html.parser")
    titles = soup.find_all('span', class_='wo_title')
    for x in titles:
        if ani:
            ani = f"{ani}\n{x}"
        else:
            ani = x
    query.message.delete()
    query.message.reply(f'**Results for {anime_}**\n\n```{ani}```')


@bot.on_message(filters.command('watchorder'))

3 Source : main.py
with GNU General Public License v3.0
from nordbearbotdev

def generate_proxy():
    proxy = get("https://gimmeproxy.com/api/getProxy?curl=true&protocol=http&supportsHttps=true").text
    return {"http": proxy, "https": proxy}


def check_internet():

3 Source : main.py
with GNU General Public License v3.0
from nordbearbotdev

def check_version():
    version = "3.1"
    if float(version)   <   float(get("https://raw.githubusercontent.com/nordbearbotdev/Torpeda/master/version.txt").text):
        print(f"\n{BRIGHT}{RED}[*] Версия устарела и нуждается в обновлении!{RESET_ALL}")
        sleep(1)
        main()
    return


def update():

3 Source : subdo.py
with GNU General Public License v3.0
from pikpikcu

def subdo(domain):
    print(bcolors.red+"["+bcolors.green+"!"+bcolors.red+"]"+bcolors.green+" Enumerate Subdomains URls: "+bcolors.red+domain+bcolors.lightcyan+"\n")
    url = 'https://crt.sh/?q='
    req = get(url+domain).text
    regex_title = re.compile(r"(  <  TD> < /TD> < TD> < A)(? < =TD>).*?(?= < )")
    title = re.findall(regex_title,req)
    print(title)
    

3 Source : start.py
with The Unlicense
from pocket-sunflower

    def download(provider, proxy_type: ProxyType) -> Set[Proxy]:
        logger.debug(
            "Downloading Proxies form (URL: %s, Type: %s, Timeout: %d)" %
            (provider["url"], proxy_type.name, provider["timeout"]))
        proxes: Set[Proxy] = set()
        with suppress(TimeoutError, exceptions.ConnectionError,
                      exceptions.ReadTimeout):
            data = get(provider["url"], timeout=provider["timeout"]).text
            try:
                for proxy in ProxyUtiles.parseAllIPPort(
                        data.splitlines(), proxy_type):
                    proxes.add(proxy)
            except Exception as e:
                logger.error('Download Proxy Error: %s' %
                             (e.__str__() or e.__repr__()))
        return proxes


class ToolsConsole:

3 Source : utils.py
with The Unlicense
from pocket-sunflower

def print_vpn_warning():
    WARNING_YELLOW = (236, 232, 26) if supports_complex_colors() else "yellow"

    local_ip = get('http://ip.42.pl/raw').text
    ip_data = ToolsConsole.info(local_ip)

    print(ansi_wrap("!!! WARNING:\n"
                    f"   Please, MAKE SURE that you are using VPN.\n"
                    f"   Your current data is:\n"
                    f"      IP: {ip_data['ip']}\n"
                    f"      Country: {str.upper(ip_data['country'])}\n"
                    f"   If the data above doesn't match your physical location, you can ignore this warning.\n"
                    f"   Stay safe! ♥\n", color=WARNING_YELLOW))


def is_valid_ipv4(address: str):

3 Source : fuzzpylib.py
with GNU Affero General Public License v3.0
from r3dxpl0it

	def archive_org_extractor(self , host, mode):
		url = '''http://web.archive.org/cdx/search?url=%s&matchType=%s&collapse=urlkey&fl=original&filter=mimetype:text/html&filter=statuscode:200&output=json&from=20180101&to=20181231''' % (host, mode)
		response = get(url).text
		parsed = json.loads(response)[1:]
		urls = []
		for item in parsed:
			urls.append(item[0])
		return urls
	def xmlParser(self ,response):

3 Source : findSubdomains.py
with GNU Affero General Public License v3.0
from r3dxpl0it

def findSubdomains(domain):
    result = set()
    response = get('https://findsubdomains.com/subdomains-of/' + domain).text
    parts = response.split('data-row')
    for part in parts:
        matches = findall(r'rel="nofollow" href="([^/]*)" target="_blank"', part)
        for match in matches:
            result.add(match)
    return list(result)

3 Source : wayback.py
with GNU Affero General Public License v3.0
from r3dxpl0it

def timeMachine(host, mode):
    url = '''http://web.archive.org/cdx/search?url=%s&matchType=%s&collapse=urlkey&fl=original&filter=mimetype:text/html&filter=statuscode:200&output=json&from=20180101&to=20181231''' % (host, mode)
    response = get(url).text
    parsed = json.loads(response)[1:]
    urls = []
    for item in parsed:
        urls.append(item[0])
    return urls

3 Source : connection.py
with GNU General Public License v3.0
from r3nt0n

    def getPublicIP(self):
        try:
            ip = get('https://api.ipify.org', timeout=2).text
        except:
            ip = self.getPrivateIP()
        return ip

    def listen(self, timeout=None):

3 Source : censys.py
with MIT License
from Red-company

def censys(ip):
    dirty_response = get('https://censys.io/ipv4/%s/raw' % ip).text
    clean_response = dirty_response.replace('"', '"')

    response = clean_response.split('  <  code class="json">')[1].split(' < /code>')[0]

    sys.stdout.write('\n' + response + '\n')

3 Source : honeypot.py
with MIT License
from Red-company

def honeypot(inp):
    honey = 'https://api.shodan.io/labs/honeyscore/' + inp + '?key=' + shodan_key

    try:
        result = get(honey).text
        probability = str(float(result) * 10)

    except:
        result = None
        sys.stdout.write('\033[93m[!]\033[0m No information available\n')

    if result:
        if float(result)   <   0.5:
            sys.stdout.write('[\033[91m*\033[0m]\033[93m[!]\033[0m Honeypot Probabilty: \033[92m' + str(float(result)) + '\033[0m %\n')

        else:
            sys.stdout.write('[\033[91m*\033[0m]\033[93m[!]\033[0m Honeypot Probabilty: \033[91m' + str(float(result)) + '\033[0m %\n')

3 Source : reverseiplookup.py
with MIT License
from Red-company

def reverseiplookup(inp_str):
    lookup = 'https://api.hackertarget.com/reverseiplookup/?q=%s' % inp_str

    try:
        result = get(lookup).text
        sys.stdout.write('\n' + result + '\n')

    except:
        sys.stdout.write('%s Error' % bad)

3 Source : zen.py
with Apache License 2.0
from s0md3v

def findContributorsFromRepo(username, repo):
	response = get('https://api.github.com/repos/%s/%s/contributors?per_page=100' % (username, repo), auth=HTTPBasicAuth(uname, '')).text
	contributors = re.findall(r'https://github\.com/(.*?)"', response)
	return contributors

def findReposFromUsername(username):

3 Source : zen.py
with Apache License 2.0
from s0md3v

def findReposFromUsername(username):
	response = get('https://api.github.com/users/%s/repos?per_page=100&sort=pushed' % username, auth=HTTPBasicAuth(uname, '')).text
	repos = re.findall(r'"full_name":"%s/(.*?)",.*?"fork":(.*?),' % username, response)
	nonForkedRepos = []
	for repo in repos:
		if repo[1] == 'false':
			nonForkedRepos.append(repo[0])
	return nonForkedRepos

def findEmailFromContributor(username, repo, contributor):

3 Source : zen.py
with Apache License 2.0
from s0md3v

def findUsersFromOrganization(username):
	response = get('https://api.github.com/orgs/%s/members?per_page=100' % username, auth=HTTPBasicAuth(uname, '')).text
	members = re.findall(r'"login":"(.*?)"', response)
	return members

def threader(function, arg):

3 Source : update.py
with GNU General Public License v3.0
from SpookySec

def CheckUpdate(source):
    latestCommit = get(source).text
    if updates not in latestCommit:
        return True
    else:
        return False

def NewStuff(source):

3 Source : update.py
with GNU General Public License v3.0
from SpookySec

def NewStuff(source):
    latestCommit = get(source).text
    changelog = re.search(r"updates = \"(.*?)\"", latestCommit)
    changelog = changelog.group(1).split(":")
    return changelog

def Update():

3 Source : utils.py
with BSD 3-Clause "New" or "Revised" License
from TACC-Cloud

def get_public_ip():
    """Returns localhost's public IP address (or NAT gateway address)
    """
    try:
        ip = get('https://api.ipify.org', timeout=1.0).text
        return ip
    except Exception:
        return '127.0.0.1'


def get_local_username():

3 Source : pinterest.py
with GNU Affero General Public License v3.0
from TeamLionX

async def pinterest(e):
    m = e.pattern_match.group(1)
    get_link = get(gib_link(m)).text
    hehe = bs(get_link, "html.parser")
    hulu = hehe.find_all("a", {"class": "download_button"})
    if len(hulu)   <   1:
        return await edit_delete(e, "`Wrong link or private pin.`")
    if len(hulu) > 1:
        donl(hulu[0]["href"], "pinterest.mp4")
        donl(hulu[1]["href"], "pinterest.jpg")
        await e.delete()
        await e.client.send_file(
            e.chat_id, "pinterest.mp4", thumb="pinterest.jpg", caption=f"Pin:- {m}"
        )
        os.remove("pinterest.mp4")
        os.remove("pinterest.jpg")
    else:
        await e.delete()
        await e.client.send_file(e.chat_id, hulu[0]["href"], caption=f"Pin:- {m}")

3 Source : tools.py
with GNU Affero General Public License v3.0
from TorhamDev

def get_ip():
    try:
        ip = get("https://api.ipify.org").text
    except Exception:
        return "cannot get ip"
    else:
        return(f'{ip}')
    

def get_info(bot_token,chat_id):

3 Source : networking.py
with MIT License
from trackmania-rl

    def __init__(self, min_samples_per_server_packet=1):
        self.__buffer = Buffer()
        self.__buffer_lock = Lock()
        self.__weights_lock = Lock()
        self.__weights = None
        self.__weights_id = 0  # this increments each time new weights are received
        self.samples_per_server_batch = min_samples_per_server_packet
        self.public_ip = get('http://api.ipify.org').text
        self.local_ip = socket.gethostbyname(socket.gethostname())

        print_with_timestamp(f"INFO SERVER: local IP: {self.local_ip}")
        print_with_timestamp(f"INFO SERVER: public IP: {self.public_ip}")

        Thread(target=self.__rollout_workers_thread, args=('', ), kwargs={}, daemon=True).start()
        Thread(target=self.__trainers_thread, args=('', ), kwargs={}, daemon=True).start()

    def __trainers_thread(self, ip):

3 Source : networking.py
with MIT License
from trackmania-rl

    def __init__(self, server_ip=None, model_path=cfg.MODEL_PATH_TRAINER):
        self.__buffer_lock = Lock()
        self.__weights_lock = Lock()
        self.__weights = None
        self.__buffer = Buffer()
        self.model_path = model_path
        self.public_ip = get('http://api.ipify.org').text
        self.local_ip = socket.gethostbyname(socket.gethostname())
        self.server_ip = server_ip if server_ip is not None else '127.0.0.1'
        self.recv_tiemout = cfg.RECV_TIMEOUT_TRAINER_FROM_SERVER

        print_with_timestamp(f"local IP: {self.local_ip}")
        print_with_timestamp(f"public IP: {self.public_ip}")
        print_with_timestamp(f"server IP: {self.server_ip}")

        Thread(target=self.__run_thread, args=(), kwargs={}, daemon=True).start()

    def __run_thread(self):

3 Source : google_client.py
with GNU General Public License v3.0
from turulomio

    def get_price(self):
        url = 'http://www.google.com/search?q={}'.format(self.ticker)    # fails
        web=get(url).text

        if web==None:
            print ("ERROR | FETCHED EMPTY PAGE")
            sys.exit(255)

        if web.find('font-size:157%">  <  b>')!=-1:
            try:
                web=web.split('font-size:157%"> < b>')[1]#Antes
                web=web.split(' < /span> -  < a class="fl"')[0]#Después
                self.price=Decimal(web.split(" < /b>")[0].replace(".","").replace(",","."))
            except:
                print("ERROR | COULDN'T CONVERT DATETIME {} AND PRICE {}".format(self.dtaware, self.price))
                sys.exit(0)
            return
def main():

0 Source : updater.py
with GNU General Public License v3.0
from 0xInfection

def updater():
    '''
    Function to update XSRFProbe seamlessly.
    '''
    print(GR+'Checking for updates...')
    vno = get('https://raw.githubusercontent.com/0xInfection/XSRFProbe/master/xsrfprobe/files/VersionNum').text
    print(GR+'Version on GitHub: '+color.CYAN+vno.strip())
    print(GR+'Version You Have : '+color.CYAN+__version__)
    if vno != __version__:
        print(G+'A new version of XSRFProbe is available!')
        current_path = os.getcwd().split('/') # if you know it, you know it
        folder = current_path[-1] # current directory name
        path = '/'.join(current_path) # current directory path
        choice = input(O+'Would you like to update? [Y/n] :> ').lower()
        if choice != 'n':
            print(GR+'Updating XSRFProbe...')
            os.system('git clone --quiet https://github.com/0xInfection/XSRFProbe %s' % (folder))
            os.system('cp -r %s/%s/* %s && rm -r %s/%s/ 2>/dev/null' % (path, folder, path, path, folder))
            print(G+'Update successful!')
    else:
        print(G+'XSRFProbe is up to date!')
    quit()

0 Source : shortenurl.py
with GNU General Public License v3.0
from Al-Noman-Pro

def short_url(longurl):
    if SHORTENER is None and SHORTENER_API is None:
        return longurl

    if "shorte.st" in SHORTENER:
        disable_warnings()
        link = rget(f'http://api.shorte.st/stxt/{SHORTENER_API}/{longurl}', verify=False).text
    elif "linkvertise" in SHORTENER:
        url = quote(b64encode(longurl.encode("utf-8")))
        linkvertise = [
            f"https://link-to.net/{SHORTENER_API}/{random.random() * 1000}/dynamic?r={url}",
            f"https://up-to-down.net/{SHORTENER_API}/{random.random() * 1000}/dynamic?r={url}",
            f"https://direct-link.net/{SHORTENER_API}/{random.random() * 1000}/dynamic?r={url}",
            f"https://file-link.net/{SHORTENER_API}/{random.random() * 1000}/dynamic?r={url}"]
        link = random.choice(linkvertise)
    elif "bitly.com" in SHORTENER:
        s = pyShortener(api_key=SHORTENER_API)
        link = s.bitly.short(longurl)
    elif "ouo.io" in SHORTENER:
        disable_warnings()
        link = rget(f'http://ouo.io/api/{SHORTENER_API}?s={longurl}', verify=False).text
    else:
        link = rget(f'https://{SHORTENER}/api?api={SHORTENER_API}&url={longurl}&format=text').text

    if len(link) == 0:
        LOGGER.error("Something is Wrong with the url shortener")
        return longurl
    return link

0 Source : android.py
with MIT License
from Amberyt

async def device_info(request):
    """ get android device basic info from its codename """
    textx = await request.get_reply_message()
    codename = request.pattern_match.group(1)
    if codename:
        pass
    elif textx:
        codename = textx.text
    else:
        await request.edit("`Usage: .device   <  codename> /  < model>`")
        return
    data = json.loads(
        get("https://raw.githubusercontent.com/androidtrackers/"
            "certified-android-devices/master/by_device.json").text)
    results = data.get(codename)
    if results:
        reply = f"**Search results for {codename}**:\n\n"
        for item in results:
            reply += f"**Brand**: {item['brand']}\n" \
                     f"**Name**: {item['name']}\n" \
                     f"**Model**: {item['model']}\n\n"
    else:
        reply = f"`Couldn't find info about {codename}!`\n"
    await request.edit(reply)


@borg.on(admin_cmd(outgoing=True, pattern=r"codename(?: |)([\S]*)(?: |)([\s\S]*)"))

0 Source : android.py
with MIT License
from Amberyt

async def codename_info(request):
    """ search for android codename """
    textx = await request.get_reply_message()
    brand = request.pattern_match.group(1).lower()
    device = request.pattern_match.group(2).lower()

    if brand and device:
        pass
    elif textx:
        brand = textx.text.split(' ')[0]
        device = ' '.join(textx.text.split(' ')[1:])
    else:
        await request.edit("`Usage: .codename   <  brand>  < device>`")
        return

    data = json.loads(
        get("https://raw.githubusercontent.com/androidtrackers/"
            "certified-android-devices/master/by_brand.json").text)
    devices_lower = {k.lower(): v
                     for k, v in data.items()}  # Lower brand names in JSON
    devices = devices_lower.get(brand)
    results = [
        i for i in devices if i["name"].lower() == device.lower()
        or i["model"].lower() == device.lower()
    ]
    if results:
        reply = f"**Search results for {brand} {device}**:\n\n"
        if len(results) > 8:
            results = results[:8]
        for item in results:
            reply += f"**Device**: {item['device']}\n" \
                     f"**Name**: {item['name']}\n" \
                     f"**Model**: {item['model']}\n\n"
    else:
        reply = f"`Couldn't find {device} codename!`\n"
    await request.edit(reply)


@borg.on(admin_cmd(outgoing=True, pattern=r"specs(?: |)([\S]*)(?: |)([\s\S]*)"))

0 Source : captcha.py
with GNU General Public License v3.0
from Aryza23

async def cb_handler(bot, query):
    cb_data = query.data
    if cb_data.startswith("new_"):
        chat_id = query.data.rsplit("_")[1]
        user_id = query.data.split("_")[2]
        captcha = query.data.split("_")[3]
        if query.from_user.id != int(user_id):
            await query.answer("This Message is Not For You!", show_alert=True)
            return
        if captcha == "N":
            type_ = "Number"
        elif captcha == "E":
            type_ = "Emoji"
        chk = manage_db().add_chat(int(chat_id), captcha)
        if chk == 404:
            await query.message.edit(
                "Captcha already tunned on here, use /remove to turn off"
            )
            return
        else:
            await query.message.edit(f"{type_} Captcha turned on for this chat.")
    elif cb_data.startswith("verify_"):
        chat_id = query.data.split("_")[1]
        user_id = query.data.split("_")[2]
        if query.from_user.id != int(user_id):
            await query.answer("This Message is Not For You!", show_alert=True)
            return
        chat = manage_db().chat_in_db(int(chat_id))
        print("proccesing cb data")
        if chat:
            c = chat["captcha"]
            markup = [[], [], []]
            if c == "N":
                print("proccesing number captcha")
                await query.answer("Creating captcha for you")
                data_ = get(
                    f"https://api.jigarvarma.tk/num_captcha?token={CC_API}"
                ).text
                data_ = json.loads(data_)
                _numbers = data_["answer"]["answer"]
                list_ = ["0", "1", "2", "3", "5", "6", "7", "8", "9"]
                random.shuffle(list_)
                tot = 2
                LocalDB[int(user_id)] = {
                    "answer": _numbers,
                    "list": list_,
                    "mistakes": 0,
                    "captcha": "N",
                    "total": tot,
                    "msg_id": None,
                }
                count = 0
                for i in range(3):
                    markup[0].append(
                        InlineKeyboardButton(
                            f"{list_[count]}",
                            callback_data=f"jv_{chat_id}_{user_id}_{list_[count]}",
                        )
                    )
                    count += 1
                for i in range(3):
                    markup[1].append(
                        InlineKeyboardButton(
                            f"{list_[count]}",
                            callback_data=f"jv_{chat_id}_{user_id}_{list_[count]}",
                        )
                    )
                    count += 1
                for i in range(3):
                    markup[2].append(
                        InlineKeyboardButton(
                            f"{list_[count]}",
                            callback_data=f"jv_{chat_id}_{user_id}_{list_[count]}",
                        )
                    )
                    count += 1
            elif c == "E":
                print("proccesing img captcha")
                await query.answer("Creating captcha for you")
                data_ = get(
                    f"https://api.jigarvarma.tk/img_captcha?token={CC_API}"
                ).text
                data_ = json.loads(data_)
                _numbers = data_["answer"]["answer"]
                list_ = data_["answer"]["list"]
                count = 0
                tot = 3
                for i in range(5):
                    markup[0].append(
                        InlineKeyboardButton(
                            f"{list_[count]}",
                            callback_data=f"jv_{chat_id}_{user_id}_{list_[count]}",
                        )
                    )
                    count += 1
                for i in range(5):
                    markup[1].append(
                        InlineKeyboardButton(
                            f"{list_[count]}",
                            callback_data=f"jv_{chat_id}_{user_id}_{list_[count]}",
                        )
                    )
                    count += 1
                for i in range(5):
                    markup[2].append(
                        InlineKeyboardButton(
                            f"{list_[count]}",
                            callback_data=f"jv_{chat_id}_{user_id}_{list_[count]}",
                        )
                    )
                    count += 1
                LocalDB[int(user_id)] = {
                    "answer": _numbers,
                    "list": list_,
                    "mistakes": 0,
                    "captcha": "E",
                    "total": tot,
                    "msg_id": None,
                }
            c = LocalDB[query.from_user.id]["captcha"]
            if c == "N":
                typ_ = "number"
            if c == "E":
                typ_ = "emoji"
            msg = await bot.send_photo(
                chat_id=chat_id,
                photo=data_["answer"]["captcha"],
                caption=f"{query.from_user.mention} Please click on each {typ_} button that is showen in image, {tot} mistacks are allowed.",
                reply_markup=InlineKeyboardMarkup(markup),
            )
            LocalDB[query.from_user.id]["msg_id"] = msg.message_id
            await query.message.delete()
    if cb_data.startswith("jv_"):
        chat_id = query.data.rsplit("_")[1]
        user_id = query.data.split("_")[2]
        _number = query.data.split("_")[3]
        if query.from_user.id != int(user_id):
            await query.answer("This Message is Not For You!", show_alert=True)
            return
        if query.from_user.id not in LocalDB:
            await query.answer("Try Again After Re-Join!", show_alert=True)
            return
        c = LocalDB[query.from_user.id]["captcha"]
        tot = LocalDB[query.from_user.id]["total"]
        if c == "N":
            typ_ = "number"
        if c == "E":
            typ_ = "emoji"
        if _number not in LocalDB[query.from_user.id]["answer"]:
            LocalDB[query.from_user.id]["mistakes"] += 1
            await query.answer(f"You pressed wrong {typ_}!", show_alert=True)
            n = tot - LocalDB[query.from_user.id]["mistakes"]
            if n == 0:
                await query.message.edit_caption(
                    f"{query.from_user.mention}, you failed to solve the captcha!\n\n"
                    f"You can try again after 1 minutes.",
                    reply_markup=None,
                )
                await asyncio.sleep(60)
                del LocalDB[query.from_user.id]
                return
            markup = MakeCaptchaMarkup(
                query.message["reply_markup"]["inline_keyboard"], _number, "❌"
            )
            await query.message.edit_caption(
                f"{query.from_user.mention}, select all the {typ_}s you see in the picture. "
                f"You are allowed only {n} mistakes.",
                reply_markup=InlineKeyboardMarkup(markup),
            )
        else:
            LocalDB[query.from_user.id]["answer"].remove(_number)
            markup = MakeCaptchaMarkup(
                query.message["reply_markup"]["inline_keyboard"], _number, "✅"
            )
            await query.message.edit_reply_markup(
                reply_markup=InlineKeyboardMarkup(markup)
            )
            if not LocalDB[query.from_user.id]["answer"]:
                await query.answer("You Passed🥳 the Captcha!", show_alert=True)
                del LocalDB[query.from_user.id]
                await bot.unban_chat_member(
                    chat_id=query.message.chat.id, user_id=query.from_user.id
                )
                await query.message.delete(True)
            await query.answer()
    elif cb_data.startswith("done_"):
        await query.answer("Dont click on same button again", show_alert=True)
    elif cb_data.startswith("wrong_"):
        await query.answer("Dont click on same button again", show_alert=True)

0 Source : server_linux.py
with MIT License
from Ashen-MG

    def argument_parser(self):
        parser = ArgumentParser(usage="python server.py [-options]")
        parser.add_argument("-ip", type=str, nargs="?", const=self.ip, default=self.ip, help="Set ip address.")
        parser.add_argument("-port", type=int, nargs="?", const=self.port, default=self.port, help="Set port. Default is set to 6000.")
        parser.add_argument("-get-local-ip", action="store_true", help="Find and set local ip.")
        parser.add_argument("-get-external-ip", action="store_true", help="Find and set external ip.")
        parser.add_argument("-l", "--list", action="store_true", help="Print all commands.")
        parser.add_argument("-w", "--wait", action="store_true", help="Start with wait command. Wait for connections.")
        args = parser.parse_args()

        if args.get_local_ip:
            device_name = socket.gethostname()
            print("Reading local ip from: {}".format(device_name))
            self.ip = socket.gethostbyname(device_name)

        elif args.get_external_ip:
            self.ip = r_get('https://api.ipify.org').text

        else:
            self.ip = args.ip
            self.port = args.port

        self.list = args.list
        self.wait_mode = args.wait

    # ----------------------------------------------
    # Main program methods
    # ----------------------------------------------

    # Basic startup
    def run(self):

0 Source : updater.py
with GNU General Public License v3.0
from bhavsec

def update():
    print('\n%s Checking for updates..' % run)
    latestCommit = get('https://raw.githubusercontent.com/bhavsec/reconspider/master/core/update_log.py').text

    if changes not in latestCommit:  # just a hack to see if a new version is available
        changelog = re.search(r"changes = '''(.*?)'''", latestCommit)
        changelog = changelog.group(1).split(';')  # splitting the changes to form a list
        print('\n%s A new version of ReconSpider is available.' % good)
        print('\n%s Changes:' % info)
        for change in changelog:  # print changes
            print('%s>%s %s' % (green, end, change))

        currentPath = os.getcwd().split('/')  # if you know it, you know it
        folder = currentPath[-1]  # current directory name
        path = '/'.join(currentPath)  # current directory path

        if sys.version_info[0] > 2:
            choice = input('\n%s Would you like to update? [Y/n] ' % que).lower()

        else:
            choice = raw_input('\n%s Would you like to update? [Y/n] ' % que).lower()


        if choice == 'y':
            print('\n%s Updating ReconSpider..' % run)
            os.system('git clone --quiet https://github.com/bhavsec/reconspider %s' % (folder))
            os.system('cp -r %s/%s/* %s && rm -r %s/%s/ 2>/dev/null' % (path, folder, path, path, folder))
            print('\n%s Update successful!' % good)
            sys.exit()
        else:
            print('\n%s Update Canceled!' % bad)

    else:
        print('\n%s ReconSpider is up to date!' % good)

See More Examples