コード例 #1
0
ファイル: Amelie.py プロジェクト: AmeliePick/AmelieBot
    def _doAction(self, inputType: str) -> None:
        ''' Do action based on user's request.

        This method must calling in a try block, because the it can generate exceptions.

        '''

        if self._chat.getInputType() == "Exit":
            self._exceptionStack.append(SystemExit(0))

        elif self._chat.getInputType() == "Search":
            url = "https://www.google.ru/search?q="
            webbrowser_open(url +
                            str(self._chat.stemming(self._chat.editInput())),
                            new=1)

        elif self._chat.getInputType() == "Youtube":
            url = "http://www.youtube.com/results?search_query="
            webbrowser_open(url +
                            str(self._chat.stemming(self._chat.editInput())),
                            new=1)

        # In this block can be an exception
        elif self._chat.getInputType() == "Open":
            Popen(self.getPathToProgram(self._chat.editInput()))

        return
コード例 #2
0
async def print_progress(data: SimpleNamespace):
    '''打印进度'''
    while len(data.bangumi_failed) > 0:
        bangumi = data.bangumi_failed.popleft()
        if bangumi in data.bili2bgm_map:
            if data.bili2bgm_map[bangumi][0] is not None:
                print_status(
                    f'** {data.bili2bgm_map[bangumi][1]}'
                    f'(Bilibili 编号 md{bangumi},'
                    f'Bangumi 编号 {data.bili2bgm_map[bangumi][0]})更新失败!')
            else:
                print_status(f'** {data.bili2bgm_map[bangumi][1]}'
                             f'(Bilibili 编号 md{bangumi})'
                             f'没有对应的 Bangumi 数据!')
        else:
            data.print_unknown_tasks.append(
                loop.create_task(print_unknown(data, bangumi)))
        if OPEN_FAILED_BANGUMI_BILI_PAGE:
            webbrowser_open(
                f'https://www.bilibili.com/bangumi/media/md{bangumi}/')

    bili_status = '[Bilibili %d/%d %.1f%%]' % (
        data.bili_processed_count, data.bili_total_count,
        (data.bili_processed_count) / data.bili_total_count * 100)
    bgm_status = '[Bangumi %d/%d %.1f%% (失败 %s)]' % (
        data.bangumi_processed_count, data.bangumi_total,
        data.bangumi_processed_count / data.bangumi_total * 100,
        data.bangumi_failed_count)
    print_status(
        f'{bili_status} -> {bgm_status} {"." * data.animation_points}',
        end='\r')
    data.animation_points += 1
    if data.animation_points > 3:
        data.animation_points = 1
コード例 #3
0
def prompt_for_user_token(username,
                          scope,
                          client_id,
                          client_secret,
                          redirect_uri,
                          redirect_link=None):

    sp_oauth = spotipy.SpotifyOAuth(
        client_id=client_id,
        client_secret=client_secret,
        redirect_uri=redirect_uri,
        scope=scope,
        cache_path=".cache",
    )

    cached_token = sp_oauth.get_cached_token()

    if not cached_token and redirect_link:
        code = sp_oauth.parse_response_code(redirect_link)
        shuffle_page(sp_oauth.get_access_token(code, as_dict=False))

    elif not cached_token and not redirect_link:
        webbrowser_open(sp_oauth.get_authorize_url())
        show_redirect_entry()

    else:
        shuffle_page(cached_token["access_token"])
