示例#1
0
文件: routes.py 项目: GWP/Brain-train
def get_stats():
    if request.method == 'GET':
        logging.info("Doing a GET")
        if 'user' not in session:
            return redirect(url_for('do_login'))
        else:
            return render_template('stats.html')
    elif request.method == 'POST':
        if 'user' not in session:
            logging.info("No user!")
            return redirect(url_for('do_login'))
        logging.info("Getting stats for {}".format(session['user']))
        try:
            user = User.query.filter_by(nickname=session['user']).first()
            logging.info("we got this far with {}".format(user))
            problems = Problem.query.filter_by(author=user).all()
            logging.info("now we got the problems {}".format(problems))
            session['num_of_problems'] = len(problems)
            additions = [n for n in problems if n.problem_type == 'Addition']
            times = [int(n.time_to_complete) for n in additions]
            average = sum(times)/len(times)
            logging.info("Your average was {} milliseconds".format(average))
            return "Your {} for {} was {}".format("average time", "Addition", average)
        except Exception as e:
            logging.error("There is a problem finding the stats: {}".format(e))
        return "We have a problem"
示例#2
0
def token(bot, message):
    try:
        message = message.message
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)

        asyncio.get_event_loop().run_until_complete(
            redis.execute("HSET", "user:{0}".format(message.from_user.id),
                          "active", "True", "VK_TOKEN",
                          message.text.split(" ")[1]))
        asyncio.get_event_loop().run_until_complete(
            redis.execute("SADD", "users",
                          "user:{0}".format(message.from_user.id)))

        bot.send_message(
            message.from_user.id,
            "Отлично! Я запомнил твой токен доступа VK, теперь буду пересылать "
            "сообщения оттуда. Спасибо, что используешь меня!")
    except Exception as e:
        try:
            bot.send_message(
                message.from_user.id,
                "❗ Произошла непредвиденная ошибка при выполнении метода. Сообщите об этом "
                "администратору для более быстрого ее исправления.")
        except:
            pass

        logging.error("Произошла ошибка при попытке выполнения метода.",
                      exc_info=True)
        return e
示例#3
0
 def get(self, product_name):
     try:
         query = [
             es_query_builder.match_query({"_parent_index": product_name})
         ]
         query = es_query_builder.build_queries(query)
         additional_results = scan_data(es, 'additional_features', query)
         product_results = scan_data(es, product_name)
     except Exception as e:
         logging.error(str(e))
         return response(404, str(e))
     else:
         additional_results = [i['_source'] for i in additional_results]
         for i in product_results:
             i['_source']['additional_features'] = dict()
             for j in additional_results:
                 if i['_id'] == j['_parent_id']:
                     i['_source']['additional_features'].update(j)
         results = list()
         for i in product_results:
             tmp = dict()
             tmp["_id"] = i["_id"]
             tmp.update(i["_source"])
             results.append(tmp)
         return response(200, message="Success", data=results)
示例#4
0
def start(bot, message):
    try:
        message = message.message
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)

        if "ru" not in message.from_user.language_code:
            bot.send_message(
                message.from_user.id,
                "❗ Unfortunately, the bot doesn't speak your language. So if you are "
                "not able to understand Russian, use an online translator such as Google Translate."
            )

        bot.send_message(message.from_user.id,
                         config.startMessage,
                         parse_mode="Markdown")
        loop.run_until_complete(
            redis.execute(
                "SET", "status:{0}".format(message.from_user.id),
                '{"status": "waiting", "method": "find_communities"}', "EX",
                180))
    except Exception as e:
        try:
            bot.send_message(
                message.from_user.id,
                "❗ Извините, что-то пошло не так, но в скором времени все исправится. "
                "Попробуйте выполнить то же самое действие через некоторое время (10-15 минут)."
            )
        except:
            pass

        logging.error(
            "Exception has been occurred while trying to execute the method.",
            exc_info=True)
        return e
示例#5
0
    def post(self, product_name):
        json_req = request.get_json(force=True)
        q_filter = json_req['filter']
        check = q_filter.get("field", False)
        if not check:
            q_filter['field'] = dict()
        q_filter['field']['slug'] = product_name
        filters = list()
        for key, val in q_filter.items():
            if key.lower() == 'date':
                q = es_query_builder.date_filter(val, date_field="date")
                filters.append(q)
            elif key.lower() == 'field':
                q = es_query_builder.match_query(val)
                filters.extend(q)

        query = es_query_builder.build_queries(filters)
        try:
            es_result = scan_data(es, index, query)
        except Exception as e:
            logging.error(str(e))
            return response(404, message=str(e))
        else:
            results = [i['_source'] for i in es_result]
            return response(200, message="Success", data=results)
