コード例 #1
0
def cmd_start(message):
    state = get_state(message.chat.id)
    # IF PROMO AND SALES
    if state == config.States.S_PROMOSALES.value:
        set_state(message.chat.id, config.States.S_PROMOSALES.value)
        bot.send_message(message.chat.id,
                         config.MAIN_ANSWER,
                         reply_markup=markup_MAIN)
    # IF CATEGORIES
    elif state == config.States.S_CATEGORIES_PROMO.value or state == config.States.S_CATEGORIES_SALES.value:
        bot.send_message(message.chat.id,
                         config.CATEGORY_ANSWER,
                         reply_markup=markup_CATEGORY)
    #IF START
    else:
        bot.send_message(message.chat.id,
                         "При возникновении проблем с ботом пропишите /start")
        bot.send_message(message.chat.id,
                         config.MAIN_ANSWER,
                         reply_markup=markup_MAIN)
        set_state(message.chat.id, config.States.S_PROMOSALES.value)
    msg = Message(api_key=config.API_KEY,
                  platform=config.PLATFORM,
                  version=config.VERSION,
                  user_id=str(message.chat.id),
                  message=message.text,
                  intent="/start")
    msg.send()
コード例 #2
0
def echo_all(message):
    if not database.is_user_new(
            user_id=message.chat.id) and database.get_state(
                user_id=message.chat.id) != 'in_progress':
        text = message.text
        urls = url_extractor(text)
        if len(urls) == 0:
            bot.reply_to(message, content.answer_for_message_no_links)
        else:
            database.set_state(user_id=message.chat.id, state='in_progress')
            bot.reply_to(message, content.answer_for_message_with_links
                         )  # answer for links it gets
            for url in urls:
                if video_id_extractor(url):
                    summary_text = get_video_summary(url)
                    if summary_text is not False:
                        bot.send_message(chat_id=message.chat.id,
                                         text=content.uploading_in_progress)
                        video = open('final_video.mp4', 'rb')
                        sended_message = bot.send_video(message.chat.id, video)
                        database.new_summary(
                            user_id=message.chat.id,
                            message_id=sended_message.message_id,
                            summary_text=summary_text,
                            url=url,
                            summary_type='video')
                        database.set_state(user_id=message.chat.id,
                                           state='waiting')
                    else:
                        bot.send_message(chat_id=message.chat.id,
                                         text=content.cannot_process)
                        database.set_state(user_id=message.chat.id,
                                           state='waiting')
                else:
                    page_text = get_page_text(url)
                    if len(page_text) != 0:
                        summary_text = get_summary(page_text)
                        text_to_speech(summary_text)
                        sended_message = bot.reply_to(
                            message, prettify_output(summary_text))
                        # Audio
                        audio = open(content.audio_file_name, 'rb')
                        bot.send_audio(message.chat.id, audio)
                        database.new_summary(
                            user_id=message.chat.id,
                            message_id=sended_message.message_id,
                            summary_text=summary_text,
                            url=url,
                            summary_type='article')
                        database.set_state(user_id=message.chat.id,
                                           state='waiting')
                    else:
                        bot.send_message(chat_id=message.chat.id,
                                         text=content.cannot_process)
                        database.set_state(user_id=message.chat.id,
                                           state='waiting')
    else:
        bot.send_message(chat_id=message.chat.id,
                         text=content.already_in_progress)
コード例 #3
0
def videoMessageHandler(user_id, file_id, caption, message_id):
    print("\n\n\n photo message handler \n\n\n")
    cState = db.get_state(user_id)
    cState, = cState[0]
    print("\n\n cState = {}\n\n".format(cState))
    if cState == 14:
        print(" \n\n\n return_state = report_sent\n\n\n")
        return report_sent(user_id=user_id,
                           text=caption,
                           message_id=message_id,
                           type=3,
                           file_id=file_id)
    print(" \n\n\n return_state = cState\n\n\n")
    return cState
コード例 #4
0
def login_page():
    cur = mysql.connection.cursor()
    message = ""
    if request.method == 'POST':
        if request.form.get("R") == "register":
            return redirect(url_for('register'))
        else:
            message = "R is : " + str(request.form.get("R"))

        username = request.form['username']
        password = request.form['password']
        if username == "alex" and password == "csgo":
            session['logged_in'] = True
            session['admin'] = True
            session['user'] = username
            return redirect(url_for('admin'))
        elif check_credentials(username, password, cur):
            message = "You are logged in as " + str(username)
            session['logged_in'] = True
            session['admin'] = False
            session['user'] = username
            print("## CHECKPOINT CHARLIE ##")
            session['level'] = get_level(cur, username)
            session['state'] = get_state(cur, username)
            session['tip_date'] = "clear"
            if reports_exist(cur, username):
                cur.close()
                return render_template("message.html", message=message, goto="/")
            else:
                cur.close()
                return render_template("message.html", message=message, goto="/intro")
        else:
            cur.close()
            message="username unknown or wrong password"


    return render_template("login.html", message=message)
