Exemplo n.º 1
0
Arquivo: ui.py Projeto: landv/agent
 def _clmode_back(self):
     try:
         self.wait_message(messages.get_message("waiting"))
         ret=self._cur_step_ui.fire_prev_step()
     except Exception:
         ret=ErrorDialog(messages.get_message('unexpectedError').format(unicode(traceback.format_exc(),errors='replace')))            
     self._op_complete(ret)
Exemplo n.º 2
0
def call_next(command, bot):
    '''
    Get the next in line from the queue.

    Args:
        command (str): the user's text input
        bot (Bot): the active bot
    '''  
    q = bot.getQueue()
    circular = bot.isCircular()

    next_person = None
    try:
        if circular:
            next_person = q[0]
            q.rotate(1)
        else:
            next_person = q.popleft()
    except:
        pass

    msg = m.get_message('next_error')
    if next_person != None:
        msg = m.get_message('next_success').replace('{name}', next_person)

    return {
        'items': q,
        'circular': circular,
        'text': msg
    }
Exemplo n.º 3
0
    def _clmode_start(self):
        try:
            import signal
            signal.signal(signal.SIGINT, self._signal_close)
            signal.signal(signal.SIGTERM, self._signal_close)
            signal.signal(signal.SIGQUIT, self._signal_close)
        except:
            None

        self._printcl(u"")
        self._printcl(u"****************************************")
        self._printcl(messages.get_message('commands') + u":")
        self._printcl(u" #BACK <" + messages.get_message('enter') + "> " +
                      messages.get_message('toBack'))
        self._printcl(u" #EXIT <" + messages.get_message('enter') + "> " +
                      messages.get_message('toExit'))
        self._printcl(u"****************************************")
        try:
            self._cur_step_ui = self._step_init(BaseUI())
            if isinstance(self._cur_step_ui, ErrorDialog):
                self._cur_step_ui = Message(self._cur_step_ui.get_message())
        except Exception as e:
            self._cur_step_ui = Message("Error: " + str(e))
        self._prepare_step(self._cur_step_ui)
        self._printcl(u"")
Exemplo n.º 4
0
def title_handler(update, context):
    # Get user id and user language
    user_id = update.message.from_user.id
    language = get_user_language(user_id=user_id, short=True)

    # Check pushed button of keyboard
    pushed_button = check_button(update, KEYBOARDS["static"]["cancel"],
                                 language)

    # If pushed button is "cancel" exit user from conversation
    if pushed_button == "cancel":
        return exit_from_conversation(update)

    # Check if user has task with such title
    if update.message.text in get_user_tasks(user_id, only_titles=True):
        update.message.reply_text(get_message("task_exist", language))
        return "title_handler"

    # Clear context.user_data for new task and load title there
    context.user_data["new_task"] = {}
    context.user_data["new_task"]["title"] = update.message.text

    # Send message to write days of the week of the task
    update.message.reply_text(get_message("write_task_days_of_the_week",
                                          language),
                              reply_markup=get_menu_keyboard(
                                  "cancel_back", language))

    return "days_of_the_week_handler"
Exemplo n.º 5
0
Arquivo: ui.py Projeto: landv/agent
 def _show_error(self,  msg):
     if self._gui_enable is True:
         dlgerr = gdi.DialogMessage(gdi.DIALOGMESSAGE_ACTIONS_OK,gdi.DIALOGMESSAGE_LEVEL_ERROR,parentwin=self._app, logopath=self._logo)
         dlgerr.set_title(self._title)
         dlgerr.set_message(msg)
         dlgerr.set_action(self._show_error_gui_ok)
         dlgerr.show();
     else:
         self._printcl(u"")
         self._printcl(messages.get_message('error') + u": " + msg)
         if self._raw_input(messages.get_message('pressEnter')) is not None:
             self._prepare_step(self._cur_step_ui)
Exemplo n.º 6
0
def test_default():
    messages.db.delete('messages', where='to_userid=2')
    msgid = messages.send_message(1, 2, 'test message')

    msg = messages.get_message(msgid)
    assert msg.content == 'test message'

    msgs = messages.get_messages(2)
    assert len(list(msgs)) == 1

    messages.read_message(msgid)
    msg = messages.get_message(msgid)
    assert msg.unread == 0
