Guest User

Untitled

a guest
Dec 2nd, 2023
248
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.54 KB | None | 0 0
  1. import sqlite3
  2. import threading
  3. import time
  4. from telegram.ext import (Updater, ConversationHandler, CommandHandler, MessageHandler, Filters)
  5. import telebot
  6. from telebot import types
  7.  
  8. TOKEN = '5718472780:AAHjGgnTJJ7pZ3Mm-Y0jtNMitZbAwVbHHHY'
  9. bot = telebot.TeleBot(TOKEN)
  10. bd = sqlite3.connect('remindnotes.db', check_same_thread=False)
  11. cursor = bd.cursor()
  12.  
  13. with open('remind.sql', 'r') as f:
  14. sql = f.read()
  15. bd.commit()
  16.  
  17. updater = Updater(TOKEN, use_context=True)
  18. disp = updater.dispatcher
  19. current_name = None
  20. current_date = None
  21.  
  22. @bot.message_handler(commands=['start'])
  23. def send_keyboard(message, text='Привет, чем я могу тебе помочь?'):
  24. keyboard = types.ReplyKeyboardMarkup(row_width=2)
  25. itembtn1 = types.KeyboardButton('Добавить новую заметку')
  26. itembtn2 = types.KeyboardButton('Новое напоминание')
  27. itembtn3 = types.KeyboardButton('Все заметки')
  28. itembtn4 = types.KeyboardButton('Удалить заметку')
  29. itembtn5 = types.KeyboardButton('Удалить все заметки')
  30. itembtn6 = types.KeyboardButton('Другое')
  31. itembtn7 = types.KeyboardButton('Пока все!')
  32. keyboard.add(itembtn1, itembtn2, itembtn3)
  33. keyboard.add(itembtn4, itembtn5, itembtn6, itembtn7)
  34.  
  35. msg = bot.send_message(message.from_user.id, text=text, reply_markup=keyboard)
  36. bot.register_next_step_handler(msg, callback_worker)
  37. def callback_worker(call):
  38. if call.text == 'Добавить новую заметку':
  39. msg = bot.send_message(call.chat.id, 'Давайте добавим дело! Пришлите его в наш чат..')
  40. bot.register_next_step_handler(msg, add_plan)
  41. elif call.text == 'Все заметки':
  42. try:
  43. show_plans(call)
  44. except:
  45. bot.send_message(call.chat.id, 'Здесь пусто.. Можно отдыхать:))')
  46. send_keyboard(call, 'Чем еще могу помочь?')
  47. elif call.text == 'Новое напоминание':
  48. try:
  49. create_new(call)
  50. except:
  51. bot.send_message(call.chat.id, 'Может нужна помощь?')
  52. send_keyboard(call, 'Чем еще могу помочь?')
  53. elif call.text == 'Удалить заметку':
  54. try:
  55. delete_one_plan(call)
  56. except:
  57. bot.send_message(call.chat.id, 'Здесь пусто.. Можно отдыхать:))')
  58. send_keyboard(call, 'Чем еще могу помочь?')
  59. elif call.text == 'Удалить все заметки':
  60. try:
  61. delete_all_plans(call)
  62. except:
  63. bot.send_message(call.chat.id, 'Здесь пусто.. Можно отдыхать:))')
  64. send_keyboard(call, 'Когда захотите продолжить - нажмите /start')
  65.  
  66. elif call.text == 'Другое':
  67. bot.send_message(call.chat.id, 'Пока я больше ничего не умею(')
  68. send_keyboard(call, 'Чем еще могу помочь?')
  69. elif call.text == 'Пока все!':
  70. bot.send_message(call.chat.id, 'Хорошего дня! Когда захотите продолжить - нажмите /start ')
  71. def add_plan(msg):
  72. with sqlite3.connect('remindnotes.db') as con:
  73. cursor = con.cursor()
  74. cursor.execute('INSERT INTO planner (user_id, plan) VALUES (?, ?)', (msg.from_user.id, msg.text))
  75. con.commit()
  76. bot.send_message(msg.chat.id, 'Запомню!')
  77. send_keyboard(msg, 'Чем еще могу помочь?')
  78. def delete_one_plan(msg):
  79. markup = types.ReplyKeyboardMarkup(row_width=2)
  80. with sqlite3.connect('remindnotes.db') as con:
  81. cursor = con.cursor()
  82. cursor.execute('SELECT plan FROM planner WHERE user_id=={}'.format(msg.from_user.id))
  83. tasks = cursor.fetchall()
  84. for value in tasks:
  85. markup.add(types.KeyboardButton(value[0]))
  86. msg = bot.send_message(msg.from_user.id, text = 'Выберите одно дело из списка', reply_markup=markup)
  87. bot.register_next_step_handler(msg, delete_one_plan_1)
  88. def delete_one_plan_1(msg):
  89. with sqlite3.connect('remindnotes.db') as con:
  90. cursor = con.cursor()
  91. cursor.execute('DELETE FROM planner WHERE user_id==? AND plan==?', (msg.from_user.id, msg.text))
  92. bot.send_message(msg.chat.id, 'Ура, минус одна задача!')
  93. send_keyboard(msg, 'Чем еще могу помочь?')
  94. def delete_all_plans(msg):
  95. with sqlite3.connect('remindnotes.db') as con:
  96. cursor = con.cursor()
  97. cursor.execute('DELETE FROM planner WHERE user_id=={}'.format(msg.from_user.id))
  98. con.commit()
  99. bot.send_message(msg.chat.id, 'Все дела удалены, хорошего отдыха!')
  100. send_keyboard(msg, 'Могу ли я еще чем то помочь?')
  101. def get_plans_string(tasks):
  102. tasks_str = []
  103. for val in list(enumerate(tasks)):
  104. tasks_str.append(str(val[0] + 1) + ') ' +val[1][0] + '\n' )
  105. return ''.join(tasks_str)
  106. def show_plans(msg):
  107. with sqlite3.connect('remindnotes.db') as con:
  108. cursor = con.cursor()
  109. cursor.execute('SELECT plan FROM planner WHERE user_id=={}'.format(msg.from_user.id))
  110. tasks = get_plans_string(cursor.fetchall())
  111. bot.send_message(msg.chat.id, tasks)
  112. send_keyboard(msg, 'Чем еще могу помочь?')
  113.  
  114. @bot.message_handler(commands=['new'])
  115. def create_new(update):
  116. bot.send_message(update.chat.id, 'Нажми /remindme для добавления задачи')
  117.  
  118. def new_reminder(update):
  119. update.message.reply_text('Введите название напоминания')
  120. return 1
  121. def get_name(update):
  122. global current_name
  123. update.message.reply_text('Напиши дату в формате ГОД-МЕСЯЦ-ДЕНЬ')
  124. return 2
  125.  
  126. def get_date(update):
  127. global current_date
  128. global cursor
  129. current_date = update.message.text
  130. user_id = update.message.chat_id
  131. cursor.execute('SELECT * FROM user WHERE id=?', (user_id,))
  132. if not cursor.fetchone():
  133. cursor.execute('INSERT INTO user (id) VALUES (?)', (user_id,))
  134. cursor.execute('INSERT INTO remind_me (user_id, note, date, reminded) VALUES (?, ?, ?, ?)',
  135. (user_id, current_name, current_date, 0))
  136. bd.commit()
  137. msg.message.reply_text('Я напомню тебе!')
  138. return ConversationHandler.END
  139.  
  140. def cancel():
  141. pass
  142.  
  143. def do_reminders():
  144. while True:
  145. # today = dt.date.today().strftime('%Y-%m-%d')
  146. cursor.execute('SELECT * FROM remind_me WHERE strftime("%d", date) = strftime("%d", "now")'
  147. 'AND strftime("%m", "now") AND reminded = 0')
  148. rows = cursor.fetchall()
  149. for row in rows:
  150. row_id = row[0]
  151. note = row[2]
  152. user_id = row[4]
  153. updater.bot.send_message(chat_id=user_id, text =f'Время для выполнения задачи {note}!')
  154. cursor.execute('UPDATE remind_me SET reminded = 1 WHERE id = ?', (row_id,))
  155. bd.commit()
  156. time.sleep(10)
  157.  
  158. conv_handler = ConversationHandler(
  159. entry_points=[CommandHandler('remindme', new_reminder)],
  160. states = {
  161. 1: [MessageHandler(Filters.text, get_name)],
  162. 2: [MessageHandler(Filters.text, get_date)]
  163. },
  164. fallbacks=[CommandHandler('cancel', cancel)]
  165. )
  166.  
  167.  
  168. threading.Thread(target=do_reminders).start()
  169.  
  170. bot.polling(none_stop=True)
Advertisement
Add Comment
Please, Sign In to add comment