示例#1
0
    def discord_proxy_image_localfile(cls, filepath, retry=True):
        data = None
        webhook_url = webhook_list[random.randint(0, len(webhook_list) - 1)]

        try:
            webhook = DiscordWebhook(url=webhook_url, content='')
            import io
            with open(filepath, 'rb') as fh:
                byteio = io.BytesIO(fh.read())
            webhook.add_file(file=byteio.getvalue(), filename='image.jpg')
            embed = DiscordEmbed()
            embed.set_image(url="attachment://image.jpg")
            response = webhook.execute()
            data = None
            if type(response) == type([]):
                if len(response) > 0:
                    data = response[0].json()
            else:
                data = response.json()

            if data is not None and 'attachments' in data:
                target = data['attachments'][0]['url']
                if requests.get(target).status_code == 200:
                    return target
            if retry:
                time.sleep(1)
                return cls.discord_proxy_image_localfile(filepath, retry=False)
        except Exception as exception:
            logger.error('Exception:%s', exception)
            logger.error(traceback.format_exc())

            if retry:
                time.sleep(1)
                return cls.discord_proxy_image_localfile(filepath, retry=False)
示例#2
0
    def discord_proxy_image_bytes(cls, bytes, retry=True):
        data = None
        idx = random.randint(0, len(webhook_list) - 1)
        webhook_url = webhook_list[idx]
        try:
            webhook = DiscordWebhook(url=webhook_url, content='')
            webhook.add_file(file=bytes, filename='image.jpg')
            embed = DiscordEmbed()
            embed.set_image(url="attachment://image.jpg")
            response = webhook.execute()
            data = None
            if type(response) == type([]):
                if len(response) > 0:
                    data = response[0].json()
            else:
                data = response.json()
            if data is not None and 'attachments' in data:
                target = data['attachments'][0]['url']
                if requests.get(target).status_code == 200:
                    return target
            logger.error(f"discord webhook error : {webhook_url}")
            logger.error(f"discord webhook error : {idx}")
            if retry:
                time.sleep(1)
                return cls.discord_proxy_image_bytes(bytes, retry=False)
        except Exception as exception:
            logger.error('Exception:%s', exception)
            logger.error(traceback.format_exc())

            if retry:
                time.sleep(1)
                return cls.discord_proxy_image_bytes(bytes, retry=False)
示例#3
0
def send_webhook(
    url: str,
    content: Optional[Union[str, DiscordEmbed]] = None,
    images: List[str] = None,
):
    """Send a Discord webhook.

    :param url:
    :type url: str
    :param content:
    :type content: Optional[Union[str, DiscordEmbed]]
    :param images:
    :type images: List[str]
    """
    images = images or []
    webhook = DiscordWebhook(url)

    if isinstance(content, str):
        webhook.set_content(content[:1900])
    elif isinstance(content, DiscordEmbed):
        webhook.add_embed(content)

    for image in images:
        with open(image, "rb") as f:
            webhook.add_file(file=f.read(), filename=os.path.basename(image))

    webhook.execute()
示例#4
0
def end():
    results = []
    for check in combos.results.keys():
        string = check + ": " + str(len(combos.results[check]))
        results.append(string)
    results = "\n".join(results)
    combo_amount = len(combos.raw)
    proxy_amount = str(proxies.working_count)

    webhook = DiscordWebhook(url=settings.events.discord_webhook_url)
    embed = DiscordEmbed(title='Checkolotl Finished', color=13369344)
    embed.set_footer(text='Checkolotl by scorpion3013')
    embed.set_timestamp()
    embed.add_embed_field(name='Combos:', value=combo_amount)
    embed.add_embed_field(name='Proxies:', value=proxy_amount)
    embed.add_embed_field(name='Server Timestamp:',
                          value=str(datetime.now()),
                          inline=False)
    embed.add_embed_field(name='Results:', value=results)
    webhook.add_embed(embed)
    webhook.execute()

    if settings.events.on_end.discord.post_results:
        webhook = DiscordWebhook(url=settings.events.discord_webhook_url)
        existing = False
        for (dirpath, dirnames, filenames) in walk(settings.paths.save):
            for filename in filenames:
                existing = True
                with open(settings.paths.save + "/" + filename, "rb") as f:
                    webhook.add_file(file=f.read(), filename=f'{filename}')
        if existing:
            webhook.execute()
