Advertisement
kelvinsiu00

telegram-bot-hactl-python

Aug 17th, 2017
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 39.98 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. # Testing Hactl Telegram Bot to handle clients' basic requests
  5. #
  6. # Duplicate function(represent as [Origin-function-name]2) is for the program running within a different state
  7.  
  8. from telegram import (ReplyKeyboardMarkup, ReplyKeyboardRemove, InlineKeyboardButton, InlineKeyboardMarkup)
  9. from telegram.ext import (Updater, CommandHandler, MessageHandler, Filters, RegexHandler,
  10. ConversationHandler, CallbackQueryHandler)
  11. from time import gmtime, strftime, sleep
  12. import logging
  13. # import MySQLdb
  14. import pymysql
  15. import sys
  16.  
  17.  
  18. CARGOCHECKING, CCOPTION, CCOPTION2, CS_OPTION, FEEDBACK, FEEDBACK_LOG, FEEDBACK_LOG_CONTACT, \
  19. CU_OPTION, CU_OPTION2, PRINTAWB, FEEDBACK2, FEEDBACK_LOG_CONTACT2, FEEDBACK_LOG2, REPEATCC, REPEATCC2, INLINE_STATE, \
  20. INLINE_STATE2, HELP_OPTION, SHOWLIST_OPTION, SHOWLIST_OPTION2, DELETE_AWB, DELETE2_AWB = range(22)
  21.  
  22.  
  23.  
  24. # Enable logging
  25. formatter_CC = logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
  26. level=logging.INFO)
  27.  
  28. formatter_CS = logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
  29. level=logging.INFO)
  30.  
  31. # logging for cargochecking
  32. logger_CC = logging.getLogger('CC')
  33. hdlr_CC = logging.FileHandler('./temp_CC.log')
  34. hdlr_CC.setFormatter(formatter_CC)
  35. logger_CC.addHandler(hdlr_CC)
  36.  
  37. # logging for customerservice
  38. logger_CS = logging.getLogger('CS')
  39. hdlr_CS = logging.FileHandler('./temp_CS.log')
  40. hdlr_CS.setFormatter(formatter_CS)
  41. logger_CS.addHandler(hdlr_CS)
  42.  
  43.  
  44. # functions starts
  45. # Showing 'CargoChecking', 'CustomerService' options(Reply-Keybaord)
  46. def start(bot, update):
  47. reply_keyboard = [['CargoChecking', 'CustomerService']]
  48.  
  49. update.effective_message.reply_text('Hi! My name is Hactl Bot. I am here to help you.\n\n'
  50. 'Click / on your keyboard to view the functions list.\n'
  51. 'Send /cancel to stop talking with me.\n\n')
  52.  
  53. update.effective_message.reply_text('First, may I know what can I do for you?',
  54. reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True,
  55. resize_keyboard=True))
  56. logger_CC.info("<<<Section Starts>>>")
  57. logger_CS.info("<<<Section Starts>>>")
  58. return CARGOCHECKING
  59.  
  60.  
  61. # telegramb_bot_python API Default function for building inline keyboard
  62. def build_menu(buttons, n_cols, header_buttons=None, footer_buttons=None):
  63. menu = [buttons[i:i + n_cols] for i in range(0, len(buttons), n_cols)]
  64. if header_buttons:
  65. menu.insert(0, header_buttons)
  66. if footer_buttons:
  67. menu.append(footer_buttons)
  68. return menu
  69.  
  70.  
  71. # Showing 'Show AWB List', 'Home Page' options after clicking 'CaroChecking' option(Reply-Keybaord) in the first page, function with log
  72. def cargochecking_after_option(bot, update):
  73. user = update.message.from_user
  74. reply_keyboard = [['Show AWB List', 'Home Page']]
  75.  
  76. update.message.reply_text('Function: Cargo Checking\n'
  77. 'Please input your AWB and click Send...',
  78. reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard = False, resize_keyboard = True))
  79.  
  80.  
  81. logger_CC.info("Function of %s: %s" % (user.id, update.message.text))
  82.  
  83. return CCOPTION
  84.  
  85. # Duplicate 'cargochecking_after_option' function
  86. def cargochecking2_after_option(bot, update):
  87. user = update.message.from_user
  88. reply_keyboard = [['Show AWB List', 'Home Page']]
  89.  
  90. update.message.reply_text('Function: Cargo Checking\n'
  91. 'Please input your AWB and click Send...',
  92. reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard = False, resize_keyboard = True))
  93.  
  94.  
  95. logger_CC.info("Function of %s: %s" % (user.id, update.message.text))
  96.  
  97. return CCOPTION2
  98.  
  99.  
  100. # Showing 'Show AWB List', 'Home Page' options after clicking 'CaroChecking' option(Reply-Keybaord) in the first page, function without log
  101. def cargochecking_after_option2(bot, update):
  102. user = update.message.from_user
  103. reply_keyboard = [['Show AWB List', 'Home Page']]
  104.  
  105. update.message.reply_text('Function: Cargo Checking\n'
  106. 'Please input your AWB and click Send...',
  107. reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard = False, resize_keyboard = True))
  108.  
  109. return CCOPTION
  110.  
  111. # Duplicate 'cargochecking_after_option2' function
  112. def cargochecking2_after_option2(bot, update):
  113. user = update.message.from_user
  114. reply_keyboard = [['Show AWB List', 'Home Page']]
  115.  
  116. update.message.reply_text('Function: Cargo Checking\n'
  117. 'Please input your AWB and click Send...',
  118. reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard = False, resize_keyboard = True))
  119.  
  120. return CCOPTION2
  121.  
  122.  
  123. # Fetch data from Database, show AWB list(Inline-Keybaord) with Inline-Keyboard
  124. def showAWBlist(bot, update):
  125. user = update.message.from_user
  126.  
  127. update.message.reply_text('Please choose from the history:',
  128. reply_markup=ReplyKeyboardRemove())
  129.  
  130. try:
  131. # open a database connection
  132. # connection = MySQLdb.connect (host = "192.168.64.2", user = "macbook", passwd = "123", db = "awbtable")
  133. connection = pymysql.connect(host="192.168.64.2", user="macbook", passwd="123", db="awbtable")
  134. # connection = pymysql.connect(host="jeffffc.com", user="kelvin", passwd="abcd1234", db="kelvin")
  135. # prepare a cursor object using cursor() method
  136.  
  137. cursor = connection.cursor()
  138. # execute the SQL query using execute() method.
  139. # Execute the SQL command
  140. cursor.execute("SELECT DISTINCT content FROM user_log WHERE user_id = %s AND type = %s", (user.id, 'awb'))
  141.  
  142. # Fetch all the rows in a list of lists.
  143. results = cursor.fetchall()
  144.  
  145. if results == ():
  146. update.message.reply_text("Sorry, no history is found...")
  147. return cargochecking_after_option(bot, update)
  148.  
  149. msg = "\n\nPress Delete to delete AWB from list."
  150.  
  151.  
  152. button_list = []
  153. for row in results:
  154. button_list.append(InlineKeyboardButton(str(row[0]), callback_data=str(row[0])))
  155.  
  156. reply_keyboard = InlineKeyboardMarkup(build_menu(button_list, 3, None,[InlineKeyboardButton("Delete", callback_data="delete"),
  157. InlineKeyboardButton("Home", callback_data="start"), InlineKeyboardButton("End Bot", callback_data="end")]))
  158.  
  159.  
  160. update.message.reply_text(msg, reply_markup = reply_keyboard)
  161.  
  162. cursor.close()
  163. # close the connection
  164. connection.close()
  165. # exit the program
  166.  
  167. except:
  168. print ("Error: Uable to Fetch Data.")
  169.  
  170. # return end(bot, update)
  171. return INLINE_STATE
  172.  
  173. # Showing AWB deatails after users clicking the Inline-Keyboard list function 'showAWBlist'
  174. def button_callback(bot, update):
  175. query = update.callback_query
  176.  
  177. if query.data == 'end':
  178. return end(bot, update)
  179.  
  180. if query.data == 'delete':
  181. return delete_awb(bot, update)
  182.  
  183. if query.data == 'start':
  184. return start(bot, update)
  185.  
  186. try:
  187. #connection = pymysql.connect(host="jeffffc.com", user="kelvin", passwd="abcd1234", db="kelvin")
  188. connection = pymysql.connect(host="192.168.64.2", user="macbook", passwd="123", db="awbtable")
  189.  
  190. cursor = connection.cursor()
  191. cursor.execute("SELECT * FROM records WHERE AWB = %s" % query.data)
  192. results = cursor.fetchall()
  193.  
  194. # No AWB record
  195. if results == ():
  196. update.message.reply_text("Sorry, no record is found...")
  197. return cargochecking_after_option(bot, update)
  198. # Record found
  199. if results != ():
  200. for row in results:
  201. update.callback_query.message.reply_text(row[1] + '\n' + row[2] + '\n' + row[3] + '\n' + row[4] + '\n' + row[5] + '\n' + row[6] +
  202. row[7] + '\n' + row[8] + row[9])
  203.  
  204. query.answer()
  205. cursor.close()
  206. connection.close()
  207. except:
  208. print ("Error: Uable to Fetch Data.")
  209.  
  210.  
  211. # Duplicate 'showAWBlist' function
  212. def showAWBlist2(bot, update):
  213. user = update.message.from_user
  214.  
  215. update.message.reply_text('Please choose from the history:',
  216. reply_markup=ReplyKeyboardRemove())
  217.  
  218. try:
  219. # open a database connection
  220. # connection = MySQLdb.connect (host = "192.168.64.2", user = "macbook", passwd = "123", db = "awbtable")
  221. connection = pymysql.connect(host="192.168.64.2", user="macbook", passwd="123", db="awbtable")
  222. # connection = pymysql.connect(host="jeffffc.com", user="kelvin", passwd="abcd1234", db="kelvin")
  223. # prepare a cursor object using cursor() method
  224.  
  225. cursor = connection.cursor()
  226. # execute the SQL query using execute() method.
  227. # Execute the SQL command
  228. cursor.execute("SELECT DISTINCT content FROM user_log WHERE user_id = %s AND type = %s", (user.id, 'awb'))
  229.  
  230. # Fetch all the rows in a list of lists.
  231. results = cursor.fetchall()
  232.  
  233. if results == ():
  234. update.message.reply_text("Sorry, no history is found...")
  235. return cargochecking_after_option(bot, update)
  236.  
  237. msg = "\n\nPress Delete to delete AWB from list."
  238.  
  239.  
  240. button_list = []
  241. for row in results:
  242. button_list.append(InlineKeyboardButton(str(row[0]), callback_data=str(row[0])))
  243.  
  244. reply_keyboard = InlineKeyboardMarkup(build_menu(button_list, 3, None,[InlineKeyboardButton("Delete", callback_data="delete"),
  245. InlineKeyboardButton("Home", callback_data="start"), InlineKeyboardButton("End Bot", callback_data="end")]))
  246.  
  247.  
  248. update.message.reply_text(msg, reply_markup = reply_keyboard)
  249.  
  250. cursor.close()
  251. # close the connection
  252. connection.close()
  253. # exit the program
  254.  
  255. except:
  256. print ("Error: Uable to Fetch Data.")
  257.  
  258. return INLINE_STATE2
  259.  
  260. # Duplicate 'button_callback' function
  261. def button_callback2(bot, update):
  262. query = update.callback_query
  263.  
  264. if query.data == 'end':
  265. return end(bot, update)
  266.  
  267. if query.data == 'delete':
  268. return delete_awb(bot, update)
  269.  
  270.  
  271. try:
  272. #connection = pymysql.connect(host="jeffffc.com", user="kelvin", passwd="abcd1234", db="kelvin")
  273. connection = pymysql.connect(host="192.168.64.2", user="macbook", passwd="123", db="awbtable")
  274.  
  275. cursor = connection.cursor()
  276. cursor.execute("SELECT * FROM records WHERE AWB = %s" % query.data)
  277. results = cursor.fetchall()
  278.  
  279. # No AWB record
  280. if results == ():
  281. update.message.reply_text("Sorry, no record is found...")
  282. return cargochecking2_after_option(bot, update)
  283. # Record found
  284. if results != ():
  285. for row in results:
  286. update.callback_query.message.reply_text(row[1] + '\n' + row[2] + '\n' + row[3] + '\n' + row[4] + '\n' + row[5] + '\n' + row[6] +
  287. row[7] + '\n' + row[8] + row[9])
  288.  
  289. query.answer()
  290. cursor.close()
  291. connection.close()
  292. except:
  293. print ("Error: Uable to Fetch Data.")
  294.  
  295.  
  296. # Terminate function for 'showAWBlist' and 'button_callback'
  297. def end_inline(bot, update):
  298. return end(bot, update)
  299.  
  300. # Duplicate 'end_inline' function
  301. def end_inline2(bot, update):
  302. return end2(bot, update)
  303.  
  304. ######################################################################################################################################################################################################################################################################
  305. # Delete AWB list (get AWB input)
  306. def delete_awb(bot, update):
  307. #user = update.message.from_user
  308. query = update.callback_query
  309.  
  310. update.callback_query.message.reply_text('Function: Delete AWB\n'
  311. 'Please input your AWB and click Send to delete it from AWB list...')
  312.  
  313. return DELETE_AWB
  314.  
  315.  
  316. # Duplicate 'delete_awb' function
  317. def delete2_awb(bot, update):
  318. #user = update.effective_message.from_user
  319. query = update.callback_query
  320.  
  321. update.callback_query.message.reply_text('Function: Delete AWB\n'
  322. 'Please input your AWB and click Send to delete it from AWB list...')
  323.  
  324. return DELETE2_AWB
  325.  
  326.  
  327. # Delete AWB list (operation)
  328. def delete_awb_op(bot, update):
  329. user = update.message.from_user
  330.  
  331. if not update.message.text.isdigit():
  332. update.message.reply_text("Sorry, you have entered a wrong type of AWB...\n"
  333. "Please try again...")
  334. return showAWBlist(bot, update)
  335.  
  336.  
  337. try:
  338. # open a database connection
  339. # connection = MySQLdb.connect (host = "192.168.64.2", user = "macbook", passwd = "123", db = "awbtable")
  340. connection = pymysql.connect(host="192.168.64.2", user="macbook", passwd="123", db="awbtable")
  341. # connection = pymysql.connect(host="jeffffc.com", user="kelvin", passwd="abcd1234", db="kelvin")
  342. # prepare a cursor object using cursor() method
  343.  
  344. cursor = connection.cursor()
  345. cursor.execute("SELECT * FROM user_log WHERE user_id = %s AND type = %s AND Content = %s", (user.id, 'awb', update.message.text))
  346.  
  347. results = cursor.fetchall()
  348.  
  349. if results == ():
  350. update.message.reply_text("Sorry, no record is found...")
  351. return cargochecking_after_option(bot, update)
  352.  
  353. if results != ():
  354. cursor.execute("DELETE FROM user_log WHERE user_id = %s AND type = %s AND Content = %s", (user.id, 'awb', update.message.text))
  355.  
  356. connection.commit()
  357. cursor.close()
  358. connection.close()
  359.  
  360. logger_CC.info("<<< AWB Deleted >>>")
  361. update.message.reply_text("<<< AWB Deleted >>>")
  362.  
  363. except pymysql.MySQLError as e:
  364. code, errormsg = e.args
  365. sqlerror = "MySQL ErrorCode: %s\nErrorMsg:%s" % (code, errormsg)
  366. print(sqlerror)
  367.  
  368.  
  369. return cargochecking_after_option2(bot, update)
  370.  
  371.  
  372. # Duplicate (delete_awb_op) function
  373. def delete2_awb_op(bot, update):
  374. user = update.message.from_user
  375.  
  376. if not update.message.text.isdigit():
  377. update.message.reply_text("Sorry, you have entered a wrong type of AWB...\n"
  378. "Please try again...")
  379. return showAWBlist2(bot, update)
  380.  
  381.  
  382. try:
  383. # open a database connection
  384. # connection = MySQLdb.connect (host = "192.168.64.2", user = "macbook", passwd = "123", db = "awbtable")
  385. connection = pymysql.connect(host="192.168.64.2", user="macbook", passwd="123", db="awbtable")
  386. # connection = pymysql.connect(host="jeffffc.com", user="kelvin", passwd="abcd1234", db="kelvin")
  387. # prepare a cursor object using cursor() method
  388.  
  389. cursor = connection.cursor()
  390. cursor.execute("SELECT * FROM user_log WHERE user_id = %s AND type = %s AND Content = %s", (user.id, 'awb', update.message.text))
  391.  
  392. results = cursor.fetchall()
  393.  
  394. if results == ():
  395. update.message.reply_text("Sorry, no record is found...")
  396. return cargochecking2_after_option(bot, update)
  397.  
  398. if results != ():
  399. cursor.execute("DELETE FROM user_log WHERE user_id = %s AND type = %s AND Content = %s", (user.id, 'awb', update.message.text))
  400.  
  401. connection.commit()
  402. cursor.close()
  403. connection.close()
  404.  
  405. logger_CC.info("<<< AWB Deleted >>>")
  406. update.message.reply_text("<<< AWB Deleted >>>")
  407.  
  408. except pymysql.MySQLError as e:
  409. code, errormsg = e.args
  410. sqlerror = "MySQL ErrorCode: %s\nErrorMsg:%s" % (code, errormsg)
  411. print(sqlerror)
  412.  
  413.  
  414. return cargochecking2_after_option2(bot, update)
  415. ######################################################################################################################################################################################################################################################################
  416. # Customer Service function with 'Feedback', 'Contact Us' options(Reply-Keybaord)
  417. def customerservice(bot, update):
  418. user = update.message.from_user
  419.  
  420. reply_keyboard = [['Feedback', 'Contact Us']]
  421. update.message.reply_text('To have a better performance,'
  422. 'we treasure all valuable opinions from our clients.')
  423.  
  424. update.message.reply_text('What can I do for you?',
  425. reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True, resize_keyboard=True))
  426.  
  427.  
  428. logger_CS.info("Function of %s: %s" % (user.id, update.message.text))
  429.  
  430. return CS_OPTION
  431.  
  432.  
  433. # Feedback function with 'Facility', 'Staff', 'Service' options(Reply-Keybaord)
  434. def feedback(bot, update):
  435. reply_keyboard = [['Facility', 'Staff', 'Service']]
  436.  
  437. update.message.reply_text('May I know which aspect(s) you want to give feedback to?\n',
  438. reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True, resize_keyboard=True))
  439.  
  440. return FEEDBACK
  441.  
  442.  
  443. # Duplicate 'feedback' function
  444. def feedback2(bot, update):
  445. reply_keyboard = [['Facility', 'Staff', 'Service']]
  446.  
  447. update.message.reply_text('May I know which aspect(s) you want to give feedback to?\n',
  448. reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True, resize_keyboard=True))
  449.  
  450. return FEEDBACK2
  451.  
  452.  
  453. # Feedback function let user enters text
  454. def feedback_input(bot, update):
  455.  
  456. user = update.message.from_user
  457. update.message.reply_text("You have chosen %s." % (update.message.text))
  458.  
  459. global fb_type
  460. fb_type = update.message.text
  461.  
  462. update.message.reply_text("Please write down your opinions in the textbox below, click Send once you have finished...")
  463.  
  464. logger_CS.info("feedback's Type: %s" % (update.message.text))
  465.  
  466. return FEEDBACK_LOG
  467.  
  468.  
  469. # Duplicate 'feedbakc_input' function
  470. def feedback_input2(bot, update):
  471. # user = update.message.from_user
  472.  
  473. user = update.message.from_user
  474. update.message.reply_text("You have chosen %s." % (update.message.text))
  475.  
  476. global fb_type
  477. fb_type = update.message.text
  478.  
  479. update.message.reply_text("Please write down your opinions in the textbox below, click Send once you have finished...")
  480.  
  481. logger_CS.info("feedback's Type: %s" % (update.message.text))
  482.  
  483. return FEEDBACK_LOG2
  484.  
  485.  
  486. # Feedback function(fetch text)
  487. def feedback_getLog(bot, update):
  488. user = update.message.from_user
  489. logger_CS.info("User's feedback: %s" % (update.message.text))
  490.  
  491.  
  492. try:
  493. # open a database connection
  494. # connection = MySQLdb.connect (host = "192.168.64.2", user = "macbook", passwd = "123", db = "awbtable")
  495. connection = pymysql.connect(host="192.168.64.2", user="macbook", passwd="123", db="awbtable")
  496. # connection = pymysql.connect(host="jeffffc.com", user="kelvin", passwd="abcd1234", db="kelvin")
  497. # prepare a cursor object using cursor() method
  498.  
  499. cursor = connection.cursor()
  500.  
  501. # Execute the SQL commandUPDATE user_log SET content = '123' WHERE user_id = 237554606
  502. currentTime = strftime('%Y-%m-%d %H:%M:%S')
  503.  
  504. cursor.execute("INSERT INTO user_log (user_id, type, feedback_type, content, log_time) VALUES (%s, %s, %s, %s, %s)",
  505. (user.id, 'feedback', fb_type, update.message.text, currentTime))
  506.  
  507. connection.commit()
  508.  
  509. cursor.close()
  510. # close the connection
  511. connection.close()
  512. # exit the program
  513.  
  514. except:
  515. print ("Error: Uable to Fetch Data.")
  516.  
  517.  
  518. update.message.reply_text("Feel free to leave your contact for follow up!\n"
  519. "or click /skip.")
  520.  
  521. return FEEDBACK_LOG_CONTACT
  522.  
  523.  
  524. # Duplicate 'feedback_getLog' function
  525. def feedback_getLog2(bot, update):
  526. # user = update.message.from_user
  527.  
  528. logger_CS.info("User's feedback: %s" % (update.message.text))
  529.  
  530. try:
  531. # open a database connection
  532. # connection = MySQLdb.connect (host = "192.168.64.2", user = "macbook", passwd = "123", db = "awbtable")
  533. connection = pymysql.connect(host="192.168.64.2", user="macbook", passwd="123", db="awbtable")
  534. # connection = pymysql.connect(host="jeffffc.com", user="kelvin", passwd="abcd1234", db="kelvin")
  535. # prepare a cursor object using cursor() method
  536.  
  537. cursor = connection.cursor()
  538.  
  539. # Execute the SQL commandUPDATE user_log SET content = '123' WHERE user_id = 237554606
  540. currentTime = strftime('%Y-%m-%d %H:%M:%S')
  541.  
  542. cursor.execute("INSERT INTO user_log (user_id, type, feedback_type, content, log_time) VALUES (%s, %s, %s, %s, %s)",
  543. (user.id, 'feedback', fb_type, update.message.text, currentTime))
  544.  
  545. connection.commit()
  546.  
  547. cursor.close()
  548. # close the connection
  549. connection.close()
  550. # exit the program
  551.  
  552. except:
  553. print ("Error: Uable to Fetch Data.")
  554.  
  555.  
  556. update.message.reply_text("Feel free to leave your contact for follow up!\n"
  557. "or click /skip.")
  558.  
  559. return FEEDBACK_LOG_CONTACT2
  560.  
  561.  
  562. # Get user contact function
  563. def feedback_getContact(bot, update):
  564. user = update.message.from_user
  565.  
  566. try:
  567. # open a database connection
  568. # connection = MySQLdb.connect (host = "192.168.64.2", user = "macbook", passwd = "123", db = "awbtable")
  569. connection = pymysql.connect(host="192.168.64.2", user="macbook", passwd="123", db="awbtable")
  570. # connection = pymysql.connect(host="jeffffc.com", user="kelvin", passwd="abcd1234", db="kelvin")
  571. # prepare a cursor object using cursor() method
  572.  
  573. cursor = connection.cursor()
  574.  
  575. # Execute the SQL command
  576.  
  577. cursor.execute("UPDATE user_log SET contact = %s WHERE user_id = %s ", (update.message.text, user.id))
  578.  
  579. connection.commit()
  580.  
  581. cursor.close()
  582. # close the connection
  583. connection.close()
  584. # exit the program
  585.  
  586. except:
  587. print ("Error: Uable to Fetch Data.")
  588.  
  589.  
  590. logger_CS.info("User's Contact: %s" % (update.message.text))
  591.  
  592. return end(bot, update)
  593.  
  594.  
  595. # Duplicate 'feedback_getContact' function
  596. def feedback_getContact2(bot, update):
  597. user = update.message.from_user
  598.  
  599. try:
  600. # open a database connection
  601. # connection = MySQLdb.connect (host = "192.168.64.2", user = "macbook", passwd = "123", db = "awbtable")
  602. connection = pymysql.connect(host="192.168.64.2", user="macbook", passwd="123", db="awbtable")
  603. # connection = pymysql.connect(host="jeffffc.com", user="kelvin", passwd="abcd1234", db="kelvin")
  604. # prepare a cursor object using cursor() method
  605.  
  606. cursor = connection.cursor()
  607.  
  608. # Execute the SQL command
  609.  
  610. cursor.execute("UPDATE user_log SET contact = %s WHERE user_id = %s ", (update.message.text, user.id))
  611.  
  612. connection.commit()
  613.  
  614. cursor.close()
  615. # close the connection
  616. connection.close()
  617. # exit the program
  618.  
  619. except:
  620. print ("Error: Uable to Fetch Data.")
  621.  
  622.  
  623. logger_CS.info("User's Contact: %s" % (update.message.text))
  624.  
  625. return end2(bot, update)
  626.  
  627.  
  628. # Skip contact
  629. def skip_contact(bot, update):
  630. logger_CS.info("User did not leave a contact.")
  631. logger_CS.info("<<<Section Ended>>>")
  632.  
  633. return end(bot, update)
  634.  
  635.  
  636. # Duplicate 'skip_contact' function
  637. def skip_contact2(bot, update):
  638. logger_CS.info("User did not leave a contact.")
  639. logger_CS.info("<<<Section Ended>>>")
  640.  
  641. return end(bot, update)
  642.  
  643.  
  644. # ContactUs Function with 'Email', 'Phone', 'Address' options(Reply-Keybaord)
  645. def contactus(bot, update):
  646. reply_keyboard = [['Email', 'Phone', 'Address']]
  647.  
  648. update.message.reply_text('Here are 3 methods to get in touch with us...'
  649. 'Please click one of them to get more details !',
  650. reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True, resize_keyboard=True))
  651.  
  652. return CU_OPTION
  653.  
  654.  
  655. # Show email detail
  656. def email_detail(bot, update):
  657. update.message.reply_text('Business Enquiry: \nbusiness@hactl.com\n'
  658. 'Media Enquiry: \nmedia@hactl.com')
  659.  
  660.  
  661. return end(bot, update)
  662.  
  663.  
  664.  
  665. # Show phone detail
  666. def phone_detail(bot, update):
  667. update.message.reply_text('Terminal Services (Cargo Handling): \n(+852)27531010\n'
  668. 'Terminal Services (Documentation Handling): \n(+852)27532412\n'
  669. 'Member Services Support: \n(+852)27531002')
  670.  
  671.  
  672. return end(bot, update)
  673.  
  674.  
  675. # Show address detail
  676. def address_detail(bot, update):
  677. update.message.reply_text('Office Address:\n'
  678. 'SuperTerminal 1\n'
  679. '9 Chun Wan Road\n'
  680. 'Hong Kong International Airport\n'
  681. 'Hong Kong')
  682.  
  683.  
  684. return end(bot, update)
  685.  
  686. def contactus2(bot, update):
  687. reply_keyboard = [['Email', 'Phone', 'Address']]
  688.  
  689. update.message.reply_text('Here are 3 methods to get in touch with us...'
  690. 'Please click one of them to get more details !',
  691. reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True, resize_keyboard=True))
  692.  
  693. return HELP_OPTION
  694.  
  695. def email_detail2(bot, update):
  696. update.message.reply_text('Business Enquiry: \nbusiness@hactl.com\n'
  697. 'Media Enquiry: \nmedia@hactl.com')
  698.  
  699.  
  700. return end2(bot, update)
  701.  
  702.  
  703.  
  704. # Show phone detail
  705. def phone_detail2(bot, update):
  706. update.message.reply_text('Terminal Services (Cargo Handling): \n(+852)27531010\n'
  707. 'Terminal Services (Documentation Handling): \n(+852)27532412\n'
  708. 'Member Services Support: \n(+852)27531002')
  709.  
  710.  
  711. return end2(bot, update)
  712.  
  713.  
  714. # Show address detail
  715. def address_detail2(bot, update):
  716. update.message.reply_text('Office Address:\n'
  717. 'SuperTerminal 1\n'
  718. '9 Chun Wan Road\n'
  719. 'Hong Kong International Airport\n'
  720. 'Hong Kong')
  721.  
  722.  
  723. return end2(bot, update)
  724.  
  725.  
  726.  
  727. # Check AWB function
  728. def bio(bot, update):
  729. user = update.message.from_user
  730.  
  731. logger_CC.info("AWB of %s: %s" % (user.id, update.message.text))
  732.  
  733. if not update.message.text.isdigit():
  734. update.message.reply_text("Sorry, you have entered a wrong type of AWB...\n"
  735. "Please try again...")
  736. return cargochecking_after_option(bot, update)
  737.  
  738. try:
  739. # open a database connection
  740. # connection = MySQLdb.connect (host = "192.168.64.2", user = "macbook", passwd = "123", db = "awbtable")
  741. connection = pymysql.connect(host="192.168.64.2", user="macbook", passwd="123", db="awbtable")
  742. # connection = pymysql.connect(host="jeffffc.com", user="kelvin", passwd="abcd1234", db="kelvin")
  743. # prepare a cursor object using cursor() method
  744.  
  745. cursor1 = connection.cursor()
  746. cursor2 = connection.cursor()
  747. # execute the SQL query using execute() method.
  748.  
  749.  
  750. # Execute the SQL command
  751. cursor1.execute("SELECT * FROM records WHERE AWB = %s", (update.message.text))
  752. # cursor2.execute("INSERT INTO awbhistory (AWB) VALUES ('%s')" % (update.message.text))
  753.  
  754. # Fetch all the rows in a list of lists.
  755. results = cursor1.fetchall()
  756.  
  757. # No AWB record
  758. if results == ():
  759. update.message.reply_text("Sorry, no record is found...")
  760. return cargochecking_after_option2(bot, update)
  761.  
  762. if results != ():
  763. for row in results:
  764. update.message.reply_text(
  765. row[1] + '\n' + row[2] + '\n' + row[3] + '\n' + row[4] + '\n' + row[5] + '\n' + row[6] +
  766. row[7] + '\n' + row[8] + row[9])
  767. # cursor2.execute("INSERT INTO awbhistory (AWB) VALUES ('%s')" % (update.message.text))
  768.  
  769. currentTime = strftime('%Y-%m-%d %H:%M:%S')
  770.  
  771. cursor2.execute("INSERT INTO user_log (user_id, type, content, log_time) VALUES (%s, %s, %s, %s)",
  772. (user.id, 'awb', update.message.text, currentTime))
  773. connection.commit()
  774.  
  775. cursor1.close()
  776. cursor2.close()
  777. # close the connection
  778. connection.close()
  779. # exit the program
  780.  
  781. except:
  782. print ("Error: Uable to Fetch Data.")
  783.  
  784.  
  785. return cargochecking_after_option(bot, update)
  786.  
  787.  
  788.  
  789. # Duplicate 'bio' function
  790. def bio2(bot, update):
  791. user = update.message.from_user
  792.  
  793. logger_CC.info("AWB of %s: %s" % (user.id, update.message.text))
  794.  
  795. if not update.message.text.isdigit():
  796. update.message.reply_text("Sorry, you have entered a wrong type of AWB...\n"
  797. "Please try again...")
  798. return cargochecking_after_option(bot, update)
  799.  
  800. try:
  801. # open a database connection
  802. # connection = MySQLdb.connect (host = "192.168.64.2", user = "macbook", passwd = "123", db = "awbtable")
  803. connection = pymysql.connect(host="192.168.64.2", user="macbook", passwd="123", db="awbtable")
  804. # connection = pymysql.connect(host="jeffffc.com", user="kelvin", passwd="abcd1234", db="kelvin")
  805. # prepare a cursor object using cursor() method
  806.  
  807. cursor1 = connection.cursor()
  808. cursor2 = connection.cursor()
  809.  
  810. # Execute the SQL command
  811. cursor1.execute("SELECT * FROM records WHERE AWB = %s", (update.message.text))
  812. # cursor2.execute("INSERT INTO awbhistory (AWB) VALUES ('%s')" % (update.message.text))
  813.  
  814. # Fetch all the rows in a list of lists.
  815. results = cursor1.fetchall()
  816.  
  817. # No AWB record
  818. if results == ():
  819. update.message.reply_text("Sorry, no record is found...")
  820. return cargochecking2_after_option2(bot, update)
  821.  
  822. if results != ():
  823. for row in results:
  824. update.message.reply_text(
  825. row[1] + '\n' + row[2] + '\n' + row[3] + '\n' + row[4] + '\n' + row[5] + '\n' + row[6] +
  826. row[7] + '\n' + row[8] + row[9])
  827. # cursor2.execute("INSERT INTO awbhistory (AWB) VALUES ('%s')" % (update.message.text))
  828.  
  829. currentTime = strftime('%Y-%m-%d %H:%M:%S')
  830.  
  831. cursor2.execute("INSERT INTO user_log (user_id, type, content, log_time) VALUES (%s, %s, %s, %s)",
  832. (user.id, 'awb', update.message.text, currentTime))
  833. connection.commit()
  834.  
  835. cursor1.close()
  836. cursor2.close()
  837. # close the connection
  838. connection.close()
  839. # exit the program
  840.  
  841. except:
  842. print ("Error: Uable to Fetch Data.")
  843.  
  844. return cargochecking2_after_option(bot, update)
  845.  
  846.  
  847. # Help function to show commands
  848. def help_menu(bot, update):
  849. update.message.reply_text("/start - Start the Bot\n"
  850. "/cargochecking - AWB Checking\n"
  851. "/showawblist - Show AWB Search History\n"
  852. "/feedback - Provide Feedback\n"
  853. "/contactus - Contact Us\n"
  854. "/cancel - Stop the Bot")
  855.  
  856. return HELP_OPTION
  857.  
  858.  
  859. # End point of function
  860. def end(bot, update):
  861. # user = update.message.from_user
  862. update.effective_message.reply_text('Thank you for your support!\nI hope we can see you again in the coming future.',
  863. reply_markup=ReplyKeyboardRemove())
  864.  
  865. sleep(1)
  866.  
  867. update.effective_message.reply_text('Enter /start if you want to talk to me again! ', reply_markup=ReplyKeyboardRemove())
  868. logger_CC.info("<<<Section Ended>>>")
  869. logger_CS.info("<<<Section Ended>>>")
  870.  
  871. return ConversationHandler.END
  872.  
  873.  
  874. # Duplicate 'end'
  875. def end2(bot, update):
  876. # user = update.message.from_user
  877. update.effective_message.reply_text('Thank you for your support!\nI hope we can see you again in the coming future.',
  878. reply_markup=ReplyKeyboardRemove())
  879.  
  880. sleep(1)
  881.  
  882. update.effective_message.reply_text('Enter /start if you want to talk to me again! ', reply_markup=ReplyKeyboardRemove())
  883. logger_CC.info("<<<Section Ended>>>")
  884. logger_CS.info("<<<Section Ended>>>")
  885.  
  886. return ConversationHandler.END
  887.  
  888.  
  889. # Cancel function with log
  890. def cancel(bot, update):
  891. user = update.message.from_user
  892. logger_CC.info("User %s canceled the conversation.\n" % (user.id))
  893. logger_CS.info("User %s canceled the conversation.\n" % (user.id))
  894.  
  895. update.message.reply_text('Bye! Thank you for your support!',
  896. reply_markup=ReplyKeyboardRemove())
  897.  
  898. sleep(1)
  899.  
  900. update.message.reply_text('Enter /start if you want to talk to me again! ', reply_markup=ReplyKeyboardRemove())
  901. logger_CC.info("<<<Section Ended>>>")
  902. logger_CS.info("<<<Section Ended>>>")
  903.  
  904. return ConversationHandler.END
  905.  
  906.  
  907. # Duplicate 'cancel' function
  908. def cancel2(bot, update):
  909. user = update.message.from_user
  910. logger_CC.info("User %s canceled the conversation.\n" % (user.id))
  911. logger_CS.info("User %s canceled the conversation.\n" % (user.id))
  912.  
  913. update.message.reply_text('Bye! Thank you for your support!',
  914. reply_markup=ReplyKeyboardRemove())
  915.  
  916. sleep(1)
  917.  
  918. update.message.reply_text('Enter /start if you want to talk with me again! ', reply_markup=ReplyKeyboardRemove())
  919.  
  920. logger_CC.info("<<<Section Ended>>>")
  921. logger_CS.info("<<<Section Ended>>>")
  922.  
  923. return ConversationHandler.END
  924.  
  925.  
  926. # Error log
  927. def error(bot, update, error):
  928. logger_CC.warn('Update "%s" caused error "%s"\n' % (update, error))
  929. logger_CS.warn('Update "%s" caused error "%s"\n' % (update, error))
  930.  
  931. ###################################################################################################################################################################################################################
  932. def main():
  933. # Telegram Bot's token
  934. updater = Updater("447528427:AAFr4sntMj_6aQhOmYVYlnNy2JsVQbEMUzE")
  935.  
  936.  
  937. # Get the dispatcher to register handlers
  938. dp = updater.dispatcher
  939.  
  940. # Add conversation handler
  941. # #1 conversation handler, for handling program starts with /start command
  942. conv_handler = ConversationHandler(
  943.  
  944. entry_points = [CommandHandler('start', start)],
  945.  
  946. states = {
  947.  
  948. CARGOCHECKING: [RegexHandler('^(CargoChecking)$', cargochecking_after_option),
  949. RegexHandler('^(CustomerService)$', customerservice),
  950. CommandHandler('contactus', contactus), CommandHandler('feedback', feedback),
  951. CommandHandler('help', help_menu), CommandHandler('cancel', cancel),
  952. MessageHandler(Filters.all, start)],
  953.  
  954.  
  955. CCOPTION: [RegexHandler('^(Show AWB List)$', showAWBlist), RegexHandler('^(Home Page)$', start),
  956. MessageHandler(Filters.text, bio)],
  957.  
  958.  
  959. INLINE_STATE: [CallbackQueryHandler(button_callback), MessageHandler(Filters.all, showAWBlist)],
  960.  
  961.  
  962. CS_OPTION: [RegexHandler('^(Feedback)$', feedback), RegexHandler('^(Contact Us)$', contactus),
  963. CommandHandler('showawblist', showAWBlist), CommandHandler('help', help_menu),
  964. CommandHandler('start', start), CommandHandler('cargochecking', cargochecking_after_option),
  965. CommandHandler('cancel', cancel), MessageHandler(Filters.all, customerservice)],
  966.  
  967.  
  968. FEEDBACK: [RegexHandler('^(Facility|Staff|Service)$', feedback_input),
  969. CommandHandler('showawblist', showAWBlist), CommandHandler('help', help_menu),
  970. CommandHandler('start', start), CommandHandler('cargochecking', cargochecking_after_option),
  971. CommandHandler('cancel', cancel), CommandHandler('contactus', contactus),
  972. MessageHandler(Filters.all, feedback)],
  973.  
  974.  
  975. FEEDBACK_LOG: [MessageHandler(Filters.text, feedback_getLog)],
  976.  
  977.  
  978. FEEDBACK_LOG_CONTACT: [MessageHandler(Filters.text, feedback_getContact),
  979. CommandHandler('skip', skip_contact)],
  980.  
  981.  
  982. CU_OPTION: [RegexHandler('^(Email)$', email_detail), RegexHandler('^(Phone)$', phone_detail),
  983. RegexHandler('^(Address)$', address_detail), MessageHandler(Filters.all, contactus)],
  984.  
  985.  
  986. DELETE_AWB: [MessageHandler(Filters.text, delete_awb_op)]
  987.  
  988. },
  989.  
  990. fallbacks = [CommandHandler('cancel', cancel)],
  991. )
  992.  
  993.  
  994.  
  995.  
  996. # #2 conversation handler, for handling program starts with /cargocheing command
  997. cargo_handler = ConversationHandler(
  998.  
  999. entry_points = [CommandHandler('cargochecking', cargochecking2_after_option)],
  1000.  
  1001. states = {
  1002. CCOPTION2: [RegexHandler('^(Show AWB List)$', showAWBlist2), RegexHandler('^(Home Page)$', start),
  1003. MessageHandler(Filters.text, bio2)],
  1004.  
  1005. INLINE_STATE2: [CallbackQueryHandler(button_callback2), MessageHandler(Filters.all, showAWBlist2)],
  1006.  
  1007. DELETE2_AWB: [MessageHandler(Filters.text, delete2_awb_op)]
  1008. },
  1009.  
  1010. fallbacks=[CommandHandler('cancel', cancel)]
  1011. )
  1012.  
  1013.  
  1014.  
  1015. # #3 conversation handler, for handling program starts with /feedback command
  1016. feedback_handler = ConversationHandler(
  1017.  
  1018. entry_points = [CommandHandler('feedback', feedback2)],
  1019.  
  1020. states = {
  1021. FEEDBACK2: [RegexHandler('^(Facility|Staff|Service)$', feedback_input2),
  1022. MessageHandler(Filters.all, feedback2)],
  1023.  
  1024. FEEDBACK_LOG2: [MessageHandler(Filters.text, feedback_getLog2)],
  1025.  
  1026. FEEDBACK_LOG_CONTACT2: [MessageHandler(Filters.text, feedback_getContact2),
  1027. CommandHandler('skip', skip_contact2)]
  1028. },
  1029.  
  1030. fallbacks = [CommandHandler('cancel', cancel)]
  1031. )
  1032.  
  1033.  
  1034. # #4 conversation handler, for handling program starts with /help command
  1035. help_handler = ConversationHandler(
  1036.  
  1037. entry_points = [CommandHandler('help', help_menu)],
  1038.  
  1039. states = {
  1040. HELP_OPTION: [CommandHandler('start', start), CommandHandler('cargochecking', cargochecking2_after_option),
  1041. CommandHandler('showawblist', showAWBlist2), CommandHandler('feedback', feedback2),
  1042. CommandHandler('contactus', contactus)]
  1043. },
  1044.  
  1045. fallbacks = [CommandHandler('cancel', cancel)])
  1046.  
  1047.  
  1048. # #5 conversation handler, for handling program starts with /contactus command
  1049. contactus_handler = ConversationHandler(
  1050.  
  1051. entry_points = [CommandHandler('contactus', contactus2)],
  1052.  
  1053. states = {
  1054. CU_OPTION2: [RegexHandler('^(Email)$', email_detail2), RegexHandler('^(Address)$', address_detail2),
  1055. RegexHandler('^(Phone)$', phone_detail2), MessageHandler(Filters.all, contactus)]
  1056. },
  1057.  
  1058. fallbacks = [CommandHandler('cancel', cancel)])
  1059.  
  1060.  
  1061. # add handler
  1062. dp.add_handler(conv_handler)
  1063. dp.add_handler(cargo_handler)
  1064. dp.add_handler(feedback_handler)
  1065. dp.add_handler(help_handler)
  1066. dp.add_handler(contactus_handler)
  1067. dp.add_handler(CommandHandler('showawblist', showAWBlist))
  1068. dp.add_handler(CommandHandler('cancel', cancel))
  1069.  
  1070. # log all errors
  1071. dp.add_error_handler(error)
  1072.  
  1073. # Start the Bot
  1074. updater.start_polling()
  1075.  
  1076. # Run the bot until you press Ctrl-C or the system receives SIGHINT or SIGTSTP
  1077. updater.idle()
  1078. sys.exit()
  1079.  
  1080.  
  1081. if __name__ == '__main__':
  1082. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement