Example #1
0
def start(update, context):
    if is_public_chat(update, context):
        remove_command(context, update)
        bot_hello = context.bot.send_message(
            chat_id=update.effective_message.chat.id,
            text=messages.msg_start,
            parse_mode=ParseMode.HTML)

        cleaner(context, bot_hello)
    else:
        username = update.message.from_user.first_name
        chat_id = update.effective_message.chat.id
        try:
            LOGGER.info(f'Subscription token message {update.message.text}')
            telegram_unique_token = update.message.text.split('/start ')[1]
            params = {
                'telegram_unique_token': telegram_unique_token,
                'chat_id': chat_id
            }
            x = requests.post(EXCHANGE_URL, data=params)
            LOGGER.info(f'Subscription response {x.status_code} {x.text}')
            if x.status_code == 200:
                message = messages.msg_subscribe.format(username, chat_id)
                context.bot.send_message(chat_id, message, parse_mode=ParseMode.HTML)
            else:
                message = messages.msg_subscribe_error
                context.bot.send_message(chat_id, message, parse_mode=ParseMode.HTML)
        except Exception as e:
            message = messages.msg_default_start.format(username)
            context.bot.send_message(chat_id, message, parse_mode=ParseMode.HTML)
            LOGGER.warning(f'<start> Exception Occured: {str(e)}')
Example #2
0
def handleTraceback(object):
    context = object.context
    entry_url = object.entry_url

    if entry_url is None:
        return

    LOGGER.info("handle traceback [%s]" % entry_url)
    try:
        cleanup_lock.acquire()
        # we don't want to produce any errors here, thus, we'll be nice and die
        # silently if an error occurs here
        try:
            transaction.begin()
            # get our logbook view to use the api
            logbook = context.unrestrictedTraverse('@@logbook')
            # get the generated error url from Products.SiteErrorLog
            err_id = urllib.splitvalue(entry_url)[1]
            # save error
            logbook.save_error(err_id, context=aq_parent(context))
            transaction.get().note('collective.logbook traceback [%s]' %
                    entry_url)
            transaction.commit()
        finally:
            cleanup_lock.release()
    # only warning
    except Exception, e:
        LOGGER.warning("An error occured while handling the traceback")
        LOGGER.warning("%s" % e)
        LOGGER.exception(e)
Example #3
0
def translate(context, update):
    if AUTO_TRANSLATE is True:
        # Checks if Language is English, if Confident it isn't Translate & Reply
        msg_text = context.effective_message.text
        lang, confidence = identifier.classify(msg_text)

        if lang != "en" and confidence >= 0.9:
            try:
                # Create Langpair to Show Translation API What We Need
                langpair = lang + '|en'

                translated_msg = requests.get(
                    'https://api.mymemory.translated.net/get',
                    params={
                        'q': msg_text,
                        'key': MYMEMORY_KEY, # API Key
                        'langpair': langpair,
                        'de': MYMEMORY_CONTACT # Contact Email
                        }).json()

                # Grab Translated Text from Nested JSON Response
                final_translation = translated_msg['matches'][0]['translation']

                # Respond with Translation to Non-English Message
                context.effective_message.reply_text(
                    messages.msg_translate.format(final_translation),
                    parse_mode='HTML')
            except Exception as e:
                LOGGER.warning(f'Translation Failed - {str(e)}')
        else:
            return
Example #4
0
def gas(update, context):
    # Show Current Estimates for Gas prices
    remove_command(context, update)
    try:
        resp = requests.get("https://api.etherscan.io/api?module=gastracker&action=gasoracle")
        if resp.status_code == 200:
            prices = resp.json()

            low = prices['result']['SafeGasPrice']
            standard = prices['result']['ProposeGasPrice']
            fast = prices['result']['FastGasPrice']

            message = messages.msg_gas.format(fast, standard, low)

            gas_msg = context.bot.send_message(
                chat_id=update.effective_message.chat.id,
                text=message,
                parse_mode=ParseMode.HTML,
                disable_web_page_preview=True
                )
            cleaner(context, gas_msg)

    except TypeError as e:
        LOGGER.warning(f'Rate Limited - {str(e)}')
        message = "Sorry Unable to Fetch Gas Estimates Right Now..."
        gas_message = context.bot.send_message(
            chat_id=update.effective_message.chat.id,
            text=message,
            parse_mode=ParseMode.HTML
            )
        cleaner(context, gas_message)
Example #5
0
def delete_bot_message(update, context):
    try:
        context.bot.deleteMessage(
            chat_id=update.effective_message.chat.id,
            message_id=update.effective_message.message_id
        )
    except BaseException as e:
        LOGGER.warning(f'<delete_bot_message> Exception Occured: {str(e)}')
        pass