示例#5
0
文件: post.py 项目: Vitor-Tx/kinobot
def notify_discord(movie_dict, image_list, comment_dict=None, nsfw=False):
    """
    :param movie_dict: movie dictionary
    :param image_list: list of jpg image paths
    :param comment_dict: comment dictionary
    :param nsfw: notify NSFW
    """
    logger.info(f"Sending notification to Botmin (nsfw: {nsfw})")

    movie = f"{movie_dict.get('title')} ({movie_dict.get('year')})"
    if nsfw:
        message = (
            f"Possible NSFW content found for {movie}. ID: "
            f"{comment_dict.get('id')}; user: {comment_dict.get('user')};")
    else:
        message = f"Query finished for {comment_dict.get('comment')}"

    webhook = DiscordWebhook(
        url=DISCORD_WEBHOOK_TEST if nsfw else DISCORD_WEBHOOK, content=message)

    for image in image_list:
        try:
            with open(image, "rb") as f:
                webhook.add_file(file=f.read(), filename=image.split("/")[-1])
        except:  # noqa
            pass
    try:
        webhook.execute()
    except Exception as error:
        logger.error(error, exc_info=True)
示例#6
0
def start():
    checkers = []
    for check in config["checkers"].keys():
        string = check
        if config["checkers"][check]["enabled"]:
            string = "✅ " + string
        else:
            string = "❌ " + string
        checkers.append(string)
    checkers = "\n".join(checkers)
    combo_amount = len(combos.raw)
    proxy_amount = len(proxies.raw)
    webhook = DiscordWebhook(url=settings.events.discord_webhook_url)
    embed = DiscordEmbed(title='Checkolotl Started', color=0x06bd22)
    embed.set_footer(text='Checkolotl by scorpion3013')
    embed.set_timestamp()
    embed.add_embed_field(name='Combos:', value=combo_amount)
    embed.add_embed_field(name='Proxies:', value=proxy_amount)
    embed.add_embed_field(name='Server Timestamp:',
                          value=str(datetime.now()),
                          inline=False)
    embed.add_embed_field(name='Checkers:', value=checkers)
    webhook.add_embed(embed)
    webhook.execute()

    if settings.events.on_start.discord.post_combos:
        webhook = DiscordWebhook(url=settings.events.discord_webhook_url)
        with open(settings.paths.combos, "rb") as f:
            webhook.add_file(file=f.read(), filename='combos.txt')
        webhook.execute()
示例#7
0
def send_file(root, name):  # sends files via the discord webhook
    webhook = DiscordWebhook(url=webhook_url)

    with open(os.path.join(root, name), "rb") as f:  # embeds file in webhook
        webhook.add_file(file=f.read(), filename=name)

    response = webhook.execute()
示例#8
0
class DiscordSensor:
    def __init__(
        self,
        sensorname,
        avatar="",
        url='https://discordapp.com/api/webhooks/708640113269276703'
        '/RtDV1ZoPKwi440NXYvQkTGUQc0wIg9UVMDJ2UrWRHXQvsEPvGDh2bX31pK4LzGoZ1Drg'
    ):
        self.webhook = DiscordWebhook(url,
                                      username=sensorname,
                                      avatar_url=avatar)
        self.embed = None

    def addFile(self, fileLocation):
        with open(fileLocation, "rb") as f:
            self.webhook.add_file(file=f.read(), filename=fileLocation)

    def addContent(self, messageIn):
        self.webhook.content = messageIn

    def addEmbed(self, embedTitle, embedMessage):
        # leave this out if you dont want an embed
        # for all params, see https://discordapp.com/developers/docs/resources/channel#embed-object
        self.embed = DiscordEmbed(title=embedTitle,
                                  description=embedMessage,
                                  color=242424)
        self.webhook.add_embed(self.embed)

    def postMessage(self):
        response = self.webhook.execute()