コード例 #5
0
def index():

    # contains json object that telegram sent
    msg = request.get_json()
    with open('request.json', 'w', encoding='utf-8') as file:
        json.dump(msg, file, ensure_ascii=False, indent=4)  

    # admins = bot_functions.get_admins()
    admins = bot_functions.get_admins()

    if 'message' in msg.keys():
        if 'contact' in msg['message'].keys():
            user_id, phone_number, firstname, lastname, username = bot_functions.proces_contact(msg)
            state = db.get_state(user_id)
            response_state = db.add_user(user_id=user_id, phone_number=phone_number, firstname=firstname, lastname=lastname, username=username)
            db.update_state(user_id=user_id, state=int(response_state))
            bot_functions.menu(user_id)
        elif 'photo' in msg['message'].keys():
            user_id, message_id, file_id, caption = bot_functions.parse_image_message(msg)
            state = db.get_state(user_id)
            if len(state) == 0:
                print("\n\n not enter in key part \n\n")
                state = 0
            else:
                print("\n\n enter in key part \n\n")
                state, = state[0]
            
            ligal = Semaphore.is_ligal(caption, user_id, state)
            if ligal:
                returned_state = bot_functions.photoMessageHandler(user_id, file_id, caption, message_id)
                db.update_state(user_id, returned_state)
            else:
                bot_functions.send_message(chat_id=user_id, text=bot_texts.get_illigalText())

        elif 'video' in msg['message'].keys():
            user_id, message_id, file_id, caption = bot_functions.parse_video_message(msg)
            state = db.get_state(user_id)
            if len(state) == 0:
                print("\n\n not enter in key part \n\n")
                state = 0
            else:
                print("\n\n enter in key part \n\n")
                state, = state[0]
            
            ligal = Semaphore.is_ligal(caption, user_id, state)
            if ligal:
                returned_state = bot_functions.videoMessageHandler(user_id, file_id, caption, message_id)
                db.update_state(user_id, returned_state)
            else:
                bot_functions.send_message(chat_id=user_id, text=bot_texts.get_illigalText())
            
        else:
            # parsing the message
            user_id, type, content, username, message_id = bot_functions.parse_message(msg)
            state = db.get_state(user_id)  
            if user_id in admins:
                admin_mesage = AdminMessage(user_id)
                if type == 1:
                    returned_state = admin_mesage.commandHandler(content)
            else:
                if len(state) == 0:
                    print("\n\n\n state = 0\n\n\n")
                    state = 0
                else:
                    state, = state[0]
                print(" \n\n type = ", state, " \n\n")
                # bot_functions.send_message(chat_id=chat_id, text=state)    
                ligal = Semaphore.is_ligal(content, user_id, state)
                if ligal:
                    if type == 1:
                        returned_state = bot_functions.commandHandler(user_id, content)
                        db.update_state(user_id, returned_state)
                        print("\n\n\n state updated : {} \n\n\n".format(returned_state))
                    else:
                        returned_state = bot_functions.regularTextHandler(user_id, content, message_id)
                        db.update_state(user_id, returned_state)
                else:
                    bot_functions.send_message(chat_id=user_id, text=bot_texts.get_illigalText())
    elif 'callback_query' in msg.keys():
        handler = InLineKeyboardHandler(msg)
        handler.execute()
    return Response('ok', status=200)