示例#6
0
def add_user():
    data = request.json
    if data['username'] == 'public':
        return s_vars.cannot_create_user, 403
    verification_code = code_gen()
    try:
        new_user = user_model.User(name=data['name'],
                                   username=data['username'],
                                   email=data['email'],
                                   verification_code=verification_code)
        new_user.set_password(data['secret'])
        new_user.set_verification_expiry()
        db.session.add(new_user)
        db.session.commit()
        res = {'result': new_user.__repr__()}
        send_mail(data['email'], 'Welcome to N4NITIN',
                  'Verification Code: {}'.format(verification_code))
        db.session.expunge(new_user)
        db.session.close()
    except KeyError:
        return s_vars.bad_request, 400
    except exc.IntegrityError as e:
        logging.error(e)
        return s_vars.user_already_exist, 409
    except smtplib.SMTPException:
        return s_vars.mail_sending_failed, 501
    return res, 200
示例#7
0
def start_polling(client):
    try:
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)

        users = asyncio.get_event_loop().run_until_complete(
            redis.execute("SMEMBERS", "users"))['details']
        logging.debug("Пользователи в Redis: " + str(users))
        while True:
            for user in users:
                user_id = user
                user = asyncio.get_event_loop().run_until_complete(
                    hgetall(user))
                if parse_as_boolean(user['active']):
                    # TODO: Использовать Dramatiq вместо этого самопального кода
                    result = poll_user(user, user_id, client)
                    logging.debug(
                        "Выполнен polling пользователя {0}, результат: {1}".
                        format(user_id, result))

            sleep(0.1)
    except Exception as e:
        logging.error(
            "Произошла ошибка при попытке начала polling'а всех аккаунтов VK.",
            exc_info=True)
        return e
示例#8
0
def debug(bot, message):
    try:
        message = message.message

        bot.send_message(
            message.from_user.id,
            "Вот информация, которая может пригодиться при выявлении проблемы и не только ее."
            "\n\nUser ID: `{0}`"
            "\nMessage ID: `{1}`"
            "\nLanguage Code: `{2}`".format(
                str(message.from_user.id), str(message.message_id),
                str(message.from_user.language_code)),
            parse_mode="Markdown")
    except Exception as e:
        try:
            bot.send_message(
                message.from_user.id,
                "❗ Извините, что-то пошло не так, но в скором времени все будет исправлено. "
                "Попробуйте выполнить то же самое действие через некоторое время (10-15 минут)."
            )
        except:
            pass

        logging.error(
            "Exception has been occurred while trying to execute the method.",
            exc_info=True)
        return e
示例#9
0
def get_witty_intent(text):
    try:
        intent = ask_wit(text)
        # pull game info (game info for scores and results)
        return intent
    except Exception as e:
        logging.error("call init failed", e)
示例#10
0
def message_handler(client, message):
    try:
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)

        try:
            assert message.reply_to_message
        except AssertionError:
            return
        tg_message_id = "{0}_{1}".format(message.reply_to_message.chat.id,
                                         message.reply_to_message.message_id)
        vk_message_id = asyncio.get_event_loop().run_until_complete(
            redis.execute(
                "GET",
                "message:telegram:{0}".format(tg_message_id)))['details']
        if not vk_message_id:
            logging.debug(
                "Сообщение, на которое ответил пользователь, не содержит ID сообщения из VK."
            )
            if config.DEVELOPER_MODE:
                message.reply(
                    "ℹ️ К сообщению, на которое вы ответили, не привязано ID сообщения из VK.",
                    disable_notification=True)
            return

        user = asyncio.get_event_loop().run_until_complete(
            hgetall("user:{0}".format(message.from_user.id)))
        peer_id = vk_message_id.split("_")[0]

        try:
            assert message.sticker
            parse_sticker(client, message.sticker.file_id, user['VK_TOKEN'],
                          user['VK_SECRET'], peer_id)
        except AssertionError:
            logging.debug("Похоже, что это сообщение не является стикером..")

        if message.text:
            data = {
                "peer_id": peer_id,
                "random_id": randbits(32),
                "message": message.text,
                "access_token": user['VK_TOKEN'],
                "v": 5.92
            }
            response = requests.post("https://api.vk.com/method/messages.send",
                                     data=sign_data(data, "messages.send",
                                                    user['VK_SECRET'])).json()
            logging.debug(
                "Сообщение было отправлено, VK вернул ответ: {0}".format(
                    response))
            if config.DEVELOPER_MODE:
                message.reply(
                    "ℹ️ Сообщение было отправлено, VK вернул ответ:\n\n`{0}`.".
                    format(response),
                    disable_notification=True)
    except Exception as e:
        logging.error("Произошла ошибка при попытке выполнения метода.",
                      exc_info=True)
        return e
示例#11
0
def callback(bot, call):
    try:
        call = call.callback_query
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)

        if call.message:
            if call.data.startswith("channel_counters"):
                counter = call.data.split("|", 2)

                if counter[1] == "time":
                    bot.answer_callback_query(callback_query_id=call.id,
                                              text="🕒 Время публикации данного поста: {0} MSK.".format(
                                                  str(datetime.fromtimestamp(
                                                      int(counter[2])).strftime("%d.%m.%y, %H:%M:%S"))),
                                              show_alert=True, cache_time=30)
                elif counter[1] == "likes":
                    bot.answer_callback_query(callback_query_id=call.id,
                                              text="💖 Количество лайков: {0}.".format(
                                                  str(counter[2])), show_alert=True, cache_time=30)
                elif counter[1] == "comments":
                    bot.answer_callback_query(callback_query_id=call.id,
                                              text="💬 Количество комментариев: {0}.".format(
                                                  str(counter[2])), show_alert=True, cache_time=30)
                elif counter[1] == "reposts":
                    bot.answer_callback_query(callback_query_id=call.id,
                                              text="🔁 Количество репостов: {0}.".format(
                                                  str(counter[2])), show_alert=True, cache_time=30)
                elif counter[1] == "views":
                    bot.answer_callback_query(callback_query_id=call.id,
                                              text="👁 Количество просмотров: {0}.".format(
                                                  str(counter[2])), show_alert=True, cache_time=30)
                elif counter[1] == "poll":
                    poll = loop.run_until_complete(redis.execute("GET", str("poll&" + str(counter[2]))))
                    if not poll:
                        logging.debug("Poll Name is None, most likely this poll isn't in the cache.")
                        refresh_stats(bot, call, expired=1)
                        return
                    bot.answer_callback_query(callback_query_id=call.id,
                                              text="📋 Название голосования: {0}.".format(
                                                  str(poll[0:170])), show_alert=True, cache_time=30)
                elif counter[1] == "poll_ans":
                    poll_answer = loop.run_until_complete(redis.execute("GET", str("poll_answer&" + str(counter[2]))))
                    if not poll_answer:
                        logging.debug("Poll Answer is None, most likely this poll isn't in the cache.")
                        refresh_stats(bot, call, expired=1)
                        return
                    else:
                        poll_answer = poll_answer.split("?|&|&|!", 1)
                    bot.answer_callback_query(callback_query_id=call.id,
                                              text="❎ Количество голосов за {0}: {1} голосов.".format(
                                                  str(poll_answer[0][0:140]), str(poll_answer[1])),
                                              show_alert=True, cache_time=30)
            elif call.data.startswith("channel_refresh_stats"):
                refresh_stats(bot, call)
            bot.answer_callback_query(callback_query_id=call.id, show_alert=False)
    except Exception as e:
        logging.error("Exception has been occurred while trying to execute the method.", exc_info=True)
        return e
示例#12
0
 def _connect(self):
     try:
         gl = gitlab.Gitlab(self.host,
                            private_token=os.getenv("GITLAB_TOKEN"),
                            ssl_verify=False)
         return gl
     except gitlab.exceptions.GitlabAuthenticationError:
         logging.error('Gitlab Authentication Failed.')
示例#13
0
async def status():
    try:
        api_status_url = "https://status.epicgames.com/api/v2/summary.json"

        f_status = (await Redis.execute("GET", "fortnite:status"))['details']
        if f_status and not config.DEVELOPER_MODE:
            f_status = json.loads(f_status)
        else:
            f_status = requests.get(api_status_url).json()
            await Redis.execute("SET", "fortnite:status", json.dumps(f_status), "EX", 20)

        # Переводим глобальное состояние сервисов на русский
        message = status_translations.translate_global_status(f_status['status']['description'])

        # Проверяем, есть ли информация о сервисах, которые не работают в штатном режиме
        if f_status['components']:
            broken_services = [service for service in f_status['components'] if not service['status'] == "operational"]
            if broken_services:
                message = "{0}\n\n⛔️ Сервисы, которые **не** работают в штатном режиме:".format(message)

                num = 1
                for service in f_status['components']:
                    if not service['status'] == "operational" and not service['group']:
                        message = "{0}\n{1}. {2}, состояние: **{3}**.".format(
                            message, num, status_translations.translate_service_name(service['name']),
                            status_translations.translate_service_status(service['status'])
                        )
                        num += 1

        # Проверяем, есть ли информация о происшествиях
        if f_status['incidents']:
            message = "{0}\n\n❗️ Происшествия, связанные с сервисами:".format(message)

            for num, incident in enumerate(f_status['incidents']):
                message = "{0}\n{1}. {2}, [подробнее]({3}).".format(message, num+1, incident['name'],
                                                                    incident['shortlink'])

        # Проверяем, есть ли информация о запланированных технических работах
        if f_status['scheduled_maintenances']:
            message = "{0}\n\n🕰 Запланированные технические работы:".format(message)

            for num, maintenance in enumerate(f_status['scheduled_maintenances']):
                scheduled_for_date = utils.convert_to_moscow(utils.convert_iso_time(maintenance['scheduled_for']))
                scheduled_until_date = utils.convert_to_moscow(utils.convert_iso_time(maintenance['scheduled_until']))

                message = "{0}\n{1}. [{2}]({3}), запланировано начало на **{4}** в **{5}**, " \
                          "окончание на **{6}** в **{7}** по московскому времени.".\
                    format(message, num+1, maintenance['name'], maintenance['shortlink'],
                           scheduled_for_date.strftime("%d.%m.%y"), scheduled_for_date.strftime("%H:%M"),
                           scheduled_until_date.strftime("%d.%m.%y"), scheduled_until_date.strftime("%H:%M"))

        message = "{0}\n\nУзнать более подробную информацию о работе сервисов Epic Games можно " \
                  "[здесь](https://status.epicgames.com/).".format(message)

        return message
    except Exception as e:
        logging.error("Произошла ошибка при попытке парсирования статуса сервисов Epic Games.", exc_info=True)
        return "Произошла ошибка при попытке парсирования статуса сервисов Epic Games."
示例#14
0
 def get(self):
     try:
         results = scan_data(es, index)
     except Exception as e:
         logging.error(str(e))
         return response(404, str(e))
     else:
         results = [i['_source'] for i in results]
         return response(200, message="Success", data=results)
示例#15
0
def start(client, message):
    try:
        client.send_message(message.chat.id,
                            "Приветствую тебя, {0} {1}!"
                            "\n\nЯ пока что являюсь секретным Ботом и про себя не могу ничего рассказывать.".format(
                                message.from_user.first_name, message.from_user.last_name))
    except Exception as e:
        logging.error("Произошла ошибка при выполнении команды /start.", exc_info=True)
        return e
示例#16
0
def status(client, message):
    try:
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)

        f_status_message = asyncio.get_event_loop().run_until_complete(parse_services_status())
        client.send_message(message.chat.id, f_status_message, disable_web_page_preview=True)
    except Exception as e:
        logging.error("Произошла ошибка при выполнении команды /status.", exc_info=True)
        return e
示例#17
0
def get_witty_intent(text):
    try:
        intent = ask_wit(text)
        # pull game info (game info for scores and results)
        return intent
    except Exception as e:
        logging.error("call init failed", e)


# send_message job
示例#18
0
 def get(self, product_name):
     try:
         query = [es_query_builder.match_query({"slug": product_name})]
         query = es_query_builder.build_queries(query)
         results = scan_data(es, index, search_query=query)
     except Exception as e:
         logging.error(str(e))
         return response(404, str(e))
     else:
         results = [i['_source'] for i in results]
         return response(200, message="Success", data=results)
示例#19
0
def handle_exception(error) -> Response:
    """ Return JSON instead of HTML for HTTP errors. """
    response = error.get_response()
    # format the response
    response.data = json.dumps({
        "code": error.code,
        "error": error.name,
        "message": error.description,
    })
    logging.error(error)
    response.content_type = "application/json"
    return response
示例#20
0
def post(client):
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)

    while True:
        try:
            asyncio.get_event_loop().run_until_complete(post_async(client))
        except Exception:
            logging.error("Произошла ошибка при публикации новостей в канал.",
                          exc_info=True)

        sleep(15)
示例#21
0
    async def create_tables():
        try:
            await Psql.execute(
                'CREATE TABLE IF NOT EXISTS "public"."channels" ("chat_id" bigint, "community_id" int NOT NULL, '
                '"owner_id" int NOT NULL, "access_token" text NOT NULL, "channel_link" text NOT NULL, '
                'PRIMARY KEY ("chat_id"), UNIQUE ("community_id"), UNIQUE ("channel_link"));'
            )

            logging.debug("Таблица channels была успешно создана в PostgreSQL.")
            return "OK"
        except Exception as e:
            logging.error("Произошла ошибка при попытке создания таблиц в PostgreSQL.", exc_info=True)
            return e
示例#22
0
def debug(client, message):
    try:
        client.send_message(
            message.chat.id,
            "Ниже находится информация, которая может оказаться полезной."
            "\n\n**Информация о приложении:** \n`Version: {0}`\n`Commit: {1}`\n`Developer Mode: {2}`"
            "\n\n**Информация о пользователе:** \n`User ID: {3}`\n`Language Code: {4}`"
            "\n\n**Информация о чате:**\n`Chat ID: {5}`\n`Message ID: {6}`".
            format(config.VERSION, config.COMMIT, config.DEVELOPER_MODE,
                   message.from_user.id, message.from_user.language_code,
                   message.chat.id, message.message_id))
    except Exception as e:
        logging.error("Произошла ошибка при выполнении команды /debug.",
                      exc_info=True)
        return e
示例#23
0
    async def connection():
        try:
            response = await Redis.execute("ping")

            logging.info(
                "The connection to Redis Server can be established successfully."
            )
            logging.debug("Returned response: " + str(response))
            return "OK"
        except Exception as e:
            logging.error(
                "Exception has been occurred while trying to establish connection with "
                "Redis.",
                exc_info=True)
            return e
示例#24
0
    async def execute(cls, *args):
        try:
            logging.debug("Passed arguments: " + str(args))

            psql_connection = await asyncpg.connect(host=config.databaseHost,
                                                    database=config.databaseName,
                                                    user=config.databaseUsername,
                                                    port=config.databasePort)

            await psql_connection.execute(*args)
            await psql_connection.close()
            return "OK"
        except Exception as e:
            logging.error("Произошла ошибка при попытке выполнения SQL запроса.", exc_info=True)
            return e
示例#25
0
    async def connection():
        try:
            psql_connection = await asyncpg.connect(host=config.databaseHost,
                                                    database=config.databaseName,
                                                    user=config.databaseUsername,
                                                    port=config.databasePort)

            logging.info("Соединение с Базой Данных PostgreSQL может быть установлено успешно.")
            logging.debug("Returned response: " + str(psql_connection))

            await psql_connection.close()
            return "OK"
        except Exception as e:
            logging.error("Произошла ошибка при попытке подключения к Базе Данных PostgreSQL.", exc_info=True)
            return e
示例#26
0
    async def execute(cls, *args):
        try:
            logging.debug("Passed arguments: " + str(args))

            redis_connection = await aioredis.create_connection(
                (config.redisHost, config.redisPort), encoding="UTF-8")

            result = await redis_connection.execute(*args, encoding="UTF-8")
            redis_connection.close()
            await redis_connection.wait_closed()
            return result
        except Exception as e:
            logging.error(
                "Exception has been occurred while trying to execute Redis statement.",
                exc_info=True)
            return e
示例#27
0
    async def fetch(cls, *args):
        try:
            logging.debug("Passed arguments: " + str(args))

            psql_connection = await asyncpg.connect(host=config.databaseHost,
                                                    database=config.databaseName,
                                                    user=config.databaseUsername,
                                                    port=config.databasePort)

            result = await psql_connection.fetch(*args)
            await psql_connection.close()
            # Результат может быть удобно парсирован так: result[0]['COLUMN']
            return result
        except Exception as e:
            logging.error("Произошла ошибка при попытке получения данных из PostgreSQL.", exc_info=True)
            return e