示例#9
0
def send_webhook(
    url: str,
    content: Optional[Union[str, DiscordEmbed]] = None,
    images: List[str] = None,
):
    """Send a Discord webhook.

    :param url:
    :type url: str
    :param content:
    :type content: Optional[Union[str, DiscordEmbed]]
    :param images:
    :type images: List[str]
    """
    if TEST is True:
        logger.debug("Testing mode. Not sending webhook: %s", content)
        return None

    images = images or []
    profile = random.choice(WEBHOOK_PROFILES)
    webhook = DiscordWebhook(url, **profile)

    if isinstance(content, str):
        webhook.set_content(content[:1900])
    elif isinstance(content, DiscordEmbed):
        webhook.add_embed(content)

    for image in images:
        with open(image, "rb") as f:
            webhook.add_file(file=f.read(), filename=os.path.basename(image))

    webhook.execute()

    return None
示例#10
0
def send_discord_webhook(config):
    webhook = DiscordWebhook(url=config["URL"], username=config["USERNAME"])
    with open(filename, "rb") as f:
        webhook.add_file(file=f.read(),
                         filename="Dilbert_" +
                         date.today().strftime('%d_%m_%Y') + ".gif")
    webhook.execute()
示例#11
0
def send_webhook_message(application, action):
    message_to_send = format_message(application, action)
    webhook = DiscordWebhook(url=DISCORD_WEBHOOK_URL, content=message_to_send)

    if ATTACH_LOGS:
        application_logs = lookup_application_logs(application)
        syslogs = lookup_application_logs('Server')

        if application_logs is not False:
            with open(application_logs, "rb+") as f:
                filename = application + '.txt'
                webhook.add_file(file=f.read(), filename=filename)

        if syslogs is not False:
            with open(syslogs, "rb+") as f:
                filename = syslogs + '.txt'
                webhook.add_file(file=f.read(), filename=filename)

    if EMBED_LOGS:
        application_logs = lookup_application_logs(application)
        syslogs = lookup_application_logs('Server')

        if application_logs is not False:
            embed = DiscordEmbed(title=application,
                                 description=tail(application_logs, 10))
            webhook.add_embed(embed)

        if syslogs is not False:
            embed = DiscordEmbed(title='/var/log/syslog',
                                 description=tail(syslogs, 10))
            webhook.add_embed(embed)

    webhook.execute()
示例#12
0
 def send_file_to_url(self, url, file_to_be_sent, file_name = None, content = None):
     """
     Sending provided file to a provided URL, with optional file_name and content
     """
     if content is not None and isinstance(content, str):
         hook = DiscordWebhook(url, content=content)
     else:
         hook = DiscordWebhook(url)
     if file_name is None:
         if isabs(file_to_be_sent):
             # For windows machines
             if '\\' in file_to_be_sent:
                 file_name = file_to_be_sent.split("\\")[-1]
             elif "/" in file_to_be_sent:
                 file_name = file_to_be_sent.split("/")[-1]
         else:
             file_name = file_to_be_sent
     if isfile(file_to_be_sent):
         with open(file_to_be_sent, "rb") as f:
             hook.add_file(file=f.read(), filename=file_name)
     else:
         print("Invalid filepath")
     resp = hook.execute()
     if resp[0].status_code == 200:
         print("Successfully sent!")
         return resp[0]
示例#13
0
def sendwebhook(url):
    webhook = DiscordWebhook(
        url=url,
        content=
        '.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n.'
    )
    with open("screen.png", "rb") as f:
        webhook.add_file(file=f.read(), filename='screen.png')
    response = webhook.execute()
示例#14
0
 def post_webhooks(result: dict, webhooks: str, options: dict):
     files = result.pop('files', [])
     options.update(result)
     hook = DiscordWebhook(
         webhooks,
         **options,
     )
     for file in files:
         hook.add_file(file=file.get('file'), filename=file.get('name'))
     hook.execute()
示例#15
0
def push(content, webhook, options={}, files=[]):
    if isinstance(content, str):
        content = [content]
    webhook = DiscordWebhook(url=webhook)
    webhook.avatar_url = options.get('avatar_url')
    webhook.username = options.get('username')
    for file in files:
        webhook.add_file(file=file['data'], filename=file['name'])
    for msg in content:
        webhook.content = msg
        webhook.execute()
示例#16
0
def hook():
    """Делает скриншот половины экрана. Сохраняет в файл. Файл отправляет в Discord."""

    # Делаем скриншот, сохраняем.
    im = grab(bbox=(0, 0, 960, 1080))
    im.save('box.png')
    # Читаем файл и отправляем.
    webhook = DiscordWebhook(url=URL)
    with open('box.png', 'rb') as f:
        webhook.add_file(file=f.read(), filename='example.jpg')

    return webhook.execute()
示例#17
0
def send_files_to_discord(file_path):
    notification = Notification.objects.all()
    if notification and notification[0].send_to_discord \
    and notification[0].discord_hook_url:
        webhook = DiscordWebhook(url=notification[0].discord_hook_url,
                                 rate_limit_retry=True,
                                 username="******")
        with open(file_path, "rb") as f:
            head, tail = os.path.split(file_path)
            webhook.add_file(file=f.read(), filename=tail)
        thread = Thread(target=webhook.execute)
        thread.start()
示例#18
0
def main(id, password, disname):
    # Headless Firefoxを起動させて休講情報のページへ移動
    options = Options()
    options.add_argument('-headless')
    browser = Firefox(executable_path='geckodriver',
                      options=options)  # Firefoxを起動
    browser.set_window_size(1080, 1080)  # ウィンドウサイズを調整
    # wait = WebDriverWait(browser, timeout=10)
    # print(id, password)

    # Campus Squareにログインする
    browser.get('http://www.comp.tmu.ac.jp/portal/')
    browser.find_element_by_name("HPB_ROLLOVER1").click()
    browser.find_element_by_id("username").send_keys(id)  # ID
    browser.find_element_by_id("password").send_keys(password)  # Password
    browser.find_element_by_css_selector('button[type="submit"]').click()

    # 休憩
    time.sleep(3)

    # 休講情報のページに飛ぶ
    browser.find_element_by_css_selector(
        'ul[class="link_item"] > li:nth-of-type(4) > span > a').click()

    # 休憩
    time.sleep(0.5)

    # 既読も表示するようにする
    browser.find_element_by_css_selector(
        'div[class="accordion"] > ul > li > a').click()
    browser.find_element_by_id("chkEtrdFlg_1").click()
    browser.find_element_by_css_selector(
        'p[class="action"] > input:nth-of-type(2)').click()

    time.sleep(0.5)

    # スクリーンショットを撮る
    browser.save_screenshot("paper.png")

    # WebhookのURLを取得しゴミを排除する
    URL = database.searchurl(disname)
    URL = URL[2:]
    URL = URL[:-3]
    print(URL)
    # URL = gosh.requestsURL()
    webhook = DiscordWebhook(url=URL, username='******')

    # 写真を送る
    with open("./paper.png", "rb") as f:
        webhook.add_file(file=f.read(), filename='example.jpg')

    webhook.execute()
示例#19
0
 def process(self, event):
     time.sleep(1)
     _, filename = os.path.split(event.src_path)
     with open(event.src_path, "rb") as f:
         webhook = DiscordWebhook(url=Main.data['webhook'])
         webhook.add_file(file=f.read(), filename=filename)
         embed = DiscordEmbed(title="Capture d'écran de " +
                              Main.data['playername'],
                              description=filename,
                              color=242424)
         embed.set_thumbnail(url='attachment://' + filename)
         webhook.add_embed(embed)
         webhook.execute()
示例#20
0
        def btn_send():
            message_content = self.ui.send_content_ph.toPlainText()
            message_file = self.ui.send_attachment_ph.text()
            embed_title = self.ui.send_title_ph.text()
            embed_url = self.ui.send_url_ph.text()
            embed_author = self.ui.send_author_ph.text()
            embed_author_icon = self.ui.send_author_icon_ph.text()
            embed_author_url = self.ui.send_author_url_ph.text()
            embed_image = self.ui.send_image_ph.text()
            embed_thumbnail = self.ui.send_thumbnail_ph.text()
            embed_footer = self.ui.send_footer_ph.text()
            embed_footer_icon = self.ui.send_footer_icon_ph.text()
            embed_timestamp = self.ui.send_timestamp_cb.isChecked()
            embed_color = self.ui.send_color_ph.text()
            if embed_color != "":
                e_color = int(embed_color, 16)
            else:
                e_color = 000000
            embed_desc = self.ui.send_desc_ph.toPlainText()
            wh_u = self.ui.wh_url_ph.text()
            wh_n = self.ui.wh_un_ph.text()
            wh_a = self.ui.wh_avatar_ph.text()
            try:
                webhook = DiscordWebhook(url=wh_u,
                                         username=wh_n,
                                         avatar_url=wh_a,
                                         content=message_content)
                embed = DiscordEmbed(title=embed_title,
                                     description=embed_desc,
                                     color=e_color,
                                     url=embed_url)
                embed.set_author(name=embed_author,
                                 url=embed_author_url,
                                 icon_url=embed_author_icon)
                embed.set_image(url=embed_image)
                embed.set_thumbnail(url=embed_thumbnail)
                embed.set_footer(text=embed_footer, icon_url=embed_footer_icon)
                if embed_timestamp == True:
                    embed.set_timestamp()
                if embed_title != "" or embed_url != "" or embed_author != "" or embed_author_icon != "" or embed_author_url != "" or embed_image != "" or embed_thumbnail != "" or embed_footer != "" or embed_footer_icon != "" or embed_timestamp == True or embed_color != "" or embed_desc != "":
                    webhook.add_embed(embed)
                if message_file != "":
                    with open(message_file, "rb") as f:
                        webhook.add_file(file=f.read(),
                                         filename=attachment_file_name)

                global sent_webhook
                sent_webhook = webhook.execute()
            except:
                show_error()
示例#21
0
def sendDis(message, config, file_name=None, role_id=None):
    import requests
    from discord_webhook import DiscordWebhook
    if role_id != None:
        message += f" <@&{role_id}>"
    webhook = DiscordWebhook(url=config.get('DISCORD', 'URL'),
                             content=message[0:1999],
                             username=config.get('DISCORD', 'USERNAME'))
    if file_name != None:
        with open(file_name, "rb") as f:
            webhook.add_file(file=f.read(), filename=file_name)
    try:
        webhook.execute()
    except requests.exceptions.RequestException:
        pass
示例#22
0
文件: discord.py 项目: soju6jan/SJVA3
    def discord_proxy_image(cls, image_url, webhook_url=None, retry=True):
        #2020-12-23
        #image_url = None
        if image_url == '' or image_url is None:
            return
        data = None

        if webhook_url is None or webhook_url == '':
            webhook_url = webhook_list[random.randint(10,
                                                      len(webhook_list) -
                                                      1)]  # sjva 채널

        try:
            from framework import py_urllib
            webhook = DiscordWebhook(url=webhook_url, content='')
            embed = DiscordEmbed()
            embed.set_timestamp()
            embed.set_image(url=image_url)
            webhook.add_embed(embed)
            import io
            byteio = io.BytesIO()
            webhook.add_file(file=byteio.getvalue(), filename='dummy')
            response = webhook.execute()
            data = None
            if type(response) == type([]):
                if len(response) > 0:
                    data = response[0].json()
            else:
                data = response.json()

            if data is not None and 'embeds' in data:
                target = data['embeds'][0]['image']['proxy_url']
                if requests.get(target).status_code == 200:
                    return target
                else:
                    return image_url
            else:
                raise Exception(str(data))
        except Exception as exception:
            logger.error('Exception:%s', exception)
            logger.error(traceback.format_exc())
            if retry:
                time.sleep(1)
                return cls.discord_proxy_image(image_url,
                                               webhook_url=None,
                                               retry=False)
            else:
                return image_url