def language_handler(update, context):
    # Get user id and user language
    user_id = update.message.from_user.id
    user_language = get_user_language(user_id=user_id, short=True)

    # Check pushed button of keyboard
    pushed_button = check_button(update, [["back"]], user_language)

    # If pushed button is "back", return to settings menu
    if pushed_button == "back":
        send_settings_menu(update)
        return "menu_handler"

    # Get user message
    text = update.message.text

    selected_language = {}

    # Check if user message is language
    for language in LANGUAGES:
        if language["title"].lower() in text.lower():
            selected_language = language
            break

    # If user message is language
    if selected_language:
        # Create database session
        session = db_session.create_session()

        # Edit user's language in database
        user = session.query(User).filter(User.telegram_id == user_id).first()
        user.language_id = selected_language["id"]

        # Commit and close database session
        session.commit()
        session.close()

        # Say user that language changed
        update.message.reply_text(
            get_message("language_changed", selected_language["short"],
                        selected_language["emoji"]))

        # Return to settings menu
        send_settings_menu(update)
        return "menu_handler"

    # If user message isn't button, ask user click on the buttons
    else:
        update.message.reply_text(get_message("click_buttons", user_language))
        return "language_handler"
Exemplo n.º 8
0
def days_of_the_week_handler(update, context):
    # Get user id and user language
    user_id = update.message.from_user.id
    language = get_user_language(user_id=user_id, short=True)

    # Check pushed button of keyboard
    pushed_button = check_button(update, KEYBOARDS["static"]["cancel_back"],
                                 language)

    # If pushed button is "cancel" exit user from conversation
    if pushed_button == "cancel":
        return exit_from_conversation(update)

    # If pushed button is "back" return user to previous
    # stage of task adding - write task title
    if pushed_button == "back":
        update.message.reply_text(get_message("write_task_title", language),
                                  reply_markup=get_menu_keyboard(
                                      "cancel", language))

        return "title_handler"

    # Get days of the week from user message
    days_of_the_week_str = get_days_of_the_week_from_string(
        update.message.text, language)

    # Check if message is incorrect
    if not days_of_the_week_str:
        update.message.reply_text(get_message("invalid_input", language))
        return "days_of_the_week_handler"

    # Load days of the week to context.user_data for new task
    context.user_data["new_task"]["days_of_the_week"] = days_of_the_week_str

    # Get data from context.user_data
    new_task_data = context.user_data["new_task"]

    # Add new task to database
    add_task(user_id, new_task_data["title"],
             new_task_data["days_of_the_week"])

    # Clear context.user_data for new task
    context.user_data["new_task"] = {}

    # Send message to user about successful adding
    update.message.reply_text(get_message("task_added", language))

    # Exit from conversation
    return exit_from_conversation(update)
Exemplo n.º 9
0
Arquivo: ui.py Projeto: landv/agent
 def _raw_input(self,msg,bpasswd=False):
     try:
         appmsg=msg + u" "
         if sys.stdout.encoding is not None:
             appmsg=appmsg.encode(sys.stdout.encoding,'replace')
         self._is_raw_input=True
         if not bpasswd:
             sr = raw_input(appmsg)
         else:
             import getpass
             sr = getpass.getpass(appmsg)
         sr=sr.decode('utf-8','replace')
         if sr.lower()==u"#exit":
             raise Exception("#EXIT")
         elif sr.lower()==u"#back":
             raise Exception("#BACK")
         self._is_raw_input=False
         return sr
     except Exception as e:
         self._is_raw_input=False
         msg = str(e)
         if msg==u"#EXIT":
             self.close()
         elif msg==u"#BACK":
             if self._cur_step_ui.is_back_enabled():
                 self._clmode_back()
             else:
                 return u""
         else:
             self._printcl(u"")
             self._printcl(u"")
             self._printcl(messages.get_message('unexpectedError').format(unicode(traceback.format_exc(),errors='replace')))
             self.close()
         return None
Exemplo n.º 10
0
Arquivo: ui.py Projeto: landv/agent
 def run(self):
     try:
         self._main._wait_ui=None
         self._main.wait_message(messages.get_message("waiting"))
         ret=self._func()  
     except SystemExit:
         self._main._action=None
         self._main.close()
         return         
     except Exception as e:
         msg = e.__class__.__name__
         if e.args is not None and len(e.args)>0 and e.args[0] != '':
             msg = e.args[0]
         ret=ErrorDialog(messages.get_message('unexpectedError').format(msg))
     if self._callback is not None:
         self._callback(ret)