示例#28
0
    async def fetchrow(cls, *args):
        try:
            logging.debug("Passed arguments: " + str(args))

            psql_connection = await asyncpg.connect(host=config.databaseHost,
                                                    database=config.databaseName,
                                                    user=config.databaseUsername,
                                                    port=config.databasePort)

            result = await psql_connection.fetchrow(*args)
            await psql_connection.close()
            return result
        except Exception as e:
            logging.error("Произошла ошибка при попытке получения линии (fetch row) данных из PostgreSQL.",
                          exc_info=True)
            return e
def check_auth_token(headers):
    token = headers.get('Shorturl-Access-Token')
    if token is not None:
        try:
            user, passwd = decode(token)
            user_in_db = au_model.User.query.filter_by(username=user).first()
            if user_in_db is not None:
                if user_in_db.check_password(passwd):
                    if user_in_db.verified:
                        return True, user
                    return False, user
            return False, ''
        except DecodeError as e:
            logging.error(e)
            return False, ''
    else:
        return False, 'public'
def date_filter(_filter, date_field="date_created"):
    if 'date_filter' in list(_filter.keys()):
        _round = False
        try:
            _round = _filter["date_filter"].get("round", False)
            _round = bool(_round)
        except Exception as e:
            logging.error(str(e))
            pass
        query = range_date(date_filter=_filter['date_filter'],
                           date_field=date_field,
                           _round=_round)
        return query
    else:
        _from = _filter.get('from', None)
        _to = _filter.get('to', None)
        query = range_date(date_from=_from, date_to=_to, date_field=date_field)
        return query
示例#31
0
    async def connection():
        try:
            response = await Redis.execute("ping")
            logging.debug("Returned response: " + str(response))

            if str(response['details']) == "PONG":
                logging.info(
                    "Соединение с Redis может быть установлено успешно.")
                return {"status": "OK", "details": response['details']}
            else:
                logging.error(
                    "Произошла ошибка при попытке установления соединения с Redis."
                )
                return {"status": "ERROR", "details": response['details']}
        except Exception as e:
            logging.error(
                "Произошла ошибка при попытке установления соединения с Redis.",
                exc_info=True)
            return {"status": "ERROR", "details": str(e)}
示例#32
0
def debug(client, message):
    try:
        client.send_message(
            message.from_user.id,
            "Ниже находится информация, которая может оказаться полезной."
            "\n\n**Информация о приложении:** \n`Version: {0}`\n`Commit: {1}`\n`Developer Mode: {2}`"
            "\n\n**Информация о пользователе:** \n`User ID: {3}`\n`Message ID: {4}`\n`Language Code: {5}`".format(
                config.VERSION, config.COMMIT, config.DEVELOPER_MODE, message.from_user.id, message.message_id,
                message.from_user.language_code))
    except Exception as e:
        try:
            client.send_message(
                message.from_user.id,
                "❗ Произошла непредвиденная ошибка при выполнении метода. Сообщите об этом администратору для более "
                "быстрого ее исправления.")
        except:
            pass

        logging.error("Произошла ошибка при попытке выполнения метода.", exc_info=True)
        return e
示例#33
0
def short_code_callback():
    if request.method == 'POST':

        # Reads the variables sent via POST from our gateway
        _from = request.values.get('from', None)
        to = request.values.get('to', None)
        text = request.values.get('text', None)
        date = request.values.get('date', None)
        id_ = request.values.get('id', None)

        try:
            # persist session variable
            # pass to queue
            intent = get_witty_intent(text=text)
            print intent.get('outcomes')[0].get('intent')

            """
            if intent.get('outcomes')[0].get('intent') == 'next_match':
                team_name = intent.get('outcomes')[0]['entities']['team'][0]['value']
                result = Football.get_next_match(team_name)
                send_message(_from, result)
            """

        except Exception as e:
            logging.error('Failed with - ', e)

        print _from, to, text, date, id_

        resp = make_response('Ok', 200)
        resp.headers['Content-Type'] = 'text/plain'
        resp.cache_control.no_cache = True
        return resp
    else:
        resp = make_response('Error', 400)
        resp.headers['Content-Type'] = 'text/plain'
        resp.cache_control.no_cache = True
        return resp