示例#23
0
def hook(content, name, files=[], username=None, avatar_url=None):
    if current_app.debug:
        name = 'debug'
    if isinstance(content, str):
        content = [content]
    links = webhooks.get(name)
    if isinstance(links, str):
        links = [links]
    for link in links:
        webhook = DiscordWebhook(link)
        webhook.username = username
        webhook.avatar_url = avatar_url
        for file in files:
            webhook.add_file(file=file['data'], filename=file['name'])
        for msg in content:
            webhook.content = msg
            webhook.execute()
示例#24
0
async def send_msg(msg, force_notify=False, file=None):
    try:
        webhook_url = os.getenv("DISCORD_WEBHOOK_URL")
        webhook_mention_user_id = os.getenv("DISCORD_MENTION_USER_ID")
        webhook_mention_role_id = os.getenv("DISCORD_MENTION_ROLE_ID")
        webhook = DiscordWebhook(url=webhook_url, rate_limit_retry=True)

        # Add the portal name.
        msg = "**{}**: {}".format(os.getenv("SKYNET_SERVER_API"), msg)

        if file and isinstance(file, str):
            is_json = is_json_string(file)
            content_type = "application/json" if is_json else "text/plain"
            ext = "json" if is_json else "txt"
            filename = "{}-{}.{}".format(
                CONTAINER_NAME,
                datetime.utcnow().strftime("%Y-%m-%d-%H:%M:%S"), ext)
            skylink = upload_to_skynet(file,
                                       filename,
                                       content_type=content_type)
            if skylink:
                msg = "{} {}".format(msg, skylink)  # append skylink to message
            else:
                webhook.add_file(file=io.BytesIO(file.encode()),
                                 filename=filename)

        if force_notify and (webhook_mention_user_id
                             or webhook_mention_role_id):
            webhook.allowed_mentions = {
                "users": [webhook_mention_user_id],
                "roles": [webhook_mention_role_id],
            }
            msg = "{} /cc".format(msg)  # separate message from mentions
            if webhook_mention_role_id:
                msg = "{} <@&{}>".format(msg, webhook_mention_role_id)
            if webhook_mention_user_id:
                msg = "{} <@{}>".format(msg, webhook_mention_user_id)

        webhook.content = msg
        webhook.execute()

        print("msg > " +
              msg)  # print message to std output for debugging purposes
    except:
        print("Failed to send message!")
        print(traceback.format_exc())
示例#25
0
    def post(self, message, attachment, data):

        webhook = DiscordWebhook(url=self.urls, username=self.username, avatar_url=self.avatar)
        embed = DiscordEmbed(title=message, color=self.side_bar)
        embed.set_footer(text='3DM-Octorant _beta 0.3.1_', icon_url="https://cdn.discordapp.com/emojis/673897582375993365.png")
        embed.set_timestamp()

        for k in data:
            if data[k] is not None:
                embed.add_embed_field(name=format(k), value=format(data[k]))

        if attachment is not None:
            webhook.add_file(file=attachment["file"][1], filename="0.png")
            embed.set_image(url='attachment://0.png')

        webhook.add_embed(embed)
        webhook.execute()
    
        return True
示例#26
0
def input_subtitle(subPath):
    filename = os.path.split(subPath)[1]

    search_name_for_myanime = myanime_search(filename)
    try:
        img = search_name_for_myanime['categories'][0]['items'][0]['image_url']
    except:
        img = ""

    info = find_suitable_torrents(os.path.splitext(filename)[0])
    if filename.count('720') > 0:
        info += find_suitable_torrents(
            os.path.splitext(filename.replace('720', '1080'))[0])
    if len(info) == 0:
        return False
    webhook = DiscordWebhook(
        url='',  ############################################ 웹훅
        username='******')
    description = ""
    for item in info:
        n_magnet = item['magnet']
        n_magnet = n_magnet[:n_magnet.find('&')]
        description = description + "\n\ntitle : %s \n size : %s \n date : %s \n S,L,D : %s , %s , %s \n magnet : %s" % (
            item['title'].strip(), item['size'], item['date'], item['seeder'],
            item['leecher'], item['downloaded'], n_magnet)
    #embed = DiscordEmbed(title=filename)
    try:
        rec_title = search_name_for_myanime['categories'][0]['items'][0][
            'name']
    except:
        rec_title = os.path.splitext(filename)[0]
    embed = DiscordEmbed(title=rec_title)
    #embed.set_author(name='Author Name', url='author url', icon_url='author icon url')
    embed.set_image(url=img)
    embed.set_footer(text=description.strip())
    with open(subPath, "rb") as f:
        filename = os.path.split(subPath)[1]
        webhook.add_file(file=f.read(), filename=filename)
        webhook.add_embed(embed)
    response = webhook.execute()
    pass