Example #6
0
 def save(self):
     self.detected_images = self.detect()
     if self.output_directory is not None:
         if not os.path.isdir(self.output_directory):
             os.mkdir(self.output_directory)
         for name, detected_image in self.detected_images.items():
             cv2.imwrite(f"{self.output_directory}/{name}", detected_image)
     else:
         LOGGER.warning(
             "Please provide output directory where images will be saved..."
         )
Example #7
0
def run():
    # TODO: break this into smaller functions
    LOGGER.info('Running music downloader...')
    tracks_to_download = get_tracks_to_download()
    if not tracks_to_download:
        LOGGER.info('No queued tracks found in database')
        return
    LOGGER.info('Found {} tracks from database to download...'.format(len(tracks_to_download)))
    options = {
        'format': 'bestaudio/best',
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'mp3',
            'preferredquality': '192',
        }],
        'quiet': False}

    for queued_track in tracks_to_download:
        exists = session.query(SavedTrack).filter(SavedTrack.artist == queued_track.artist,
                                                  SavedTrack.title == queued_track.title).count() > 0
        if exists:
            LOGGER.info('Track already exists as Saved Track, deleting Queued track and skipping download.')
            session.delete(queued_track)
            session.commit()
            continue
        track_save_name = u'{} - {}'.format(queued_track.artist, queued_track.title)
        final_track_path = TRACK_DIRECTORY + track_save_name + '.mp3'
        holding_track_path = HOLD_DIRECTORY + track_save_name + '.mp3'
        LOGGER.info('Downloading track: {}'.format(track_save_name))
        options['outtmpl'] = u'{}/{}.%(ext)s'.format(HOLD_DIRECTORY, track_save_name)
        ydl = youtube_dl.YoutubeDL(options)
        download_link = build_download_link(queued_track.youtube_video_id)
        # download the track
        try:
            ydl.download([download_link])
        except youtube_dl.utils.DownloadError as e:
            LOGGER.warning('youtube-dl encountered an error: {}' .format(e.message))
            continue
        saved_track = SavedTrack()
        saved_track.update_from_dict(queued_track.as_dict())
        saved_track.path = final_track_path
        saved_track.md5 = calculate_md5(holding_track_path)
        fingerprint_duration = fingerprint_file(holding_track_path, 30)
        saved_track.fingerprint = fingerprint_duration[1]
        saved_track.duration = fingerprint_duration[0]

        session.merge(saved_track)
        session.delete(queued_track)
        session.commit()
        os.rename(holding_track_path, final_track_path)
        LOGGER.info('Complete. Downloaded track data committed to database.')
Example #8
0
def subscribe(update, context):
    try:
        username = update.message.from_user.first_name
        chat_id = update.effective_message.chat.id
        telegram_unique_token = update.message.text.split('/subscribe ')[1]
        params = {
            'telegram_unique_token': telegram_unique_token,
            'chat_id': chat_id
        }
        x = requests.post(EXCHANGE_URL, data=params)
        if x.status_code == 200:
            message = messages.msg_subscribe.format(username, chat_id)
            context.message.reply_text(message, parse_mode=ParseMode.HTML)
        else:
            message = messages.msg_subscribe_error
            context.message.reply_text(message, parse_mode=ParseMode.HTML)
    except Exception as e:
        message = messages.msg_default_start.format(username)
        context.message.reply_text(message, parse_mode=ParseMode.HTML)
        LOGGER.warning(f'<subscribe> Exception Occured: {str(e)}')
Example #9
0
 def detect_vertical(self, show=False):
     if self.output_directory is None:
         raise LOGGER.warning(
             "Please provide output directory where images will be saved..."
         )
     if not os.path.isdir(self.output_directory):
         os.mkdir(self.output_directory)
     for img in self.images:
         [image, image_name] = [img[0], img[1]]
         out_h = ndimage.convolve(image, KERNEL_VERTICAL, mode='reflect')
         out_h *= 255
         cv2.imwrite(f"{self.output_directory}/{image_name}", out_h)
         if show:
             self.plot_two(f"{ROOT_DIRECTORY}/data/{image_name}",
                           f"{ROOT_DIRECTORY}/detected/{image_name}",
                           tekst="Vertical line detection")
Example #10
0
def shutdown_session(exception=None):
    if exception:
        LOGGER.warning("Shutdown Exception: %s", exception)
    db_session.remove()
Example #11
0
def error(update, context):
    LOGGER.warning('Update "%s" caused error "%s"', update, context.error)