示例#34
0
def airtime_dlr_callback():
    if request.method == 'POST':

        # Reads the variables sent via POST from our gateway
        _from = request.values.get('from', None)
        to = request.values.get('to', None)
        id_ = request.values.get('text', None)

        print id_, _from, to
        try:
            # write to redis
            pass
        except Exception as e:
            logging.error('Storing fail -> ', e)

        resp = make_response('Ok', 200)
        resp.headers['Content-Type'] = 'application/json'
        resp.cache_control.no_cache = True
        return resp
    else:
        resp = make_response('Error', 400)
        resp.headers['Content-Type'] = 'application/json'
        resp.cache_control.no_cache = True
        return resp
示例#35
0
 def findHostItemByName(self, name):
     result = self.ui.hostsList.findItems(name, Qt.MatchExactly)
     resultLen = len(result)
     if resultLen != 1:  # should be only one host
         logging.error("Host not found. Got %d results" % resultLen)
     return result[0]
示例#36
0
def voice_callback():
    if request.method == 'POST':
        is_active = request.values.get('isActive', None)
        session_id = request.values.get('sessionId', None)
        caller_number = request.values.get('callerNumber', None)
        direction = request.values.get('direction', None)

        try:
            # store session info
            pass
        except Exception as e:
            logging.error('Storing fail -> ', e)

        print "is_active -> ", is_active
        print caller_number, session_id

        if direction == "inbound":
            response = '<?xml version="1.0" encoding="UTF-8"?>'
            response += '<Response>'
            response += '<Say maxDuration="5" playBeep="false"> I am Lucy, vote for me! </Say>'
            response += '</Response>'

            resp = make_response(response, 200)
            resp.headers['Content-Type'] = "application/xml"
            resp.cache_control.no_cache = True
            return resp

        if is_active == str(0):
            # Compose the response
            duration = request.values.get('durationInSeconds', None)
            currency_code = request.values.get('currencyCode', None)
            amount = request.values.get('amount', None)
            # update session info to Redis

            print duration, currency_code, amount

            response = '<?xml version="1.0" encoding="UTF-8"?>'
            response += '<Response>'
            response += '<Say playBeep="false" >You are right, sending you airtime!</Say>'
            response += '</Response>'

            resp = make_response(response, 200)
            resp.headers['Content-Type'] = "application/xml"
            resp.cache_control.no_cache = True
            return resp

        if is_active == str(1):
            dtmf_digits = request.values.get('dtmfDigits', None)
            if dtmf_digits is not None:
                if dtmf_digits == str(6):
                    api = AfricasTalkingGateway(
                        apiKey_=settings.api_key, username_=settings.username)
                    try:
                        api.sendAirtime([{'phoneNumber':
                                        caller_number, 'amount': 'KES 10'}])
                    except AfricasTalkingGatewayException:
                        logging.error('Sending airtime failed')

                    response = '<?xml version="1.0" encoding="UTF-8"?>'
                    response += '<Response>'
                    response += '<Say playBeep="false" >You are right, sending you airtime!</Say>'
                    response += '</Response>'

                    resp = make_response(response, 200)
                    resp.headers['Content-Type'] = "application/xml"
                    resp.cache_control.no_cache = True
                    return resp

                else:
                    response = '<?xml version="1.0" encoding="UTF-8"?>'
                    response += '<Response>'
                    response += '<Say playBeep="false" >You are wrong, sorry!</Say>'
                    response += '</Response>'

                    resp = make_response(response, 200)
                    resp.headers['Content-Type'] = "application/xml"
                    resp.cache_control.no_cache = True
                    return resp

            else:
                # Compose the response
                response = '<?xml version="1.0" encoding="UTF-8"?>'
                response += '<Response>'
                response += '<GetDigits timeout="20" finishOnKey="#">'
                response += '<Say playBeep="false" >How old is Africa\'s Talking? end with hash sign</Say>'
                response += '</GetDigits>'
                response += '</Response>'

                results = gateway.call("+254711082306", "+254721339381")

                for result in results:
                    print "Status : %s; phoneNumber : %s " % (result['status'],
                                                              result['phoneNumber'])

                resp = make_response(response, 200)
                resp.headers['Content-Type'] = "application/xml"
                resp.cache_control.no_cache = True
                return resp

    else:
        resp = make_response('Bad Request', 400)
        resp.headers['Content-Type'] = "application/xml"
        resp.cache_control.no_cache = True
        return resp