Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import sqlite3
- import threading
- import time
- from telegram.ext import (Updater, ConversationHandler, CommandHandler, MessageHandler, Filters)
- import telebot
- from telebot import types
- TOKEN = '5718472780:AAHjGgnTJJ7pZ3Mm-Y0jtNMitZbAwVbHHHY'
- bot = telebot.TeleBot(TOKEN)
- bd = sqlite3.connect('remindnotes.db', check_same_thread=False)
- cursor = bd.cursor()
- with open('remind.sql', 'r') as f:
- sql = f.read()
- bd.commit()
- updater = Updater(TOKEN, use_context=True)
- disp = updater.dispatcher
- current_name = None
- current_date = None
- @bot.message_handler(commands=['start'])
- def send_keyboard(message, text='Привет, чем я могу тебе помочь?'):
- keyboard = types.ReplyKeyboardMarkup(row_width=2)
- itembtn1 = types.KeyboardButton('Добавить новую заметку')
- itembtn2 = types.KeyboardButton('Новое напоминание')
- itembtn3 = types.KeyboardButton('Все заметки')
- itembtn4 = types.KeyboardButton('Удалить заметку')
- itembtn5 = types.KeyboardButton('Удалить все заметки')
- itembtn6 = types.KeyboardButton('Другое')
- itembtn7 = types.KeyboardButton('Пока все!')
- keyboard.add(itembtn1, itembtn2, itembtn3)
- keyboard.add(itembtn4, itembtn5, itembtn6, itembtn7)
- msg = bot.send_message(message.from_user.id, text=text, reply_markup=keyboard)
- bot.register_next_step_handler(msg, callback_worker)
- def callback_worker(call):
- if call.text == 'Добавить новую заметку':
- msg = bot.send_message(call.chat.id, 'Давайте добавим дело! Пришлите его в наш чат..')
- bot.register_next_step_handler(msg, add_plan)
- elif call.text == 'Все заметки':
- try:
- show_plans(call)
- except:
- bot.send_message(call.chat.id, 'Здесь пусто.. Можно отдыхать:))')
- send_keyboard(call, 'Чем еще могу помочь?')
- elif call.text == 'Новое напоминание':
- try:
- create_new(call)
- except:
- bot.send_message(call.chat.id, 'Может нужна помощь?')
- send_keyboard(call, 'Чем еще могу помочь?')
- elif call.text == 'Удалить заметку':
- try:
- delete_one_plan(call)
- except:
- bot.send_message(call.chat.id, 'Здесь пусто.. Можно отдыхать:))')
- send_keyboard(call, 'Чем еще могу помочь?')
- elif call.text == 'Удалить все заметки':
- try:
- delete_all_plans(call)
- except:
- bot.send_message(call.chat.id, 'Здесь пусто.. Можно отдыхать:))')
- send_keyboard(call, 'Когда захотите продолжить - нажмите /start')
- elif call.text == 'Другое':
- bot.send_message(call.chat.id, 'Пока я больше ничего не умею(')
- send_keyboard(call, 'Чем еще могу помочь?')
- elif call.text == 'Пока все!':
- bot.send_message(call.chat.id, 'Хорошего дня! Когда захотите продолжить - нажмите /start ')
- def add_plan(msg):
- with sqlite3.connect('remindnotes.db') as con:
- cursor = con.cursor()
- cursor.execute('INSERT INTO planner (user_id, plan) VALUES (?, ?)', (msg.from_user.id, msg.text))
- con.commit()
- bot.send_message(msg.chat.id, 'Запомню!')
- send_keyboard(msg, 'Чем еще могу помочь?')
- def delete_one_plan(msg):
- markup = types.ReplyKeyboardMarkup(row_width=2)
- with sqlite3.connect('remindnotes.db') as con:
- cursor = con.cursor()
- cursor.execute('SELECT plan FROM planner WHERE user_id=={}'.format(msg.from_user.id))
- tasks = cursor.fetchall()
- for value in tasks:
- markup.add(types.KeyboardButton(value[0]))
- msg = bot.send_message(msg.from_user.id, text = 'Выберите одно дело из списка', reply_markup=markup)
- bot.register_next_step_handler(msg, delete_one_plan_1)
- def delete_one_plan_1(msg):
- with sqlite3.connect('remindnotes.db') as con:
- cursor = con.cursor()
- cursor.execute('DELETE FROM planner WHERE user_id==? AND plan==?', (msg.from_user.id, msg.text))
- bot.send_message(msg.chat.id, 'Ура, минус одна задача!')
- send_keyboard(msg, 'Чем еще могу помочь?')
- def delete_all_plans(msg):
- with sqlite3.connect('remindnotes.db') as con:
- cursor = con.cursor()
- cursor.execute('DELETE FROM planner WHERE user_id=={}'.format(msg.from_user.id))
- con.commit()
- bot.send_message(msg.chat.id, 'Все дела удалены, хорошего отдыха!')
- send_keyboard(msg, 'Могу ли я еще чем то помочь?')
- def get_plans_string(tasks):
- tasks_str = []
- for val in list(enumerate(tasks)):
- tasks_str.append(str(val[0] + 1) + ') ' +val[1][0] + '\n' )
- return ''.join(tasks_str)
- def show_plans(msg):
- with sqlite3.connect('remindnotes.db') as con:
- cursor = con.cursor()
- cursor.execute('SELECT plan FROM planner WHERE user_id=={}'.format(msg.from_user.id))
- tasks = get_plans_string(cursor.fetchall())
- bot.send_message(msg.chat.id, tasks)
- send_keyboard(msg, 'Чем еще могу помочь?')
- @bot.message_handler(commands=['new'])
- def create_new(update):
- bot.send_message(update.chat.id, 'Нажми /remindme для добавления задачи')
- def new_reminder(update):
- update.message.reply_text('Введите название напоминания')
- return 1
- def get_name(update):
- global current_name
- update.message.reply_text('Напиши дату в формате ГОД-МЕСЯЦ-ДЕНЬ')
- return 2
- def get_date(update):
- global current_date
- global cursor
- current_date = update.message.text
- user_id = update.message.chat_id
- cursor.execute('SELECT * FROM user WHERE id=?', (user_id,))
- if not cursor.fetchone():
- cursor.execute('INSERT INTO user (id) VALUES (?)', (user_id,))
- cursor.execute('INSERT INTO remind_me (user_id, note, date, reminded) VALUES (?, ?, ?, ?)',
- (user_id, current_name, current_date, 0))
- bd.commit()
- msg.message.reply_text('Я напомню тебе!')
- return ConversationHandler.END
- def cancel():
- pass
- def do_reminders():
- while True:
- # today = dt.date.today().strftime('%Y-%m-%d')
- cursor.execute('SELECT * FROM remind_me WHERE strftime("%d", date) = strftime("%d", "now")'
- 'AND strftime("%m", "now") AND reminded = 0')
- rows = cursor.fetchall()
- for row in rows:
- row_id = row[0]
- note = row[2]
- user_id = row[4]
- updater.bot.send_message(chat_id=user_id, text =f'Время для выполнения задачи {note}!')
- cursor.execute('UPDATE remind_me SET reminded = 1 WHERE id = ?', (row_id,))
- bd.commit()
- time.sleep(10)
- conv_handler = ConversationHandler(
- entry_points=[CommandHandler('remindme', new_reminder)],
- states = {
- 1: [MessageHandler(Filters.text, get_name)],
- 2: [MessageHandler(Filters.text, get_date)]
- },
- fallbacks=[CommandHandler('cancel', cancel)]
- )
- threading.Thread(target=do_reminders).start()
- bot.polling(none_stop=True)
Advertisement
Add Comment
Please, Sign In to add comment