Exemplo n.º 11
0
Arquivo: ui.py Projeto: landv/agent
 def fire_next_step(self):
     #Verifica mandatory
     for i in range(len(self._arinputs)):
         inp = self._arinputs[i]
         if inp['mandatory'] is True and inp['variable'].get().strip()=="":
             return ErrorDialog(messages.get_message("fieldRequired").format(inp['label']))
     return BaseUI.fire_next_step(self)
Exemplo n.º 12
0
def start_handler(update, context):
    language = get_user_language(update=update, short=True)

    update.message.reply_text(get_message("welcome", language))
    send_main_menu(update)

    return 'main_menu'
Exemplo n.º 13
0
def set_queue(command, bot):
    '''
    Create a queue with a list of items. Phrases passed will trigger a deque.
    If items is not set, the queue will automatically use the Slack user list.

    Args:
        command (str): the user's text input
        bot (Bot): the active bot
    '''  
    if(command):
        circular = '-c' in command
        items = bot.getUsers()
        phrases = []

        has_items = False 
        has_phrases = False
        arg1 = command.split("--items")
        if len(arg1) > 1:
            has_items = True
            arg2 = arg1[1].split("--phrases")
            if len(arg2) > 1:
                has_phrases = True

        if has_items and has_phrases:
            items = arg2[0].strip().split(",")
            phrases = arg2[1].strip().split(",")
        elif has_items:
            items = arg1[1].strip().split(",")

        return {
            'items': deque(items),
            'circular': circular,
            'phrases': phrases,
            'text': m.get_message('set_success') 
        }
Exemplo n.º 14
0
def stub(message):
    steps_stack.append(message)

    markup = markups.get_return_markup()

    reply_text = messages.get_message('stub')
    bot.send_message(message.chat.id, reply_text, reply_markup=markup)
Exemplo n.º 15
0
def send_notification(phone_number, event):
    conn = psycopg2.connect(
        database='defaultdb',
        user='******',
        port=26257,
        sslmode='verify-full',
        host='mature-hyena-8jv.gcp-us-west2.cockroachlabs.cloud',
        sslrootcert='certs/mature-hyena-ca.crt',
        password='******')
    global EVENT
    EVENT = event
    message = get_message(event)
    global STATIC_MESSAGE
    STATIC_MESSAGE = message
    response_message = '\n'.join(message['text'])
    translate_response = translate_text(
        DETECTED_LANGUAGE, str(response_message)
    ) if DETECTED_LANGUAGE != "en" else str(response_message)

    twilio.messages.create(from_=TWILIO_NUMBER,
                           to='whatsapp:+' + phone_number,
                           body=translate_response,
                           media_url=message['image'])
    with conn.cursor() as cur:
        print(
            f'INSERT INTO notifications (notification_type, phone_number) VALUES ({event}, {phone_number});'
        )
        cur.execute(
            f"INSERT INTO notifications (notification_type, phone_number) VALUES ('{event}', '{phone_number}');"
        )
    conn.commit()

    return jsonify({'status_code': 200, 'message': 'Message sent!'})
Exemplo n.º 16
0
def cryptocurrency(message):
    steps_stack.append(message)

    markup = markups.get_cryptocurrency_markup()
    reply_text = messages.get_message(message.text)

    bot.send_message(message.chat.id, reply_text, reply_markup=markup)
Exemplo n.º 17
0
def start(message):
    steps_stack.append(message)

    markup = markups.get_start_markup()
    reply_text = messages.get_message(message.text)

    bot.send_message(message.chat.id, reply_text, reply_markup=markup)
Exemplo n.º 18
0
def exchange_rates(message):
    steps_stack.append(message)

    markup = markups.get_exchange_rates_markup()
    reply_text = messages.get_message(message.text)

    bot.send_message(message.chat.id, reply_text, reply_markup=markup)
Exemplo n.º 19
0
def currency_step_one(message):
    steps_stack.append(message)

    markup = markups.get_currency_markup()
    reply_text = messages.get_message(message.text)

    bot.send_message(message.chat.id, reply_text, reply_markup=markup)
    bot.register_next_step_handler(message, currency_step_two)
Exemplo n.º 20
0
def send_edit_mode_menu(update):
    # Get user language
    language = get_user_language(update=update, short=True)

    # Send menu
    update.message.reply_text(get_message("choice_action", language),
                              reply_markup=get_menu_keyboard(
                                  "edit_task_menu", language))
