def __init__(self): active_bots = BotProfile.objects(active=True) for bot in active_bots: try: self.run(bot) except Exception as ex: bot.active = False BotProfile.save(bot)
def send(self, mailing_id): mailing = Mailing.objects(id=mailing_id).first() if mailing is None: return '', 404 if request.form: bots = [ dict(bot_id=bot_id, bot=BotManager().get(bot_id)) for bot_id in request.form.getlist('bots') ] bots = [bot for bot in bots if bot['bot'] is not None] if bots is None or len(bots) == 0: flash('Нет активных ботов', category='error') else: for bot in bots: Thread(target=methods.send_messages, args=( bot['bot_id'], bot['bot'], mailing, )).start() flash(f'Отправлено ({len(bots)})', category='success') return redirect(url_for('mailing.send', mailing_id=mailing_id)) return self.render('mailing_send.html', mailing=mailing, bots=BotProfile.objects(active=True))
def _search(self, query, search_term): op, term = parse_like_term(search_term) criteria = None for field in self._search_fields: if field.name == 'bot': bots = BotProfile.objects(name__contains=term) for bot in bots: if not (bot is None): flt = {'%s__%s' % (field.name, 'exact'): bot.id} q = mongoengine.Q(**flt) if criteria is None: criteria = q else: criteria |= q else: flt = {'%s__%s' % (field.name, op): term} q = mongoengine.Q(**flt) if criteria is None: criteria = q else: criteria |= q return query.filter(criteria)
def off_all(self): bots = BotProfile.objects() for bot in bots: bot_id = bot.id.binary.hex() if BotManager().is_running(bot_id): BotManager().stop(bot_id) bot.active = False bot.save() return 'good'
def create_wallet(self): if request.form: not_for_all = False wallet = request.form['wallet'] for key in request.form: try: if key != 'wallet': bot_id = request.form[key] bot = BotProfile.objects(id=bot_id).first() bot.wallet = wallet bot.save() except Exception: not_for_all = True flash('К боту ' + request.form[key] + ' не удалось привязать кошелек') if not not_for_all: flash('Кошелек успешно привязан') return self.render('wallet.html', bots=BotProfile.objects())
def set_active(self, bot_id): bot = BotProfile.objects(id=bot_id).first() if bot is None: return '', 404 bot.active = request.args['active'] == 'true' bot.save() if bot.active and not BotManager().is_running(bot_id): BotManager().run(bot) elif not bot.active and BotManager().is_running(bot_id): BotManager().stop(bot_id) return {'active': bot.active}
def final_state(self, message, entry=False): texts = self.get_texts() user = self.get_user(message) if entry: if self.botType == "fi": messId = message.chat.id keybd = keyboards2 elif self.botType == "sec": messId = message.from_user.id keybd = keyboards else: messId = "" keybd = "" bot = BotProfile.objects(id=self.bot_id).first() text = Payment.objects( id=user.payment.id).first().answer_text.replace( '#wallet#', bot.wallet) self._bot.send_message( messId, text, reply_markup=keybd.set_keyboard(texts, [], back_btn=True, done_btn=True)) else: if self.botType == "fi": messText = message.text elif self.botType == "sec": messText = message.data else: messText = "" if messText == texts['done_btn']: methods.create_order(self, user) self._go_to_state(message, self.districts_state) elif messText == texts['back_btn']: self._go_to_state(message, self.payment_state) else: if self.botType == "fi": messId = message.chat.id keybd = keyboards2 elif self.botType == "sec": messId = message.from_user.id keybd = keyboards else: messId = "" keybd = "" text = Payment.objects( id=user.payment.id).first().answer_on_payment self._bot.send_message(messId, text, reply_markup=keybd.set_keyboard( texts, [], back_btn=True)) user.code = messText user.save() methods.create_order(self, user)
def bot_photo(self, bot_id): bot = BotProfile.objects(id=bot_id).first() if bot is None or bot.photo_file_id is None or len( bot.photo_file_id) == 0: return '', 404 photo = BotPhoto.objects(t_bot_id=bot.t_id, file_id=bot.photo_file_id).first() if photo is None: return '', 404 resp = flask.Response(photo.data) resp.headers['Content-Type'] = 'image/png' return resp
def on_all(self): bots = BotProfile.objects() for bot in bots: bot_id = bot.id.binary.hex() if not BotManager().is_running(bot_id): try: BotManager().run(bot) bot.active = True bot.save() except Exception as ex: if '401' in str(ex): flash('Бот ' + bot.name + ' был забанен') return 'good'
def statistics(self): try: Botnames = BotProfile.objects() count = 0 for i in Botnames: count += 1 print("Обновлена статистика у " + str(count) + "/" + str(len(Botnames))) # print(i.name) FinalId = MyBotProfileView.statistic(self, i.name) i.stat = FinalId i.save() except ApiException as e: print(e) return dict(error='WRONG_TOKEN'), 400 return "good"
def statistic(self, username): users = User.objects() count = 0 countSec = 0 countThird = 0 Err = False for user in users: try: # print(user.bot, "BOTNAME") if user.bot is not None: name1 = BotProfile(name=user.bot) # print("Second", " 2", name1, type(name1)) if str(name1) == str(username): # print("GotchA!!!") count += 1 date_was = user.datetime date_now = datetime.now() dates = dt.datetime.today() daysOfMonth = dates.day hours = int(daysOfMonth) * 24 # print(hours, 'hours') if not (date_was is None) and ( date_now - date_was).total_seconds() / 60 / 60 <= hours: countSec += 1 if not (date_was is None) and (date_now - date_was ).total_seconds() / 60 / 60 <= 24: countThird += 1 except Exception as e: print(e) print("Default") Err = True if not Err: # print(count, "111") # print("ste", str(countSec)) # print("third", str(countThird)) return "{0}-{1}-{2}".format(count, countSec, countThird) else: return "{0}-{1}-{2}".format(count, countSec, countThird)
def create_wallet(self, bot_id): if request.form: not_for_all = False wallet = request.form['greet_msg'] for key in request.form: try: if key != 'greet_msg': bot_id = request.form[key] text = Texts.objects(bot_id=bot_id) if str(text) != "[]": for i in text: if str(i) != "None": i.greet_msg = wallet i.save() else: Texts(greet_msg=wallet, bot_id=bot_id, back_btn=BACKBTN, use_buttons_msg=USEBUTTONS, choose_good_msg=CHOOSEGOOD, choose_city_msg=CHOOSESITY, choose_district_msg=CHOOSEDISTRICT, choose_payment_msg=CHOOSEPAYMENT, done_btn=DONE, leads_btn=LEADS, new_order_msg=NEWORDER, selected_good_msg=SELECTED, selected_good_msg2=SELECTED2).save() except Exception as e: print(e) not_for_all = True flash('К боту ' + request.form[key] + ' не удалось привязать greet msg') if not not_for_all: flash('Greet msg успешно привязано') return self.render('MyMsg.html', bot_id=bot_id, bots=BotProfile.objects())
def get_url(self, endpoint, **kwargs): bots = BotProfile.objects(active=True) for bot in bots: kwargs.update(bot_id=bot.id.binary.hex()) return url_for(endpoint, **kwargs)
def create_dub(self, bot_id, bot_2): try: telebot.TeleBot(bot_2).get_me() except Exception: return 'ERROR, go back' bot_2 = loads( BotProfile.objects(token=bot_2).first().to_json())['_id']['$oid'] text = Texts.objects(bot_id=bot_id).first() if not (text is None): text_dict = loads(text.to_json()) dub_text = {} for key in text_dict: if key != '_id': dub_text.update({key: text_dict[key]}) dub_text['bot_id'] = bot_2 new_text = Texts(**dub_text) new_text.save() cities = City.objects(bot_id=bot_id) if cities is not None: for city in cities: if not (city is None): city_dict = loads(city.to_json()) dub_city = {} for key in city_dict: if key != '_id': dub_city.update({key: city_dict[key]}) dub_city['bot_id'] = bot_2 new_city = City(**dub_city) new_city.save() goods = Good.objects(city_id=city.id.binary.hex()) for good in goods: if good is not None: Good(name=good.name, city_id=new_city.id.binary.hex(), price=good.price, description=good.description, photo=good.photo, districts=good.districts).save() payment = Payment.objects(bot_id=bot_id).first() if not (payment is None): payment_dict = loads(payment.to_json()) dub_payment = {} for key in payment_dict: if key != '_id': dub_payment.update({key: payment_dict[key]}) dub_payment['bot_id'] = bot_2 new_payment = Payment(**dub_payment) new_payment.save() return str(bot_2)