Пример #1
0
def webhook():
    # endpoint for processing incoming messaging events
    db = DBHelper()
    mood = Mood()
    data = request.get_json()
    logger(data, status=StatusType.INFO)
    mood_items = db.get_items()
    current_mood = ''
    if mood in mood_items:
        current_mood = mood_items[0]
    else:
        db.add_item(mood.TONE_NEUTRAL)
        current_mood = mood.TONE_NEUTRAL
    default_reply = mood.CONST_DEFAULT_REPLY
    if data["object"] == "page":
        for entry in data["entry"]:
            for messaging_event in entry["messaging"]:
                if messaging_event.get("message"):  # someone sent us a message
                    # the facebook ID of the person sending the bot the message
                    sender_id = messaging_event["sender"]["id"]
                    # the message sent by the user
                    if messaging_event["message"]["text"]:
                        message_text = messaging_event["message"]["text"]
                        # if can be an image or attachment ?
                        message_text = message_text.lower()
                        if message_text == mood.CONST_MOOD:
                            mood_items = db.get_items()
                            if mood in mood_items:
                                current_mood = mood
                                db.delete_item(mood)
                            else:
                                pass
                            send_message(sender_id, current_mood)
                        elif message_text in mood.default_messages:
                            send_message(sender_id, default_reply)
                        else:
                            send_response(mood=mood,
                                          message_text=message_text,
                                          sender_id=sender_id)
                    else:
                        logger(
                            "Can't process the message as it is not a text, it can either "
                            "be an attachment or something :) ",
                            StatusType.INFO)
                if messaging_event.get("delivery"):  # delivery confirmation
                    pass
                if messaging_event.get("optin"):  # optin confirmation
                    pass
                if messaging_event.get(
                        "postback"
                ):  # user clicked/tapped "postback" button in earlier message
                    pass
    return "OK", 200
Пример #2
0
def set_coursecode(bot, update):
    db = DBHelper()
    db.setup()
    error_msg = """
	It seems you did not enter properly courseCode. Please try again!
	"""
    courseCode = update.message.text[16:]
    if (len(courseCode) < 10 or (len(courseCode) > 22)):
        update.message.reply_text(error_msg)
        return None
    chat = update.message.chat_id
    db.add_item(courseCode, chat)
    update.message.reply_text(
        "Great, I added this course to list. To see the full list enter /get_list"
    )
Пример #3
0
def record_take_note_data(bot, update, user_data):
    db = DBHelper()
    text = update.message.text
    category = user_data['note_type']
    user_data[category] = text
    db_desc = "{} - {}".format(user_data['note_type'], text)
    message = "{} - {}".format(user_data['note_type'], text)
    update.message.reply_text("Success! Note: {}".format(message))
    send_feed_messages(bot, message)
    db.add_item(db_desc, update.message.chat.id, user_data['note_type'],
                update.message.chat.first_name, update.message.date)
    del user_data['note_type']
    time.sleep(.5)
    start(bot, update)

    return ConversationHandler.END
Пример #4
0
class WeatherBot:

    def __init__(self):
        self.c = Config()
        self.TOKEN = self.c.getToken()
        self.OWMKEY = self.c.getOWMKEY()
        self.URL = self.c.getURL()
        self.db = DBHelper()

    def initializeDB(self):
        self.db.setup()

    def get_content(self,url):
        response = requests.get(url)
        content = response.content.decode("utf8")
        return content

    def get_json_from_url(self,url):
        content = self.get_content(url)
        js = json.loads(content)
        return js

    def get_updates(self,offset=None):
        url = self.URL + "getUpdates"
        if offset:
            url += "?offset={}".format(offset)
        js = self.get_json_from_url(url)
        return js

    def get_last_update_id(self,updates):
        update_ids = []
        for update in updates["result"]:
            update_ids.append(int(update["update_id"]))
        return max(update_ids)

    def handle_updates(self,updates):
        for update in updates["result"]:
            text = update["message"]["text"]
            chat = update["message"]["chat"]["id"]
            items = self.db.get_items(chat)  ##
            if text == "/done":
                keyboard = self.build_keyboard(items)
                self.send_message("Select an item to delete", chat, keyboard)
            elif text == "/start":
                self.send_message("Welcome to your personal To Do list. Send any text to me and I'll store it as an item. Send /done to remove items", chat)
            elif text.startswith("/"):
                continue
            elif text in items:
                self.db.delete_item(text, chat)  ##
                items = self.db.get_items(chat)  ##
                keyboard = self.build_keyboard(items)
                self.send_message("Select an item to delete", chat, keyboard)
            else:
                self.db.add_item(text, chat)  ##
                items = self.db.get_items(chat)  ##
                message = "\n".join(items)
                self.send_message(message, chat)

    def get_last_chat_id_and_text(self,updates):
        num_updates = len(updates["result"])
        last_update = num_updates - 1
        text = updates["result"][last_update]["message"]["text"]
        chat_id = updates["result"][last_update]["message"]["chat"]["id"]
        return (text, chat_id)

    def send_message(self,text, chat_id, reply_markup=None):
        text = urllib.parse.quote_plus(text)
        url = self.URL + "sendMessage?text={}&chat_id={}&parse_mode=Markdown".format(text, chat_id)
        if reply_markup:
            url += "&reply_markup={}".format(reply_markup)
        self.get_content(url)

    def build_keyboard(self,items):
        keyboard = [[item] for item in items]
        reply_markup = {"keyboard":keyboard, "one_time_keyboard": True}
        return json.dumps(reply_markup)