Exemplo n.º 21
0
def process_subsmission(submission):
	if not submission.is_self:
		logger.info('Skip: link submission: {}'.format(submission.permalink))
		return

	# Rough check to see if bot hasn't replied already
	submission.comments.replace_more(limit=0)
	if any(1 for comment in submission.comments if comment.author == me):
		logger.warning('Skip: already replied to: {}'.format(submission.permalink))
		return

	match_control.check_all(submission.selftext)
	b = match_control[TopicFlags]
	y = match_control[ExtraFlags]

	if b == 0:
		logger.info('Skip: no match: {}'.format(submission.permalink))
		return

	logger.info('Process submission: {}'.format(submission.permalink))

	message_kwargs = {
		'topic_flags': b,
		'signature': 1,
		'pester': True,
		'passed': False,
		'some': bool(y & ExtraFlags.contains_code_block),
		'thing_kind': type(submission).__name__,
		'redditor': submission.author.name,
		'old_reddit_permalink': 'https://old.reddit.com' + submission.permalink,
		'new_reddit_permalink': 'https://new.reddit.com' + submission.permalink
	}

	message = get_message(**message_kwargs)
	reply = submission.reply(message)

	message_kwargs.update({
		'signature': 2,
		'bot_name': me.name,
		'reply_id': reply.id
	})

	message = get_message(**message_kwargs)
	reply.edit(message)

	db_services.record_submission_reply(submission, reply, b, y)
Exemplo n.º 22
0
def handler(update, context):
    # Get user id and user language
    user_id = update.message.from_user.id
    language = get_user_language(user_id=user_id, short=True)

    # Check pushed button of keyboard
    pushed_button = check_button(update, KEYBOARDS["static"]["main_menu"],
                                 language)

    # If pushed button is "today_tasks"
    if pushed_button == "today_tasks":
        # Get user's today tasks
        today_tasks = get_user_tasks(user_id,
                                     only_titles=True,
                                     today_tasks=True)

        # If user has today tasks, make list of tasks
        if today_tasks:
            text = get_message("today_tasks", language) + '\n\n'
            for task in today_tasks:
                text += task + "\n"

        # If user hasn't today tasks, say user about it
        else:
            text = get_message("not_tasks_today", language)

        update.message.reply_text(text)

        return "main_menu"

    # If pushed button is "editor", proceed to editor menu
    elif pushed_button == "editor":
        send_editor_menu(update)
        return "editor"

    # If pushed button is "settings", proceed to settings menu
    elif pushed_button == "settings":
        send_settings_menu(update)
        return "settings"

    # If user message isn't button, ask user click on the buttons
    else:
        update.message.reply_text(get_message("click_buttons", language))
        send_main_menu(update)
        return "main_menu"
Exemplo n.º 23
0
Arquivo: ui.py Projeto: landv/agent
 def _guimode_close(self, e):
     if self._cur_step_ui is None or (self._cur_step_ui.is_next_enabled() or self._cur_step_ui.is_back_enabled()) :
         dlgerr = gdi.DialogMessage(gdi.DIALOGMESSAGE_ACTIONS_YESNO,gdi.DIALOGMESSAGE_LEVEL_INFO,parentwin=self._app, logopath=self._logo)
         dlgerr.set_title(self._title)
         dlgerr.set_message(messages.get_message('confirmExit'))
         dlgerr.set_action(self._guimode_close_action)
         dlgerr.show();
     else:
         self.close()
Exemplo n.º 24
0
Arquivo: ui.py Projeto: landv/agent
 def wait_message(self, msg, perc=None, progr=None, allowclose=False):
     if self._gui_enable is True:
         if perc is not None:
             msg=msg + "     (" + str(perc) + "%)"
         self._wait_message_gui(msg, progr, allowclose)
     else:
         if self._prev_msg_wait!=msg:
             self._prev_msg_wait=msg
             if allowclose:
                 msg+=u"\n\nCTRL+C " + messages.get_message('toExit') + u"\n" 
             self._printcl(msg) 
Exemplo n.º 25
0
Arquivo: ui.py Projeto: landv/agent
 def fire_next_step(self):
     #Verifica se selezionato
     bok = False
     for i in range(len(self._archooser)):
         inp = self._archooser[i]
         if self._variable.get()==inp["key"]:
             bok = True
             break
     if not bok:
         return ErrorDialog(messages.get_message("mustSelectOptions"))
     return BaseUI.fire_next_step(self)
