def add_poll(update: Update, context: CallbackContext) -> bool: user_id = update.poll_answer.user.id user: User = current_list_users.get(user_id, None) if user and user.askedSkill: msg = [] flag = 0 for i in update.poll_answer.option_ids: Db.get_instance().add_interest(user_id, i) msg.append(INTEREST_LIST[i]) flag += 1 if flag == 3: break user.askedSkill = False context.bot.send_message( text=f'``` Selected Interest:- {",".join(msg)} ```', parse_mode=ParseMode.MARKDOWN, chat_id=user_id, ) del current_list_users[user_id] context.bot.send_message( text=f'``` You are all set to go Anonymous ```', parse_mode=ParseMode.MARKDOWN, chat_id=user_id, ) helper(user_id, context) return True return False
def check_batch(update: Update, context: CallbackContext) -> bool: user: User = current_list_users.get(update.message.chat.id, None) if user and user.askedBatch: user.set_batch(update.message.text) user.askedBatch = False delete_msg(update.message.chat.id, context) context.bot.send_message( text=f'``` Inserted Data\n' f'Name {user.name}\n' f'Instagram {user.instagram_id}\n' f'Gender {user.GENDER[user.gender]}\n' f'Year {user.batch}```', parse_mode=ParseMode.MARKDOWN, chat_id=update.message.chat.id, ) Db.get_instance().write_user(user) Db.get_instance().read_users() active_commands[update.message.chat.id] = context.bot.send_poll( update.message.chat.id, ASK_FOR_INTEREST, INTEREST_LIST, allows_multiple_answers=True, is_anonymous=False).message_id return True return False
def accept_request(update: Update, context: CallbackContext): tel_to = update.callback_query.message.chat.id tel_id = active_requests.get(tel_to, None) if tel_id: tel_id = tel_id[0] active_chats[tel_id] = active_requests[tel_id][0] active_chats[active_chats[tel_id]] = tel_id del active_requests[tel_id] del active_requests[active_chats[tel_id]] delete_msg(tel_id, context) delete_msg(tel_to, context) active_commands[tel_id] = context.bot.send_message( text=f'``` Request Accepted ```', parse_mode=ParseMode.MARKDOWN, chat_id=tel_id).message_id context.bot.send_message( text= f'``` The Messages Now on (except Commands will be visible to the Anonymous ' f'person) ```', parse_mode=ParseMode.MARKDOWN, chat_id=tel_id) context.bot.send_message( text= f'``` The Messages Now on (except Commands will be visible to the Anonymous ' f'person) ```', parse_mode=ParseMode.MARKDOWN, chat_id=tel_to) res = Db.get_instance().get_common_interests(tel_id, tel_to) data = [INTEREST_LIST[x] for x in res[0].intersection(res[1])] if len(data) != 0: context.bot.send_message( text=f'``` Common Interest {" ".join(data)}```', parse_mode=ParseMode.MARKDOWN, chat_id=tel_id) context.bot.send_message( text=f'``` Common Interest {" ".join(data)} ```', parse_mode=ParseMode.MARKDOWN, chat_id=tel_to) else: context.bot.send_message( text= f'``` Interests the Anonymous User have:- {" ".join([INTEREST_LIST[i] for i in res[1]])}```', parse_mode=ParseMode.MARKDOWN, chat_id=tel_id) context.bot.send_message( text= f'``` Interests the Anonymous User have:- {" ".join([INTEREST_LIST[i] for i in res[0]])} ```', parse_mode=ParseMode.MARKDOWN, chat_id=tel_to) req = Request() req.make(tel_id, tel_to, 3) Db.get_instance().update_request(req) else: delete_msg(tel_to, context) active_commands[tel_to] = context.bot.send_message( text=f'``` Expired Request ```', parse_mode=ParseMode.MARKDOWN, chat_id=tel_to).message_id
def reveal(update: Update, context: CallbackContext) -> None: data = Db.get_instance().read_user_id( update.callback_query.message.chat_id) if data: if data.name == PLACEHOLDER: delete_msg(update.callback_query.message.chat.id, context) active_commands[ update.callback_query.message.chat. id] = context.bot.send_message( text="""``` You haven't provided the details```""", parse_mode=ParseMode.MARKDOWN, chat_id=update.callback_query.message.chat.id, ).message_id return else: data = Db.get_instance().read_user_id( active_chats[update.callback_query.message.chat_id]) if data: if data.name == PLACEHOLDER: delete_msg(update.callback_query.message.chat.id, context) active_commands[ update.callback_query.message.chat. id] = context.bot.send_message( text= """``` The user who's chatting with you hasn't provided the details```""", parse_mode=ParseMode.MARKDOWN, chat_id=update.callback_query.message.chat.id, ).message_id return keyboard = [ [ InlineKeyboardButton( "ACCEPT", callback_data=ACCEPT_REVEAL_CALLBACK_DATA), InlineKeyboardButton( "DECLINE", callback_data=DECLINE_REVEAL_CALLBACK_DATA), ], ] delete_msg( active_chats.get(update.callback_query.message.chat.id, None), context) delete_msg(update.callback_query.message.chat.id, context) active_commands[active_chats[ update.callback_query.message.chat.id]] = context.bot.send_message( text="""``` Reveal Request```""", parse_mode=ParseMode.MARKDOWN, chat_id=active_chats[update.callback_query.message.chat.id], reply_markup=InlineKeyboardMarkup(keyboard)).message_id active_commands[ update.callback_query.message.chat.id] = context.bot.send_message( text="""``` Reveal Request Sent```""", parse_mode=ParseMode.MARKDOWN, chat_id=update.callback_query.message.chat.id, ).message_id else: helper(update.callback_query.message.chat_id, context)
def questionnaire(update: Update, context: CallbackContext): chat_id = update.callback_query.message.chat.id delete_msg(chat_id, context) print(Db.get_instance().get_questions(chat_id)) if Db.get_instance().get_questions(chat_id) is None: active_commands[chat_id] = context.bot.send_message( text=ASK_FOR_QN, chat_id=chat_id, parse_mode=ParseMode.MARKDOWN).message_id asked_questionnaire[update.callback_query.message.chat.id] = True else: view_questionnaire(update, context)
def report_confirmation(update: Update, context: CallbackContext): if update.callback_query.data == ACCEPT_REPORT_CALLBACK_DATA: Db.get_instance().update_block( active_chats[update.callback_query.message.chat.id]) cancel_chat(update, context) elif update.callback_query.data == DECLINE_CALLBACK_DATA: delete_msg(update.callback_query.message.chat.id, context) active_commands[ update.callback_query.message.chat.id] = context.bot.send_message( text="""``` Report Request Closed```""", chat_id=update.callback_query.message.chat.id, parse_mode=ParseMode.MARKDOWN).message_id
def send_poll(update: Update, context: CallbackContext) -> None: delete_msg(update.callback_query.message.chat.id, context) user = Db.get_instance().read_user_id( update.callback_query.message.chat.id) user.askedSkill = True current_list_users[user.tel_id] = user Db.get_instance().delete_interest(user.tel_id) active_commands[ update.callback_query.message.chat.id] = context.bot.send_poll( update.callback_query.message.chat.id, ASK_FOR_INTEREST, INTEREST_LIST, allows_multiple_answers=True, is_anonymous=False).message_id
def cancel_chat(update: Update, context: CallbackContext): tel_id = active_chats.get(update.callback_query.message.chat.id, None) if tel_id: Db.get_instance().update_user_disconnected(tel_id) Db.get_instance().update_user_disconnected(active_chats[tel_id]) req = Request() req.make(tel_id, active_chats[tel_id], 1) Db.get_instance().update_request(req) req.make(active_chats[tel_id], tel_id, 1) Db.get_instance().update_request(req) delete_msg(tel_id, context) delete_msg(active_chats[tel_id], context) active_commands[tel_id] = context.bot.send_message( text=f'``` Chat Cancelled ```', parse_mode=ParseMode.MARKDOWN, chat_id=tel_id).message_id active_commands[active_chats[tel_id]] = context.bot.send_message( text=f'``` Chat Cancelled ```', parse_mode=ParseMode.MARKDOWN, chat_id=active_chats[tel_id]).message_id context.bot.send_message(text="/chat for chat settings", parse_mode=ParseMode.MARKDOWN, chat_id=active_chats[tel_id]) context.bot.send_message(text="/chat for chat settings", parse_mode=ParseMode.MARKDOWN, chat_id=tel_id) del active_chats[active_chats[tel_id]] del active_chats[tel_id]
def status_code(chat_id: int): if active_chats.get(chat_id, None): return 1 elif active_requests.get(chat_id, None): return 0 elif Db.get_instance().read_user_id(chat_id): return -1
def accept_reveal_request(update: Update, context: CallbackContext) -> None: user_id = update.callback_query.message.chat.id delete_msg(active_chats.get(user_id, None), context) delete_msg(user_id, context) data = Db.get_instance().read_user_id(user_id) if data: msg = f"``` Name:- {data.name}\n Instagram Id:- {data.instagram_id}\n Gender:- {data.GENDER[data.gender]}\n Year:- {data.batch}```" context.bot.send_message(text=msg, parse_mode=ParseMode.MARKDOWN, chat_id=active_chats[user_id]) data = Db.get_instance().read_user_id(active_chats[user_id]) if data: msg = f"``` Name:- {data.name}\n Instagram Id:- {data.instagram_id}\n Gender:- {data.GENDER[data.gender]}\n Year:- {data.batch}```" context.bot.send_message(text=msg, parse_mode=ParseMode.MARKDOWN, chat_id=user_id)
def register_user(update: Update, context: CallbackContext): chat_id = update.callback_query.message.chat.id if Db.get_instance().read_user_id(chat_id) is None: if current_list_users.get(chat_id, None) is None: delete_msg(chat_id, context) active_commands[chat_id] = context.bot.send_message( text=ASK_FOR_NAME, parse_mode=ParseMode.MARKDOWN, chat_id=chat_id).message_id user = User(update.callback_query.message.chat.id) current_list_users[update.callback_query.message.chat.id] = user
def decline_request(update: Update, context: CallbackContext): tel_to = update.callback_query.message.chat.id tel_id = active_requests.get(tel_to, None) if tel_id: tel_id = tel_id[0] del active_requests[tel_to] del active_requests[tel_id] delete_msg(tel_id, context) delete_msg(tel_to, context) active_commands[tel_id] = context.bot.send_message( text=f'``` Request Cancelled ```', parse_mode=ParseMode.MARKDOWN, chat_id=tel_id).message_id active_commands[tel_to] = context.bot.send_message( text=f'``` Request Cancelled ```', parse_mode=ParseMode.MARKDOWN, chat_id=tel_to).message_id Db.get_instance().update_user_disconnected(tel_id) Db.get_instance().update_user_disconnected(tel_to) req = Request() req.make(tel_id, tel_to, 2) Db.get_instance().update_request(req) else: delete_msg(tel_to, context) active_commands[tel_to] = context.bot.send_message( text=f'``` Expired Request ```', parse_mode=ParseMode.MARKDOWN, chat_id=tel_to).message_id
def parse_questions(update: Update, context: CallbackContext): delete_msg(update.message.chat.id, context) ques = update.message.text.split('/') if Db.get_instance().get_questions(update.message.chat_id): Db.get_instance().delete_questions(update.message.chat_id) Db.get_instance().add_questions(update.message.chat_id, ques) msg = "Entered Questions\n" for i in ques: msg += f"{ques.index(i) + 1} {i.strip()}\n" keyboard = [ [ InlineKeyboardButton("Edit Questionnaire", callback_data=QUESTIONNAIRE_SET), InlineKeyboardButton("<- Menu", callback_data=MENU), ], ] active_commands[update.message.chat.id] = context.bot.send_message( text=f"```{msg}```", parse_mode=ParseMode.MARKDOWN, chat_id=update.message.chat_id, reply_markup=InlineKeyboardMarkup(keyboard)).message_id asked_questionnaire[update.message.chat.id] = False
def skip_process(message, context: CallbackContext): chat_id = message.chat_id if not Db.get_instance().read_user_id(chat_id): if current_list_users.get(chat_id, None): user = current_list_users[chat_id] Db.get_instance().write_user(user) del current_list_users[chat_id] else: user = User(chat_id) Db.get_instance().write_user(user) delete_msg(message.chat.id, context) user = User(chat_id) user.askedId = False user.askedGender = False user.askedName = False user.askedBatch = False current_list_users[chat_id] = user active_commands[message.chat.id] = context.bot.send_poll( chat_id, ASK_FOR_INTEREST, INTEREST_LIST, allows_multiple_answers=True, is_anonymous=False).message_id
def send_questionnaire(update: Update, context: CallbackContext): delete_msg(update.callback_query.message.chat.id, context) ques = Db.get_instance().get_questions( update.callback_query.message.chat.id) for i in ques: msg = context.bot.send_poll( active_chats[update.callback_query.message.chat.id], f"{ques.index(i) + 1}) {i.strip()}", OPTION_LIST, is_anonymous=False) active_polls[msg.poll.id] = (msg.message_id, i) active_commands[ update.callback_query.message.chat.id] = context.bot.send_message( update.callback_query.message.chat.id, "``` Poll Sent Waiting for reply```", parse_mode=ParseMode.MARKDOWN).message_id
class EchoLayer(YowInterfaceLayer): database = Db() questions = database.getQuestions() responses = database.getResponses() def reinitialize(self): print 'resetting questions and responses...' self.questions = database.getQuestions() self.responses = database.getResponses() @ProtocolEntityCallback("message") def onMessage(self, messageProtocolEntity): #send receipt otherwise we keep receiving the same message over and print 'message van:', messageProtocolEntity.getFrom() print 'message participants:', messageProtocolEntity.getParticipant() print messageProtocolEntity.getBody() if messageProtocolEntity.getBody() == 'chat reset': self.reinitialize() receipt = OutgoingReceiptProtocolEntity( messageProtocolEntity.getId(), messageProtocolEntity.getFrom(), 'read', messageProtocolEntity.getParticipant()) messagebody = messageProtocolEntity.getBody().lower() # else: # outgoingMessageProtocolEntity = TextMessageProtocolEntity( # messageProtocolEntity.getBody(), # to = messageProtocolEntity.getFrom()) self.toLower(receipt) # uncomment to send msg defined in outgoingMessageProtocolEntity # self.toLower(outgoingMessageProtocolEntity) @ProtocolEntityCallback("receipt") def onReceipt(self, entity): ack = OutgoingAckProtocolEntity(entity.getId(), "receipt", entity.getType(), entity.getFrom()) self.toLower(ack) #Test. IQ info: http://xmpp.org/rfcs/rfc6120.html#stanzas-semantics-iq @ProtocolEntityCallback("iq") def onIq(self, entity): print(entity)
def view_questionnaire(update: Update, context: CallbackContext): chat_id = update.callback_query.message.chat_id delete_msg(chat_id, context) data = Db.get_instance().get_questions(chat_id) msg = "Entered Questions\n" for i in data: msg += f"{data.index(i) + 1} {i.strip()}\n" keyboard = [ [ InlineKeyboardButton("Edit Questionnaire", callback_data=QUESTIONNAIRE_SET), InlineKeyboardButton("<- Menu", callback_data=MENU), ], ] active_commands[chat_id] = context.bot.send_message( text=f"```{msg}```", parse_mode=ParseMode.MARKDOWN, chat_id=chat_id, reply_markup=InlineKeyboardMarkup(keyboard)).message_id asked_questionnaire[chat_id] = False
def error_handle(update: Update, context: CallbackContext): logger = logging.getLogger() logger.error(msg="Exception while handling an update:", exc_info=context.error) tb_list = traceback.format_exception(None, context.error, context.error.__traceback__) print(context.error) if isinstance(context.error, error.BadRequest): update.message.reply_markdown("``` Kindly Repeat the process ```") active_commands[update.message.chat_id] = None elif isinstance(context.error, error.Unauthorized): if status_code(update.message.chat_id) == 1: context.bot.send_message(update.message.chat_id, "``` The Anonymous user blocked the chat bot so we are stopping the chat````", parse_mode=ParseMode.MARKDOWN, ) Db.get_instance().delete_user(active_chats[update.message.chat_id]) Db.get_instance().update_user_disconnected(update.message.chat_id) del active_chats[update.message.chat_id] elif status_code(update.message.chat_id) == 0: context.bot.send_message(update.message.chat_id, "``` The Anonymous user blocked the chat bot so make another request````", parse_mode=ParseMode.MARKDOWN, ) cancel_request(update.message, context) Db.get_instance().delete_user(active_requests[update.message.chat_id]) elif isinstance(context.error, error.TimedOut): context.bot.send_message(update.message.chat_id, "``` Connection Timed Out Repeat the process````", parse_mode=ParseMode.MARKDOWN, ) helper(update.message.chat_id, context) tb_string = ''.join(tb_list) message = ( f'An exception was raised while handling an update\n' f'<pre>update = {html.escape(json.dumps(update.to_dict(), indent=2, ensure_ascii=False))}' '</pre>\n\n' f'<pre>context.chat_data = {html.escape(str(context.chat_data))}</pre>\n\n' f'<pre>context.user_data = {html.escape(str(context.user_data))}</pre>\n\n' f'<pre>{html.escape(tb_string)}</pre>' ) context.bot.send_message(chat_id=ADMIN_ID, text=message, parse_mode=ParseMode.HTML)
def set_up_random_chat(update: Update, context: CallbackContext) -> None: data = status_code(update.callback_query.message.chat_id) if data == 1: context.bot.send_message( text=f'``` Close the current chat portal to start a new one ```', parse_mode=ParseMode.MARKDOWN, chat_id=update.callback_query.message.chat.id, ) return if data == 0: data = active_requests.get(update.callback_query.message.chat.id, None) delete_msg(update.callback_query.message.chat_id, context) print(data) if data[1] == 1: keyboard = [[ InlineKeyboardButton( "CANCEL REQUEST", callback_data=CANCEL_REQUEST_CALLBACK_DATA) ]] msg_id = context.bot.send_message( update.callback_query.message.chat.id, """``` You are in request phase Waiting for Accepting```""", parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(keyboard)).message_id active_commands[update.callback_query.message.chat.id] = msg_id elif data[1] == -1: keyboard = [ [ InlineKeyboardButton("ACCEPT", callback_data=ACCEPT_CALLBACK_DATA), InlineKeyboardButton("DECLINE", callback_data=DECLINE_CALLBACK_DATA), ], ] msg_id = context.bot.send_message( update.callback_query.message.chat.id, """``` You are in request phase```""", parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(keyboard)).message_id active_commands[update.callback_query.message.chat.id] = msg_id return data = Db.get_instance().read_available_users( update.callback_query.message.chat.id) if len(data) == 0: context.bot.send_message( text=f'``` Oops! No Users Available try after some time ```', parse_mode=ParseMode.MARKDOWN, chat_id=update.callback_query.message.chat.id, ) else: user = sample(data, 1)[0] request = Request() request.make(update.callback_query.message.chat.id, user.tel_id, 0) Db.get_instance().write_request(request) active_requests[request.tel_id] = (request.tel_to, 1) active_requests[request.tel_to] = (request.tel_id, -1) delete_msg(request.tel_id, context) keyboard = [[ InlineKeyboardButton("CANCEL REQUEST", callback_data=CANCEL_REQUEST_CALLBACK_DATA) ]] active_commands[request.tel_id] = context.bot.send_message( text=f'``` Waiting for Confirmation ```', parse_mode=ParseMode.MARKDOWN, chat_id=request.tel_id, reply_markup=InlineKeyboardMarkup(keyboard)).message_id keyboard = [ [ InlineKeyboardButton("ACCEPT", callback_data=ACCEPT_CALLBACK_DATA), InlineKeyboardButton("DECLINE", callback_data=DECLINE_CALLBACK_DATA), ], ] delete_msg(request.tel_to, context) active_commands[request.tel_to] = context.bot.send_message( text=f'``` Anonymous Chat Request ```', parse_mode=ParseMode.MARKDOWN, chat_id=request.tel_to, reply_markup=InlineKeyboardMarkup(keyboard)).message_id Db.get_instance().update_user_connected(request.tel_id) Db.get_instance().update_user_connected(request.tel_to)
def __init__(self): self.__database = Db.getInstance() self.__analyst = [] self.__analyst = self.__getAllAnalyst()
def __init__(self, task: list = []): self.__database = Db.getInstance() self.__task = task
def __init__(self, attachment_ids: list = []): self.__attachment: list = [] self.__database = Db.getInstance() self.loadAttachments(attachment_ids)
from responseBuilder import ResponseBuilder from database.db import Db from database.sampledata import Sampledata db = Db() rb = ResponseBuilder() sampledata = Sampledata() print 'starting...' class SampleMessageProtocolEntity: def __init__(self, sender, message): self.sender = sender self.message = unicode(message) def getFrom(self): return self.sender def getBody(self): return self.message db.clearTestIncomingMsg() samplemessages = sampledata.getMessages() testpass = 0 testfail = 0 for i, message in enumerate(samplemessages): print 'running test ', i, ' of: ', len(samplemessages) db.insertTestIncomingMsg({'message': message['qtext'], 'sender': 'testuser'})
from responseBuilder import ResponseBuilder from database.db import Db db = Db() rb = ResponseBuilder() print 'starting...' class SampleMessageProtocolEntity: def __init__(self, sender, message): self.sender = sender self.message = unicode(message) def getFrom(self): return self.sender def getBody(self): return self.message while True: incomingmsg = raw_input('Incoming message:') db.insertTestIncomingMsg({'message': incomingmsg, 'sender': 'testuser'}) testmsg = db.getMostRecentTestIncomingMsg() msgentity = SampleMessageProtocolEntity(testmsg['sender'], testmsg['message']) response = rb.getResponsesForMessage(msgentity) if not response: print 'no response for input ', incomingmsg
from responseBuilder import ResponseBuilder from database.db import Db from database.sampledata import Sampledata db = Db() rb = ResponseBuilder() sampledata = Sampledata() print 'starting...' class SampleMessageProtocolEntity: def __init__(self, sender, message): self.sender = sender self.message = unicode(message) def getFrom(self): return self.sender def getBody(self): return self.message db.clearTestIncomingMsg() samplemessages = sampledata.getMessages() testpass = 0 testfail = 0 for i, message in enumerate(samplemessages): print 'running test ', i, ' of: ', len(samplemessages)
if __name__ == '__main__': # TOKEN = HERE updater = Updater(TOKEN, use_context=True, request_kwargs={'read_timeout': 6, 'connect_timeout': 7}) dp = updater.dispatcher if os.path.isfile('active_chats'): data.deserialize() dp.add_handler(CommandHandler('start', help_menu)) dp.add_handler(CommandHandler('status', status)) dp.add_handler(CommandHandler('menu', store)) dp.add_handler(CommandHandler('help', help_menu)) dp.add_handler(CommandHandler('chat', help_menu)) dp.add_handler(CommandHandler('cancel', cancel)) dp.add_handler(CommandHandler('skip', skip)) dp.add_handler(CommandHandler('chat_id', chat_id)) dp.add_handler(CallbackQueryHandler(callback_query_handler)) dp.add_handler(MessageHandler(Filters.text & ~Filters.command, message_handler)) dp.add_handler(MessageHandler(Filters.sticker, sticker_handler)) dp.add_handler(MessageHandler(Filters.all, message_all_handler)) dp.add_handler(PollHandler(poll_handler)) dp.add_handler(PollAnswerHandler(poll_answer_handler)) dp.add_error_handler(error_handle) Db.get_instance().create_black_list() Db.get_instance().create_active_command_list() updater.start_polling() updater.idle()
corresponding answer to the question 5. Echo the corresponding question 6. Update the conversationstate ''' from database.sampledata import Sampledata from database.db import Db from datetime import time, tzinfo, datetime, timedelta import datetime as dt import time import re import logging, sys logging.basicConfig(stream=sys.stderr, level=logging.INFO) # logging.basicConfig(stream=sys.stderr, level=logging.DEBUG) db = Db() sb = Sampledata() messages = db.getMessages() conversations = sb.getConversations() resetmsg = 'chatreset' conversationTimeoutThreshold = dt.timedelta(seconds=10) # Keeps track of the state of different conversations, so different people # can talk to the bot at the same time without the chat intermingling a # response.MessageProtocolEntity.getFrom() will be key.The most recent # interaction with the bot will be tracked to figure out if the conversation # has timed out and should be reset. Finally, it tracks how far into the # conversation they are. # conversationstates = { # m.getFrom() : [ # {conv_id : x, mostrecentinteraction: timestamp, mostrecentquestion: question_nr},
class ResponseBuilder: # logging.basicConfig(stream=sys.stderr, level=logging.INFO) logging.basicConfig(stream=sys.stderr, level=logging.WARNING) # logging.basicConfig(stream=sys.stderr, level=logging.DEBUG) db = Db() messages = db.getMessages() conversations = db.getConversations() resetmsg = 'chatreset' conversationTimeoutThreshold = dt.timedelta(seconds=10) # Keeps track of the state of different conversations, so different people # can talk to the bot at the same time without the chat intermingling a # response.MessageProtocolEntity.getFrom() will be key.The most recent # interaction with the bot will be tracked to figure out if the conversation # has timed out and should be reset. Finally, it tracks how far into the # conversation they are. # conversationstates = { # m.getFrom() : [ # {conv_id : x, mostrecentinteraction: timestamp, mostrecentquestion: question_nr}, # {conv_id : x, mostrecentinteraction: timestamp, mostrecentquestion: question_nr}, # {conv_id : x, mostrecentinteraction: timestamp, mostrecentquestion: question_nr}], # m.getFrom() : [ # {conv_id : x, mostrecentinteraction: timestamp, mostrecentquestion: question_nr}, # {conv_id : x, mostrecentinteraction: timestamp, mostrecentquestion: question_nr}], # m.getFrom() : [ # {conv_id : x, mostrecentinteraction: timestamp, mostrecentquestion: question_nr}, # {conv_id : x, mostrecentinteraction: timestamp, mostrecentquestion: question_nr}, # {conv_id : x, mostrecentinteraction: timestamp, mostrecentquestion: question_nr}] # } # # messages: [ # { "m_nr" : 1, "qtext" : "hoi1", "rtext" : "doei 1", "is_alternative" : False, "conv_id" : 1 }, # ..] conversationstates = {} # searces through self.messages to find if the incoming message # matches any of the preprogramming input def findMessageQuestionMatches(self, incomingmessage): matches = [] for message in self.messages: loweredmessage = message['qtext'].lower() if (re.search(r'\b' + loweredmessage + r'\b', incomingmessage)): # print '\n\nRE match, appending', loweredmessage, incomingmessage, re.search(r'\b' + loweredmessage + r'\b', incomingmessage) matches.append(message) elif loweredmessage == incomingmessage: # print 'exact match, appending', message matches.append(message) # print 'returning matches:', matches return matches def isFirstQuestion(self, question): return (question['m_nr'] == 1) def isUserRegisteredInConversationState(self, messageSender): return (messageSender in self.conversationstates) def isFollowUpQuestion(self, messageSender, question): m_nrs = self.getm_nrsAndis_alternativeForConvId(question['conv_id']) try: for convstate in self.conversationstates[messageSender]: if convstate['conv_id'] == question['conv_id']: if question['m_nr'] == (convstate['mostrecentquestion'] + 1): return True else: return self.testPreviousMessagesAreAlternatives( question['m_nr'], convstate['mostrecentquestion'], m_nrs) except Exception, e: print 'exception, probably indexerror ', e return False return False
'user': os.environ.get('username_local'), 'password': os.environ.get('dbPass_local') } # Localhost db - TEST! localTest_parm = { 'host': os.environ.get('host_local'), 'database': os.environ.get('dbName_test'), 'user': os.environ.get('username_local'), 'password': os.environ.get('dbPass_local') } # Azure azureHost_parm = { 'host': os.environ.get('host_azure'), 'database': os.environ.get('dbName_azure'), 'user': os.environ.get('username_azure'), 'password': os.environ.get('dbPass_azure') } localHost = Db(localHost_parm['user'], localHost_parm['password'], localHost_parm["database"], localHost_parm['host']) localTest = Db(localHost_parm['user'], localHost_parm['password'], localTest_parm["database"], localHost_parm['host']) azure = Db(azureHost_parm['user'], azureHost_parm['password'], azureHost_parm['database'], azureHost_parm['host']) current_db = localHost
def setUp(self, client='Client', db='Db'): self.client = Client.read_config(client) self.db = Db.read_config(db)
def __init__(self): self.db = Db() reactor.listenTCP(8123, RssdFactory(self)) reactor.run()
from responseBuilder import ResponseBuilder from database.db import Db db = Db() rb = ResponseBuilder() print 'starting...' class SampleMessageProtocolEntity: def __init__(self, sender, message): self.sender = sender self.message = unicode(message) def getFrom(self): return self.sender def getBody(self): return self.message while True: incomingmsg = raw_input('Incoming message:') db.insertTestIncomingMsg({'message': incomingmsg, 'sender': 'testuser' }) testmsg = db.getMostRecentTestIncomingMsg() msgentity = SampleMessageProtocolEntity(testmsg['sender'], testmsg['message']) response = rb.getResponsesForMessage(msgentity) if not response: print 'no response for input ', incomingmsg
5. Echo the corresponding question 6. Update the conversationstate ''' from database.sampledata import Sampledata from database.db import Db from datetime import time, tzinfo, datetime, timedelta import datetime as dt import time import re import logging, sys logging.basicConfig(stream=sys.stderr, level=logging.INFO) # logging.basicConfig(stream=sys.stderr, level=logging.DEBUG) db = Db() sb = Sampledata() messages = db.getMessages() conversations = sb.getConversations() resetmsg = 'chatreset' conversationTimeoutThreshold = dt.timedelta(seconds=10) # Keeps track of the state of different conversations, so different people # can talk to the bot at the same time without the chat intermingling a # response.MessageProtocolEntity.getFrom() will be key.The most recent # interaction with the bot will be tracked to figure out if the conversation # has timed out and should be reset. Finally, it tracks how far into the # conversation they are. # conversationstates = { # m.getFrom() : [ # {conv_id : x, mostrecentinteraction: timestamp, mostrecentquestion: question_nr},
def __init__(self): self.__log = [] self.__database = Db.getInstance() self.updateLogHandler()
class Rssd: def __init__(self): self.db = Db() reactor.listenTCP(8123, RssdFactory(self)) reactor.run() def update(self): self.db.update_news() def add_feed(self, param): self.db.add_feed(param["feed"]) def get_feeds(self): for f in self.db.get_feeds(): yield {"cmd": "get_feeds", "results": f.get_info()} def get_news_id(self, param=None): if param and "feed" in param: for n in self.db.get_news(param["unread"], param["feed"]): yield {"cmd": "get_news", "results": n.id_news} else: for n in self.db.get_news(): yield {"cmd": "get_news", "results": n.id_news} def get_news(self, param=None): if param and "feed" in param: for n in self.db.get_news(param["unread"], param["feed"]): yield {"cmd": "get_news", "results": n.get_info()} else: for n in self.db.get_news(): yield {"cmd": "get_news", "results": n.get_info()} def set_read(self, param): self.db.get_new(param["new"]).is_read = True self.db.commit()