コード例 #6
0
def regularTextHandler(user_id, content, message_id, type=1):
    aliases = db.get_aliases(user_id)
    if content == '📝 ارسال گزارش':
        return select_reporting(user_id)

    elif content == '😉 سبزی پاک کنیم':
        return select_CleaningVegetable(user_id)

    elif content == '❓ قوانین و راهنما':
        return help(user_id)

    elif content == '👤 پروفایل':
        return select_profile(user_id)

    elif content == 'انتخاب نام مستعار':
        aliases = db.get_aliases(user_id)
        if len(aliases) == 0:
            return get_alias_from_user_while_reporting(user_id)
        else:
            return choose_aliases(user_id, aliases)
    elif content == '💰 امتیازات':
        return show_scores(user_id)
    elif content == '❌ تمایلی ندارم':
        return restart(user_id)
    elif content == 'شروع مجدد':
        return start(user_id)
    elif content == "\U000027A1 بازگشت به منو اصلی":
        return menu(user_id)
    elif content == "\U000021AA بازگشت به پروفایل":
        return select_profile(user_id)
    elif content in city_num:
        return get_report(user_id, content)
    elif content == '\U00002712 نوشتن گزارش':
        return start_reporting(user_id)
    elif content == '\U0001F465 افزودن نام مستعار جدید':
        return add_new_alias_profile(user_id)
    elif content in aliases:
        return select_city(user_id, content)
    else:
        cState, = db.get_state(user_id)[0]
        if cState == 12:
            return regester_new_alias(user_id, content)
        elif cState == 14:
            return report_sent(user_id, content, message_id, type=1)
        elif cState == 22:
            reply_markup = {
                'keyboard': [[{
                    'text': '\U000021AA بازگشت به پروفایل'
                }], [{
                    'text': '\U000027A1 بازگشت به منو اصلی'
                }]],
                "resize_keyboard":
                True,
                "one_time_keyboard":
                True
            }
            state22_text = "نام مستعار شما با موقییت اضافه شد"
            send_message(chat_id=user_id,
                         text=state22_text,
                         reply_markup=reply_markup)
            num = len(aliases) + 1
            db.add_alias(user_id, content, num)
            return 23


# New change. make sure there is no rideman in performance
        else:
            return cState
コード例 #7
0
 def check_new_msg(self):
     url = self.url + "getUpdates?offset={}".format(self.offset)
     content = self.get_url(url)
     if content == None:
         return
     try:
         update_id = content['update_id']
         txt = content['message']['text']
         user_id = content['message']['from']['id']
         self.update_offset(update_id)
         if int(check_user(user_id)) == 1:
             if get_state(user_id,"on_register")[0][0] == 1:
                 txt = txt.strip(" ")
                 try:
                     text = txt.split(",")
                     res = change_parameters(user_id,text[0],text[1],text[2],text[3], text[4])
                 except Exception as e:
                     print(e)
                     res = 0
                 if res ==1:
                     self.send_message(user_id, "Valores registrados con exito!")
                     reset_field(user_id,"ack_eth")
                     reset_field(user_id,"ack_btc")
                 else:
                     self.send_message(user_id, "Hubo un problema registrando sus valores. Intentelo nuevamente")
                 reset_field(user_id, "on_register")
             else:
                 print(txt)
                 if txt == '1':
                     history_file = open("./history.txt")
                     last_prices = history_file.readlines()[-1]
                     history_file.close()
                     last_prices = last_prices.strip("\n")
                     last_prices = last_prices.split(",")
                     self.send_message(user_id,"Los ultimos precios registrados son:\nFECHA: "+last_prices[0]+"\nBTC = "+last_prices[1]+" USD"+"\nETH = "+last_prices[2]+" USD")
                 elif txt == '2':
                     generate_plot('BTC', get_state(user_id, 'hours')[0][0])
                     generate_plot('ETH', get_state(user_id, 'hours')[0][0])
                     self.send_img(user_id,"./btc.png")
                     self.send_img(user_id,"./eth.png")
                     self.send_img(user_id,"./btc_candlestick.png")
                     self.send_img(user_id,"./eth_candlestick.png")
                 elif txt == '3':
                     self.send_message(user_id,"Para registrarse correctamente, escriba los limites superiores e inferiores de su alarma separados por coma. Si no desea tener en cuenta un parametro escriba -1 en su valor. Por ejemplo: btc_sup,btc_inf,eth_sup,eth_inf, hours.\n")
                     set_field(user_id, "on_register")
                 elif txt == '4':
                     th_sup_btc = get_state(user_id,'th_sup_btc')[0][0]
                     th_inf_btc = get_state(user_id,'th_inf_btc')[0][0]
                     th_sup_eth = get_state(user_id,'th_sup_eth')[0][0]
                     th_inf_eth = get_state(user_id,'th_inf_eth')[0][0]
                     hours = str(get_state(user_id,'hours')[0][0])
                     self.send_message(user_id,"Tus parametros actuales son:\nLIMITE SUPERIOR BTC = " +th_sup_btc+"\nLIMITE INFERIOR BTC = "+th_inf_btc+"\nLIMITE SUPERIOR ETH = "+th_sup_eth+"\nLIMITE INFERIOR ETH = "+th_inf_eth+"\nVENTANA DE TIEMPO PARA GRAFICOS = "+hours+"h")
                 elif txt == 'btc_ok':
                     set_field(user_id , "ack_btc")
                     self.send_message(user_id, " Alarma de BTC reconocida!")
                     print("BTC ACK = 1")
                 elif txt == 'eth_ok':
                     set_field(user_id , "ack_eth")
                     self.send_message(user_id, " Alarma de ETH reconocida!")
                     print("ETH ACK = 1")
                 else:    
                     self.display_options(user_id)
         else:
             self.send_message(user_id,"Para registrarse correctamente, escriba los limites superiores e inferiores de su alarma separados por coma. Si no desea tener en cuenta un parametro escriba -1 en su valor. Por ejemplo: btc_sup,btc_inf,eth_sup,eth_inf, hours.\n")
             print(add_user(user_id))
             set_field(user_id, "on_register")
     except Exception as e:
         self.update_offset(update_id)
         print(e)
         pass
