def guide_edit_handler(bot: DialogBot, params): """ Обработчик изменения гайда, "GUIDE_EDIT" """ if params[0].sender_uid not in DELETE_CACHE: guide_name = params[0].message.textMessage.text if not Guide.select().where(Guide.name == guide_name).exists(): bot.messaging.send_message( params[0].peer, "Такого гайда не существует. Попробуйте другое название или напишите /menu для возврата в главное меню" ) return utils.send_guide_by_name(bot, params, guide_name) bot.messaging.send_message( params[0].peer, "Напишите, на что мне заменить текущий текст:" ) DELETE_CACHE[params[0].sender_uid] = guide_name else: new_text = params[0].message.textMessage.text guide = Guide.select().where(Guide.name == DELETE_CACHE[params[0].sender_uid]).get() guide.text = new_text guide.save() bot.messaging.send_message( params[0].peer, "Текст успешно обновлен" ) del DELETE_CACHE[params[0].sender_uid] utils.cancel_handler(bot, params)
def default_schedule_add_handler(bot: DialogBot, params): """ Обработчик шеулдера, "GUIDE_SCHEDULE_ADD" """ if params[0].sender_uid not in SCHEDULE_CACHE: guide_name = params[0].message.textMessage.text if not Guide.select().where(Guide.name == guide_name).exists(): bot.messaging.send_message( params[0].peer, "Такого гайда не существует. Попробуйте другое название или напишите /cancel для возврата в главное меню" ) return guide_id = Guide.select().where(Guide.name == guide_name).get().get_id() SCHEDULE_CACHE[params[0].sender_uid] = guide_id bot.messaging.send_message( params[0].peer, "Когда мне следует его опубликовать?" ) bot.messaging.send_message( params[0].peer, "Рекомендуемый формат даты: ДД/ММ/ГГ ЧЧ:ММ \nДругие возможные форматы:\n" "* Завтра в 12:01\n" "* послезавтра" ) else: date_from_user = params[0].message.textMessage.text date = dateparser.parse(date_from_user) if date is None: bot.messaging.send_message( params[0].peer, "Не могу понять дату, попробуйте другой формат" ) return bot.messaging.send_message( params[0].peer, f"Хорошо, я отправлю его всем пользователям {date.day}/{date.month}/{date.year} в {date.hour}:{date.minute}" ) # TODO: Сделать подтверждение, когда пофиксят баг new_job = Job.create( guide_id=SCHEDULE_CACHE[params[0].sender_uid], publication_time=date ) new_job.save() del SCHEDULE_CACHE[params[0].sender_uid] utils.cancel_handler(bot, params)
def scheduled_job_delete_handler(bot: DialogBot, params): job_id = int(params[0].value) job = Job.select().where(Job.id == job_id).get() # TODO Когда баг пофиксят, надо подтверждение удаления name = Guide.select().where(Guide.id == job.guide_id).get().name job.delete_instance() bot.messaging.send_message( bot.users.get_user_peer_by_id(params[0].uid), f"Гайд '{name}' был успешно удален из отложенных" ) jobs = {} for job in Job.select().order_by(Job.publication_time): jobs[str(job.get_id())] = f"{Guide.select().where(Guide.id == job.guide_id).get().name} " \ f" {job.publication_time.hour}:{job.publication_time.minute}" \ f" {job.publication_time.day}/{job.publication_time.month}/{job.publication_time.year}" if len(jobs): bot.messaging.update_message( params[0], "Удаление отсроченного гайда", utils.get_scheduled_jobs_list(jobs) ) else: utils.cancel_handler(bot, params)
def guide_deletion_handler(bot: DialogBot, params): """ Обработчик статуса GUIDE_DELETION """ guide_name = params[0].message.textMessage.text if not Guide.select().where(Guide.name == guide_name).exists(): bot.messaging.send_message( params[0].peer, "Гайда с таким названием не существует" ) else: guide = Guide.select().where(Guide.name == guide_name).get() guide.delete_instance() # TODO: Замутить подтверждение удаления, когда баг пофиксят bot.messaging.send_message( params[0].peer, "Гайд успешно удален" ) utils.cancel_handler(bot, params)
def addguide_url(): name=request.args.get('name') password=request.args.get('password') gender=request.args.get('gender') age = request.args.get('age') rating = request.args.get('rating') list_review=request.args.get('list_review') avatar = request.args.get('avatar') bio =request.args.get('bio') language =request.args.get('language') cred = request.args.get('cred') location = request.args.get('location') videolink= request.args.get('videolink') cvlink =request.args.get('cvlink') linkin = request.args.get('linkin') email =request.args.get('email') act_level = request.args.get('act_level') exp = request.args.get('exp') price_hour = request.args.get('price_hour') address = request.args.get('address') freetime = request.args.get('freetime') phone = request.args.get('phone') calender = request.args.get('calender') try: guide=Guide( name=name, password=password, gender=gender, age = age, rating = rating, list_review=list_review, avatar = avatar, bio =bio, language =language, cred = cred, location = location, videolink= videolink, cvlink =cvlink, linkin = linkin, email =email, act_level = act_level, exp = exp, price_hour = price_hour, address = address, freetime = freetime, phone = phone, calender = calender, ) db.session.add(guide) db.session.commit() return "Guide added. guide id={}".format(guide.id) except Exception as e: return(str(e))
def default_admin_handler(bot: DialogBot, params): """ Обработчик главного меню для администратора бота, "default_admin" """ if params[0].value == "list_guides": guides = [guide for guide in Guide.select()] if len(guides): bot.messaging.send_message( bot.users.get_user_peer_by_id(params[0].uid), "Выберите гайд для просмотра", utils.get_guides_layout(guides) ) else: bot.messaging.send_message( bot.users.get_user_peer_by_id(params[0].uid), "Пока не существует ни одного общедоступного гайда" ) elif params[0].value == "delete_guide": bot.messaging.send_message( bot.users.get_user_peer_by_id(params[0].uid), "Для удаления гайда напиши, пожалуйста, его название. Для отмены операции напиши /cancel" ) utils.set_state_by_uid(params[0].uid, "GUIDE_DELETION") elif params[0].value == "new_guide": bot.messaging.send_message( bot.users.get_user_peer_by_id(params[0].uid), "Отправь название нового гайда, одним сообщением" ) utils.set_state_by_uid(params[0].uid, "NEW_GUIDE_NAME") elif params[0].value == "edit_guide": bot.messaging.send_message( bot.users.get_user_peer_by_id(params[0].uid), "Какой гайд требуется редактировать?" ) utils.set_state_by_uid(params[0].uid, "GUIDE_EDIT") elif params[0].value == "schedule": bot.messaging.send_message( bot.users.get_user_peer_by_id(params[0].uid), "Настройки отсроченной отправки гайда всем пользователям", utils.get_schedule_layout() )
def addguide_random(): try: language=["English","Spanish","Vietnamese","Frech","Chinese","Russian","Korean","Japanese"] location=["HoChiMinh","Hoian","Danang","Hanoi","Hue","Sapa","Phuquoc","Halong", "Phanthiet","Mekong","Cuchi"] act_level=["Sightseeing","Foodserve","Historical","Exploration"] exp=["1year","2year","fresher","student"] password = str(random.randrange(10000000)) print(password) avatar = "../static/avatar/"+str(random.randrange(20))+".jpg" age = str(random.randrange(18,35)) guide=Guide("Rebecca Sanders",password,"Female",age,str(random.choice([1, 2, 3, 5,4])),"",avatar,"XIN CHAO (Good Morning Vietnam) Let's call me Chau(Joe). I have been working as a Tour Guide, ...",random.choice(language),"",random.choice(location),"https://www.youtube.com/embed/jgE3W8PSj2g","","https://www.linkedin.com/in/lorem","*****@*****.**",str(random.choice(act_level)),random.choice(exp),str(random.randrange(1,20)),"123 Tran Hung Dao, 1 District, HCMC","2a;4b;3c;5c;5b","0909190247","12032020a") db.session.add(guide) db.session.commit() return "Guide added. guide id={}".format(guide.id) except Exception as e: return(str(e))
def guide_build_profile(): if request.method == 'POST': print(request.form) if "idprofile" in request.form: if request.form["idprofile"]=="Generate": text = request.form['ipinput1'] #Check if text is not in database: use empty select check_exist = bool(Guide.query.filter_by(password=str(int(hashlib.sha1(text.encode('utf-8')).hexdigest(), 16) % (10 ** 8))).first()) #If in database => notification if check_exist: flash("Invalid Code, try another") return redirect(request.url) #If not in database guide = Guide("",text,"","","","","","","","","","https://www.youtube.com/embed/jgE3W8PSj2g","","","","","","","","","","") try: db.session.add(guide) db.session.commit() flash("Your Profile ID was created, save it for edit in future") except Exception as e: flash("Fail to create new profile, check your Internet connection") return redirect(request.url) return render_template('guide/build_profile.html',guide=guide, sample_profile=False) if request.form["idprofile"]=="Load": text = request.form['ipinput2'] try: guide=Guide.query.filter_by(password=str(int(hashlib.sha1(text.encode('utf-8')).hexdigest(), 16) % (10 ** 8))).first() #If password was not created, add some notification #Due with case have two password print( jsonify(guide.serialize())) except Exception as e: guide_default = Guide("","12345678","","","","","","","","","","https://www.youtube.com/embed/jgE3W8PSj2g","","","","","","","","","","") flash("This Profile code was not created, please generate new one") return render_template('guide/build_profile.html',guide=guide_default,sample_profile=True) flash("Your Previous Updated Profile was loaded") return render_template('guide/build_profile.html',guide=guide,sample_profile=False) print(request.form) print("--------------------------------------") print(request.args.getlist('apps[]')) if "save" in request.form: print("Enter Save") try: print("Enter button") if DEV: engine = create_engine("postgresql:///oxo") else: engine = create_engine(os.environ['DATABASE_URL'] )# "postgresql:///oxo") #postgresql://noah:noahpostgres@localhost:4600/oxo') connection = engine.connect() print(request.form) print(request.files) print("Connected") #print(request.form['idprofile']) #If dont have , try to trick it in form(return outside of form) curID = request.form['virtual_get_id'] name = request.form['name'] address = request.form['address'] age = request.form['age'] gender = request.form['gender'] location = request.form['location'] language = request.form['language'] act_level = request.form['act_level'] exp = request.form['exp'] bio = request.form['bio'] email = request.form['email'] phone = request.form['phone'] linkin = request.form['linkin'] price_hour = request.form['price_hour'] videolink = request.form['videolink'] print("@@@@@@@@@@@@@@@@@@@@") cvlink="" cred ="" avatar="" print("@@@@@@@@@@@@@@@@@@@@") print(request.files) if "avatar" in request.files: if request.files.get('avatar', None): f = request.files['avatar'] avatar= "../static/avatar/"+curID+f.filename f.save("static/avatar/"+curID+f.filename) #print(request.files['cvlink'].filename) if "cvlink" in request.files: if request.files.get('cvlink', None): print("ot null") f = request.files['cvlink'] cvlink= "../static/cv/"+curID+f.filename f.save("static/cv/"+curID+f.filename) if "cred" in request.files: if request.files.get('cred', None): f = request.files['cred'] cred= "../static/cred/"+curID+f.filename f.save("static/cred/"+curID+f.filename) #ListUpadate = ["name","cvlink","cred","address","age","gender","location","language","act_level","exp","bio","email","phone","linkin","price_hour","videolink",] my_query = ("UPDATE guides SET "+ "name ='"+name+"'," + "address ='"+address+"'," + "age ='"+age+"'," + "gender ='"+gender+"'," + "location ='"+location+"'," + "language ='"+language+"'," + "act_level ='"+act_level+"'," + "exp ='"+exp+"'," + "bio ='"+bio+"'," + "email ='"+email+"'," + "phone ='"+phone+"'," + "linkin ='"+linkin+"'," + "price_hour ='"+price_hour+"'," + "videolink ='"+videolink+"' ") if cvlink!="": my_query+=",cvlink ='"+cvlink+"'" if cred !="": my_query+=",cred ='"+cred+"'" if avatar !="": my_query+=",avatar ='"+avatar+"'" my_query+= " WHERE id = "+curID+";" print(my_query) connection.execute(my_query) # # try: guide=Guide.query.filter_by(id=curID).first() print(guide) except Exception as e: flash("Save Fail, check internet") return redirect(request.url) flash("Profile was saved") return render_template('guide/build_profile.html',guide=guide, sample_profile=False) except Exception as e: return(str(e)) if "changeid" in request.form: curID = request.form["changeid"] try: guide=Guide.query.filter_by(id=curID).first() print(guide) except Exception as e: flash("Can not move to Edit CV") return redirect(request.url) flash("Moved to Edit CV") return render_template('guide/build_profile.html',guide=guide, sample_profile=False) return redirect(request.url) else: guide_default = Guide("","12345678","","","","","","","","","","https://www.youtube.com/embed/jgE3W8PSj2g","","","","","","","","","","") return render_template('guide/build_profile.html',guide=guide_default, sample_profile=True)
def send_guide_by_id(bot: DialogBot, params, guide_id: int): guide = Guide.select().where(Guide.id == guide_id).get() _send_guide(bot, params, guide)
def send_guide_by_name(bot: DialogBot, params, guide_name: str): guide = Guide.select().where(Guide.name == guide_name).get() _send_guide(bot, params, guide)
def guide_creation_handler(bot: DialogBot, params): """ Обработчик создания гайда, "NEW_GUIDE_*", "new_guide_essential" """ try: state = User.select().where(User.uid == params[0].sender_uid).get().state except (AttributeError, KeyError): state = User.select().where(User.uid == params[0].uid).get().state if state == "NEW_GUIDE_NAME": name = params[0].message.textMessage.text if Guide.select().where(Guide.name == name).exists(): bot.messaging.send_message( params[0].peer, "Гайд с таким именем уже есть. Придумай другое." ) return GUIDE_CACHE[params[0].sender_uid] = { "name": name, "text": "", "essential": False } bot.messaging.send_message( params[0].peer, "Теперь напиши гайд. Что бы закончить, напиши /end" ) utils.set_state_by_uid(params[0].sender_uid, "NEW_GUIDE_TEXT") elif state == "NEW_GUIDE_TEXT": text = params[0].message.textMessage.text if text == "/end": bot.messaging.send_message( params[0].peer, "Мне следует показывать этот гайдов в списке гайдов по умолчанию для каждого пользователя? ", utils.get_essentialness() ) utils.set_state_by_uid(params[0].sender_uid, "NEW_GUIDE_ESSENTIAL") return try: GUIDE_CACHE[params[0].sender_uid]["text"] += "\n" GUIDE_CACHE[params[0].sender_uid]["text"] += text except (AttributeError, KeyError): bot.messaging.send_message( params[0].peer, "Кажется, бот перезагрузился и у него исчез кеш. Вам придется написать гайд еще раз :(" ) utils.cancel_handler(bot, params) return elif state == "NEW_GUIDE_ESSENTIAL": try: if params[0].value == "True": GUIDE_CACHE[params[0].uid]["essential"] = True else: GUIDE_CACHE[params[0].uid]["essential"] = False except (AttributeError, KeyError): bot.messaging.send_message( bot.users.get_user_peer_by_id(params[0].uid), "Кажется, бот перезагрузился и у него исчез кеш. Вам придется написать гайд еще раз :(" ) utils.cancel_handler(bot, params) return guide = Guide.create(**GUIDE_CACHE[params[0].uid]) guide.save() del GUIDE_CACHE[params[0].uid] bot.messaging.send_message( bot.users.get_user_peer_by_id(params[0].uid), "Гайд успешно создан!" ) utils.set_state_by_uid(params[0].uid, "START") utils.cancel_handler(bot, params)
bot = DialogBot.get_secure_bot( ENDPOINT, # bot endpoint from environment grpc.ssl_channel_credentials(), # SSL credentials (empty by default!) BOT_TOKEN # bot token from environment ) bot.messaging.on_message_async(on_msg, on_click) while (True): time.sleep(59) now = datetime.now() for job in Job.select(): if (job.publication_time - now).seconds <= 60: guide = Guide.select().where(Guide.id == job.guide_id).get() for user in User.select(): if not user.is_admin: bot.messaging.send_message( bot.users.get_user_peer_by_id(user.uid), f"Отложенная отправка гайда '{guide.name}':") bot.messaging.send_message( bot.users.get_user_peer_by_id(user.uid), guide.text) else: bot.messaging.send_message( bot.users.get_user_peer_by_id(user.uid), f"Пользователям был успешно отправлен гайд '{guide.name}':" ) job.delete_instance()