示例#27
0
文件: discord.py 项目: soju6jan/SJVA3
    def discord_cdn(cls,
                    byteio=None,
                    filepath=None,
                    filename=None,
                    webhook_url=None,
                    content='',
                    retry=True):
        data = None
        if webhook_url is None:
            webhook_url = webhook_list[random.randint(0, 9)]  # sjva 채널

        try:
            from discord_webhook import DiscordWebhook, DiscordEmbed
            webhook = DiscordWebhook(url=webhook_url, content=content)
            if byteio is None and filepath is not None:
                import io
                with open(filepath, 'rb') as fh:
                    byteio = io.BytesIO(fh.read())

            webhook.add_file(file=byteio.getvalue(), filename=filename)
            embed = DiscordEmbed()
            response = webhook.execute()
            data = None
            if type(response) == type([]):
                if len(response) > 0:
                    data = response[0].json()
            else:
                data = response.json()

            if data is not None and 'attachments' in data:
                target = data['attachments'][0]['url']
                if requests.get(target).status_code == 200:
                    return target
        except Exception as exception:
            logger.error('Exception:%s', exception)
            logger.error(traceback.format_exc())
            if retry:
                time.sleep(1)
                return cls.discord_proxy_image_localfile(filepath, retry=False)
def screenshot(srm_opt):
    hook = 'https://discordapp.com/api/webhooks/745098847881265303/QJRM5MbF7fHAuidNelyK4HsJUveTDhusqqt8OjvKMyFxjw17kJoq7x9VLzvSBHdGNzLz'

    #take screenshot and save to running directory

    screenshot = pyautogui.screenshot()
    screenshot.save("screen.png")

    #upload screenshot to discord webhook

    webhook = DiscordWebhook(url=hook)

    with open("screen.png", "rb") as f:
        webhook.add_file(file=f.read(), filename='screen.png')

    response = webhook.execute()

    f.close()

#option to remove file

    if srm_opt == True:
        srm.srm('screen.png')
示例#29
0
select2 = app.find_element_by_xpath('//*[@id="rspns02"]')
select2.click()

select3 = app.find_element_by_xpath('//*[@id="rspns070"]')
select3.click()

select4 = app.find_element_by_xpath('//*[@id="rspns080"]')
select4.click()

select5 = app.find_element_by_xpath('//*[@id="rspns090"]')
select5.click()

time.sleep(3)
select6 = app.find_element_by_xpath('//*[@id="btnConfirm"]')
select6.click()

is_complete = app.get_screenshot_as_file("ok.png")
if is_complete:
    with open("ok.png", "rb") as f:
        webhook.add_file(file=f.read(), filename='self-diagnosis.png')
    embed = DiscordEmbed(title='Auto Self-diagnosis',
                         description='교육부 코로나19 자가진단 자동화 System',
                         color=242424)
    embed.set_image(url="attachment://self-diagnosis.png")
    webhook.add_embed(embed)
    response = webhook.execute()