Exemplo n.º 26
0
def handler(update, context):
    # Get user id and user language
    user_id = update.message.from_user.id
    language = get_user_language(user_id=user_id, short=True)

    # Check pushed button of keyboard
    pushed_button = check_button(update, KEYBOARDS["static"]["editor_menu"],
                                 language)

    # If pushed button is "add_task", proceed to task adding
    if pushed_button == "add_task":
        update.message.reply_text(get_message("write_task_title", language),
                                  reply_markup=get_menu_keyboard(
                                      "cancel", language))

        return "add_task"

    # If pushed button is "add_task"
    elif pushed_button == "edit_task":
        # If user has tasks, proceed to task editing
        if get_user_tasks(user_id):
            send_choice_tasks_menu(update)
            return "edit_task"

        # If user hasn't tasks, stay in editor menu
        else:
            update.message.reply_text(get_message("not_tasks", language))
            send_editor_menu(update)

            return "editor_menu"

    # If pushed button is "back", exit from conversation
    elif pushed_button == "back":
        return exit_from_conversation(update)

    # If user message isn't button, ask user click on the buttons
    else:
        update.message.reply_text(get_message("click_buttons", language))
        send_editor_menu(update)

        return "editor_menu"
Exemplo n.º 27
0
def editmessage(message_id, previous, identifier):
    m_content = messages.get_message(message_id)
    user_id = users.user_id()
    admin = users.admin()
    if user_id != m_content[1] and admin == 0:
        return render_template(
            "rules.html",
            message='Sinulla ei ole oikeutta muokata viestiä!',
            additional=error_redirect)
    return render_template("editmessage.html",
                           messagecontent=m_content[0],
                           m_id=message_id)
Exemplo n.º 28
0
def location_quick_reply(sender, text=None):
    if not text:
        text = get_message('location-button')
    return {
        "recipient": {
            "id": sender
        },
        "message": {
            "text": text,
            "quick_replies": [{
                "content_type": "location",
            }]
        }
    }
Exemplo n.º 29
0
def cancel_queue(command, bot):
    '''
    Cancel the current queue.

    Args:
        command (str): the user's text input
        bot (Bot): the active bot
    '''
    return {
        'items': deque(bot.getUsers()),
        'circular': False,
        'phrases': [],
        'text': m.get_message('cancel_success')
    }
def new_days_of_the_week_handler(update, context):
    # Get user language
    language = get_user_language(update=update, short=True)

    # Check pushed button of keyboard
    pushed_button = check_button(update, KEYBOARDS["static"]["cancel"],
                                 language)

    # If pushed button is "cancel", send edit mode menu
    if pushed_button == "cancel":
        send_edit_mode_menu(update)
        return "edit_mode_handler"

    # Get days of the week from user message
    days_of_the_week_str = get_days_of_the_week_from_string(
        update.message.text, language)

    # Check if message is incorrect
    if not days_of_the_week_str:
        update.message.reply_text(get_message("invalid_input", language))
        return "new_days_of_the_week_handler"

    # Edit task title
    edit_result = edit_task(context.user_data["selected_task_id"],
                            days_of_the_week=days_of_the_week_str)

    # If editing is successful, return to edit mode handler
    if edit_result:
        update.message.reply_text(
            get_message("task_days_of_the_week_edited", language))
        send_edit_mode_menu(update)
        return "edit_mode_handler"

    # Else send message to user about invalid input
    else:
        update.message.reply_text(get_message("invalid_input", language))
        return "new_days_of_the_week_handler"
def new_title_handler(update, context):
    # Get user id and user language
    user_id = update.message.from_user.id
    language = get_user_language(user_id=user_id, short=True)

    # Check pushed button of keyboard
    pushed_button = check_button(update, KEYBOARDS["static"]["cancel"],
                                 language)

    # If pushed button is "cancel", send edit mode menu
    if pushed_button == "cancel":
        send_edit_mode_menu(update)
        return "edit_mode_handler"

    new_title = update.message.text

    task_titles_list = get_user_tasks(user_id, only_titles=True)

    # Check if title with such title exist
    if new_title in task_titles_list:
        update.message.reply_text(get_message("task_exist", language))
        return "new_title_handler"

    # Edit task title
    edit_result = edit_task(context.user_data["selected_task_id"],
                            title=new_title)

    # If editing is successful, return to edit mode handler
    if edit_result:
        update.message.reply_text(get_message("task_title_edited", language))
        send_edit_mode_menu(update)
        return "edit_mode_handler"

    # Else send message to user about invalid input
    else:
        update.message.reply_text(get_message("invalid_input", language))
        return "new_title_handler"