コード例 #4
0
ファイル: auth.py プロジェクト: wopub/Bilibili2Bangumi
async def auth_bgm(app_id, app_secret):
    '''取得 Bangumi 授权'''
    code = None

    async def handler(request):
        '''Bangumi 授权请求处理器'''
        nonlocal code
        code = request.query['code']
        return web.Response(
            content_type='text/html',
            text='<!DOCTYPE html><html><body><h1 align="center">'
            'Bangumi 授权请求已接受,请关闭此页面。'
            '</h1></body></html>')

    print_debug('创建 Bangumi 授权请求处理器...')
    app = web.Application()
    app.add_routes([web.get('/', handler)])
    runner = web.AppRunner(app)
    await runner.setup()
    site = web.TCPSite(runner, 'localhost', 3000)
    await site.start()

    print_debug('打开 Bangumi 授权页面...')
    link = (
        f'https://bgm.tv/oauth/authorize?client_id={app_id}&response_type=code'
    )
    webbrowser_open(link)

    print_status('请在弹出的授权页面中点击授权。')
    print_status('若授权页面没有自动弹出,请手动复制链接至浏览器中打开:')
    print_status(f'{link}')

    print_debug('等待 Bangumi 授权请求...')
    while code is None:
        await sleep(0.001)
    await site.stop()
    await runner.shutdown()

    print_status('正在尝试取得授权...')

    print_debug('请求 Bangumi 授权码...')
    bgm_auth_data_raw = await try_for_times_async_json(  # 尝试五次
        5, lambda: client.post('https://bgm.tv/oauth/access_token',
                               data={
                                   'grant_type': 'authorization_code',
                                   'client_id': app_id,
                                   'client_secret': app_secret,
                                   'code': code,
                                   'redirect_uri': 'http://localhost:3000'
                               }))
    token = (f'{bgm_auth_data_raw["token_type"]}'
             f' {bgm_auth_data_raw["access_token"]}')
    print_debug('完成!')
    return token
コード例 #5
0
    def pretty_message(self, message):
        dt = datetime.fromtimestamp(message['time'])
        dt_str = dt.strftime('%H:%M:%S')
        self.messages.append(message['name'] + ' ' + dt_str)
        self.messages.append(message['text'])
        self.messages.append('')

        if message['text'] == 'бот пришли пёсика':
            self.messages.append('*открываю браузер*')
            self.messages.append('')
            url = get_image_url()
            webbrowser_open(url)

        self.messages.repaint()
コード例 #6
0
    def assign(self):

        base_url = "https://www.meitulu.com/item/%s.html"
        address = ''

        def get_address():
            print(
                "地址编号即网页地址结尾的*.html中的*\n举个例子:https://www.meitulu.com/item/1.html中,编号为1\n"
            )
            address = input("现在,请输入地址编号:\n")
            while True:
                if address.isdigit():
                    return address
                else:
                    address = input("输入非法,请确认后重新输入:\n")

        def make_urls(url):
            html = httpget(url)
            result = etree.HTML(html)
            title = result.xpath("/html/body/div[2]/div[1]/h1/text()")[
                0]  # 获取图集标题
            print(title)
            info_list = result.xpath(
                "/html/body/div[2]/div[2]/p/text()")  # 获取含有图片数量的列表(扩大了范围)
            for item in info_list:
                print(item)
            s = ''.join(info_list)  # 合成为一个字符串
            print(s)
            num = search(r'(?<=图片数量:).*(?=张)', s, M).group().strip()  # 提取图片数量
            photo_url = "https://mtl.gzhuibei.com/images/img/%s/" % address + "%d.jpg"  # 图片链接模板

            urls = []  # 用于储存一个图集中所有图片链接
            for i in range(int(num)):  # 生成图片链接
                urls.append(photo_url % (i + 1))

            self.titles.append(title)
            self.allurls.append(urls)

        try:
            address = get_address()
            make_urls(base_url % address)
            self.download()
            print("按地址序号下载功能added by 吾爱破解 河瞬\n原作者@吾爱破解 lihaisanhui")
            address = input("按Enter键退出...\n")
        except:
            print("本模块出现错误,请检查地址编号。如确认无误联系作者并提交需爬取的页面编号")
            c = input("是否反馈问题?(回车键退出,输入任意字符回车进入反馈页面)")
            if c != "":
                webbrowser_open(
                    "https://github.com/heshunme/Python_Work/issues")
コード例 #7
0
 def run(self):
     while True:
         choose = input('请选择操作模式[1=搜索,2=标签, 3=直接输入地址序号,4=查看帮助页]: ')
         if choose == '1':
             self.search()
             break
         elif choose == '2':
             self.tag()
             break
         elif choose == '3':  # added
             self.assign()
             exit()
         elif choose == '4':
             webbrowser_open('https://github.com/zhukeyi123/Python_Work/blob/master/mtl_spider/mtl_spider_help.md')
         else:
             print(colorama.Back.RED + '没有这个选项!')
     self.makeurls()
     self.download()