print("Complete!")
time.sleep(2)
app.close()
示例#30
0
    def __get_download_list(html, tree, site_instance, item):
        download_list = []
        try:
            if 'DOWNLOAD_REGEX' not in site_instance.info:
                return download_list
            #logger.debug(html)
            #tmp = html.find('a href="https://www.rgtorrent.me/bbs/download.php')
            #if tmp != -1:
            #    logger.debug(html[tmp-300:tmp+300])
            #logger.debug(site_instance.info['DOWNLOAD_REGEX'])
            tmp = re.compile(site_instance.info['DOWNLOAD_REGEX'],
                             re.MULTILINE).finditer(html)
            for t in tmp:
                #logger.debug(t.group('url'))
                #logger.debug(t.group('filename'))
                if t.group('filename').strip() == '':
                    continue
                entity = {}
                entity['link'] = py_urllib.unquote(
                    t.group('url').strip()).strip()
                entity['link'] = unescape(entity['link'])
                logger.debug(entity['link'])
                entity['filename'] = py_urllib.unquote(
                    t.group('filename').strip())
                entity['filename'] = unescape(entity['filename'])
                if 'DOWNLOAD_URL_SUB' in site_instance.info:
                    logger.debug(entity['link'])
                    entity['link'] = re.sub(
                        site_instance.info['DOWNLOAD_URL_SUB'][0],
                        site_instance.info['DOWNLOAD_URL_SUB'][1].format(
                            URL=site_instance.info['TORRENT_SITE_URL']),
                        entity['link']).strip()
                if not entity['link'].startswith('http'):
                    form = '%s%s' if entity['link'].startswith(
                        '/') else '%s/%s'
                    entity['link'] = form % (
                        site_instance.info['TORRENT_SITE_URL'], entity['link'])
                if 'FILENAME_SUB' in site_instance.info:
                    entity['filename'] = re.sub(
                        site_instance.info['FILENAME_SUB'][0],
                        site_instance.info['FILENAME_SUB'][1],
                        entity['filename']).strip()
                exist = False
                for tt in download_list:
                    if tt['link'] == entity['link']:
                        exist = True
                        break
                if not exist:
                    if app.config['config']['is_sjva_server'] and len(
                            item['magnet']) > 0:  # or True:
                        try:
                            ext = os.path.splitext(
                                entity['filename'])[1].lower()
                            #item['magnet']
                            if ext in ['.smi', '.srt', '.ass']:
                                #if True:
                                import io
                                if 'USE_SELENIUM' in site_instance.info[
                                        'EXTRA']:
                                    from system import SystemLogicSelenium
                                    driver = SystemLogicSelenium.get_driver()
                                    driver.get(entity['link'])
                                    import time
                                    time.sleep(10)
                                    files = SystemLogicSelenium.get_downloaded_files(
                                    )
                                    logger.debug(files)
                                    # 파일확인
                                    filename_no_ext = os.path.splitext(
                                        entity['filename'].split('/')[-1])
                                    file_index = 0
                                    for idx, value in enumerate(files):
                                        if value.find(
                                                filename_no_ext[0]) != -1:
                                            file_index = idx
                                            break
                                    logger.debug('fileindex : %s', file_index)
                                    content = SystemLogicSelenium.get_file_content(
                                        files[file_index])

                                    byteio = io.BytesIO()
                                    byteio.write(content)
                                else:
                                    data = LogicFromSite.get_html(
                                        entity['link'],
                                        referer=item['url'],
                                        stream=True)
                                    byteio = io.BytesIO()
                                    for chunk in data.iter_content(1024):
                                        byteio.write(chunk)
                                from discord_webhook import DiscordWebhook, DiscordEmbed
                                webhook_url = app.config['config'][
                                    'rss_subtitle_webhook']
                                text = '%s\n<%s>' % (item['title'],
                                                     item['url'])
                                webhook = DiscordWebhook(url=webhook_url,
                                                         content=text)
                                webhook.add_file(file=byteio.getvalue(),
                                                 filename=entity['filename'])
                                response = webhook.execute()
                                discord = response.json()
                                logger.debug(discord)
                                if 'attachments' in discord:
                                    entity['direct_url'] = discord[
                                        'attachments'][0]['url']
                        except Exception as e:
                            logger.debug('Exception:%s', e)
                            logger.debug(traceback.format_exc())
                    download_list.append(entity)
            return download_list

        except Exception as e:
            logger.debug('Exception:%s', e)
            logger.debug(traceback.format_exc())
        return download_list