コード例 #8
0
 def get_response(self):
     if not self.check():
         return 'ERROR'
     db = database.connect_db()
     state = database.get_state(str(self.uid), db)
     print state
     # -----------------------------------------------------
     # state=1
     # 转移至对线模式
     if state[0] == 1:
         return self.mode_1_duixian()
     # -----------------------------------------------------
     # state=2
     # 成语接龙模式
     if state[0] == 2:
         return self.mode_2_idiom()
     # -----------------------------------------------------
     # state=0 自由模式
     # ---------
     # 自我介绍
     # ---------
     res = """我是Noir哟,由Navi开发的第一代基于 HTTP + Flask 的 QuneBot。详细信息可以在这里查看哦:https://navihx.github.io/2020/04/09/QQBot%E5%BC%80%E5%8F%91/\n"""
     pattern = re.compile(u'自我介绍')
     matched = re.search(pattern, self.message)
     if matched:
         return res
     pattern = re.compile(u'你是谁')
     matched = re.search(pattern, self.message)
     if matched:
         return res
     # ---------
     # 改名
     # ---------
     matched = re.search(pattern=r"[(.*?)]",
                         string=self.message,
                         flags=re.M | re.I)
     if matched:
         new_name = matched.group(1)
         return database.change_name(self.uid, new_name, db)  # 直接在数据库中更改
     # ---------
     # 骰子
     # ---------
     list = [u'骰子']
     for key in list:
         pattern = re.compile(key)
         matched = re.search(pattern, self.message)
         if matched:
             pattern = re.compile(u'([0-9]*?)面')
             matched = re.search(pattern, self.message)
             if matched:
                 return throwDice(int(matched.group(1)))
             else:
                 return throwDice()
     # --------
     # 进入高强度对线
     # --------
     if self.setting['nmsl']['on']:
         list = self.setting['nmsl']['key']
         for key in list:
             pattern = re.compile(key)
             matched = re.search(pattern, self.message)
             if matched:
                 db = database.connect_db()
                 if database.change_state(self.uid, 1, db):
                     return '你真的做好被骂的觉悟了吗?\n不道歉我可是不会停下来的噢'
                 else:
                     return '别以为我说不过你,只是我今天不想骂人而已'
     # --------
     # 成语接龙
     # --------
     if self.setting['idiom']['on']:
         list = self.setting['idiom']['key']
         for key in list:
             pattern = re.compile(key)
             matched = re.search(pattern, self.message)
             if matched:
                 db = database.connect_db()
                 if database.change_state(self.uid, 2, db):
                     idiom.init(self.uid)
                     return '那就一起来玩成语接龙吧'
                 else:
                     return '今天不是很想玩呢'
     # --------
     # 默认回复
     # --------
     return "不好意思你在说什么我怎么听不懂QAQ"
コード例 #9
0
        bot.send_message(message.chat.id,
                         "При возникновении проблем с ботом пропишите /start")
        bot.send_message(message.chat.id,
                         config.MAIN_ANSWER,
                         reply_markup=markup_MAIN)
        set_state(message.chat.id, config.States.S_PROMOSALES.value)
    msg = Message(api_key=config.API_KEY,
                  platform=config.PLATFORM,
                  version=config.VERSION,
                  user_id=str(message.chat.id),
                  message=message.text,
                  intent="/start")
    msg.send()


@bot.message_handler(func=lambda message: get_state(message.chat.id) == config.
                     States.S_PROMOSALES.value)
def user_choosing_section(message):
    if message.text == config.PROMOCODES_BUTTON:
        set_state(message.chat.id, config.States.S_CATEGORIES_PROMO.value)
        bot.send_message(message.chat.id,
                         config.CATEGORY_ANSWER,
                         reply_markup=markup_CATEGORY)
    elif message.text == config.SALES_BUTTON:
        set_state(message.chat.id, config.States.S_CATEGORIES_SALES.value)
        bot.send_message(message.chat.id,
                         config.CATEGORY_ANSWER,
                         reply_markup=markup_CATEGORY)
    elif message.text == config.CONTACT_BUTTON:
        bot.send_message(message.chat.id,
                         config.get_text(config.SRC_CONTACT),