コード例 #8
0
ファイル: cli.py プロジェクト: ierror/stream-steam
    def _demo_tracking_web():
        echo.h1("Web Tracking Demo")
        serve_url = f"http://{HTTP_SERVE_ADDRESS}:{HTTP_SERVE_PORT}/"

        # create index.html
        cf_stack = CloudformationStack(cf_stack_name, cfg)
        create_demo_index_file(
            f'{cf_stack.get_output("APIGatewayEndpoint")}/matomo-event-receiver/'
        )

        # serve the demo
        echo.enum_elm(f"serving demo at {serve_url}")
        echo.enum_elm("quit the server with <strg|control>-c.")
        echo.info("")
        serve_demo()

        # open browser
        webbrowser_open(serve_url)
コード例 #9
0
    def __acessar_site_reporte(self):
        website_forms = "https://forms.gle/J4kE2Li8c58fz4hh6"

        self.__bt_report.configure(
            text=self.interface_idioma["abrir_formulario"][self.idioma])

        t = Thread(target=lambda event=None: webbrowser_open(website_forms))
        t.start()

        self.__destruir_interface()
コード例 #10
0
    def abrir_site(self, url):
        self.tp_atualizacao.destroy()

        th = Thread(target=lambda url=url: webbrowser_open(url))
        th.start()
コード例 #11
0
ファイル: scanner.py プロジェクト: firebitsbr/PhantomScanner
def main():

    # Get file hash
    def getFilemd5(filename):
        hash_md5 = md5()
        with open(filename, "rb") as f:
            for chunk in iter(lambda: f.read(4096), b""):
                hash_md5.update(chunk)
        return hash_md5.hexdigest()

    # Select file
    file = input(Fore.CYAN + ' >>> Select file: ' + Fore.RESET)
    if not path.exists(file):
        exit(Fore.RED + "[!] File " + path.basename(file) + " not found!" +
             Fore.RESET)
    else:
        file_md5 = getFilemd5(file)

    # Get VirusTotal results
    virustotal = json_loads(
        request.urlopen('https://www.virustotal.com/ui/search?query=' +
                        file_md5).read())

    # Show scanners results in table
    try:
        detection = virustotal['data'][0]['attributes'][
            'last_analysis_results']
    except IndexError:
        print(Fore.YELLOW + "[!] File " + path.basename(file) +
              " has never been uploaded to VirusTotal" + Fore.RESET)
        if input(Fore.BLUE +
                 '[?] Open VirusTotal to upload file? (y/n)\n ---> ' +
                 Fore.RESET).lower() in ('y', 'yes'):
            webbrowser_open('https://www.virustotal.com/gui/home/upload')
        exit()
    else:
        table_data = [['Scanner', 'Category']]
        for res in detection:
            engine = detection[res]['engine_name']
            category = detection[res]['category']

            # Change color if file malicious
            if category.lower() == "undetected":
                category = Fore.GREEN + category
            else:
                category = Fore.RED + category

            category += Fore.RESET
            # Add to table
            table_data.append([engine, category])

        # Table
        table = AsciiTable(table_data)
        print(table.table)

        # Show stats
        detection = virustotal['data'][0]['attributes']['last_analysis_stats']
        print("\n>> STATS:"
              "\n   Malicious   : " + str(detection['malicious']) +
              "\n   Suspicious  : " + str(detection['suspicious']) +
              "\n   Harmless    : " + str(detection['harmless']) +
              "\n   Undetected  : " + str(detection['undetected']))

        # Open full report?
        if virustotal['data']:
            if input(Fore.YELLOW +
                     '[?] Open full VirusTotal report? (y/n)\n ---> ' +
                     Fore.RESET).lower() in ('y', 'yes'):
                webbrowser_open('https://www.virustotal.com/gui/file/' +
                                file_md5 + '/detection')
コード例 #12
0
 def show_trailer(self):
     webbrowser_open(self.trailer)
コード例 #13
0
 def callback(url):
     webbrowser_open(url)