From 2169a3e3c20acb8012e0c565041514ec6a0fb77e Mon Sep 17 00:00:00 2001 From: ashat1701 Date: Sun, 21 Apr 2019 15:36:33 +0300 Subject: [PATCH 01/49] fix bot syntax and token) --- setup.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/setup.py b/setup.py index 1984203..83c1656 100644 --- a/setup.py +++ b/setup.py @@ -5,11 +5,11 @@ level=logging.INFO) -def echo(update, context): - context.bot.send_message(chat_id=update.message.chat_id, text=update.message.text) +def echo(bot, update): + bot.send_message(chat_id=update.message.chat_id, text=update.message.text) -TOKEN = "820703303:AAHZXbuIVVA4oQm4s6SrxNtV7WX9m1xNGw8" +TOKEN = os.environ["TOKEN"] PORT = int(os.environ.get('PORT', '8443')) updater = telegram.ext.Updater(token=TOKEN) dispatcher = updater.dispatcher From 7f6a4d10ab29796ed43cde405f5dc4400b652dba Mon Sep 17 00:00:00 2001 From: ashat1701 Date: Tue, 23 Apr 2019 16:25:34 +0300 Subject: [PATCH 02/49] Try to up flask server.. --- auth.py | 8 ++++++++ requirements.txt | 6 ++++++ setup.py | 2 ++ templates/googleb6f1161798ffa448.html | 1 + templates/index.html | 9 +++++++++ webserver.py | 20 ++++++++++++++++++++ 6 files changed, 46 insertions(+) create mode 100644 auth.py create mode 100644 templates/googleb6f1161798ffa448.html create mode 100644 templates/index.html create mode 100644 webserver.py diff --git a/auth.py b/auth.py new file mode 100644 index 0000000..55f2660 --- /dev/null +++ b/auth.py @@ -0,0 +1,8 @@ +from flask import Flask, request + + +class GoogleAuth: + pass + + + diff --git a/requirements.txt b/requirements.txt index cd15d2f..4d4578f 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1 +1,7 @@ python-telegram-bot==12.0.0b1 +google-api-python-client +google-auth +google-auth-oauthlib +google-auth-httplib2 +flask +requests \ No newline at end of file diff --git a/setup.py b/setup.py index 83c1656..03e299a 100644 --- a/setup.py +++ b/setup.py @@ -1,8 +1,10 @@ import telegram.ext import os +import webserver import logging logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) +webserver.init() def echo(bot, update): diff --git a/templates/googleb6f1161798ffa448.html b/templates/googleb6f1161798ffa448.html new file mode 100644 index 0000000..283c2c4 --- /dev/null +++ b/templates/googleb6f1161798ffa448.html @@ -0,0 +1 @@ +google-site-verification: googleb6f1161798ffa448.html \ No newline at end of file diff --git a/templates/index.html b/templates/index.html new file mode 100644 index 0000000..7af18aa --- /dev/null +++ b/templates/index.html @@ -0,0 +1,9 @@ + + + + Oops... + + +

This is simple web server to provide google auth))

+ + \ No newline at end of file diff --git a/webserver.py b/webserver.py new file mode 100644 index 0000000..e958a7e --- /dev/null +++ b/webserver.py @@ -0,0 +1,20 @@ +from flask import Flask, render_template + + +def init(): + global app + app = Flask(__name__) + + +@app.route('/login', methods=['GET, POST']) +def get_login_hook(): + pass + + +@app.route('/') +def index(): + return render_template('index.html') + +@app.route('/') +def obr(name): + return render_template(name) From a3e52c8ab0d0347a5b570a01f6ca88f2623af6c5 Mon Sep 17 00:00:00 2001 From: ashat1701 Date: Tue, 23 Apr 2019 16:27:41 +0300 Subject: [PATCH 03/49] fix server --- webserver.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/webserver.py b/webserver.py index e958a7e..ef429be 100644 --- a/webserver.py +++ b/webserver.py @@ -1,9 +1,8 @@ from flask import Flask, render_template - +app = Flask(__name__) def init(): - global app - app = Flask(__name__) + pass @app.route('/login', methods=['GET, POST']) From df9fba6f005cc3625ad6ac45be25a60f7e33e5a3 Mon Sep 17 00:00:00 2001 From: ashat1701 Date: Tue, 23 Apr 2019 16:35:29 +0300 Subject: [PATCH 04/49] fix server --- setup.py | 1 + 1 file changed, 1 insertion(+) diff --git a/setup.py b/setup.py index 03e299a..484dd4f 100644 --- a/setup.py +++ b/setup.py @@ -5,6 +5,7 @@ logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) webserver.init() +webserver.app.run() def echo(bot, update): From c1539729a2dc09102fd5d78dcee123ee369f42ca Mon Sep 17 00:00:00 2001 From: ashat1701 Date: Tue, 23 Apr 2019 21:20:40 +0300 Subject: [PATCH 05/49] fix http server and add command to start --- Procfile | 2 +- requirements.txt | 3 ++- setup.py | 6 ++---- webserver.py | 10 ++++++++-- 4 files changed, 13 insertions(+), 8 deletions(-) diff --git a/Procfile b/Procfile index 7a4f760..ad712a2 100644 --- a/Procfile +++ b/Procfile @@ -1 +1 @@ -web: python setup.py \ No newline at end of file +web: python setup.py & gunicorn webserver:app & wait -n \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index 4d4578f..4e637ea 100644 --- a/requirements.txt +++ b/requirements.txt @@ -4,4 +4,5 @@ google-auth google-auth-oauthlib google-auth-httplib2 flask -requests \ No newline at end of file +requests +gunicorn \ No newline at end of file diff --git a/setup.py b/setup.py index 484dd4f..ef1043d 100644 --- a/setup.py +++ b/setup.py @@ -1,12 +1,10 @@ import telegram.ext import os -import webserver import logging + + logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) -webserver.init() -webserver.app.run() - def echo(bot, update): bot.send_message(chat_id=update.message.chat_id, text=update.message.text) diff --git a/webserver.py b/webserver.py index ef429be..a396b0c 100644 --- a/webserver.py +++ b/webserver.py @@ -1,15 +1,17 @@ from flask import Flask, render_template +from werkzeug.contrib.fixers import ProxyFix app = Flask(__name__) + + def init(): - pass + app.wsgi_app = ProxyFix(app.wsgi_app) @app.route('/login', methods=['GET, POST']) def get_login_hook(): pass - @app.route('/') def index(): return render_template('index.html') @@ -17,3 +19,7 @@ def index(): @app.route('/') def obr(name): return render_template(name) + +if __name__ == "__main__": + init() + app.run() \ No newline at end of file From 4814ec322c453fc89ddb6dd793f7fc9274ef34ed Mon Sep 17 00:00:00 2001 From: ashat1701 Date: Tue, 23 Apr 2019 21:43:16 +0300 Subject: [PATCH 06/49] move http server to another project --- Procfile | 2 +- requirements.txt | 5 +---- templates/googleb6f1161798ffa448.html | 1 - templates/index.html | 9 --------- webserver.py | 25 ------------------------- 5 files changed, 2 insertions(+), 40 deletions(-) delete mode 100644 templates/googleb6f1161798ffa448.html delete mode 100644 templates/index.html delete mode 100644 webserver.py diff --git a/Procfile b/Procfile index ad712a2..7a4f760 100644 --- a/Procfile +++ b/Procfile @@ -1 +1 @@ -web: python setup.py & gunicorn webserver:app & wait -n \ No newline at end of file +web: python setup.py \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index 4e637ea..f1bad12 100644 --- a/requirements.txt +++ b/requirements.txt @@ -2,7 +2,4 @@ python-telegram-bot==12.0.0b1 google-api-python-client google-auth google-auth-oauthlib -google-auth-httplib2 -flask -requests -gunicorn \ No newline at end of file +google-auth-httplib2 \ No newline at end of file diff --git a/templates/googleb6f1161798ffa448.html b/templates/googleb6f1161798ffa448.html deleted file mode 100644 index 283c2c4..0000000 --- a/templates/googleb6f1161798ffa448.html +++ /dev/null @@ -1 +0,0 @@ -google-site-verification: googleb6f1161798ffa448.html \ No newline at end of file diff --git a/templates/index.html b/templates/index.html deleted file mode 100644 index 7af18aa..0000000 --- a/templates/index.html +++ /dev/null @@ -1,9 +0,0 @@ - - - - Oops... - - -

This is simple web server to provide google auth))

- - \ No newline at end of file diff --git a/webserver.py b/webserver.py deleted file mode 100644 index a396b0c..0000000 --- a/webserver.py +++ /dev/null @@ -1,25 +0,0 @@ -from flask import Flask, render_template -from werkzeug.contrib.fixers import ProxyFix - -app = Flask(__name__) - - -def init(): - app.wsgi_app = ProxyFix(app.wsgi_app) - - -@app.route('/login', methods=['GET, POST']) -def get_login_hook(): - pass - -@app.route('/') -def index(): - return render_template('index.html') - -@app.route('/') -def obr(name): - return render_template(name) - -if __name__ == "__main__": - init() - app.run() \ No newline at end of file From 4ca78e0f6f1d661ce68b705c795ee72d6d4ee3a0 Mon Sep 17 00:00:00 2001 From: ashat1701 Date: Wed, 24 Apr 2019 01:27:02 +0300 Subject: [PATCH 07/49] add login handler --- auth.py | 20 ++++++++++++++++---- client_secret.json | 1 + database.py | 17 +++++++++++++++++ setup.py | 21 +++++++++++++++++---- 4 files changed, 51 insertions(+), 8 deletions(-) create mode 100644 client_secret.json create mode 100644 database.py diff --git a/auth.py b/auth.py index 55f2660..36cf655 100644 --- a/auth.py +++ b/auth.py @@ -1,8 +1,20 @@ -from flask import Flask, request +import google.oauth2.credentials +import google_auth_oauthlib.flow +import base64 class GoogleAuth: - pass - - + def __init__(self, chat_id): + self.chat_id = chat_id + def generate_url(self): + flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( + 'client_secret.json', + scope=['https://www.googleapis.com/auth/calendar.events']) + flow.redirect_uri = "https://server-for-task-bot.herokuapp.com/login" + state = base64.urlsafe_b64decode(self.chat_id) + authorization_url, st = flow.authorization_url( + access_type='offline', + state=state, + include_granted_scopes='true') + return authorization_url diff --git a/client_secret.json b/client_secret.json new file mode 100644 index 0000000..e926ae4 --- /dev/null +++ b/client_secret.json @@ -0,0 +1 @@ +{"web":{"client_id":"160369947774-dfnki1coiacp9qnu8mn7i4c51kfd0uft.apps.googleusercontent.com","project_id":"yet-another-task-bot","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://oauth2.googleapis.com/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","redirect_uris": ["https://server-for-task-bot.herokuapp.com/login"],"javascript_origins":["https://server-for-task-bot.herokuapp.com"]}} \ No newline at end of file diff --git a/database.py b/database.py new file mode 100644 index 0000000..31bb22d --- /dev/null +++ b/database.py @@ -0,0 +1,17 @@ + +class Database: + __instance = None + + def __new__(cls, *args, **kwargs): + if cls.__instance is None: + cls.__instance = super(cls).__new__(cls, *args, **kwargs) + cls.__instance.ids = [] + cls.__instance.auth_tokens = {} + return cls.__instance + + def get_token(self, chat_id): + return self.auth_tokens[chat_id] + + def is_auth(self, chat_id): + return chat_id in self.auth_tokens.keys() + diff --git a/setup.py b/setup.py index ef1043d..c99def2 100644 --- a/setup.py +++ b/setup.py @@ -1,20 +1,33 @@ import telegram.ext import os import logging - +import database +import auth logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) -def echo(bot, update): - bot.send_message(chat_id=update.message.chat_id, text=update.message.text) +# TODO: delete this after debug +def echo(update, context): + update.bot.send_message(chat_id=update.message.chat_id, text=update.message.text) + + +def login(update, context): + db = database.Database() + chat_id = update.message.chat_id + if db.is_token(chat_id): + update.bot.send_message(chat_id=chat_id, text="Вы уже вошли в свой аккаунт.") + else: + googleAuth = auth.GoogleAuth(chat_id) + update.bot.send_message(chat_id=chat_id, text=googleAuth.generate_url()) TOKEN = os.environ["TOKEN"] PORT = int(os.environ.get('PORT', '8443')) -updater = telegram.ext.Updater(token=TOKEN) +updater = telegram.ext.Updater(token=TOKEN, use_context=True) dispatcher = updater.dispatcher dispatcher.add_handler(telegram.ext.MessageHandler(telegram.ext.Filters.text, echo)) +dispatcher.add_handler(telegram.ext.CommandHandler('login', login)) updater.start_webhook(listen="0.0.0.0", port=PORT, url_path=TOKEN) From 6acb685b267a5c6b07fd103eef63667b221301a6 Mon Sep 17 00:00:00 2001 From: ashat1701 Date: Wed, 24 Apr 2019 01:39:18 +0300 Subject: [PATCH 08/49] fix handlers with beta version of API --- setup.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/setup.py b/setup.py index c99def2..bcbacbb 100644 --- a/setup.py +++ b/setup.py @@ -9,17 +9,17 @@ # TODO: delete this after debug def echo(update, context): - update.bot.send_message(chat_id=update.message.chat_id, text=update.message.text) + context.bot.send_message(chat_id=update.message.chat_id, text=update.message.text) def login(update, context): db = database.Database() chat_id = update.message.chat_id if db.is_token(chat_id): - update.bot.send_message(chat_id=chat_id, text="Вы уже вошли в свой аккаунт.") + context.bot.send_message(chat_id=chat_id, text="Вы уже вошли в свой аккаунт.") else: googleAuth = auth.GoogleAuth(chat_id) - update.bot.send_message(chat_id=chat_id, text=googleAuth.generate_url()) + context.bot.send_message(chat_id=chat_id, text=googleAuth.generate_url()) TOKEN = os.environ["TOKEN"] From 9077ab42730faac676aab8873ddc9e2d8055f2d2 Mon Sep 17 00:00:00 2001 From: ashat1701 Date: Wed, 24 Apr 2019 01:42:38 +0300 Subject: [PATCH 09/49] fix singleton --- database.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/database.py b/database.py index 31bb22d..b8318e1 100644 --- a/database.py +++ b/database.py @@ -4,7 +4,7 @@ class Database: def __new__(cls, *args, **kwargs): if cls.__instance is None: - cls.__instance = super(cls).__new__(cls, *args, **kwargs) + cls.__instance = super().__new__(cls, *args, **kwargs) cls.__instance.ids = [] cls.__instance.auth_tokens = {} return cls.__instance From c40f3c0f1fcf91e7f52b062886ebd312c3a96f6a Mon Sep 17 00:00:00 2001 From: ashat1701 Date: Wed, 24 Apr 2019 01:45:18 +0300 Subject: [PATCH 10/49] fix login handler --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index bcbacbb..b5091c5 100644 --- a/setup.py +++ b/setup.py @@ -15,7 +15,7 @@ def echo(update, context): def login(update, context): db = database.Database() chat_id = update.message.chat_id - if db.is_token(chat_id): + if db.is_auth(chat_id): context.bot.send_message(chat_id=chat_id, text="Вы уже вошли в свой аккаунт.") else: googleAuth = auth.GoogleAuth(chat_id) From ecd6e83a9e88e6506cc3c8dd20037927883f6854 Mon Sep 17 00:00:00 2001 From: ashat1701 Date: Wed, 24 Apr 2019 01:54:38 +0300 Subject: [PATCH 11/49] Google API docs lied) --- auth.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/auth.py b/auth.py index 36cf655..384cd95 100644 --- a/auth.py +++ b/auth.py @@ -10,7 +10,7 @@ def __init__(self, chat_id): def generate_url(self): flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( 'client_secret.json', - scope=['https://www.googleapis.com/auth/calendar.events']) + scopes=['https://www.googleapis.com/auth/calendar.events']) flow.redirect_uri = "https://server-for-task-bot.herokuapp.com/login" state = base64.urlsafe_b64decode(self.chat_id) authorization_url, st = flow.authorization_url( From e040b6527c9b43d3e690bc46ecbbbb1c6975ff3d Mon Sep 17 00:00:00 2001 From: ashat1701 Date: Wed, 24 Apr 2019 01:57:15 +0300 Subject: [PATCH 12/49] fix chat_id to str --- auth.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/auth.py b/auth.py index 384cd95..4d017d5 100644 --- a/auth.py +++ b/auth.py @@ -12,7 +12,7 @@ def generate_url(self): 'client_secret.json', scopes=['https://www.googleapis.com/auth/calendar.events']) flow.redirect_uri = "https://server-for-task-bot.herokuapp.com/login" - state = base64.urlsafe_b64decode(self.chat_id) + state = base64.urlsafe_b64decode(str(self.chat_id)) authorization_url, st = flow.authorization_url( access_type='offline', state=state, From e2ff912cf3d1185ea1b38ed0d8020108716d028a Mon Sep 17 00:00:00 2001 From: ashat1701 Date: Wed, 24 Apr 2019 02:02:18 +0300 Subject: [PATCH 13/49] fix base64 --- auth.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/auth.py b/auth.py index 4d017d5..efb19c2 100644 --- a/auth.py +++ b/auth.py @@ -12,7 +12,7 @@ def generate_url(self): 'client_secret.json', scopes=['https://www.googleapis.com/auth/calendar.events']) flow.redirect_uri = "https://server-for-task-bot.herokuapp.com/login" - state = base64.urlsafe_b64decode(str(self.chat_id)) + state = str(self.chat_id) authorization_url, st = flow.authorization_url( access_type='offline', state=state, From 006e1d4ef7c9fddfbfe92426f7c11b5f4b16dca3 Mon Sep 17 00:00:00 2001 From: ashat1701 Date: Wed, 24 Apr 2019 17:42:29 +0300 Subject: [PATCH 14/49] fix json and db --- auth.py | 2 ++ client_secret.json | 2 +- requirements.txt | 3 ++- 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/auth.py b/auth.py index efb19c2..fa4f06b 100644 --- a/auth.py +++ b/auth.py @@ -11,6 +11,8 @@ def generate_url(self): flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( 'client_secret.json', scopes=['https://www.googleapis.com/auth/calendar.events']) + flow.credentials + flow.redirect_uri = "https://server-for-task-bot.herokuapp.com/login" state = str(self.chat_id) authorization_url, st = flow.authorization_url( diff --git a/client_secret.json b/client_secret.json index e926ae4..eeb6d3f 100644 --- a/client_secret.json +++ b/client_secret.json @@ -1 +1 @@ -{"web":{"client_id":"160369947774-dfnki1coiacp9qnu8mn7i4c51kfd0uft.apps.googleusercontent.com","project_id":"yet-another-task-bot","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://oauth2.googleapis.com/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","redirect_uris": ["https://server-for-task-bot.herokuapp.com/login"],"javascript_origins":["https://server-for-task-bot.herokuapp.com"]}} \ No newline at end of file +{"web":{"client_id":"160369947774-dfnki1coiacp9qnu8mn7i4c51kfd0uft.apps.googleusercontent.com","project_id":"yet-another-task-bot","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://oauth2.googleapis.com/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_secret":"8Sh0_Qzc_HiM2vgKJ2sUJomc","redirect_uris":["https://server-for-task-bot.herokuapp.com/login"],"javascript_origins":["https://server-for-task-bot.herokuapp.com"]}} \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index f1bad12..244605d 100644 --- a/requirements.txt +++ b/requirements.txt @@ -2,4 +2,5 @@ python-telegram-bot==12.0.0b1 google-api-python-client google-auth google-auth-oauthlib -google-auth-httplib2 \ No newline at end of file +google-auth-httplib2 +psycopg2-binary \ No newline at end of file From 1d013c6c1fc560656c5a6f2221a0c58f59971bef Mon Sep 17 00:00:00 2001 From: ashat1701 Date: Wed, 24 Apr 2019 17:44:23 +0300 Subject: [PATCH 15/49] fix auth --- auth.py | 1 - 1 file changed, 1 deletion(-) diff --git a/auth.py b/auth.py index fa4f06b..f5ea060 100644 --- a/auth.py +++ b/auth.py @@ -11,7 +11,6 @@ def generate_url(self): flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( 'client_secret.json', scopes=['https://www.googleapis.com/auth/calendar.events']) - flow.credentials flow.redirect_uri = "https://server-for-task-bot.herokuapp.com/login" state = str(self.chat_id) From bb2223180a9a46940cd196ac155eda86a1adcce1 Mon Sep 17 00:00:00 2001 From: ashat1701 Date: Wed, 24 Apr 2019 21:52:23 +0300 Subject: [PATCH 16/49] add handlers for db --- database.py | 26 ++++++++++++++++++++------ setup.py | 12 ++++++++++++ 2 files changed, 32 insertions(+), 6 deletions(-) diff --git a/database.py b/database.py index b8318e1..b0c89b1 100644 --- a/database.py +++ b/database.py @@ -1,3 +1,7 @@ +import psycopg2 +import os +from psycopg2.extras import DictCursor + class Database: __instance = None @@ -5,13 +9,23 @@ class Database: def __new__(cls, *args, **kwargs): if cls.__instance is None: cls.__instance = super().__new__(cls, *args, **kwargs) - cls.__instance.ids = [] - cls.__instance.auth_tokens = {} + DATABASE_URL = os.environ['DATABASE_URL'] + cls.__instance.conn = psycopg2.connect(DATABASE_URL, sslmode='require') + return cls.__instance - def get_token(self, chat_id): - return self.auth_tokens[chat_id] + def get_cred(self, chat_id): + cursor = self.conn.cursor(cursor_factory=DictCursor) + cursor.execute("SELECT * FROM auth WHERE chat_id = %s", (str(chat_id))) + return cursor.fetchone() - def is_auth(self, chat_id): - return chat_id in self.auth_tokens.keys() + def is_auth(self, chat_id): + cursor = self.conn.cursor(cursor_factory=DictCursor) + cursor.execute("SELECT chat_id FROM auth WHERE chat_id = %s", (str(chat_id))) + if len(cursor.fetchone()): + cursor.close() + return True + else: + cursor.close() + return False diff --git a/setup.py b/setup.py index b5091c5..8270e0d 100644 --- a/setup.py +++ b/setup.py @@ -7,6 +7,7 @@ logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) + # TODO: delete this after debug def echo(update, context): context.bot.send_message(chat_id=update.message.chat_id, text=update.message.text) @@ -22,12 +23,23 @@ def login(update, context): context.bot.send_message(chat_id=chat_id, text=googleAuth.generate_url()) +def start_callback(update, context, args): + if args == "": + context.bot.send_message(chat_id=int(update.message.chat_id), text="Здравствуйте! Вам нужно войти в свой аккаунт Google для использования этого бота") + else: + db = database.Database() + chat_id = args + if db.is_auth(chat_id): + context.bot.send_message(chat_id=int(chat_id), text="Вы успешно вошли в аккаунт") + + TOKEN = os.environ["TOKEN"] PORT = int(os.environ.get('PORT', '8443')) updater = telegram.ext.Updater(token=TOKEN, use_context=True) dispatcher = updater.dispatcher dispatcher.add_handler(telegram.ext.MessageHandler(telegram.ext.Filters.text, echo)) dispatcher.add_handler(telegram.ext.CommandHandler('login', login)) +dispatcher.add_handler(telegram.ext.CommandHandler("start", start_callback)) updater.start_webhook(listen="0.0.0.0", port=PORT, url_path=TOKEN) From c9b248f563e9560320224fae83431917a47e22ea Mon Sep 17 00:00:00 2001 From: ashat1701 Date: Wed, 24 Apr 2019 22:03:11 +0300 Subject: [PATCH 17/49] fix tuple --- database.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/database.py b/database.py index b0c89b1..fd9e387 100644 --- a/database.py +++ b/database.py @@ -16,13 +16,13 @@ def __new__(cls, *args, **kwargs): def get_cred(self, chat_id): cursor = self.conn.cursor(cursor_factory=DictCursor) - cursor.execute("SELECT * FROM auth WHERE chat_id = %s", (str(chat_id))) + cursor.execute("SELECT * FROM auth WHERE chat_id = %s", (str(chat_id),)) return cursor.fetchone() def is_auth(self, chat_id): cursor = self.conn.cursor(cursor_factory=DictCursor) - cursor.execute("SELECT chat_id FROM auth WHERE chat_id = %s", (str(chat_id))) + cursor.execute("SELECT chat_id FROM auth WHERE chat_id = %s", (str(chat_id),)) if len(cursor.fetchone()): cursor.close() return True From f9b0f5910b333ca46790c7530a63554fc0fdb564 Mon Sep 17 00:00:00 2001 From: ashat1701 Date: Wed, 24 Apr 2019 22:53:38 +0300 Subject: [PATCH 18/49] fix db --- database.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/database.py b/database.py index fd9e387..78dd96a 100644 --- a/database.py +++ b/database.py @@ -23,7 +23,7 @@ def get_cred(self, chat_id): def is_auth(self, chat_id): cursor = self.conn.cursor(cursor_factory=DictCursor) cursor.execute("SELECT chat_id FROM auth WHERE chat_id = %s", (str(chat_id),)) - if len(cursor.fetchone()): + if cursor.fetchone() is not None: cursor.close() return True else: From dfeb649c908ca5f5ce63f340aaabb796ad5e89a4 Mon Sep 17 00:00:00 2001 From: ashat1701 Date: Wed, 24 Apr 2019 23:04:39 +0300 Subject: [PATCH 19/49] fix start_callback --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 8270e0d..95d7371 100644 --- a/setup.py +++ b/setup.py @@ -39,7 +39,7 @@ def start_callback(update, context, args): dispatcher = updater.dispatcher dispatcher.add_handler(telegram.ext.MessageHandler(telegram.ext.Filters.text, echo)) dispatcher.add_handler(telegram.ext.CommandHandler('login', login)) -dispatcher.add_handler(telegram.ext.CommandHandler("start", start_callback)) +dispatcher.add_handler(telegram.ext.CommandHandler("start", start_callback, pass_args=True)) updater.start_webhook(listen="0.0.0.0", port=PORT, url_path=TOKEN) From 7373216c12eb8d0ea2702ca6896635e5f70897df Mon Sep 17 00:00:00 2001 From: ashat1701 Date: Wed, 24 Apr 2019 23:10:37 +0300 Subject: [PATCH 20/49] fix start_callback --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 95d7371..d5204df 100644 --- a/setup.py +++ b/setup.py @@ -23,7 +23,7 @@ def login(update, context): context.bot.send_message(chat_id=chat_id, text=googleAuth.generate_url()) -def start_callback(update, context, args): +def start_callback(update, context, args=""): if args == "": context.bot.send_message(chat_id=int(update.message.chat_id), text="Здравствуйте! Вам нужно войти в свой аккаунт Google для использования этого бота") else: From 826cb7b119de52f1c864b3ffb47551ddb2495cb6 Mon Sep 17 00:00:00 2001 From: ashat1701 Date: Wed, 24 Apr 2019 23:40:09 +0300 Subject: [PATCH 21/49] fix start_callback --- setup.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/setup.py b/setup.py index d5204df..7e50a22 100644 --- a/setup.py +++ b/setup.py @@ -23,7 +23,8 @@ def login(update, context): context.bot.send_message(chat_id=chat_id, text=googleAuth.generate_url()) -def start_callback(update, context, args=""): +def start_callback(update, context): + args = "".join(context.args) if args == "": context.bot.send_message(chat_id=int(update.message.chat_id), text="Здравствуйте! Вам нужно войти в свой аккаунт Google для использования этого бота") else: From 436d205468f06dfe76869ee12735b28bfe32f9c1 Mon Sep 17 00:00:00 2001 From: ashat1701 Date: Wed, 24 Apr 2019 23:46:41 +0300 Subject: [PATCH 22/49] fix start_callback --- setup.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/setup.py b/setup.py index 7e50a22..99f34c0 100644 --- a/setup.py +++ b/setup.py @@ -32,6 +32,8 @@ def start_callback(update, context): chat_id = args if db.is_auth(chat_id): context.bot.send_message(chat_id=int(chat_id), text="Вы успешно вошли в аккаунт") + else: + context.bot.send_message(chat_id=int(chat_id), text="Вам необходимо войти в аккаунт. Используйте /login") TOKEN = os.environ["TOKEN"] From b1cf811e1077563900cf49cedba2730dcc76edec Mon Sep 17 00:00:00 2001 From: ashat1701 Date: Thu, 25 Apr 2019 02:02:45 +0300 Subject: [PATCH 23/49] add menu --- setup.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 99f34c0..ccabdae 100644 --- a/setup.py +++ b/setup.py @@ -26,7 +26,8 @@ def login(update, context): def start_callback(update, context): args = "".join(context.args) if args == "": - context.bot.send_message(chat_id=int(update.message.chat_id), text="Здравствуйте! Вам нужно войти в свой аккаунт Google для использования этого бота") + reply_markup = telegram.ReplyKeyboardMarkup(["Login"]) + context.bot.send_message(chat_id=int(update.message.chat_id), text="Здравствуйте! Вам нужно войти в свой аккаунт Google для использования этого бота", reply_markup=reply_markup) else: db = database.Database() chat_id = args @@ -36,6 +37,7 @@ def start_callback(update, context): context.bot.send_message(chat_id=int(chat_id), text="Вам необходимо войти в аккаунт. Используйте /login") + TOKEN = os.environ["TOKEN"] PORT = int(os.environ.get('PORT', '8443')) updater = telegram.ext.Updater(token=TOKEN, use_context=True) From 29f806fd382a36731c4365e3b658966553b2182c Mon Sep 17 00:00:00 2001 From: ashat1701 Date: Thu, 25 Apr 2019 02:20:28 +0300 Subject: [PATCH 24/49] fix menu --- setup.py | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/setup.py b/setup.py index ccabdae..af0b981 100644 --- a/setup.py +++ b/setup.py @@ -8,6 +8,12 @@ level=logging.INFO) +def get_menu(): + buttons = [["/plan", "/get_today_tasks"], ["/logout"]] + reply_markup = telegram.ReplyKeyboardMarkup(buttons, resize_keyboard=True) + return reply_markup + + # TODO: delete this after debug def echo(update, context): context.bot.send_message(chat_id=update.message.chat_id, text=update.message.text) @@ -26,15 +32,16 @@ def login(update, context): def start_callback(update, context): args = "".join(context.args) if args == "": - reply_markup = telegram.ReplyKeyboardMarkup(["Login"]) + reply_markup = telegram.ReplyKeyboardMarkup([["/login"]], resize_keyboard=True) context.bot.send_message(chat_id=int(update.message.chat_id), text="Здравствуйте! Вам нужно войти в свой аккаунт Google для использования этого бота", reply_markup=reply_markup) else: db = database.Database() chat_id = args if db.is_auth(chat_id): - context.bot.send_message(chat_id=int(chat_id), text="Вы успешно вошли в аккаунт") + context.bot.send_message(chat_id=int(chat_id), text="Вы успешно вошли в аккаунт", reply_markup=get_menu()) else: - context.bot.send_message(chat_id=int(chat_id), text="Вам необходимо войти в аккаунт. Используйте /login") + reply_markup = telegram.ReplyKeyboardMarkup([["/login"]], resize_keyboard=True) + context.bot.send_message(chat_id=int(chat_id), text="Вам необходимо войти в аккаунт. Используйте /login", reply_markup=reply_markup) From 735068a580ca3bae563ce4fe9263bde5bb819159 Mon Sep 17 00:00:00 2001 From: ashat1701 Date: Thu, 25 Apr 2019 02:22:13 +0300 Subject: [PATCH 25/49] another fix menu --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index af0b981..a750c10 100644 --- a/setup.py +++ b/setup.py @@ -23,7 +23,7 @@ def login(update, context): db = database.Database() chat_id = update.message.chat_id if db.is_auth(chat_id): - context.bot.send_message(chat_id=chat_id, text="Вы уже вошли в свой аккаунт.") + context.bot.send_message(chat_id=chat_id, text="Вы уже вошли в свой аккаунт.", reply_markup=get_menu()) else: googleAuth = auth.GoogleAuth(chat_id) context.bot.send_message(chat_id=chat_id, text=googleAuth.generate_url()) From 802986261327bcd7dc954c8e665cd34408eadd99 Mon Sep 17 00:00:00 2001 From: ashat1701 Date: Thu, 25 Apr 2019 23:28:06 +0300 Subject: [PATCH 26/49] Add logout and today_tasks handler --- calendar.py | 25 ++++++++++++++++++++ callbacks.py | 66 ++++++++++++++++++++++++++++++++++++++++++++++++++++ database.py | 7 +++++- setup.py | 49 +++++++------------------------------- 4 files changed, 105 insertions(+), 42 deletions(-) create mode 100644 calendar.py create mode 100644 callbacks.py diff --git a/calendar.py b/calendar.py new file mode 100644 index 0000000..1b1684a --- /dev/null +++ b/calendar.py @@ -0,0 +1,25 @@ +import database +import google.oauth2.credentials +import googleapiclient.discovery +import datetime + + +def get_today_tasks_list(chat_id): + db = database.Database() + creds_dict = db.get_cred(chat_id) + del creds_dict["chat_id"] + credentials = google.oauth2.credentials.Credentials(**creds_dict) + calendar = googleapiclient.discovery.build("calendar", "v3", credentials=credentials) + now = datetime.datetime.utcnow().isoformat() + 'Z' + # TODO: fix this for other UTC + today = datetime.datetime.combine(datetime.date.today(), datetime.datetime.min.time()) + start_of_day = today.isoformat() + '+03:00' + end = datetime.datetime.combine(datetime.date.today(), datetime.datetime.max.time()) + end_of_day = end.isoformat() + '+03:00' + print(start_of_day, end_of_day) + events_result = calendar.events().list(calendar_id="primary", singleEvents=True, orderBy='startTime', timeMin=start_of_day, timeMax=end_of_day).execute() + events = events_result.get('items', []) + if not events: + return "No today events" + else: + return events diff --git a/callbacks.py b/callbacks.py new file mode 100644 index 0000000..27c3105 --- /dev/null +++ b/callbacks.py @@ -0,0 +1,66 @@ +import telegram +import database +import auth +import calendar + +def get_menu(): + buttons = [["/plan", "/get_today_tasks"], ["/logout"]] + reply_markup = telegram.ReplyKeyboardMarkup(buttons, resize_keyboard=True) + return reply_markup + + +# TODO: delete this after debug +def echo_callback(update, context): + context.bot.send_message(chat_id=update.message.chat_id, text=update.message.text) + + +def logout_callback(update, context): + db = database.Database() + chat_id = update.message.chat_id + db.delete_cred(chat_id) + start_callback(update, context) + + +def get_today_tasks(update, context): + chat_id = update.message.chat_id + db = database.Database() + if db.is_auth(chat_id): + response = calendar.get_today_tasks_list(chat_id) + if response is str: + context.bot.send_message(chat_id=chat_id, text=response, reply_markup=get_menu()) + else: + text = "Events for today: \n" + counter = 1 + for event in response: + text = text + str(counter) + ". " + event["start"].get("dateTime", event['start'].get('date')) + "\n" + text = text + event["summary"] + "\n" + context.bot.send_message(chat_id=chat_id, text=text, reply_markup=get_menu()) + else: + reply_markup = telegram.ReplyKeyboardMarkup([["/login"]], resize_keyboard=True) + context.bot.send_message(chat_id=chat_id, text="Вам необходимо войти в аккаунт. Используйте /login", + reply_markup=reply_markup) + + +def login_callback(update, context): + db = database.Database() + chat_id = update.message.chat_id + if db.is_auth(chat_id): + context.bot.send_message(chat_id=chat_id, text="Вы уже вошли в свой аккаунт.", reply_markup=get_menu()) + else: + googleAuth = auth.GoogleAuth(chat_id) + context.bot.send_message(chat_id=chat_id, text=googleAuth.generate_url()) + + +def start_callback(update, context): + args = "".join(context.args) + if args == "": + reply_markup = telegram.ReplyKeyboardMarkup([["/login"]], resize_keyboard=True) + context.bot.send_message(chat_id=int(update.message.chat_id), text="Здравствуйте! Вам нужно войти в свой аккаунт Google для использования этого бота", reply_markup=reply_markup) + else: + db = database.Database() + chat_id = args + if db.is_auth(chat_id): + context.bot.send_message(chat_id=int(chat_id), text="Вы успешно вошли в аккаунт", reply_markup=get_menu()) + else: + reply_markup = telegram.ReplyKeyboardMarkup([["/login"]], resize_keyboard=True) + context.bot.send_message(chat_id=int(chat_id), text="Вам необходимо войти в аккаунт. Используйте /login", reply_markup=reply_markup) diff --git a/database.py b/database.py index 78dd96a..2ae9955 100644 --- a/database.py +++ b/database.py @@ -19,7 +19,6 @@ def get_cred(self, chat_id): cursor.execute("SELECT * FROM auth WHERE chat_id = %s", (str(chat_id),)) return cursor.fetchone() - def is_auth(self, chat_id): cursor = self.conn.cursor(cursor_factory=DictCursor) cursor.execute("SELECT chat_id FROM auth WHERE chat_id = %s", (str(chat_id),)) @@ -29,3 +28,9 @@ def is_auth(self, chat_id): else: cursor.close() return False + + def delete_cred(self, chat_id): + cursor = self.conn.cursor(cursor_factory=DictCursor) + cursor.execute("DELETE FROM auth WHERE chat_id = %s", (str(chat_id),)) + self.conn.commit() + cursor.close() diff --git a/setup.py b/setup.py index a750c10..e9ead6e 100644 --- a/setup.py +++ b/setup.py @@ -1,60 +1,27 @@ import telegram.ext import os import logging -import database -import auth +from callbacks import echo_callback, login_callback, start_callback, logout_callback, get_today_tasks logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) -def get_menu(): - buttons = [["/plan", "/get_today_tasks"], ["/logout"]] - reply_markup = telegram.ReplyKeyboardMarkup(buttons, resize_keyboard=True) - return reply_markup - - -# TODO: delete this after debug -def echo(update, context): - context.bot.send_message(chat_id=update.message.chat_id, text=update.message.text) - - -def login(update, context): - db = database.Database() - chat_id = update.message.chat_id - if db.is_auth(chat_id): - context.bot.send_message(chat_id=chat_id, text="Вы уже вошли в свой аккаунт.", reply_markup=get_menu()) - else: - googleAuth = auth.GoogleAuth(chat_id) - context.bot.send_message(chat_id=chat_id, text=googleAuth.generate_url()) - - -def start_callback(update, context): - args = "".join(context.args) - if args == "": - reply_markup = telegram.ReplyKeyboardMarkup([["/login"]], resize_keyboard=True) - context.bot.send_message(chat_id=int(update.message.chat_id), text="Здравствуйте! Вам нужно войти в свой аккаунт Google для использования этого бота", reply_markup=reply_markup) - else: - db = database.Database() - chat_id = args - if db.is_auth(chat_id): - context.bot.send_message(chat_id=int(chat_id), text="Вы успешно вошли в аккаунт", reply_markup=get_menu()) - else: - reply_markup = telegram.ReplyKeyboardMarkup([["/login"]], resize_keyboard=True) - context.bot.send_message(chat_id=int(chat_id), text="Вам необходимо войти в аккаунт. Используйте /login", reply_markup=reply_markup) - - - TOKEN = os.environ["TOKEN"] PORT = int(os.environ.get('PORT', '8443')) updater = telegram.ext.Updater(token=TOKEN, use_context=True) dispatcher = updater.dispatcher -dispatcher.add_handler(telegram.ext.MessageHandler(telegram.ext.Filters.text, echo)) -dispatcher.add_handler(telegram.ext.CommandHandler('login', login)) + +dispatcher.add_handler(telegram.ext.MessageHandler(telegram.ext.Filters.text, echo_callback())) +dispatcher.add_handler(telegram.ext.CommandHandler('login', login_callback)) dispatcher.add_handler(telegram.ext.CommandHandler("start", start_callback, pass_args=True)) +dispatcher.add_handler(telegram.ext.CommandHandler("logout", logout_callback)) +dispatcher.add_handler(telegram.ext.CommandHandler("get_today_tasks", get_today_tasks)) + updater.start_webhook(listen="0.0.0.0", port=PORT, url_path=TOKEN) + updater.bot.set_webhook("https://yet-another-task-bot.herokuapp.com/" + TOKEN) updater.idle() \ No newline at end of file From aaf021b2971af7626c831eb9830da0a49a1783fb Mon Sep 17 00:00:00 2001 From: ashat1701 Date: Thu, 25 Apr 2019 23:34:39 +0300 Subject: [PATCH 27/49] fix echo_callback --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index e9ead6e..96ad215 100644 --- a/setup.py +++ b/setup.py @@ -12,7 +12,7 @@ updater = telegram.ext.Updater(token=TOKEN, use_context=True) dispatcher = updater.dispatcher -dispatcher.add_handler(telegram.ext.MessageHandler(telegram.ext.Filters.text, echo_callback())) +dispatcher.add_handler(telegram.ext.MessageHandler(telegram.ext.Filters.text, echo_callback)) dispatcher.add_handler(telegram.ext.CommandHandler('login', login_callback)) dispatcher.add_handler(telegram.ext.CommandHandler("start", start_callback, pass_args=True)) dispatcher.add_handler(telegram.ext.CommandHandler("logout", logout_callback)) From 1602dc23319c60a880deff70408d53e47572d879 Mon Sep 17 00:00:00 2001 From: ashat1701 Date: Thu, 25 Apr 2019 23:35:20 +0300 Subject: [PATCH 28/49] temp fix --- callbacks.py | 1 + 1 file changed, 1 insertion(+) diff --git a/callbacks.py b/callbacks.py index 27c3105..9fce5a1 100644 --- a/callbacks.py +++ b/callbacks.py @@ -22,6 +22,7 @@ def logout_callback(update, context): def get_today_tasks(update, context): + return chat_id = update.message.chat_id db = database.Database() if db.is_auth(chat_id): From de38d71242cf8900418bea47e61521984495356b Mon Sep 17 00:00:00 2001 From: ashat1701 Date: Thu, 25 Apr 2019 23:40:10 +0300 Subject: [PATCH 29/49] naming fix --- callbacks.py | 6 +++--- auth.py => gauth.py | 0 2 files changed, 3 insertions(+), 3 deletions(-) rename auth.py => gauth.py (100%) diff --git a/callbacks.py b/callbacks.py index 9fce5a1..41ef2cb 100644 --- a/callbacks.py +++ b/callbacks.py @@ -1,8 +1,9 @@ import telegram import database -import auth +import gauth import calendar + def get_menu(): buttons = [["/plan", "/get_today_tasks"], ["/logout"]] reply_markup = telegram.ReplyKeyboardMarkup(buttons, resize_keyboard=True) @@ -22,7 +23,6 @@ def logout_callback(update, context): def get_today_tasks(update, context): - return chat_id = update.message.chat_id db = database.Database() if db.is_auth(chat_id): @@ -48,7 +48,7 @@ def login_callback(update, context): if db.is_auth(chat_id): context.bot.send_message(chat_id=chat_id, text="Вы уже вошли в свой аккаунт.", reply_markup=get_menu()) else: - googleAuth = auth.GoogleAuth(chat_id) + googleAuth = gauth.GoogleAuth(chat_id) context.bot.send_message(chat_id=chat_id, text=googleAuth.generate_url()) diff --git a/auth.py b/gauth.py similarity index 100% rename from auth.py rename to gauth.py From 042658b1ac0e33ddec166a9662e3be7b616016cd Mon Sep 17 00:00:00 2001 From: ashat1701 Date: Thu, 25 Apr 2019 23:42:14 +0300 Subject: [PATCH 30/49] naming fix --- callbacks.py | 4 ++-- calendar.py => gcalendar.py | 0 2 files changed, 2 insertions(+), 2 deletions(-) rename calendar.py => gcalendar.py (100%) diff --git a/callbacks.py b/callbacks.py index 41ef2cb..4cd76c1 100644 --- a/callbacks.py +++ b/callbacks.py @@ -1,7 +1,7 @@ import telegram import database import gauth -import calendar +import gcalendar def get_menu(): @@ -26,7 +26,7 @@ def get_today_tasks(update, context): chat_id = update.message.chat_id db = database.Database() if db.is_auth(chat_id): - response = calendar.get_today_tasks_list(chat_id) + response = gcalendar.get_today_tasks_list(chat_id) if response is str: context.bot.send_message(chat_id=chat_id, text=response, reply_markup=get_menu()) else: diff --git a/calendar.py b/gcalendar.py similarity index 100% rename from calendar.py rename to gcalendar.py From bc257c8fe12e9def3c4d99f3516694c764c0b08b Mon Sep 17 00:00:00 2001 From: ashat1701 Date: Thu, 25 Apr 2019 23:44:51 +0300 Subject: [PATCH 31/49] db fix --- database.py | 2 +- requirements.txt | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/database.py b/database.py index 2ae9955..f830c6b 100644 --- a/database.py +++ b/database.py @@ -17,7 +17,7 @@ def __new__(cls, *args, **kwargs): def get_cred(self, chat_id): cursor = self.conn.cursor(cursor_factory=DictCursor) cursor.execute("SELECT * FROM auth WHERE chat_id = %s", (str(chat_id),)) - return cursor.fetchone() + return cursor.fetchall() def is_auth(self, chat_id): cursor = self.conn.cursor(cursor_factory=DictCursor) diff --git a/requirements.txt b/requirements.txt index 244605d..26e3940 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,5 +1,6 @@ python-telegram-bot==12.0.0b1 google-api-python-client + google-auth google-auth-oauthlib google-auth-httplib2 From f49857158dec31940e576262354b1e8e168c9bff Mon Sep 17 00:00:00 2001 From: ashat1701 Date: Thu, 25 Apr 2019 23:48:19 +0300 Subject: [PATCH 32/49] db fix --- database.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/database.py b/database.py index f830c6b..8f4ce6a 100644 --- a/database.py +++ b/database.py @@ -17,7 +17,7 @@ def __new__(cls, *args, **kwargs): def get_cred(self, chat_id): cursor = self.conn.cursor(cursor_factory=DictCursor) cursor.execute("SELECT * FROM auth WHERE chat_id = %s", (str(chat_id),)) - return cursor.fetchall() + return cursor.fetchall()[0] def is_auth(self, chat_id): cursor = self.conn.cursor(cursor_factory=DictCursor) From e0922595c92ac1ed1bec7a7304da08c320c46eda Mon Sep 17 00:00:00 2001 From: ashat1701 Date: Thu, 25 Apr 2019 23:52:47 +0300 Subject: [PATCH 33/49] db fix --- database.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/database.py b/database.py index 8f4ce6a..3c17fdb 100644 --- a/database.py +++ b/database.py @@ -1,6 +1,6 @@ import psycopg2 import os -from psycopg2.extras import DictCursor +from psycopg2.extras import RealDictCursor class Database: @@ -15,12 +15,12 @@ def __new__(cls, *args, **kwargs): return cls.__instance def get_cred(self, chat_id): - cursor = self.conn.cursor(cursor_factory=DictCursor) + cursor = self.conn.cursor(cursor_factory=RealDictCursor) cursor.execute("SELECT * FROM auth WHERE chat_id = %s", (str(chat_id),)) return cursor.fetchall()[0] def is_auth(self, chat_id): - cursor = self.conn.cursor(cursor_factory=DictCursor) + cursor = self.conn.cursor(cursor_factory=RealDictCursor) cursor.execute("SELECT chat_id FROM auth WHERE chat_id = %s", (str(chat_id),)) if cursor.fetchone() is not None: cursor.close() @@ -30,7 +30,7 @@ def is_auth(self, chat_id): return False def delete_cred(self, chat_id): - cursor = self.conn.cursor(cursor_factory=DictCursor) + cursor = self.conn.cursor(cursor_factory=RealDictCursor) cursor.execute("DELETE FROM auth WHERE chat_id = %s", (str(chat_id),)) self.conn.commit() cursor.close() From f06bdcbcb028ce638b7f0cbdb40040d91d2ba960 Mon Sep 17 00:00:00 2001 From: ashat1701 Date: Thu, 25 Apr 2019 23:56:33 +0300 Subject: [PATCH 34/49] fix gcalendar --- gcalendar.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gcalendar.py b/gcalendar.py index 1b1684a..0c3db1b 100644 --- a/gcalendar.py +++ b/gcalendar.py @@ -17,7 +17,7 @@ def get_today_tasks_list(chat_id): end = datetime.datetime.combine(datetime.date.today(), datetime.datetime.max.time()) end_of_day = end.isoformat() + '+03:00' print(start_of_day, end_of_day) - events_result = calendar.events().list(calendar_id="primary", singleEvents=True, orderBy='startTime', timeMin=start_of_day, timeMax=end_of_day).execute() + events_result = calendar.events().list(calendarId="primary", singleEvents=True, orderBy='startTime', timeMin=start_of_day, timeMax=end_of_day).execute() events = events_result.get('items', []) if not events: return "No today events" From 13dccadf201369e70f0b9ae6b5febf4f58eb07bb Mon Sep 17 00:00:00 2001 From: ashat1701 Date: Fri, 26 Apr 2019 00:11:45 +0300 Subject: [PATCH 35/49] fix req --- gcalendar.py | 1 + requirements.txt | 5 +++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/gcalendar.py b/gcalendar.py index 0c3db1b..22d97fb 100644 --- a/gcalendar.py +++ b/gcalendar.py @@ -8,6 +8,7 @@ def get_today_tasks_list(chat_id): db = database.Database() creds_dict = db.get_cred(chat_id) del creds_dict["chat_id"] + print(creds_dict) credentials = google.oauth2.credentials.Credentials(**creds_dict) calendar = googleapiclient.discovery.build("calendar", "v3", credentials=credentials) now = datetime.datetime.utcnow().isoformat() + 'Z' diff --git a/requirements.txt b/requirements.txt index 26e3940..ad09ff3 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,7 +1,8 @@ python-telegram-bot==12.0.0b1 google-api-python-client - +google google-auth google-auth-oauthlib google-auth-httplib2 -psycopg2-binary \ No newline at end of file +psycopg2-binary +google \ No newline at end of file From 1ec38124dab8d8fc48ce8ab136f8c6ad76cd8b6b Mon Sep 17 00:00:00 2001 From: ashat1701 Date: Fri, 26 Apr 2019 00:17:30 +0300 Subject: [PATCH 36/49] fix gapi req --- requirements.txt | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index ad09ff3..a9268f8 100644 --- a/requirements.txt +++ b/requirements.txt @@ -5,4 +5,7 @@ google-auth google-auth-oauthlib google-auth-httplib2 psycopg2-binary -google \ No newline at end of file +google +oauth2client +googleapis-common-protos +google-cloud \ No newline at end of file From a1aaafcc701f8b6f9f6e076be1c8c072da130614 Mon Sep 17 00:00:00 2001 From: ashat1701 Date: Fri, 26 Apr 2019 00:23:49 +0300 Subject: [PATCH 37/49] fix gapi req --- callbacks.py | 4 ++-- gcalendar.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/callbacks.py b/callbacks.py index 4cd76c1..aec8330 100644 --- a/callbacks.py +++ b/callbacks.py @@ -27,8 +27,8 @@ def get_today_tasks(update, context): db = database.Database() if db.is_auth(chat_id): response = gcalendar.get_today_tasks_list(chat_id) - if response is str: - context.bot.send_message(chat_id=chat_id, text=response, reply_markup=get_menu()) + if response: + context.bot.send_message(chat_id=chat_id, text="Ваш день сегодня свободен. Везет же)", reply_markup=get_menu()) else: text = "Events for today: \n" counter = 1 diff --git a/gcalendar.py b/gcalendar.py index 22d97fb..ad739be 100644 --- a/gcalendar.py +++ b/gcalendar.py @@ -21,6 +21,6 @@ def get_today_tasks_list(chat_id): events_result = calendar.events().list(calendarId="primary", singleEvents=True, orderBy='startTime', timeMin=start_of_day, timeMax=end_of_day).execute() events = events_result.get('items', []) if not events: - return "No today events" + return False else: return events From eba23fb58b5332577d93d0958fee05bacc86b598 Mon Sep 17 00:00:00 2001 From: ashat1701 Date: Fri, 26 Apr 2019 00:26:22 +0300 Subject: [PATCH 38/49] fix some bugs --- callbacks.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/callbacks.py b/callbacks.py index aec8330..2d9a4b2 100644 --- a/callbacks.py +++ b/callbacks.py @@ -27,7 +27,7 @@ def get_today_tasks(update, context): db = database.Database() if db.is_auth(chat_id): response = gcalendar.get_today_tasks_list(chat_id) - if response: + if not response: context.bot.send_message(chat_id=chat_id, text="Ваш день сегодня свободен. Везет же)", reply_markup=get_menu()) else: text = "Events for today: \n" From 248254b3090d47df4f8890f5983ecd14a0839710 Mon Sep 17 00:00:00 2001 From: ashat1701 Date: Fri, 26 Apr 2019 00:44:26 +0300 Subject: [PATCH 39/49] fix some bugs --- gcalendar.py | 2 +- requirements.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/gcalendar.py b/gcalendar.py index ad739be..0803ac6 100644 --- a/gcalendar.py +++ b/gcalendar.py @@ -18,7 +18,7 @@ def get_today_tasks_list(chat_id): end = datetime.datetime.combine(datetime.date.today(), datetime.datetime.max.time()) end_of_day = end.isoformat() + '+03:00' print(start_of_day, end_of_day) - events_result = calendar.events().list(calendarId="primary", singleEvents=True, orderBy='startTime', timeMin=start_of_day, timeMax=end_of_day).execute() + events_result = calendar.events().list(calendarId="primary", singleEvents=True, orderBy='startTime').execute() events = events_result.get('items', []) if not events: return False diff --git a/requirements.txt b/requirements.txt index a9268f8..35da91e 100644 --- a/requirements.txt +++ b/requirements.txt @@ -8,4 +8,4 @@ psycopg2-binary google oauth2client googleapis-common-protos -google-cloud \ No newline at end of file +google-cloud From 2c56512cf3670ab058dd50138e2b578e557d9249 Mon Sep 17 00:00:00 2001 From: ashat1701 Date: Fri, 26 Apr 2019 01:24:32 +0300 Subject: [PATCH 40/49] fix some bugs --- gcalendar.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gcalendar.py b/gcalendar.py index 0803ac6..0ad9591 100644 --- a/gcalendar.py +++ b/gcalendar.py @@ -18,7 +18,7 @@ def get_today_tasks_list(chat_id): end = datetime.datetime.combine(datetime.date.today(), datetime.datetime.max.time()) end_of_day = end.isoformat() + '+03:00' print(start_of_day, end_of_day) - events_result = calendar.events().list(calendarId="primary", singleEvents=True, orderBy='startTime').execute() + events_result = calendar.events().list(calendarId="primary", singleEvents=True, orderBy='startTime', timeMin=start_of_day).execute() events = events_result.get('items', []) if not events: return False From f9ceb168e2bc616ba12a6f2aab55f4b31f5641ec Mon Sep 17 00:00:00 2001 From: ashat1701 Date: Fri, 26 Apr 2019 01:48:12 +0300 Subject: [PATCH 41/49] fix some st --- callbacks.py | 1 + 1 file changed, 1 insertion(+) diff --git a/callbacks.py b/callbacks.py index 2d9a4b2..015710e 100644 --- a/callbacks.py +++ b/callbacks.py @@ -35,6 +35,7 @@ def get_today_tasks(update, context): for event in response: text = text + str(counter) + ". " + event["start"].get("dateTime", event['start'].get('date')) + "\n" text = text + event["summary"] + "\n" + counter+=1 context.bot.send_message(chat_id=chat_id, text=text, reply_markup=get_menu()) else: reply_markup = telegram.ReplyKeyboardMarkup([["/login"]], resize_keyboard=True) From f2b123f5a3d83acc8492859d467e66d7ca3505ed Mon Sep 17 00:00:00 2001 From: ashat1701 Date: Fri, 26 Apr 2019 11:03:43 +0300 Subject: [PATCH 42/49] fix some st --- callbacks.py | 2 +- gcalendar.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/callbacks.py b/callbacks.py index 015710e..7bad8fe 100644 --- a/callbacks.py +++ b/callbacks.py @@ -35,7 +35,7 @@ def get_today_tasks(update, context): for event in response: text = text + str(counter) + ". " + event["start"].get("dateTime", event['start'].get('date')) + "\n" text = text + event["summary"] + "\n" - counter+=1 + counter += 1 context.bot.send_message(chat_id=chat_id, text=text, reply_markup=get_menu()) else: reply_markup = telegram.ReplyKeyboardMarkup([["/login"]], resize_keyboard=True) diff --git a/gcalendar.py b/gcalendar.py index 0ad9591..ad739be 100644 --- a/gcalendar.py +++ b/gcalendar.py @@ -18,7 +18,7 @@ def get_today_tasks_list(chat_id): end = datetime.datetime.combine(datetime.date.today(), datetime.datetime.max.time()) end_of_day = end.isoformat() + '+03:00' print(start_of_day, end_of_day) - events_result = calendar.events().list(calendarId="primary", singleEvents=True, orderBy='startTime', timeMin=start_of_day).execute() + events_result = calendar.events().list(calendarId="primary", singleEvents=True, orderBy='startTime', timeMin=start_of_day, timeMax=end_of_day).execute() events = events_result.get('items', []) if not events: return False From 10ae967d2bd85bd3c16536c6e968a239aa27be86 Mon Sep 17 00:00:00 2001 From: ashat1701 Date: Sat, 27 Apr 2019 03:54:56 +0300 Subject: [PATCH 43/49] add events handler --- callbacks.py | 35 ++++++++++++++++++++++++++++++++--- gcalendar.py | 27 ++++++++++++++++++++++++--- requirements.txt | 1 + setup.py | 9 +++++---- 4 files changed, 62 insertions(+), 10 deletions(-) diff --git a/callbacks.py b/callbacks.py index 7bad8fe..c115b44 100644 --- a/callbacks.py +++ b/callbacks.py @@ -10,11 +10,40 @@ def get_menu(): return reply_markup -# TODO: delete this after debug -def echo_callback(update, context): +def text_callback(update, context): + reply_markup = telegram.ReplyKeyboardMarkup([["/cancel"]], resize_keyboard=True) + if context.user_data["state"] == "summary": + context.user_data["state"] = "date" + context.user_data["summary"] = update.message.text + context.bot.send_message(chat_id=update.message.chat_id, text="Введите дату в формате ГГГГ-ММ-ДД", reply_markup=reply_markup) + elif context.user_data["state"] == "date": + context.user_data["state"] = "time" + # TODO: check if it is correct date + context.user_data["date"] = update.message.text + context.bot.send_message(chat_id=update.message.chat_id, text="Введите время события", reply_markup=reply_markup) + elif context.user_data["state"] == "time": + gcalendar.set_new_task(update.message.chat_id, update.message.text, context.user_data["date"], context.user_data["summary"]) + context.bot.send_message(chat_id=update.message.chat_id, text="Задача успешно добавлена", reply_markup=get_menu()) + else: + context.bot.send_message(chat_id=update.message.chat_id, text="Команда не распознана", reply_markup=get_menu()) context.bot.send_message(chat_id=update.message.chat_id, text=update.message.text) +def plan_callback(update, context): + context.user_data["state"] = "summary" + reply_markup = telegram.ReplyKeyboardMarkup([["/cancel"]], resize_keyboard=True) + context.bot.send_message(chat_id=update.message.chat_id, text="Введите текст для задачи.", reply_markup=reply_markup) + + +def back_callback(update, context): + pass + + +def cancel_callback(update, context): + context.user_data.clear() + context.bot.send_message(chat_id=update.message.chat_id, text="Выберете команду", reply_markup=get_menu()) + + def logout_callback(update, context): db = database.Database() chat_id = update.message.chat_id @@ -22,7 +51,7 @@ def logout_callback(update, context): start_callback(update, context) -def get_today_tasks(update, context): +def get_today_tasks_callback(update, context): chat_id = update.message.chat_id db = database.Database() if db.is_auth(chat_id): diff --git a/gcalendar.py b/gcalendar.py index ad739be..fe905b8 100644 --- a/gcalendar.py +++ b/gcalendar.py @@ -2,6 +2,7 @@ import google.oauth2.credentials import googleapiclient.discovery import datetime +import pytz def get_today_tasks_list(chat_id): @@ -11,11 +12,11 @@ def get_today_tasks_list(chat_id): print(creds_dict) credentials = google.oauth2.credentials.Credentials(**creds_dict) calendar = googleapiclient.discovery.build("calendar", "v3", credentials=credentials) - now = datetime.datetime.utcnow().isoformat() + 'Z' # TODO: fix this for other UTC - today = datetime.datetime.combine(datetime.date.today(), datetime.datetime.min.time()) + date = datetime.datetime.now(pytz.timezone('Europe/Moscow')) + today = datetime.datetime.combine(datetime.date(date.year, date.month, date.day), datetime.datetime.min.time()) start_of_day = today.isoformat() + '+03:00' - end = datetime.datetime.combine(datetime.date.today(), datetime.datetime.max.time()) + end = datetime.datetime.combine(datetime.date(date.year, date.month, date.day), datetime.datetime.max.time()) end_of_day = end.isoformat() + '+03:00' print(start_of_day, end_of_day) events_result = calendar.events().list(calendarId="primary", singleEvents=True, orderBy='startTime', timeMin=start_of_day, timeMax=end_of_day).execute() @@ -24,3 +25,23 @@ def get_today_tasks_list(chat_id): return False else: return events + + +def set_new_task(chat_id, time, date, summary): + db = database.Database() + creds_dict = db.get_cred(chat_id) + del creds_dict["chat_id"] + credentials = google.oauth2.credentials.Credentials(**creds_dict) + calendar = googleapiclient.discovery.build("calendar", "v3", credentials=credentials) + event = { + 'summary': summary, + 'start' : { + 'dateTime' : date + "T" + time + ":00+03:00", + 'timeZone' : 'Europe/Moscow', + }, + 'end' : { + 'dateTime': date + "T" + time + ":00+03:00", + 'timeZone': 'Europe/Moscow', + }, + } + calendar.events().insert(calendar_id="primary", body=event).execute() diff --git a/requirements.txt b/requirements.txt index 35da91e..07d9bb1 100644 --- a/requirements.txt +++ b/requirements.txt @@ -9,3 +9,4 @@ google oauth2client googleapis-common-protos google-cloud +pytz \ No newline at end of file diff --git a/setup.py b/setup.py index 96ad215..c4d826a 100644 --- a/setup.py +++ b/setup.py @@ -1,7 +1,7 @@ import telegram.ext import os import logging -from callbacks import echo_callback, login_callback, start_callback, logout_callback, get_today_tasks +from callbacks import text_callback, login_callback, start_callback, logout_callback, get_today_tasks_callback, plan_callback, cancel_callback logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) @@ -12,12 +12,13 @@ updater = telegram.ext.Updater(token=TOKEN, use_context=True) dispatcher = updater.dispatcher -dispatcher.add_handler(telegram.ext.MessageHandler(telegram.ext.Filters.text, echo_callback)) +dispatcher.add_handler(telegram.ext.MessageHandler(telegram.ext.Filters.text, text_callback)) dispatcher.add_handler(telegram.ext.CommandHandler('login', login_callback)) dispatcher.add_handler(telegram.ext.CommandHandler("start", start_callback, pass_args=True)) dispatcher.add_handler(telegram.ext.CommandHandler("logout", logout_callback)) -dispatcher.add_handler(telegram.ext.CommandHandler("get_today_tasks", get_today_tasks)) - +dispatcher.add_handler(telegram.ext.CommandHandler("get_today_tasks", get_today_tasks_callback)) +dispatcher.add_handler(telegram.ext.CommandHandler("plan", plan_callback)) +dispatcher.add_handler(telegram.ext.CommandHandler("cancel", cancel_callback)) updater.start_webhook(listen="0.0.0.0", port=PORT, url_path=TOKEN) From b709421e471ea0d38f83e21a8ff168695535deaf Mon Sep 17 00:00:00 2001 From: ashat1701 Date: Sat, 27 Apr 2019 03:58:56 +0300 Subject: [PATCH 44/49] fix gcalendar --- gcalendar.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gcalendar.py b/gcalendar.py index fe905b8..4196c3e 100644 --- a/gcalendar.py +++ b/gcalendar.py @@ -44,4 +44,4 @@ def set_new_task(chat_id, time, date, summary): 'timeZone': 'Europe/Moscow', }, } - calendar.events().insert(calendar_id="primary", body=event).execute() + calendar.events().insert(calendarId="primary", body=event).execute() From dcee55e5056f2f6fc17696cf00d3f7becd7f1880 Mon Sep 17 00:00:00 2001 From: ashat1701 Date: Sat, 27 Apr 2019 04:44:07 +0300 Subject: [PATCH 45/49] add daily announcment --- callbacks.py | 32 ++++++++++++++++++++++++++++---- 1 file changed, 28 insertions(+), 4 deletions(-) diff --git a/callbacks.py b/callbacks.py index c115b44..d5479a3 100644 --- a/callbacks.py +++ b/callbacks.py @@ -2,7 +2,8 @@ import database import gauth import gcalendar - +import datetime +import pytz def get_menu(): buttons = [["/plan", "/get_today_tasks"], ["/logout"]] @@ -26,7 +27,6 @@ def text_callback(update, context): context.bot.send_message(chat_id=update.message.chat_id, text="Задача успешно добавлена", reply_markup=get_menu()) else: context.bot.send_message(chat_id=update.message.chat_id, text="Команда не распознана", reply_markup=get_menu()) - context.bot.send_message(chat_id=update.message.chat_id, text=update.message.text) def plan_callback(update, context): @@ -59,7 +59,7 @@ def get_today_tasks_callback(update, context): if not response: context.bot.send_message(chat_id=chat_id, text="Ваш день сегодня свободен. Везет же)", reply_markup=get_menu()) else: - text = "Events for today: \n" + text = "События на сегодня: \n" counter = 1 for event in response: text = text + str(counter) + ". " + event["start"].get("dateTime", event['start'].get('date')) + "\n" @@ -79,7 +79,9 @@ def login_callback(update, context): context.bot.send_message(chat_id=chat_id, text="Вы уже вошли в свой аккаунт.", reply_markup=get_menu()) else: googleAuth = gauth.GoogleAuth(chat_id) - context.bot.send_message(chat_id=chat_id, text=googleAuth.generate_url()) + reply_markup = telegram.ReplyKeyboardMarkup([["/login"]], resize_keyboard=True) + #TODO : strange behavior with /login twice + context.bot.send_message(chat_id=chat_id, text=googleAuth.generate_url(), reply_markup=reply_markup) def start_callback(update, context): @@ -92,6 +94,28 @@ def start_callback(update, context): chat_id = args if db.is_auth(chat_id): context.bot.send_message(chat_id=int(chat_id), text="Вы успешно вошли в аккаунт", reply_markup=get_menu()) + context.job_queue.run_daily(daily_announce, datetime.time(hour=8, minute=0, second=0, tzinfo=pytz.timezone("Europe/Moscow"))) else: reply_markup = telegram.ReplyKeyboardMarkup([["/login"]], resize_keyboard=True) context.bot.send_message(chat_id=int(chat_id), text="Вам необходимо войти в аккаунт. Используйте /login", reply_markup=reply_markup) + + +def daily_announce(bot, job): + # TODO: Repeating code + chat_id = job.context + db = database.Database() + if db.is_auth(chat_id): + bot.send_message(chat_id=chat_id, text="Доброе утро!") + response = gcalendar.get_today_tasks_list(chat_id) + if not response: + bot.send_message(chat_id=chat_id, text="Ваш день сегодня свободен. Везет же)", + reply_markup=get_menu()) + else: + text = "События на сегодня: \n" + counter = 1 + #TODO: add enumerate + for event in response: + text = text + str(counter) + ". " + event["start"].get("dateTime", event['start'].get('date')) + "\n" + text = text + event["summary"] + "\n" + counter += 1 + bot.send_message(chat_id=chat_id, text=text, reply_markup=get_menu()) \ No newline at end of file From c7fee95c1dda5729032e8cc6b07c60456786424b Mon Sep 17 00:00:00 2001 From: ashat1701 Date: Sat, 27 Apr 2019 17:56:56 +0300 Subject: [PATCH 46/49] fix some shit --- callbacks.py | 5 ++++- requirements.txt | 3 ++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/callbacks.py b/callbacks.py index d5479a3..9c45808 100644 --- a/callbacks.py +++ b/callbacks.py @@ -4,6 +4,8 @@ import gcalendar import datetime import pytz +import dateutil.parser + def get_menu(): buttons = [["/plan", "/get_today_tasks"], ["/logout"]] @@ -115,7 +117,8 @@ def daily_announce(bot, job): counter = 1 #TODO: add enumerate for event in response: - text = text + str(counter) + ". " + event["start"].get("dateTime", event['start'].get('date')) + "\n" + date = dateutil.parser.parse( event["start"].get("dateTime", event['start'].get('date'))) + text = text + str(counter) + ". " + date.time() + "\n" text = text + event["summary"] + "\n" counter += 1 bot.send_message(chat_id=chat_id, text=text, reply_markup=get_menu()) \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index 07d9bb1..d9fa4dc 100644 --- a/requirements.txt +++ b/requirements.txt @@ -9,4 +9,5 @@ google oauth2client googleapis-common-protos google-cloud -pytz \ No newline at end of file +pytz +python-dateutil \ No newline at end of file From cdddc9b4e7fa6543103f7d7cd3b0c8ae0e1ecc67 Mon Sep 17 00:00:00 2001 From: ashat1701 Date: Sat, 27 Apr 2019 18:10:50 +0300 Subject: [PATCH 47/49] fix some shi --- callbacks.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/callbacks.py b/callbacks.py index 9c45808..9a7b034 100644 --- a/callbacks.py +++ b/callbacks.py @@ -118,7 +118,7 @@ def daily_announce(bot, job): #TODO: add enumerate for event in response: date = dateutil.parser.parse( event["start"].get("dateTime", event['start'].get('date'))) - text = text + str(counter) + ". " + date.time() + "\n" + text = text + str(counter) + ". {}:{}".format(date.time().hour, date.time().minute) + + "\n" text = text + event["summary"] + "\n" counter += 1 bot.send_message(chat_id=chat_id, text=text, reply_markup=get_menu()) \ No newline at end of file From 9f57a9a0482a659b538c66a55ff9f726230a536b Mon Sep 17 00:00:00 2001 From: ashat1701 Date: Sat, 27 Apr 2019 18:17:28 +0300 Subject: [PATCH 48/49] fix some bugs --- callbacks.py | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/callbacks.py b/callbacks.py index 9a7b034..38db2a9 100644 --- a/callbacks.py +++ b/callbacks.py @@ -15,18 +15,19 @@ def get_menu(): def text_callback(update, context): reply_markup = telegram.ReplyKeyboardMarkup([["/cancel"]], resize_keyboard=True) - if context.user_data["state"] == "summary": - context.user_data["state"] = "date" - context.user_data["summary"] = update.message.text - context.bot.send_message(chat_id=update.message.chat_id, text="Введите дату в формате ГГГГ-ММ-ДД", reply_markup=reply_markup) - elif context.user_data["state"] == "date": - context.user_data["state"] = "time" - # TODO: check if it is correct date - context.user_data["date"] = update.message.text - context.bot.send_message(chat_id=update.message.chat_id, text="Введите время события", reply_markup=reply_markup) - elif context.user_data["state"] == "time": - gcalendar.set_new_task(update.message.chat_id, update.message.text, context.user_data["date"], context.user_data["summary"]) - context.bot.send_message(chat_id=update.message.chat_id, text="Задача успешно добавлена", reply_markup=get_menu()) + if "state" in context.user_data: + if context.user_data["state"] == "summary": + context.user_data["state"] = "date" + context.user_data["summary"] = update.message.text + context.bot.send_message(chat_id=update.message.chat_id, text="Введите дату в формате ГГГГ-ММ-ДД", reply_markup=reply_markup) + elif context.user_data["state"] == "date": + context.user_data["state"] = "time" + # TODO: check if it is correct date + context.user_data["date"] = update.message.text + context.bot.send_message(chat_id=update.message.chat_id, text="Введите время события", reply_markup=reply_markup) + elif context.user_data["state"] == "time": + gcalendar.set_new_task(update.message.chat_id, update.message.text, context.user_data["date"], context.user_data["summary"]) + context.bot.send_message(chat_id=update.message.chat_id, text="Задача успешно добавлена", reply_markup=get_menu()) else: context.bot.send_message(chat_id=update.message.chat_id, text="Команда не распознана", reply_markup=get_menu()) From ce710763df647a0a622a68a776856dceaef484aa Mon Sep 17 00:00:00 2001 From: Khayrullin Askhat Date: Sun, 19 May 2019 19:42:59 +0300 Subject: [PATCH 49/49] Reformat code --- callbacks.py | 48 +++++++++++++++++++++++++++++----------------- client_secret.json | 1 - database.py | 10 +++++++--- gauth.py | 2 -- gcalendar.py | 21 +++++++++++--------- setup.py | 20 +++++++++++-------- 6 files changed, 61 insertions(+), 41 deletions(-) delete mode 100644 client_secret.json diff --git a/callbacks.py b/callbacks.py index 38db2a9..e0a22c6 100644 --- a/callbacks.py +++ b/callbacks.py @@ -1,10 +1,12 @@ +import datetime + +import dateutil.parser +import pytz import telegram + import database import gauth import gcalendar -import datetime -import pytz -import dateutil.parser def get_menu(): @@ -19,15 +21,19 @@ def text_callback(update, context): if context.user_data["state"] == "summary": context.user_data["state"] = "date" context.user_data["summary"] = update.message.text - context.bot.send_message(chat_id=update.message.chat_id, text="Введите дату в формате ГГГГ-ММ-ДД", reply_markup=reply_markup) + context.bot.send_message(chat_id=update.message.chat_id, text="Введите дату в формате ГГГГ-ММ-ДД", + reply_markup=reply_markup) elif context.user_data["state"] == "date": context.user_data["state"] = "time" # TODO: check if it is correct date context.user_data["date"] = update.message.text - context.bot.send_message(chat_id=update.message.chat_id, text="Введите время события", reply_markup=reply_markup) + context.bot.send_message(chat_id=update.message.chat_id, text="Введите время события", + reply_markup=reply_markup) elif context.user_data["state"] == "time": - gcalendar.set_new_task(update.message.chat_id, update.message.text, context.user_data["date"], context.user_data["summary"]) - context.bot.send_message(chat_id=update.message.chat_id, text="Задача успешно добавлена", reply_markup=get_menu()) + gcalendar.set_new_task(update.message.chat_id, update.message.text, context.user_data["date"], + context.user_data["summary"]) + context.bot.send_message(chat_id=update.message.chat_id, text="Задача успешно добавлена", + reply_markup=get_menu()) else: context.bot.send_message(chat_id=update.message.chat_id, text="Команда не распознана", reply_markup=get_menu()) @@ -35,7 +41,8 @@ def text_callback(update, context): def plan_callback(update, context): context.user_data["state"] = "summary" reply_markup = telegram.ReplyKeyboardMarkup([["/cancel"]], resize_keyboard=True) - context.bot.send_message(chat_id=update.message.chat_id, text="Введите текст для задачи.", reply_markup=reply_markup) + context.bot.send_message(chat_id=update.message.chat_id, text="Введите текст для задачи.", + reply_markup=reply_markup) def back_callback(update, context): @@ -60,7 +67,8 @@ def get_today_tasks_callback(update, context): if db.is_auth(chat_id): response = gcalendar.get_today_tasks_list(chat_id) if not response: - context.bot.send_message(chat_id=chat_id, text="Ваш день сегодня свободен. Везет же)", reply_markup=get_menu()) + context.bot.send_message(chat_id=chat_id, text="Ваш день сегодня свободен. Везет же)", + reply_markup=get_menu()) else: text = "События на сегодня: \n" counter = 1 @@ -83,7 +91,7 @@ def login_callback(update, context): else: googleAuth = gauth.GoogleAuth(chat_id) reply_markup = telegram.ReplyKeyboardMarkup([["/login"]], resize_keyboard=True) - #TODO : strange behavior with /login twice + # TODO : strange behavior with /login twice context.bot.send_message(chat_id=chat_id, text=googleAuth.generate_url(), reply_markup=reply_markup) @@ -91,16 +99,20 @@ def start_callback(update, context): args = "".join(context.args) if args == "": reply_markup = telegram.ReplyKeyboardMarkup([["/login"]], resize_keyboard=True) - context.bot.send_message(chat_id=int(update.message.chat_id), text="Здравствуйте! Вам нужно войти в свой аккаунт Google для использования этого бота", reply_markup=reply_markup) + context.bot.send_message(chat_id=int(update.message.chat_id), + text="Здравствуйте! Вам нужно войти в свой аккаунт Google для использования этого бота", + reply_markup=reply_markup) else: db = database.Database() chat_id = args if db.is_auth(chat_id): context.bot.send_message(chat_id=int(chat_id), text="Вы успешно вошли в аккаунт", reply_markup=get_menu()) - context.job_queue.run_daily(daily_announce, datetime.time(hour=8, minute=0, second=0, tzinfo=pytz.timezone("Europe/Moscow"))) + context.job_queue.run_daily(daily_announce, datetime.time(hour=8, minute=0, second=0, + tzinfo=pytz.timezone("Europe/Moscow"))) else: reply_markup = telegram.ReplyKeyboardMarkup([["/login"]], resize_keyboard=True) - context.bot.send_message(chat_id=int(chat_id), text="Вам необходимо войти в аккаунт. Используйте /login", reply_markup=reply_markup) + context.bot.send_message(chat_id=int(chat_id), text="Вам необходимо войти в аккаунт. Используйте /login", + reply_markup=reply_markup) def daily_announce(bot, job): @@ -112,14 +124,14 @@ def daily_announce(bot, job): response = gcalendar.get_today_tasks_list(chat_id) if not response: bot.send_message(chat_id=chat_id, text="Ваш день сегодня свободен. Везет же)", - reply_markup=get_menu()) + reply_markup=get_menu()) else: text = "События на сегодня: \n" counter = 1 - #TODO: add enumerate + # TODO: add enumerate for event in response: - date = dateutil.parser.parse( event["start"].get("dateTime", event['start'].get('date'))) - text = text + str(counter) + ". {}:{}".format(date.time().hour, date.time().minute) + + "\n" + date = dateutil.parser.parse(event["start"].get("dateTime", event['start'].get('date'))) + text = text + str(counter) + ". {}:{}".format(date.time().hour, date.time().minute) + + "\n" text = text + event["summary"] + "\n" counter += 1 - bot.send_message(chat_id=chat_id, text=text, reply_markup=get_menu()) \ No newline at end of file + bot.send_message(chat_id=chat_id, text=text, reply_markup=get_menu()) diff --git a/client_secret.json b/client_secret.json deleted file mode 100644 index eeb6d3f..0000000 --- a/client_secret.json +++ /dev/null @@ -1 +0,0 @@ -{"web":{"client_id":"160369947774-dfnki1coiacp9qnu8mn7i4c51kfd0uft.apps.googleusercontent.com","project_id":"yet-another-task-bot","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://oauth2.googleapis.com/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_secret":"8Sh0_Qzc_HiM2vgKJ2sUJomc","redirect_uris":["https://server-for-task-bot.herokuapp.com/login"],"javascript_origins":["https://server-for-task-bot.herokuapp.com"]}} \ No newline at end of file diff --git a/database.py b/database.py index 3c17fdb..38384c6 100644 --- a/database.py +++ b/database.py @@ -1,5 +1,7 @@ -import psycopg2 +import logging import os + +import psycopg2 from psycopg2.extras import RealDictCursor @@ -10,8 +12,10 @@ def __new__(cls, *args, **kwargs): if cls.__instance is None: cls.__instance = super().__new__(cls, *args, **kwargs) DATABASE_URL = os.environ['DATABASE_URL'] - cls.__instance.conn = psycopg2.connect(DATABASE_URL, sslmode='require') - + try: + cls.__instance.conn = psycopg2.connect(DATABASE_URL, sslmode='require') + except ConnectionError: + logging.error("No database in DATABASE_URL environ") return cls.__instance def get_cred(self, chat_id): diff --git a/gauth.py b/gauth.py index f5ea060..3be9945 100644 --- a/gauth.py +++ b/gauth.py @@ -1,6 +1,4 @@ -import google.oauth2.credentials import google_auth_oauthlib.flow -import base64 class GoogleAuth: diff --git a/gcalendar.py b/gcalendar.py index 4196c3e..1321288 100644 --- a/gcalendar.py +++ b/gcalendar.py @@ -1,15 +1,18 @@ -import database +import datetime +import logging + import google.oauth2.credentials import googleapiclient.discovery -import datetime import pytz +import database + def get_today_tasks_list(chat_id): db = database.Database() creds_dict = db.get_cred(chat_id) del creds_dict["chat_id"] - print(creds_dict) + logging.info("Get new task list request{}".format(creds_dict)) credentials = google.oauth2.credentials.Credentials(**creds_dict) calendar = googleapiclient.discovery.build("calendar", "v3", credentials=credentials) # TODO: fix this for other UTC @@ -18,8 +21,8 @@ def get_today_tasks_list(chat_id): start_of_day = today.isoformat() + '+03:00' end = datetime.datetime.combine(datetime.date(date.year, date.month, date.day), datetime.datetime.max.time()) end_of_day = end.isoformat() + '+03:00' - print(start_of_day, end_of_day) - events_result = calendar.events().list(calendarId="primary", singleEvents=True, orderBy='startTime', timeMin=start_of_day, timeMax=end_of_day).execute() + events_result = calendar.events().list(calendarId="primary", singleEvents=True, orderBy='startTime', + timeMin=start_of_day, timeMax=end_of_day).execute() events = events_result.get('items', []) if not events: return False @@ -35,11 +38,11 @@ def set_new_task(chat_id, time, date, summary): calendar = googleapiclient.discovery.build("calendar", "v3", credentials=credentials) event = { 'summary': summary, - 'start' : { - 'dateTime' : date + "T" + time + ":00+03:00", - 'timeZone' : 'Europe/Moscow', + 'start': { + 'dateTime': date + "T" + time + ":00+03:00", + 'timeZone': 'Europe/Moscow', }, - 'end' : { + 'end': { 'dateTime': date + "T" + time + ":00+03:00", 'timeZone': 'Europe/Moscow', }, diff --git a/setup.py b/setup.py index c4d826a..20695fe 100644 --- a/setup.py +++ b/setup.py @@ -1,13 +1,19 @@ -import telegram.ext -import os import logging -from callbacks import text_callback, login_callback, start_callback, logout_callback, get_today_tasks_callback, plan_callback, cancel_callback +import os -logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', - level=logging.INFO) +import telegram.ext +from callbacks import text_callback, login_callback, start_callback, logout_callback, get_today_tasks_callback, \ + plan_callback, cancel_callback + +logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + level=logging.INFO) TOKEN = os.environ["TOKEN"] +SECRET_CLIENT = os.environ["SECRET_TOKEN"] +with open("client_secret.json", "w") as f: + print(SECRET_CLIENT, file=f) + PORT = int(os.environ.get('PORT', '8443')) updater = telegram.ext.Updater(token=TOKEN, use_context=True) dispatcher = updater.dispatcher @@ -22,7 +28,5 @@ updater.start_webhook(listen="0.0.0.0", port=PORT, url_path=TOKEN) - updater.bot.set_webhook("https://yet-another-task-bot.herokuapp.com/" + TOKEN) - -updater.idle() \ No newline at end of file +updater.idle()