def post(self, id): try: body = request.get_json() user_id = get_jwt_identity() user = User.objects.get(id=user_id) to_remove = User.objects.get(id=body['id']) chat = Chat.objects.get(id=id) if to_remove not in chat.users: return '', 401 to_remove_name = to_remove.name + ' ' + to_remove.surname if user in chat.admins or user == chat.host: chat.users.remove(to_remove) message = Message(type='userRemoved', text=to_remove_name, author=user) chat.messages.append(message) message.save() chat.save() return '', 200 return '', 401 except DoesNotExist: raise DocumentMissing except Exception as e: raise InternalServerError
async def process_successful_payment(message: types.Message, state: FSMContext): user = DataBaseFunc.get_user(message.from_user.id) data = await state.get_data() course = DataBaseFunc.get_course(user.course_id) DataBaseFunc.add_course_in_user(user, course) user.subscribe_end = False DataBaseFunc.commit() for channel in course.channels: try: await bot.unban_chat_member(chat_id=channel.channels.id, user_id=user.id) except: continue mess = await bot.send_message( message.chat.id, str(get_text(user, 'subscribe_menu_good_pay')).format( amount=course.cost, currency=message.successful_payment.currency, coursename=course.name)) mess2 = await bot.send_message(message.chat.id, get_text(user, 'start'), reply_markup=await UserGeneratorKeyboard.start_button(user)) await DataBaseFunc.delete_messages(user) ms = Message(user_id=user.id, message_id=mess.message_id) ms2 = Message(user_id=user.id, message_id=mess2.message_id) DataBaseFunc.add(ms) DataBaseFunc.add(ms2) await UserStateMainMenu.main_menu.set()
def post(self, conversation_id): body = request.get_json() user_id = get_jwt_identity() conversation = Conversation.objects.get(id=conversation_id) user = User.objects.get(id=user_id) message = Message(**body) message.conversation = conversation message.save() id = message.id return {'id': str(id)}, 200
def post(self, id): try: user_id = get_jwt_identity() user = User.objects.get(id=user_id) chat = Chat.objects.get(id=id) if user in chat.users: chat.users.remove(user) message = Message(type='userLeft', text='', author=user) chat.messages.append(message) message.save() chat.save() return '', 200 elif user in chat.admins: chat.admins.remove(user) message = Message(type='userLeft', text='', author=user) chat.messages.append(message) message.save() chat.save() return '', 200 return '', 404 except DoesNotExist: raise DocumentMissing except Exception as e: raise InternalServerError
def main(): print('Starting script...') client = ApiHandler(API_ID, API_HASH) print('Auth - successfully!') messages = Message.select() print('Getting messages...\nGot {} messages'.format(len(messages))) user_ids = [] for message in messages: if message.from_id and message.from_id not in user_ids: try: user_ids.append(message.from_id) except Exception: pass print('Got {} unique users'.format(len(user_ids))) users = client.get_users(user_ids) for user in users: User.get_or_create(user_id=user['id'], username=user['username'], first_name=user['first_name'], last_name=user['last_name']) print('Done!')
def save_item(item: Item, spider): if isinstance(item, MessageItem): def message_is_unique(message_model: Message, limit=20) -> bool: subquery = session.query(Message) \ .order_by(Message.created_at.desc(), Message.id.desc()) \ .limit(limit) \ .subquery() alias = aliased(Message, subquery) return not session.query( session.query(alias).filter( alias.text == message_model.text, alias.image == message_model.image).exists()).scalar() def message_fit_the_length(message_model: Message) -> bool: if message_model.image: return len(remove_tags(message_model.text)) <= 1024 return len(remove_tags(message_model.text)) <= 4096 message = Message(text=item.get('text'), image=item.get('image'), url=item.get('url')) if message_is_unique(message) and message_fit_the_length(message): with session.begin(): session.add(message)
async def subscribe_continue_pay(callback: types.CallbackQuery, state: FSMContext): """Продлить подписку после её окончания""" await callback.answer() user = DataBaseFunc.get_user(callback.from_user.id) course = DataBaseFunc.get_course(user.course_id) timestamp = get_timestamp(user) PRICE = types.LabeledPrice(label=course.name, amount=int(f"{course.cost}00")) await state.update_data(last_course_id=user.course_id) mess = await bot.send_invoice( callback.message.chat.id, title=course.name, description=course.description, provider_token=TOKEN_SHOP_YANDEX, currency="rub", is_flexible=False, prices=[PRICE], start_parameter=f"course_id_{course.id}", payload=timestamp, # reply_markup=UserGeneratorKeyboard.course_back_in_list(user) # start_parameter = f"lol-lel-cheburek", # payload = "test-payload-check" ) await DataBaseFunc.delete_messages(user) ms = Message(user_id=user.id, message_id=mess.message_id) DataBaseFunc.add(ms)
async def start_message(message: types.Message): """Обработчик команды /start.""" user = DataBaseFunc.get_user(message.from_user.id) if user != None: if (user.chat_id != message.chat.id): user.chat_id = message.chat.id DataBaseFunc.commit() await message.delete() if user == None: user = User(id=message.from_user.id, username=message.from_user.username, chat_id=message.chat.id, is_check_seven_days=False) DataBaseFunc.add(user) DataBaseFunc.commit() mess = await message.answer( get_text(user, 'register'), reply_markup=UserGeneratorKeyboard.register_button(user)) await DataBaseFunc.delete_messages(user) ms = Message(user_id=user.id, message_id=mess.message_id) DataBaseFunc.add(ms) await UserStateRegister.main_menu.set() elif user.is_register == False: if (user.chat_id == None): user.chat_id = message.chat.id mess = await message.answer( get_text(user, 'register'), reply_markup=UserGeneratorKeyboard.register_button(user)) await DataBaseFunc.delete_messages(user) ms = Message(user_id=user.id, message_id=mess.message_id) DataBaseFunc.add(ms) await UserStateRegister.main_menu.set() else: if (user.chat_id == None): user.chat_id = message.chat.id mess = await message.answer(get_text(user, 'start'), reply_markup=await UserGeneratorKeyboard.start_button(user)) await DataBaseFunc.delete_messages(user) ms = Message(user_id=user.id, message_id=mess.message_id) DataBaseFunc.add(ms) await UserStateMainMenu.main_menu.set()
def send_message_seven(user): text = "Добрый день. Ваша подписка на онлайн-курс Юланы Селивановой «Здоровая кожа» заканчивается через неделю. Успейте посмотреть все уроки, которые откладывали на потом. Когда подписка закончится ее можно будет возобновить через бота Telegram." data = {'chat_id': user.chat_id, 'text': text} answer = create_requets("POST", "sendMessage", data=data) message_id = json.loads(answer)['result']["message_id"] message = Message(user_id=user.id, message_id=message_id) DataBaseFunc.add(message)
def post(self, id): try: user_id = get_jwt_identity() chat = Chat.objects.get(id=id) user = User.objects.get(id=user_id) message = Message(text=request.form['text'], author=user) chat.messages.append(message) message.save() chat.save() if 'file[]' in request.files: filenames = [] files = request.files.getlist('file[]') for file in files: filename = str(message.id) + file.filename if save_file(filename, file): filenames.append(filename) message.images = filenames message.save() socketio.emit('update', {}, room='chat' + str(chat.id)) return { 'id': str(message.id) }, 200 except DoesNotExist: raise DocumentMissing except Exception as e: raise InternalServerError
def post(self): jti = get_jwt()['jti'] body = request.get_json() user = get_user_by_jti(jti) if user: if token_valid(user): token_update(user) message = Message(user.name, body["message"]) id = message.save() return { 'id': id, 'sender': message.sender, 'message': message.message } else: return response_token_expired_logout(user) else: return response_token_invalid()
def handleMessage(data): # data: contain { message: { _id: uuid4, text: "", user: {_id: "", name: "", avatar: ""}, createdAt: "" }, conversationId: "1", receiverId: "" } # convert the data to python Dictionary data = json.loads(data) # print("data['receiverId'] ", data['receiverId']) # send the new message to conversation print("message ", data['message'], " conversationId ", data['conversationId']) emit("message", data['message'], room=data['conversationId']) # set the sender # try to get user from db. try: sender = User.objects.get(userId=data['message']['user']['_id']) print("User in message from db", json.loads(sender.to_json())) # if user does not exist. except User.DoesNotExist: sender = User(userId=data['message']['user']['_id'], name=data['message']['user']['name'], avatar=data['message']['user']['avatar']).save() print("\n\n\nsender: ", sender, "\nchat.py L:156") # get the conversation conversation = Conversation.objects.get( conversationId=str(data['conversationId'])) # set the new message newMessage = Message(messageId=data['message']['_id'], createdAt=str(data['message']['createdAt']), text=data['message']['text'], user=sender) # , conversationRef=conversation) print("\n\n\nnewMessage: ", newMessage.to_json(), "\nchat.py L:160") print("\n\n\nnewMessage: ", newMessage, "\nchat.py L:162") # save the chages on the database # newMessage.save() # add the new message to messages in the conversation conversation.addMessage(newMessage) # set readStatus # conversation.updateReadStatus(userId=sender.userId) conversation.save() print("new message to conversationId ", str(data['conversationId']))
def main(): print('Starting script...') parser = argparse.ArgumentParser() parser.add_argument("-full_history", action="append", help="increase output verbosity") args = parser.parse_args() FULL_HISTORY = True if args.full_history else False print('Getting all messages - {}'.format(FULL_HISTORY)) client = ApiHandler(API_ID, API_HASH) print('Auth - successfully!') sources = export_sources(need_history=FULL_HISTORY) print('Getting sourses...\nGot {} sources'.format(len(sources))) for source in sources: print('Getting {} messages...'.format(source.username)) if FULL_HISTORY: messages = client.get_chat_messages(source.username, all=True) else: messages = client.get_chat_messages(source.username) print('Got {} messages.\nSaving {} messages...'.format(len(messages), source.username)) for message in messages: try: Message.get_or_create( source_id=source._get_pk_value(), message_id=message['id'], message=message['message'], date=message['date'], media='Yes' if message['media'] else 'No', from_id=message['from_id'] ) except KeyError: pass print('Done!')
def post(self, host_id): try: user_id = get_jwt_identity() user = User.objects.get(id=user_id) host = User.objects.get(id=host_id) host_chat_info = None chat = Chat.objects(host=host, type='public').first() if chat: if user not in chat.users and user not in chat.admins and user != chat.host: chat.users.append(user) else: chat = Chat(host=host) chat.users.append(user) host_chat_info = ChatInfo(chat=chat, user=host) message = Message(type='userJoined', text='', author=user) chat.messages.append(message) chat_info = ChatInfo.objects(chat=chat, user=user).first() if not chat_info: chat_info = ChatInfo(chat=chat, user=user) chat_info.message = get_last_message(chat) message.save() chat.save() chat_info.save() if host_chat_info: host_chat_info.save() return { 'id': str(chat.id) }, 200 except DoesNotExist: raise DocumentMissing except Exception as e: raise InternalServerError
def post(self, conversation_id): conversation = Conversation.objects.get(id=conversation_id) query = Message.objects() character = Character.objects.get(id=conversation.character.id) query = Knowledge.objects() knowledges = Knowledge.objects(character=conversation.character.id) ramdom_message = [] for i in range(0,random.randint(1, 10)): ramdom_message.append(knowledges[random.randrange(len(knowledges))].content+' ') message = Message() message.content = ''.join(ramdom_message).strip() message.conversation = conversation message.sender_character = True message.save() return Response(message.to_json(), mimetype="application/json", status=200)
def send_message(user): text = "У вас кончилась подписка, пожалуйста, продлите её, чтобы иметь доступ к каналам." text_button = "Продлить подписку" keyboard = json.dumps({ "inline_keyboard": [[{ "text": "Продлить подписку", "callback_data": "subscribe_continue_pay" }], [{ "text": "Связаться с менеджером", "callback_data": "continue_subs_manager", "url": "t.me/oxybes" }]] }) data = {'chat_id': user.chat_id, 'text': text, 'reply_markup': keyboard} answer = create_requets("POST", "sendMessage", data=data) message_id = json.loads(answer)['result']["message_id"] message = Message(user_id=user.id, message_id=message_id) DataBaseFunc.add(message)
def post(self, c_id): ''' save the message in to the dB failure: 400 (bad request if the c_id is not valid) success: 200 Arg: c_id - the company id to submit the message to msg - the msg string to submit name - the name of the person who submitted the message. ''' parser = reqparse.RequestParser() parser.add_argument('msg', type=str, required=True) parser.add_argument('name', type=str, required=True) data = parser.parse_args() if Company.query.filter_by(id=int(c_id)).first( ) is None: # best is to use first_or_404() but as i am not going with exception, so handling this way. return {"msg", "Invalid Company ID"}, 400 msg = Message(c_id=int(c_id), by=data["name"], msg=data['msg']) db.session.add(msg) db.session.commit() return {"msg": "Message added to board."}, 200
def submit_order_by_shopcart(token_type,user_info): result={'code':1,'msg':'ok'} try: data=request.get_json() pay_type=data.get('pay_type',0)#0货到付款 1在线支付 use_coupons=data.get('use_coupons',None) get_coupons=data.get('get_coupons',None) buyerAddress=BuyerAddress.query.filter_by(buyer_id=user_info.buyer_id,is_default='1').first() rv=[] if not buyerAddress: raise Exception('user dont have default address') carGrouptList=getOrderCartList(user_info.buyer_id, buyerAddress.address_id) communityId=buyerAddress.community_id community= Community.query.filter_by(community_id=communityId).first() detailAddress='' if community: detailAddress=community.community_name+" "+buyerAddress.detail_address else: detailAddress=buyerAddress.detail_address for order_info in carGrouptList: order=Order() order.order_no=build_order_no() order.shop_id=order_info['shop_id'] order.buyer_id=user_info.buyer_id order.sale_money=order_info['sum_the_shop'] order.freight=order_info['freight'] order.submit_time=datetime.now().strftime('%Y-%m-%d %H:%M:%S') order.address_id=buyerAddress.address_id order.send_address=detailAddress order.receiver=buyerAddress.consignee order.phone=buyerAddress.phone order.remark=data.get('remark','') order.status='0' #已提交 order.pay_type=pay_type get_coupon_money=0 if use_coupons: for use_coupon in use_coupons: if int(use_coupon['shop_id'])==int(order.shop_id): sql='''insert into tb_coupon (CouponType,ShopID,BuyerID,OrderNO,CouponMoney) values(%s,%s,%s,%s,%s)''' db.engine.execute(sql,('1',order.shop_id,user_info.buyer_id,order.order_no,use_coupon['coupon_money'])) order.use_coupon=use_coupon['coupon_money'] if get_coupons: for get_coupon in get_coupons: if int(get_coupon['shop_id']==int(order.shop_id)): get_coupon_money=get_coupon['coupon_money'] order.get_coupon=get_coupon_money if not order.use_coupon: order.use_coupon=0 order.sale_money=float(order.sale_money)-float(order.use_coupon) db.session.add(order) goods_list=getGoodsList(order.shop_id,order.buyer_id) for goods_info in goods_list: purchase=Purchase.query.filter_by(goods_id=goods_info['goods_id']).order_by(Purchase.batch_no).first() quantity=goods_info['quantity'] if purchase: purchase.quantity-=quantity db.session.commit() order_detail=OrderDetail() order_detail.order_no=order.order_no order_detail.goods_id=goods_info['goods_id'] if purchase: order_detail.batch_no=purchase.batch_no order_detail.sale_price=goods_info['sale_price'] order_detail.quantity=quantity order_detail.discount_price=goods_info['discount_price'] db.session.add(order_detail) r_map={} r_map['order_no']=order.order_no r_map['shop_id']=order.shop_id r_map['sale_money']=str(order.sale_money) r_map['use_coupon']=str(order.use_coupon) r_map['get_coupon']=str(order.get_coupon) r_map['freight']=str(order.freight) r_map['has_alipay']=order_info['has_alipay'] r_map['has_online_bank']=order_info['has_online_bank'] rv.append(r_map) message=Message() message.sender_type='3' message.sender_name='系统消息' message.receiver_type='1' #商铺 message.receiver=order_info['shop_id'] message.receiver_name=order_info['shop_name'] message.send_title=r'您有一个新订单:'+order.order_no message.send_content=r'''您有一个新的订单:<a style='text-decoration:underline' href='index.php/Display/OrderDetailPage?OrderNo=".$OrderNo."'>".$OrderNo."</a><br/><div class='date'>点击订单编号查看详细信息!</div> ''' message.send_time=datetime.now() db.session.add(message) db.session.commit() send_email_2_shop(order.shop_id, order.order_no) #删除购物车 delete_cart_sql=''' delete from tb_shoppingcart where BuyerID=%s and IsSelected='1' ''' db.engine.execute(delete_cart_sql,(user_info.buyer_id)) db.session.commit() result['orders']=rv except Exception,e: current_app.logger.exception(e) result['code']=0 result['msg']=e.message
def get(self, conversation_id): conversation = Conversation.objects.get(id=conversation_id) query = Message.objects() print("Id: "+conversation_id) messages = Message.objects(conversation=conversation.id).to_json() return Response(messages, mimetype="application/json", status=200)