Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- #
- # Testing Hactl Telegram Bot to handle clients' basic requests
- #
- # Duplicate function(represent as [Origin-function-name]2) is for the program running within a different state
- from telegram import (ReplyKeyboardMarkup, ReplyKeyboardRemove, InlineKeyboardButton, InlineKeyboardMarkup)
- from telegram.ext import (Updater, CommandHandler, MessageHandler, Filters, RegexHandler,
- ConversationHandler, CallbackQueryHandler)
- from time import gmtime, strftime, sleep
- import logging
- # import MySQLdb
- import pymysql
- import sys
- CARGOCHECKING, CCOPTION, CCOPTION2, CS_OPTION, FEEDBACK, FEEDBACK_LOG, FEEDBACK_LOG_CONTACT, \
- CU_OPTION, CU_OPTION2, PRINTAWB, FEEDBACK2, FEEDBACK_LOG_CONTACT2, FEEDBACK_LOG2, REPEATCC, REPEATCC2, INLINE_STATE, \
- INLINE_STATE2, HELP_OPTION, SHOWLIST_OPTION, SHOWLIST_OPTION2, DELETE_AWB, DELETE2_AWB = range(22)
- # Enable logging
- formatter_CC = logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
- level=logging.INFO)
- formatter_CS = logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
- level=logging.INFO)
- # logging for cargochecking
- logger_CC = logging.getLogger('CC')
- hdlr_CC = logging.FileHandler('./temp_CC.log')
- hdlr_CC.setFormatter(formatter_CC)
- logger_CC.addHandler(hdlr_CC)
- # logging for customerservice
- logger_CS = logging.getLogger('CS')
- hdlr_CS = logging.FileHandler('./temp_CS.log')
- hdlr_CS.setFormatter(formatter_CS)
- logger_CS.addHandler(hdlr_CS)
- # functions starts
- # Showing 'CargoChecking', 'CustomerService' options(Reply-Keybaord)
- def start(bot, update):
- reply_keyboard = [['CargoChecking', 'CustomerService']]
- update.effective_message.reply_text('Hi! My name is Hactl Bot. I am here to help you.\n\n'
- 'Click / on your keyboard to view the functions list.\n'
- 'Send /cancel to stop talking with me.\n\n')
- update.effective_message.reply_text('First, may I know what can I do for you?',
- reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True,
- resize_keyboard=True))
- logger_CC.info("<<<Section Starts>>>")
- logger_CS.info("<<<Section Starts>>>")
- return CARGOCHECKING
- # telegramb_bot_python API Default function for building inline keyboard
- def build_menu(buttons, n_cols, header_buttons=None, footer_buttons=None):
- menu = [buttons[i:i + n_cols] for i in range(0, len(buttons), n_cols)]
- if header_buttons:
- menu.insert(0, header_buttons)
- if footer_buttons:
- menu.append(footer_buttons)
- return menu
- # Showing 'Show AWB List', 'Home Page' options after clicking 'CaroChecking' option(Reply-Keybaord) in the first page, function with log
- def cargochecking_after_option(bot, update):
- user = update.message.from_user
- reply_keyboard = [['Show AWB List', 'Home Page']]
- update.message.reply_text('Function: Cargo Checking\n'
- 'Please input your AWB and click Send...',
- reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard = False, resize_keyboard = True))
- logger_CC.info("Function of %s: %s" % (user.id, update.message.text))
- return CCOPTION
- # Duplicate 'cargochecking_after_option' function
- def cargochecking2_after_option(bot, update):
- user = update.message.from_user
- reply_keyboard = [['Show AWB List', 'Home Page']]
- update.message.reply_text('Function: Cargo Checking\n'
- 'Please input your AWB and click Send...',
- reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard = False, resize_keyboard = True))
- logger_CC.info("Function of %s: %s" % (user.id, update.message.text))
- return CCOPTION2
- # Showing 'Show AWB List', 'Home Page' options after clicking 'CaroChecking' option(Reply-Keybaord) in the first page, function without log
- def cargochecking_after_option2(bot, update):
- user = update.message.from_user
- reply_keyboard = [['Show AWB List', 'Home Page']]
- update.message.reply_text('Function: Cargo Checking\n'
- 'Please input your AWB and click Send...',
- reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard = False, resize_keyboard = True))
- return CCOPTION
- # Duplicate 'cargochecking_after_option2' function
- def cargochecking2_after_option2(bot, update):
- user = update.message.from_user
- reply_keyboard = [['Show AWB List', 'Home Page']]
- update.message.reply_text('Function: Cargo Checking\n'
- 'Please input your AWB and click Send...',
- reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard = False, resize_keyboard = True))
- return CCOPTION2
- # Fetch data from Database, show AWB list(Inline-Keybaord) with Inline-Keyboard
- def showAWBlist(bot, update):
- user = update.message.from_user
- update.message.reply_text('Please choose from the history:',
- reply_markup=ReplyKeyboardRemove())
- try:
- # open a database connection
- # connection = MySQLdb.connect (host = "192.168.64.2", user = "macbook", passwd = "123", db = "awbtable")
- connection = pymysql.connect(host="192.168.64.2", user="macbook", passwd="123", db="awbtable")
- # connection = pymysql.connect(host="jeffffc.com", user="kelvin", passwd="abcd1234", db="kelvin")
- # prepare a cursor object using cursor() method
- cursor = connection.cursor()
- # execute the SQL query using execute() method.
- # Execute the SQL command
- cursor.execute("SELECT DISTINCT content FROM user_log WHERE user_id = %s AND type = %s", (user.id, 'awb'))
- # Fetch all the rows in a list of lists.
- results = cursor.fetchall()
- if results == ():
- update.message.reply_text("Sorry, no history is found...")
- return cargochecking_after_option(bot, update)
- msg = "\n\nPress Delete to delete AWB from list."
- button_list = []
- for row in results:
- button_list.append(InlineKeyboardButton(str(row[0]), callback_data=str(row[0])))
- reply_keyboard = InlineKeyboardMarkup(build_menu(button_list, 3, None,[InlineKeyboardButton("Delete", callback_data="delete"),
- InlineKeyboardButton("Home", callback_data="start"), InlineKeyboardButton("End Bot", callback_data="end")]))
- update.message.reply_text(msg, reply_markup = reply_keyboard)
- cursor.close()
- # close the connection
- connection.close()
- # exit the program
- except:
- print ("Error: Uable to Fetch Data.")
- # return end(bot, update)
- return INLINE_STATE
- # Showing AWB deatails after users clicking the Inline-Keyboard list function 'showAWBlist'
- def button_callback(bot, update):
- query = update.callback_query
- if query.data == 'end':
- return end(bot, update)
- if query.data == 'delete':
- return delete_awb(bot, update)
- if query.data == 'start':
- return start(bot, update)
- try:
- #connection = pymysql.connect(host="jeffffc.com", user="kelvin", passwd="abcd1234", db="kelvin")
- connection = pymysql.connect(host="192.168.64.2", user="macbook", passwd="123", db="awbtable")
- cursor = connection.cursor()
- cursor.execute("SELECT * FROM records WHERE AWB = %s" % query.data)
- results = cursor.fetchall()
- # No AWB record
- if results == ():
- update.message.reply_text("Sorry, no record is found...")
- return cargochecking_after_option(bot, update)
- # Record found
- if results != ():
- for row in results:
- update.callback_query.message.reply_text(row[1] + '\n' + row[2] + '\n' + row[3] + '\n' + row[4] + '\n' + row[5] + '\n' + row[6] +
- row[7] + '\n' + row[8] + row[9])
- query.answer()
- cursor.close()
- connection.close()
- except:
- print ("Error: Uable to Fetch Data.")
- # Duplicate 'showAWBlist' function
- def showAWBlist2(bot, update):
- user = update.message.from_user
- update.message.reply_text('Please choose from the history:',
- reply_markup=ReplyKeyboardRemove())
- try:
- # open a database connection
- # connection = MySQLdb.connect (host = "192.168.64.2", user = "macbook", passwd = "123", db = "awbtable")
- connection = pymysql.connect(host="192.168.64.2", user="macbook", passwd="123", db="awbtable")
- # connection = pymysql.connect(host="jeffffc.com", user="kelvin", passwd="abcd1234", db="kelvin")
- # prepare a cursor object using cursor() method
- cursor = connection.cursor()
- # execute the SQL query using execute() method.
- # Execute the SQL command
- cursor.execute("SELECT DISTINCT content FROM user_log WHERE user_id = %s AND type = %s", (user.id, 'awb'))
- # Fetch all the rows in a list of lists.
- results = cursor.fetchall()
- if results == ():
- update.message.reply_text("Sorry, no history is found...")
- return cargochecking_after_option(bot, update)
- msg = "\n\nPress Delete to delete AWB from list."
- button_list = []
- for row in results:
- button_list.append(InlineKeyboardButton(str(row[0]), callback_data=str(row[0])))
- reply_keyboard = InlineKeyboardMarkup(build_menu(button_list, 3, None,[InlineKeyboardButton("Delete", callback_data="delete"),
- InlineKeyboardButton("Home", callback_data="start"), InlineKeyboardButton("End Bot", callback_data="end")]))
- update.message.reply_text(msg, reply_markup = reply_keyboard)
- cursor.close()
- # close the connection
- connection.close()
- # exit the program
- except:
- print ("Error: Uable to Fetch Data.")
- return INLINE_STATE2
- # Duplicate 'button_callback' function
- def button_callback2(bot, update):
- query = update.callback_query
- if query.data == 'end':
- return end(bot, update)
- if query.data == 'delete':
- return delete_awb(bot, update)
- try:
- #connection = pymysql.connect(host="jeffffc.com", user="kelvin", passwd="abcd1234", db="kelvin")
- connection = pymysql.connect(host="192.168.64.2", user="macbook", passwd="123", db="awbtable")
- cursor = connection.cursor()
- cursor.execute("SELECT * FROM records WHERE AWB = %s" % query.data)
- results = cursor.fetchall()
- # No AWB record
- if results == ():
- update.message.reply_text("Sorry, no record is found...")
- return cargochecking2_after_option(bot, update)
- # Record found
- if results != ():
- for row in results:
- update.callback_query.message.reply_text(row[1] + '\n' + row[2] + '\n' + row[3] + '\n' + row[4] + '\n' + row[5] + '\n' + row[6] +
- row[7] + '\n' + row[8] + row[9])
- query.answer()
- cursor.close()
- connection.close()
- except:
- print ("Error: Uable to Fetch Data.")
- # Terminate function for 'showAWBlist' and 'button_callback'
- def end_inline(bot, update):
- return end(bot, update)
- # Duplicate 'end_inline' function
- def end_inline2(bot, update):
- return end2(bot, update)
- ######################################################################################################################################################################################################################################################################
- # Delete AWB list (get AWB input)
- def delete_awb(bot, update):
- #user = update.message.from_user
- query = update.callback_query
- update.callback_query.message.reply_text('Function: Delete AWB\n'
- 'Please input your AWB and click Send to delete it from AWB list...')
- return DELETE_AWB
- # Duplicate 'delete_awb' function
- def delete2_awb(bot, update):
- #user = update.effective_message.from_user
- query = update.callback_query
- update.callback_query.message.reply_text('Function: Delete AWB\n'
- 'Please input your AWB and click Send to delete it from AWB list...')
- return DELETE2_AWB
- # Delete AWB list (operation)
- def delete_awb_op(bot, update):
- user = update.message.from_user
- if not update.message.text.isdigit():
- update.message.reply_text("Sorry, you have entered a wrong type of AWB...\n"
- "Please try again...")
- return showAWBlist(bot, update)
- try:
- # open a database connection
- # connection = MySQLdb.connect (host = "192.168.64.2", user = "macbook", passwd = "123", db = "awbtable")
- connection = pymysql.connect(host="192.168.64.2", user="macbook", passwd="123", db="awbtable")
- # connection = pymysql.connect(host="jeffffc.com", user="kelvin", passwd="abcd1234", db="kelvin")
- # prepare a cursor object using cursor() method
- cursor = connection.cursor()
- cursor.execute("SELECT * FROM user_log WHERE user_id = %s AND type = %s AND Content = %s", (user.id, 'awb', update.message.text))
- results = cursor.fetchall()
- if results == ():
- update.message.reply_text("Sorry, no record is found...")
- return cargochecking_after_option(bot, update)
- if results != ():
- cursor.execute("DELETE FROM user_log WHERE user_id = %s AND type = %s AND Content = %s", (user.id, 'awb', update.message.text))
- connection.commit()
- cursor.close()
- connection.close()
- logger_CC.info("<<< AWB Deleted >>>")
- update.message.reply_text("<<< AWB Deleted >>>")
- except pymysql.MySQLError as e:
- code, errormsg = e.args
- sqlerror = "MySQL ErrorCode: %s\nErrorMsg:%s" % (code, errormsg)
- print(sqlerror)
- return cargochecking_after_option2(bot, update)
- # Duplicate (delete_awb_op) function
- def delete2_awb_op(bot, update):
- user = update.message.from_user
- if not update.message.text.isdigit():
- update.message.reply_text("Sorry, you have entered a wrong type of AWB...\n"
- "Please try again...")
- return showAWBlist2(bot, update)
- try:
- # open a database connection
- # connection = MySQLdb.connect (host = "192.168.64.2", user = "macbook", passwd = "123", db = "awbtable")
- connection = pymysql.connect(host="192.168.64.2", user="macbook", passwd="123", db="awbtable")
- # connection = pymysql.connect(host="jeffffc.com", user="kelvin", passwd="abcd1234", db="kelvin")
- # prepare a cursor object using cursor() method
- cursor = connection.cursor()
- cursor.execute("SELECT * FROM user_log WHERE user_id = %s AND type = %s AND Content = %s", (user.id, 'awb', update.message.text))
- results = cursor.fetchall()
- if results == ():
- update.message.reply_text("Sorry, no record is found...")
- return cargochecking2_after_option(bot, update)
- if results != ():
- cursor.execute("DELETE FROM user_log WHERE user_id = %s AND type = %s AND Content = %s", (user.id, 'awb', update.message.text))
- connection.commit()
- cursor.close()
- connection.close()
- logger_CC.info("<<< AWB Deleted >>>")
- update.message.reply_text("<<< AWB Deleted >>>")
- except pymysql.MySQLError as e:
- code, errormsg = e.args
- sqlerror = "MySQL ErrorCode: %s\nErrorMsg:%s" % (code, errormsg)
- print(sqlerror)
- return cargochecking2_after_option2(bot, update)
- ######################################################################################################################################################################################################################################################################
- # Customer Service function with 'Feedback', 'Contact Us' options(Reply-Keybaord)
- def customerservice(bot, update):
- user = update.message.from_user
- reply_keyboard = [['Feedback', 'Contact Us']]
- update.message.reply_text('To have a better performance,'
- 'we treasure all valuable opinions from our clients.')
- update.message.reply_text('What can I do for you?',
- reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True, resize_keyboard=True))
- logger_CS.info("Function of %s: %s" % (user.id, update.message.text))
- return CS_OPTION
- # Feedback function with 'Facility', 'Staff', 'Service' options(Reply-Keybaord)
- def feedback(bot, update):
- reply_keyboard = [['Facility', 'Staff', 'Service']]
- update.message.reply_text('May I know which aspect(s) you want to give feedback to?\n',
- reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True, resize_keyboard=True))
- return FEEDBACK
- # Duplicate 'feedback' function
- def feedback2(bot, update):
- reply_keyboard = [['Facility', 'Staff', 'Service']]
- update.message.reply_text('May I know which aspect(s) you want to give feedback to?\n',
- reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True, resize_keyboard=True))
- return FEEDBACK2
- # Feedback function let user enters text
- def feedback_input(bot, update):
- user = update.message.from_user
- update.message.reply_text("You have chosen %s." % (update.message.text))
- global fb_type
- fb_type = update.message.text
- update.message.reply_text("Please write down your opinions in the textbox below, click Send once you have finished...")
- logger_CS.info("feedback's Type: %s" % (update.message.text))
- return FEEDBACK_LOG
- # Duplicate 'feedbakc_input' function
- def feedback_input2(bot, update):
- # user = update.message.from_user
- user = update.message.from_user
- update.message.reply_text("You have chosen %s." % (update.message.text))
- global fb_type
- fb_type = update.message.text
- update.message.reply_text("Please write down your opinions in the textbox below, click Send once you have finished...")
- logger_CS.info("feedback's Type: %s" % (update.message.text))
- return FEEDBACK_LOG2
- # Feedback function(fetch text)
- def feedback_getLog(bot, update):
- user = update.message.from_user
- logger_CS.info("User's feedback: %s" % (update.message.text))
- try:
- # open a database connection
- # connection = MySQLdb.connect (host = "192.168.64.2", user = "macbook", passwd = "123", db = "awbtable")
- connection = pymysql.connect(host="192.168.64.2", user="macbook", passwd="123", db="awbtable")
- # connection = pymysql.connect(host="jeffffc.com", user="kelvin", passwd="abcd1234", db="kelvin")
- # prepare a cursor object using cursor() method
- cursor = connection.cursor()
- # Execute the SQL commandUPDATE user_log SET content = '123' WHERE user_id = 237554606
- currentTime = strftime('%Y-%m-%d %H:%M:%S')
- cursor.execute("INSERT INTO user_log (user_id, type, feedback_type, content, log_time) VALUES (%s, %s, %s, %s, %s)",
- (user.id, 'feedback', fb_type, update.message.text, currentTime))
- connection.commit()
- cursor.close()
- # close the connection
- connection.close()
- # exit the program
- except:
- print ("Error: Uable to Fetch Data.")
- update.message.reply_text("Feel free to leave your contact for follow up!\n"
- "or click /skip.")
- return FEEDBACK_LOG_CONTACT
- # Duplicate 'feedback_getLog' function
- def feedback_getLog2(bot, update):
- # user = update.message.from_user
- logger_CS.info("User's feedback: %s" % (update.message.text))
- try:
- # open a database connection
- # connection = MySQLdb.connect (host = "192.168.64.2", user = "macbook", passwd = "123", db = "awbtable")
- connection = pymysql.connect(host="192.168.64.2", user="macbook", passwd="123", db="awbtable")
- # connection = pymysql.connect(host="jeffffc.com", user="kelvin", passwd="abcd1234", db="kelvin")
- # prepare a cursor object using cursor() method
- cursor = connection.cursor()
- # Execute the SQL commandUPDATE user_log SET content = '123' WHERE user_id = 237554606
- currentTime = strftime('%Y-%m-%d %H:%M:%S')
- cursor.execute("INSERT INTO user_log (user_id, type, feedback_type, content, log_time) VALUES (%s, %s, %s, %s, %s)",
- (user.id, 'feedback', fb_type, update.message.text, currentTime))
- connection.commit()
- cursor.close()
- # close the connection
- connection.close()
- # exit the program
- except:
- print ("Error: Uable to Fetch Data.")
- update.message.reply_text("Feel free to leave your contact for follow up!\n"
- "or click /skip.")
- return FEEDBACK_LOG_CONTACT2
- # Get user contact function
- def feedback_getContact(bot, update):
- user = update.message.from_user
- try:
- # open a database connection
- # connection = MySQLdb.connect (host = "192.168.64.2", user = "macbook", passwd = "123", db = "awbtable")
- connection = pymysql.connect(host="192.168.64.2", user="macbook", passwd="123", db="awbtable")
- # connection = pymysql.connect(host="jeffffc.com", user="kelvin", passwd="abcd1234", db="kelvin")
- # prepare a cursor object using cursor() method
- cursor = connection.cursor()
- # Execute the SQL command
- cursor.execute("UPDATE user_log SET contact = %s WHERE user_id = %s ", (update.message.text, user.id))
- connection.commit()
- cursor.close()
- # close the connection
- connection.close()
- # exit the program
- except:
- print ("Error: Uable to Fetch Data.")
- logger_CS.info("User's Contact: %s" % (update.message.text))
- return end(bot, update)
- # Duplicate 'feedback_getContact' function
- def feedback_getContact2(bot, update):
- user = update.message.from_user
- try:
- # open a database connection
- # connection = MySQLdb.connect (host = "192.168.64.2", user = "macbook", passwd = "123", db = "awbtable")
- connection = pymysql.connect(host="192.168.64.2", user="macbook", passwd="123", db="awbtable")
- # connection = pymysql.connect(host="jeffffc.com", user="kelvin", passwd="abcd1234", db="kelvin")
- # prepare a cursor object using cursor() method
- cursor = connection.cursor()
- # Execute the SQL command
- cursor.execute("UPDATE user_log SET contact = %s WHERE user_id = %s ", (update.message.text, user.id))
- connection.commit()
- cursor.close()
- # close the connection
- connection.close()
- # exit the program
- except:
- print ("Error: Uable to Fetch Data.")
- logger_CS.info("User's Contact: %s" % (update.message.text))
- return end2(bot, update)
- # Skip contact
- def skip_contact(bot, update):
- logger_CS.info("User did not leave a contact.")
- logger_CS.info("<<<Section Ended>>>")
- return end(bot, update)
- # Duplicate 'skip_contact' function
- def skip_contact2(bot, update):
- logger_CS.info("User did not leave a contact.")
- logger_CS.info("<<<Section Ended>>>")
- return end(bot, update)
- # ContactUs Function with 'Email', 'Phone', 'Address' options(Reply-Keybaord)
- def contactus(bot, update):
- reply_keyboard = [['Email', 'Phone', 'Address']]
- update.message.reply_text('Here are 3 methods to get in touch with us...'
- 'Please click one of them to get more details !',
- reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True, resize_keyboard=True))
- return CU_OPTION
- # Show email detail
- def email_detail(bot, update):
- update.message.reply_text('Business Enquiry: \nbusiness@hactl.com\n'
- 'Media Enquiry: \nmedia@hactl.com')
- return end(bot, update)
- # Show phone detail
- def phone_detail(bot, update):
- update.message.reply_text('Terminal Services (Cargo Handling): \n(+852)27531010\n'
- 'Terminal Services (Documentation Handling): \n(+852)27532412\n'
- 'Member Services Support: \n(+852)27531002')
- return end(bot, update)
- # Show address detail
- def address_detail(bot, update):
- update.message.reply_text('Office Address:\n'
- 'SuperTerminal 1\n'
- '9 Chun Wan Road\n'
- 'Hong Kong International Airport\n'
- 'Hong Kong')
- return end(bot, update)
- def contactus2(bot, update):
- reply_keyboard = [['Email', 'Phone', 'Address']]
- update.message.reply_text('Here are 3 methods to get in touch with us...'
- 'Please click one of them to get more details !',
- reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True, resize_keyboard=True))
- return HELP_OPTION
- def email_detail2(bot, update):
- update.message.reply_text('Business Enquiry: \nbusiness@hactl.com\n'
- 'Media Enquiry: \nmedia@hactl.com')
- return end2(bot, update)
- # Show phone detail
- def phone_detail2(bot, update):
- update.message.reply_text('Terminal Services (Cargo Handling): \n(+852)27531010\n'
- 'Terminal Services (Documentation Handling): \n(+852)27532412\n'
- 'Member Services Support: \n(+852)27531002')
- return end2(bot, update)
- # Show address detail
- def address_detail2(bot, update):
- update.message.reply_text('Office Address:\n'
- 'SuperTerminal 1\n'
- '9 Chun Wan Road\n'
- 'Hong Kong International Airport\n'
- 'Hong Kong')
- return end2(bot, update)
- # Check AWB function
- def bio(bot, update):
- user = update.message.from_user
- logger_CC.info("AWB of %s: %s" % (user.id, update.message.text))
- if not update.message.text.isdigit():
- update.message.reply_text("Sorry, you have entered a wrong type of AWB...\n"
- "Please try again...")
- return cargochecking_after_option(bot, update)
- try:
- # open a database connection
- # connection = MySQLdb.connect (host = "192.168.64.2", user = "macbook", passwd = "123", db = "awbtable")
- connection = pymysql.connect(host="192.168.64.2", user="macbook", passwd="123", db="awbtable")
- # connection = pymysql.connect(host="jeffffc.com", user="kelvin", passwd="abcd1234", db="kelvin")
- # prepare a cursor object using cursor() method
- cursor1 = connection.cursor()
- cursor2 = connection.cursor()
- # execute the SQL query using execute() method.
- # Execute the SQL command
- cursor1.execute("SELECT * FROM records WHERE AWB = %s", (update.message.text))
- # cursor2.execute("INSERT INTO awbhistory (AWB) VALUES ('%s')" % (update.message.text))
- # Fetch all the rows in a list of lists.
- results = cursor1.fetchall()
- # No AWB record
- if results == ():
- update.message.reply_text("Sorry, no record is found...")
- return cargochecking_after_option2(bot, update)
- if results != ():
- for row in results:
- update.message.reply_text(
- row[1] + '\n' + row[2] + '\n' + row[3] + '\n' + row[4] + '\n' + row[5] + '\n' + row[6] +
- row[7] + '\n' + row[8] + row[9])
- # cursor2.execute("INSERT INTO awbhistory (AWB) VALUES ('%s')" % (update.message.text))
- currentTime = strftime('%Y-%m-%d %H:%M:%S')
- cursor2.execute("INSERT INTO user_log (user_id, type, content, log_time) VALUES (%s, %s, %s, %s)",
- (user.id, 'awb', update.message.text, currentTime))
- connection.commit()
- cursor1.close()
- cursor2.close()
- # close the connection
- connection.close()
- # exit the program
- except:
- print ("Error: Uable to Fetch Data.")
- return cargochecking_after_option(bot, update)
- # Duplicate 'bio' function
- def bio2(bot, update):
- user = update.message.from_user
- logger_CC.info("AWB of %s: %s" % (user.id, update.message.text))
- if not update.message.text.isdigit():
- update.message.reply_text("Sorry, you have entered a wrong type of AWB...\n"
- "Please try again...")
- return cargochecking_after_option(bot, update)
- try:
- # open a database connection
- # connection = MySQLdb.connect (host = "192.168.64.2", user = "macbook", passwd = "123", db = "awbtable")
- connection = pymysql.connect(host="192.168.64.2", user="macbook", passwd="123", db="awbtable")
- # connection = pymysql.connect(host="jeffffc.com", user="kelvin", passwd="abcd1234", db="kelvin")
- # prepare a cursor object using cursor() method
- cursor1 = connection.cursor()
- cursor2 = connection.cursor()
- # Execute the SQL command
- cursor1.execute("SELECT * FROM records WHERE AWB = %s", (update.message.text))
- # cursor2.execute("INSERT INTO awbhistory (AWB) VALUES ('%s')" % (update.message.text))
- # Fetch all the rows in a list of lists.
- results = cursor1.fetchall()
- # No AWB record
- if results == ():
- update.message.reply_text("Sorry, no record is found...")
- return cargochecking2_after_option2(bot, update)
- if results != ():
- for row in results:
- update.message.reply_text(
- row[1] + '\n' + row[2] + '\n' + row[3] + '\n' + row[4] + '\n' + row[5] + '\n' + row[6] +
- row[7] + '\n' + row[8] + row[9])
- # cursor2.execute("INSERT INTO awbhistory (AWB) VALUES ('%s')" % (update.message.text))
- currentTime = strftime('%Y-%m-%d %H:%M:%S')
- cursor2.execute("INSERT INTO user_log (user_id, type, content, log_time) VALUES (%s, %s, %s, %s)",
- (user.id, 'awb', update.message.text, currentTime))
- connection.commit()
- cursor1.close()
- cursor2.close()
- # close the connection
- connection.close()
- # exit the program
- except:
- print ("Error: Uable to Fetch Data.")
- return cargochecking2_after_option(bot, update)
- # Help function to show commands
- def help_menu(bot, update):
- update.message.reply_text("/start - Start the Bot\n"
- "/cargochecking - AWB Checking\n"
- "/showawblist - Show AWB Search History\n"
- "/feedback - Provide Feedback\n"
- "/contactus - Contact Us\n"
- "/cancel - Stop the Bot")
- return HELP_OPTION
- # End point of function
- def end(bot, update):
- # user = update.message.from_user
- update.effective_message.reply_text('Thank you for your support!\nI hope we can see you again in the coming future.',
- reply_markup=ReplyKeyboardRemove())
- sleep(1)
- update.effective_message.reply_text('Enter /start if you want to talk to me again! ', reply_markup=ReplyKeyboardRemove())
- logger_CC.info("<<<Section Ended>>>")
- logger_CS.info("<<<Section Ended>>>")
- return ConversationHandler.END
- # Duplicate 'end'
- def end2(bot, update):
- # user = update.message.from_user
- update.effective_message.reply_text('Thank you for your support!\nI hope we can see you again in the coming future.',
- reply_markup=ReplyKeyboardRemove())
- sleep(1)
- update.effective_message.reply_text('Enter /start if you want to talk to me again! ', reply_markup=ReplyKeyboardRemove())
- logger_CC.info("<<<Section Ended>>>")
- logger_CS.info("<<<Section Ended>>>")
- return ConversationHandler.END
- # Cancel function with log
- def cancel(bot, update):
- user = update.message.from_user
- logger_CC.info("User %s canceled the conversation.\n" % (user.id))
- logger_CS.info("User %s canceled the conversation.\n" % (user.id))
- update.message.reply_text('Bye! Thank you for your support!',
- reply_markup=ReplyKeyboardRemove())
- sleep(1)
- update.message.reply_text('Enter /start if you want to talk to me again! ', reply_markup=ReplyKeyboardRemove())
- logger_CC.info("<<<Section Ended>>>")
- logger_CS.info("<<<Section Ended>>>")
- return ConversationHandler.END
- # Duplicate 'cancel' function
- def cancel2(bot, update):
- user = update.message.from_user
- logger_CC.info("User %s canceled the conversation.\n" % (user.id))
- logger_CS.info("User %s canceled the conversation.\n" % (user.id))
- update.message.reply_text('Bye! Thank you for your support!',
- reply_markup=ReplyKeyboardRemove())
- sleep(1)
- update.message.reply_text('Enter /start if you want to talk with me again! ', reply_markup=ReplyKeyboardRemove())
- logger_CC.info("<<<Section Ended>>>")
- logger_CS.info("<<<Section Ended>>>")
- return ConversationHandler.END
- # Error log
- def error(bot, update, error):
- logger_CC.warn('Update "%s" caused error "%s"\n' % (update, error))
- logger_CS.warn('Update "%s" caused error "%s"\n' % (update, error))
- ###################################################################################################################################################################################################################
- def main():
- # Telegram Bot's token
- updater = Updater("447528427:AAFr4sntMj_6aQhOmYVYlnNy2JsVQbEMUzE")
- # Get the dispatcher to register handlers
- dp = updater.dispatcher
- # Add conversation handler
- # #1 conversation handler, for handling program starts with /start command
- conv_handler = ConversationHandler(
- entry_points = [CommandHandler('start', start)],
- states = {
- CARGOCHECKING: [RegexHandler('^(CargoChecking)$', cargochecking_after_option),
- RegexHandler('^(CustomerService)$', customerservice),
- CommandHandler('contactus', contactus), CommandHandler('feedback', feedback),
- CommandHandler('help', help_menu), CommandHandler('cancel', cancel),
- MessageHandler(Filters.all, start)],
- CCOPTION: [RegexHandler('^(Show AWB List)$', showAWBlist), RegexHandler('^(Home Page)$', start),
- MessageHandler(Filters.text, bio)],
- INLINE_STATE: [CallbackQueryHandler(button_callback), MessageHandler(Filters.all, showAWBlist)],
- CS_OPTION: [RegexHandler('^(Feedback)$', feedback), RegexHandler('^(Contact Us)$', contactus),
- CommandHandler('showawblist', showAWBlist), CommandHandler('help', help_menu),
- CommandHandler('start', start), CommandHandler('cargochecking', cargochecking_after_option),
- CommandHandler('cancel', cancel), MessageHandler(Filters.all, customerservice)],
- FEEDBACK: [RegexHandler('^(Facility|Staff|Service)$', feedback_input),
- CommandHandler('showawblist', showAWBlist), CommandHandler('help', help_menu),
- CommandHandler('start', start), CommandHandler('cargochecking', cargochecking_after_option),
- CommandHandler('cancel', cancel), CommandHandler('contactus', contactus),
- MessageHandler(Filters.all, feedback)],
- FEEDBACK_LOG: [MessageHandler(Filters.text, feedback_getLog)],
- FEEDBACK_LOG_CONTACT: [MessageHandler(Filters.text, feedback_getContact),
- CommandHandler('skip', skip_contact)],
- CU_OPTION: [RegexHandler('^(Email)$', email_detail), RegexHandler('^(Phone)$', phone_detail),
- RegexHandler('^(Address)$', address_detail), MessageHandler(Filters.all, contactus)],
- DELETE_AWB: [MessageHandler(Filters.text, delete_awb_op)]
- },
- fallbacks = [CommandHandler('cancel', cancel)],
- )
- # #2 conversation handler, for handling program starts with /cargocheing command
- cargo_handler = ConversationHandler(
- entry_points = [CommandHandler('cargochecking', cargochecking2_after_option)],
- states = {
- CCOPTION2: [RegexHandler('^(Show AWB List)$', showAWBlist2), RegexHandler('^(Home Page)$', start),
- MessageHandler(Filters.text, bio2)],
- INLINE_STATE2: [CallbackQueryHandler(button_callback2), MessageHandler(Filters.all, showAWBlist2)],
- DELETE2_AWB: [MessageHandler(Filters.text, delete2_awb_op)]
- },
- fallbacks=[CommandHandler('cancel', cancel)]
- )
- # #3 conversation handler, for handling program starts with /feedback command
- feedback_handler = ConversationHandler(
- entry_points = [CommandHandler('feedback', feedback2)],
- states = {
- FEEDBACK2: [RegexHandler('^(Facility|Staff|Service)$', feedback_input2),
- MessageHandler(Filters.all, feedback2)],
- FEEDBACK_LOG2: [MessageHandler(Filters.text, feedback_getLog2)],
- FEEDBACK_LOG_CONTACT2: [MessageHandler(Filters.text, feedback_getContact2),
- CommandHandler('skip', skip_contact2)]
- },
- fallbacks = [CommandHandler('cancel', cancel)]
- )
- # #4 conversation handler, for handling program starts with /help command
- help_handler = ConversationHandler(
- entry_points = [CommandHandler('help', help_menu)],
- states = {
- HELP_OPTION: [CommandHandler('start', start), CommandHandler('cargochecking', cargochecking2_after_option),
- CommandHandler('showawblist', showAWBlist2), CommandHandler('feedback', feedback2),
- CommandHandler('contactus', contactus)]
- },
- fallbacks = [CommandHandler('cancel', cancel)])
- # #5 conversation handler, for handling program starts with /contactus command
- contactus_handler = ConversationHandler(
- entry_points = [CommandHandler('contactus', contactus2)],
- states = {
- CU_OPTION2: [RegexHandler('^(Email)$', email_detail2), RegexHandler('^(Address)$', address_detail2),
- RegexHandler('^(Phone)$', phone_detail2), MessageHandler(Filters.all, contactus)]
- },
- fallbacks = [CommandHandler('cancel', cancel)])
- # add handler
- dp.add_handler(conv_handler)
- dp.add_handler(cargo_handler)
- dp.add_handler(feedback_handler)
- dp.add_handler(help_handler)
- dp.add_handler(contactus_handler)
- dp.add_handler(CommandHandler('showawblist', showAWBlist))
- dp.add_handler(CommandHandler('cancel', cancel))
- # log all errors
- dp.add_error_handler(error)
- # Start the Bot
- updater.start_polling()
- # Run the bot until you press Ctrl-C or the system receives SIGHINT or SIGTSTP
- updater.idle()
- sys.exit()
- if __name__ == '__main__':
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement