From 07c0e82018f6617c6e84c32d249f851c889f9f37 Mon Sep 17 00:00:00 2001 From: Vlad Date: Fri, 14 May 2021 11:35:05 +0300 Subject: [PATCH 001/147] first commit --- bot.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/bot.py b/bot.py index 74d3d8b..b2df52b 100644 --- a/bot.py +++ b/bot.py @@ -8,7 +8,7 @@ level=logging.INFO) logger = logging.getLogger(__name__) -TOKEN = 'YOURTELEGRAMBOTTOKEN' +TOKEN = '1841783209:AAHrDitzlrEGtxSyCUgRr2oSl-vQsgBzPK8' # Define a few command handlers. These usually take the two arguments update and # context. Error handlers also receive the raised TelegramError object in error. @@ -52,7 +52,7 @@ def main(): updater.start_webhook(listen="0.0.0.0", port=int(PORT), url_path=TOKEN) - updater.bot.setWebhook('https://yourherokuappname.herokuapp.com/' + TOKEN) + updater.bot.setWebhook('https://frozen-scrubland-72051.herokuapp.com/' + TOKEN) # Run the bot until you press Ctrl-C or the process receives SIGINT, # SIGTERM or SIGABRT. This should be used most of the time, since From 8494f65f0a902e80c0c9530152c6d6e4b16690ae Mon Sep 17 00:00:00 2001 From: Vlad Date: Fri, 14 May 2021 13:59:15 +0300 Subject: [PATCH 002/147] add login function --- bot.py | 29 +++++++++++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/bot.py b/bot.py index b2df52b..dbea36c 100644 --- a/bot.py +++ b/bot.py @@ -9,9 +9,15 @@ logger = logging.getLogger(__name__) TOKEN = '1841783209:AAHrDitzlrEGtxSyCUgRr2oSl-vQsgBzPK8' +bot = '' +login = None +password = None +user = None + # Define a few command handlers. These usually take the two arguments update and # context. Error handlers also receive the raised TelegramError object in error. + def start(update, context): """Send a message when the command /start is issued.""" update.message.reply_text('Hi!') @@ -22,19 +28,38 @@ def help(update, context): def echo(update, context): """Echo the user message.""" - update.message.reply_text(update.message.text) + global user + if user == None: + login(update) + else: + update.message.reply_text('Авторизация прошла успешно') + + #update.message.reply_text(update.message.text) def error(update, context): """Log Errors caused by Updates.""" logger.warning('Update "%s" caused error "%s"', update, context.error) +def login(update): + global login + global password + global user + if login == None: + login = update.message.text + update.message.reply_text('Введите пароль') + else: + password = update.message.text + user = 'User' + update.message.reply_text('Авторизация прошла успешно') + def main(): """Start the bot.""" # Create the Updater and pass it your bot's token. # Make sure to set use_context=True to use the new context based callbacks # Post version 12 this will no longer be necessary updater = Updater(TOKEN, use_context=True) - + global bot + bot = updater.bot # Get the dispatcher to register handlers dp = updater.dispatcher From 58ba0af8d491fab5e098b1cb02ab36ac42542aa1 Mon Sep 17 00:00:00 2001 From: Vlad Date: Fri, 14 May 2021 14:04:36 +0300 Subject: [PATCH 003/147] change start message --- bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot.py b/bot.py index dbea36c..a40d2b4 100644 --- a/bot.py +++ b/bot.py @@ -20,7 +20,7 @@ def start(update, context): """Send a message when the command /start is issued.""" - update.message.reply_text('Hi!') + update.message.reply_text('Введите логин') def help(update, context): """Send a message when the command /help is issued.""" From 6a4748c8e543a342ee5b54b13224f001d0ad3308 Mon Sep 17 00:00:00 2001 From: Vlad Date: Fri, 14 May 2021 14:06:40 +0300 Subject: [PATCH 004/147] change aithorization message --- bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot.py b/bot.py index a40d2b4..054858b 100644 --- a/bot.py +++ b/bot.py @@ -32,7 +32,7 @@ def echo(update, context): if user == None: login(update) else: - update.message.reply_text('Авторизация прошла успешно') + update.message.reply_text('ты не должен видеть это сообщение') #update.message.reply_text(update.message.text) From 804cea178bf2e939f9315afe6dbce10dd9498acb Mon Sep 17 00:00:00 2001 From: Vlad Date: Fri, 14 May 2021 14:10:03 +0300 Subject: [PATCH 005/147] delete password tree --- bot.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/bot.py b/bot.py index 054858b..9853a6f 100644 --- a/bot.py +++ b/bot.py @@ -47,10 +47,7 @@ def login(update): if login == None: login = update.message.text update.message.reply_text('Введите пароль') - else: - password = update.message.text - user = 'User' - update.message.reply_text('Авторизация прошла успешно') + def main(): """Start the bot.""" From d4502a616381952e86b78f56b9c09ad0614fea0a Mon Sep 17 00:00:00 2001 From: Vlad Date: Fri, 14 May 2021 14:14:48 +0300 Subject: [PATCH 006/147] change login variable to username --- bot.py | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/bot.py b/bot.py index 9853a6f..7fb83fe 100644 --- a/bot.py +++ b/bot.py @@ -10,7 +10,7 @@ logger = logging.getLogger(__name__) TOKEN = '1841783209:AAHrDitzlrEGtxSyCUgRr2oSl-vQsgBzPK8' bot = '' -login = None +username = None password = None user = None @@ -41,13 +41,16 @@ def error(update, context): logger.warning('Update "%s" caused error "%s"', update, context.error) def login(update): - global login + global username global password global user - if login == None: - login = update.message.text + if username == None: + username = update.message.text update.message.reply_text('Введите пароль') - + else: + password = update.message.text + user = 'User' + update.message.reply_text('Авторизация прошла успешно') def main(): """Start the bot.""" From 14da3799d77e02c5bb917f84310aa7ab95eaf6d0 Mon Sep 17 00:00:00 2001 From: Vlad Date: Fri, 14 May 2021 14:37:48 +0300 Subject: [PATCH 007/147] connect to salesforce --- bot.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/bot.py b/bot.py index 7fb83fe..f567486 100644 --- a/bot.py +++ b/bot.py @@ -1,6 +1,14 @@ import logging from telegram.ext import Updater, CommandHandler, MessageHandler, Filters +from simple_salesforce import Salesforce import os + +sf = Salesforce( +username='max2433186@mindful-impala-acpsha.com', +password='JKlw124O2kanv5kLLf', +security_token='') +contact = sf.Contact.get('0035g000003X49iAAC') + PORT = int(os.environ.get('PORT', 5000)) # Enable logging @@ -20,7 +28,7 @@ def start(update, context): """Send a message when the command /start is issued.""" - update.message.reply_text('Введите логин') + update.message.reply_text(contact.Email) def help(update, context): """Send a message when the command /help is issued.""" From 2c846480c973555331dde9b11793e6387ed9e926 Mon Sep 17 00:00:00 2001 From: Vlad Date: Fri, 14 May 2021 14:54:57 +0300 Subject: [PATCH 008/147] change requirments.txt --- requirements.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/requirements.txt b/requirements.txt index 2e299b8..9123cc8 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1 +1,2 @@ python-telegram-bot==12.7 +simple_salesforce==1.11.1 \ No newline at end of file From dd461c3af686f8ffda67875a44f96837e4934f9b Mon Sep 17 00:00:00 2001 From: Vlad Date: Fri, 14 May 2021 15:03:45 +0300 Subject: [PATCH 009/147] delete security token --- bot.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/bot.py b/bot.py index f567486..55c0b0e 100644 --- a/bot.py +++ b/bot.py @@ -5,8 +5,7 @@ sf = Salesforce( username='max2433186@mindful-impala-acpsha.com', -password='JKlw124O2kanv5kLLf', -security_token='') +password='JKlw124O2kanv5kLLf') contact = sf.Contact.get('0035g000003X49iAAC') PORT = int(os.environ.get('PORT', 5000)) From 521df830fa11759ef5efa495a66176c0bf2a0585 Mon Sep 17 00:00:00 2001 From: Vlad Date: Fri, 14 May 2021 15:15:09 +0300 Subject: [PATCH 010/147] delete contact var --- bot.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/bot.py b/bot.py index 55c0b0e..dbd8062 100644 --- a/bot.py +++ b/bot.py @@ -5,8 +5,8 @@ sf = Salesforce( username='max2433186@mindful-impala-acpsha.com', -password='JKlw124O2kanv5kLLf') -contact = sf.Contact.get('0035g000003X49iAAC') +password='JKlw124O2kanv5kLLf', +security_token='') PORT = int(os.environ.get('PORT', 5000)) @@ -27,7 +27,8 @@ def start(update, context): """Send a message when the command /start is issued.""" - update.message.reply_text(contact.Email) + update.message.reply_text('Введите логин') + sf.Contact.create({'LastName':'simple_salesforce','Email':'example@example.com'}) def help(update, context): """Send a message when the command /help is issued.""" From 2d7e571152b59d3e36a2d3276a8baae2a4189afb Mon Sep 17 00:00:00 2001 From: Vlad Date: Fri, 14 May 2021 15:36:06 +0300 Subject: [PATCH 011/147] add class UserTelegram --- bot.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/bot.py b/bot.py index dbd8062..3b48c3c 100644 --- a/bot.py +++ b/bot.py @@ -21,13 +21,21 @@ password = None user = None +class UserTelegram: + def __init__(self, login, password, id): + self.login = login + self.password = password + self.id = id + +usersTelegram = [] # Define a few command handlers. These usually take the two arguments update and # context. Error handlers also receive the raised TelegramError object in error. def start(update, context): """Send a message when the command /start is issued.""" - update.message.reply_text('Введите логин') + + update.message.reply_text(update.message.from.id) sf.Contact.create({'LastName':'simple_salesforce','Email':'example@example.com'}) def help(update, context): From 31e780115e43c8492a0de39545d5a18a7f49b292 Mon Sep 17 00:00:00 2001 From: Vlad Date: Fri, 14 May 2021 15:39:27 +0300 Subject: [PATCH 012/147] change start message --- bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot.py b/bot.py index 3b48c3c..70405c8 100644 --- a/bot.py +++ b/bot.py @@ -35,7 +35,7 @@ def __init__(self, login, password, id): def start(update, context): """Send a message when the command /start is issued.""" - update.message.reply_text(update.message.from.id) + update.message.reply_text(update.update_id) sf.Contact.create({'LastName':'simple_salesforce','Email':'example@example.com'}) def help(update, context): From 57ceb85be1d6f71afae780b19b36df4d0f2591ed Mon Sep 17 00:00:00 2001 From: Vlad Date: Fri, 14 May 2021 15:41:48 +0300 Subject: [PATCH 013/147] update password message --- bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot.py b/bot.py index 70405c8..c27e844 100644 --- a/bot.py +++ b/bot.py @@ -62,7 +62,7 @@ def login(update): global user if username == None: username = update.message.text - update.message.reply_text('Введите пароль') + update.message.reply_text(update.update_id) else: password = update.message.text user = 'User' From ad2b95489d09c73d809d3d621ba04c9b6b7d69d2 Mon Sep 17 00:00:00 2001 From: Vlad Date: Fri, 14 May 2021 15:44:31 +0300 Subject: [PATCH 014/147] change login,password message --- bot.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/bot.py b/bot.py index c27e844..4380e31 100644 --- a/bot.py +++ b/bot.py @@ -35,7 +35,7 @@ def __init__(self, login, password, id): def start(update, context): """Send a message when the command /start is issued.""" - update.message.reply_text(update.update_id) + update.message.reply_text(update._effective_user.id) sf.Contact.create({'LastName':'simple_salesforce','Email':'example@example.com'}) def help(update, context): @@ -62,7 +62,7 @@ def login(update): global user if username == None: username = update.message.text - update.message.reply_text(update.update_id) + update.message.reply_text(update._effective_user.id) else: password = update.message.text user = 'User' From 23afe0ad377c365adb77ce3fb2e930610b0ab595 Mon Sep 17 00:00:00 2001 From: Vlad Date: Fri, 14 May 2021 15:46:52 +0300 Subject: [PATCH 015/147] change login,password message --- bot.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/bot.py b/bot.py index 4380e31..a315cf3 100644 --- a/bot.py +++ b/bot.py @@ -35,7 +35,7 @@ def __init__(self, login, password, id): def start(update, context): """Send a message when the command /start is issued.""" - update.message.reply_text(update._effective_user.id) + update.message.reply_text('Введите логин') sf.Contact.create({'LastName':'simple_salesforce','Email':'example@example.com'}) def help(update, context): @@ -62,7 +62,7 @@ def login(update): global user if username == None: username = update.message.text - update.message.reply_text(update._effective_user.id) + update.message.reply_text('Введите пароль') else: password = update.message.text user = 'User' From 9c0d1a412406ae644c54efea0a98d8671590f04b Mon Sep 17 00:00:00 2001 From: Vlad Date: Fri, 14 May 2021 16:03:22 +0300 Subject: [PATCH 016/147] add usersTelegram --- bot.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/bot.py b/bot.py index a315cf3..253c9b2 100644 --- a/bot.py +++ b/bot.py @@ -22,12 +22,11 @@ user = None class UserTelegram: - def __init__(self, login, password, id): + def __init__(self, login, password): self.login = login self.password = password - self.id = id -usersTelegram = [] +usersTelegram = {} # Define a few command handlers. These usually take the two arguments update and # context. Error handlers also receive the raised TelegramError object in error. @@ -35,8 +34,11 @@ def __init__(self, login, password, id): def start(update, context): """Send a message when the command /start is issued.""" - update.message.reply_text('Введите логин') - sf.Contact.create({'LastName':'simple_salesforce','Email':'example@example.com'}) + if update._effective_user.id not in usersTelegram: + update.message.reply_text('Введите логин') + else: + update.message.reply_text('Вы уже зарегистрированы!') + # sf.Contact.create({'LastName':'simple_salesforce','Email':'example@example.com'}) def help(update, context): """Send a message when the command /help is issued.""" From e3b1f1e70984d541d4fc833c76b67324aeb067a4 Mon Sep 17 00:00:00 2001 From: Vlad Date: Fri, 14 May 2021 16:19:59 +0300 Subject: [PATCH 017/147] change usrname password global var on object var --- bot.py | 29 ++++++++++++++++++----------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/bot.py b/bot.py index 253c9b2..fa63523 100644 --- a/bot.py +++ b/bot.py @@ -25,6 +25,7 @@ class UserTelegram: def __init__(self, login, password): self.login = login self.password = password + self.exist = False usersTelegram = {} @@ -33,8 +34,9 @@ def __init__(self, login, password): def start(update, context): """Send a message when the command /start is issued.""" - - if update._effective_user.id not in usersTelegram: + userId = update._effective_user.id + createUserIfItNeed(userId) + if usersTelegram[userId].exist == False: update.message.reply_text('Введите логин') else: update.message.reply_text('Вы уже зарегистрированы!') @@ -46,8 +48,9 @@ def help(update, context): def echo(update, context): """Echo the user message.""" - global user - if user == None: + userId = update._effective_user.id + createUserIfItNeed(userId) + if usersTelegram[userId].exist == False: login(update) else: update.message.reply_text('ты не должен видеть это сообщение') @@ -59,17 +62,21 @@ def error(update, context): logger.warning('Update "%s" caused error "%s"', update, context.error) def login(update): - global username - global password - global user - if username == None: - username = update.message.text + userId = update._effective_user.id + user = usersTelegram[userId] + + if user.login == None: + user.login = update.message.text update.message.reply_text('Введите пароль') else: - password = update.message.text - user = 'User' + user.password = update.message.text + user.exist = True update.message.reply_text('Авторизация прошла успешно') +def createUserIfItNeed(userId): + if userId not in usersTelegram: + usersTelegram[userId] = UserTelegram(None,None) + def main(): """Start the bot.""" # Create the Updater and pass it your bot's token. From 8dcad13e3d3ee3e10bb322c6bb0bafbe0123d6ab Mon Sep 17 00:00:00 2001 From: Vlad Date: Fri, 14 May 2021 16:26:56 +0300 Subject: [PATCH 018/147] add bool isUserLog --- bot.py | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/bot.py b/bot.py index fa63523..eee2094 100644 --- a/bot.py +++ b/bot.py @@ -17,9 +17,6 @@ logger = logging.getLogger(__name__) TOKEN = '1841783209:AAHrDitzlrEGtxSyCUgRr2oSl-vQsgBzPK8' bot = '' -username = None -password = None -user = None class UserTelegram: def __init__(self, login, password): @@ -36,10 +33,11 @@ def start(update, context): """Send a message when the command /start is issued.""" userId = update._effective_user.id createUserIfItNeed(userId) - if usersTelegram[userId].exist == False: - update.message.reply_text('Введите логин') - else: + isUserLog = not usersTelegram[userId].exist + if isUserLog: update.message.reply_text('Вы уже зарегистрированы!') + else: + update.message.reply_text('Введите логин') # sf.Contact.create({'LastName':'simple_salesforce','Email':'example@example.com'}) def help(update, context): From e6a519f7b22c5429e11f4209427091c0470a7547 Mon Sep 17 00:00:00 2001 From: Vlad Date: Fri, 14 May 2021 16:29:25 +0300 Subject: [PATCH 019/147] remove not in isUserLog --- bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot.py b/bot.py index eee2094..f18ed32 100644 --- a/bot.py +++ b/bot.py @@ -33,7 +33,7 @@ def start(update, context): """Send a message when the command /start is issued.""" userId = update._effective_user.id createUserIfItNeed(userId) - isUserLog = not usersTelegram[userId].exist + isUserLog = usersTelegram[userId].exist if isUserLog: update.message.reply_text('Вы уже зарегистрированы!') else: From 49e8a1a6c68ec7cd590f72ef6b9e0b0f37e512d3 Mon Sep 17 00:00:00 2001 From: Vlad Date: Fri, 14 May 2021 16:37:30 +0300 Subject: [PATCH 020/147] add end function --- bot.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/bot.py b/bot.py index f18ed32..bfcc3ce 100644 --- a/bot.py +++ b/bot.py @@ -55,6 +55,12 @@ def echo(update, context): #update.message.reply_text(update.message.text) +def end(update, context): + """Send a message when the command /help is issued.""" + userId = update._effective_user.id + usersTelegram.pop(userId) + update.message.reply_text('Good Bye!') + def error(update, context): """Log Errors caused by Updates.""" logger.warning('Update "%s" caused error "%s"', update, context.error) From 0c271df3365433b2360f9321e2769ceba4bd5cf0 Mon Sep 17 00:00:00 2001 From: Vlad Date: Fri, 14 May 2021 16:44:57 +0300 Subject: [PATCH 021/147] change end function on cancel --- bot.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/bot.py b/bot.py index bfcc3ce..f9e6c13 100644 --- a/bot.py +++ b/bot.py @@ -55,8 +55,7 @@ def echo(update, context): #update.message.reply_text(update.message.text) -def end(update, context): - """Send a message when the command /help is issued.""" +def cancel(update, context): userId = update._effective_user.id usersTelegram.pop(userId) update.message.reply_text('Good Bye!') From 86a357ac711771fb2281ed1cdc43071a6783bc5b Mon Sep 17 00:00:00 2001 From: Vlad Date: Fri, 14 May 2021 16:55:49 +0300 Subject: [PATCH 022/147] change place end function --- bot.py | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/bot.py b/bot.py index f9e6c13..34c2803 100644 --- a/bot.py +++ b/bot.py @@ -40,6 +40,9 @@ def start(update, context): update.message.reply_text('Введите логин') # sf.Contact.create({'LastName':'simple_salesforce','Email':'example@example.com'}) +def end(update, context): + update.message.reply_text('Good Bye!') + def help(update, context): """Send a message when the command /help is issued.""" update.message.reply_text('Help!') @@ -55,11 +58,6 @@ def echo(update, context): #update.message.reply_text(update.message.text) -def cancel(update, context): - userId = update._effective_user.id - usersTelegram.pop(userId) - update.message.reply_text('Good Bye!') - def error(update, context): """Log Errors caused by Updates.""" logger.warning('Update "%s" caused error "%s"', update, context.error) From a954bfe31242a035f864efe1e64265ed1df37f97 Mon Sep 17 00:00:00 2001 From: Vlad Date: Fri, 14 May 2021 16:58:49 +0300 Subject: [PATCH 023/147] add comment for end function --- bot.py | 1 + 1 file changed, 1 insertion(+) diff --git a/bot.py b/bot.py index 34c2803..18ef35e 100644 --- a/bot.py +++ b/bot.py @@ -41,6 +41,7 @@ def start(update, context): # sf.Contact.create({'LastName':'simple_salesforce','Email':'example@example.com'}) def end(update, context): + """Send a message when the command /end is issued.""" update.message.reply_text('Good Bye!') def help(update, context): From 80d615fdcb80d880c8fc784cee6465b93a54ed2c Mon Sep 17 00:00:00 2001 From: Vlad Date: Fri, 14 May 2021 17:14:41 +0300 Subject: [PATCH 024/147] add end in echo function --- bot.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/bot.py b/bot.py index 18ef35e..01a1ca5 100644 --- a/bot.py +++ b/bot.py @@ -40,10 +40,6 @@ def start(update, context): update.message.reply_text('Введите логин') # sf.Contact.create({'LastName':'simple_salesforce','Email':'example@example.com'}) -def end(update, context): - """Send a message when the command /end is issued.""" - update.message.reply_text('Good Bye!') - def help(update, context): """Send a message when the command /help is issued.""" update.message.reply_text('Help!') @@ -51,9 +47,15 @@ def help(update, context): def echo(update, context): """Echo the user message.""" userId = update._effective_user.id - createUserIfItNeed(userId) + + if usersTelegram not in userId: + start(update,context) + + message = update.message.text.lower() if usersTelegram[userId].exist == False: login(update) + elif message == '/bye' or message == '/end': + usersTelegram.pop(userId) else: update.message.reply_text('ты не должен видеть это сообщение') From d85847cd941241501c9baa9cc0df6978950a8113 Mon Sep 17 00:00:00 2001 From: Vlad Date: Fri, 14 May 2021 17:18:38 +0300 Subject: [PATCH 025/147] change if in echo --- bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot.py b/bot.py index 01a1ca5..7323867 100644 --- a/bot.py +++ b/bot.py @@ -48,7 +48,7 @@ def echo(update, context): """Echo the user message.""" userId = update._effective_user.id - if usersTelegram not in userId: + if userId not in usersTelegram: start(update,context) message = update.message.text.lower() From b3d183d67ef0e7e9e603f66f6b49a2acae6a9343 Mon Sep 17 00:00:00 2001 From: Vlad Date: Fri, 14 May 2021 17:24:50 +0300 Subject: [PATCH 026/147] add return in echo --- bot.py | 1 + 1 file changed, 1 insertion(+) diff --git a/bot.py b/bot.py index 7323867..1e39f44 100644 --- a/bot.py +++ b/bot.py @@ -50,6 +50,7 @@ def echo(update, context): if userId not in usersTelegram: start(update,context) + return message = update.message.text.lower() if usersTelegram[userId].exist == False: From e129b5be08672dae3b4696d67a1c406fc428ac1c Mon Sep 17 00:00:00 2001 From: Vlad Date: Fri, 14 May 2021 17:33:16 +0300 Subject: [PATCH 027/147] delete run start function in echo --- bot.py | 1 - 1 file changed, 1 deletion(-) diff --git a/bot.py b/bot.py index 1e39f44..a16a6f2 100644 --- a/bot.py +++ b/bot.py @@ -49,7 +49,6 @@ def echo(update, context): userId = update._effective_user.id if userId not in usersTelegram: - start(update,context) return message = update.message.text.lower() From 76d053bce1a33d74eb2117125f2663a38d60fc56 Mon Sep 17 00:00:00 2001 From: Vlad Date: Fri, 14 May 2021 17:38:22 +0300 Subject: [PATCH 028/147] add invoke start in echo --- bot.py | 1 + 1 file changed, 1 insertion(+) diff --git a/bot.py b/bot.py index a16a6f2..1e39f44 100644 --- a/bot.py +++ b/bot.py @@ -49,6 +49,7 @@ def echo(update, context): userId = update._effective_user.id if userId not in usersTelegram: + start(update,context) return message = update.message.text.lower() From dd18105b66ff1f680b9fa6109989a8682459ba06 Mon Sep 17 00:00:00 2001 From: Vlad Date: Sat, 15 May 2021 11:04:40 +0300 Subject: [PATCH 029/147] filled contact fill in userTelegram object in login function --- bot.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/bot.py b/bot.py index 1e39f44..6ec0408 100644 --- a/bot.py +++ b/bot.py @@ -23,6 +23,7 @@ def __init__(self, login, password): self.login = login self.password = password self.exist = False + self.contact = None usersTelegram = {} @@ -76,7 +77,8 @@ def login(update): else: user.password = update.message.text user.exist = True - update.message.reply_text('Авторизация прошла успешно') + user.contact = sf.query("SELECT Id, Email FROM Contact WHERE Email = 'worker2@gmail.com'") + update.message.reply_text('Авторизация прошла успешно ' + contact) def createUserIfItNeed(userId): if userId not in usersTelegram: From e216f26d0acc8143aa1e10057eb66a762afbb90e Mon Sep 17 00:00:00 2001 From: Vlad Date: Sat, 15 May 2021 11:05:46 +0300 Subject: [PATCH 030/147] change 'contact' on 'user.contact' --- bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot.py b/bot.py index 6ec0408..d62ec04 100644 --- a/bot.py +++ b/bot.py @@ -78,7 +78,7 @@ def login(update): user.password = update.message.text user.exist = True user.contact = sf.query("SELECT Id, Email FROM Contact WHERE Email = 'worker2@gmail.com'") - update.message.reply_text('Авторизация прошла успешно ' + contact) + update.message.reply_text('Авторизация прошла успешно ' + user.contact) def createUserIfItNeed(userId): if userId not in usersTelegram: From 8b33a2358bc92cf71c8b202d95164c0296332835 Mon Sep 17 00:00:00 2001 From: Vlad Date: Sat, 15 May 2021 11:15:05 +0300 Subject: [PATCH 031/147] add str(user.contact) in login --- bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot.py b/bot.py index d62ec04..bbd16f2 100644 --- a/bot.py +++ b/bot.py @@ -78,7 +78,7 @@ def login(update): user.password = update.message.text user.exist = True user.contact = sf.query("SELECT Id, Email FROM Contact WHERE Email = 'worker2@gmail.com'") - update.message.reply_text('Авторизация прошла успешно ' + user.contact) + update.message.reply_text('Авторизация прошла успешно ' + str(user.contact)) def createUserIfItNeed(userId): if userId not in usersTelegram: From c825d0a3a255beee88afc4a4380e791fe10e3e7e Mon Sep 17 00:00:00 2001 From: Vlad Date: Sat, 15 May 2021 11:27:39 +0300 Subject: [PATCH 032/147] get email in contact --- bot.py | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/bot.py b/bot.py index bbd16f2..9cbea2c 100644 --- a/bot.py +++ b/bot.py @@ -78,7 +78,7 @@ def login(update): user.password = update.message.text user.exist = True user.contact = sf.query("SELECT Id, Email FROM Contact WHERE Email = 'worker2@gmail.com'") - update.message.reply_text('Авторизация прошла успешно ' + str(user.contact)) + update.message.reply_text('Авторизация прошла успешно ' + str(user.contact['records']['Email'])) def createUserIfItNeed(userId): if userId not in usersTelegram: @@ -117,4 +117,13 @@ def main(): updater.idle() if __name__ == '__main__': - main() \ No newline at end of file + main() + # OrderedDict([ + # ('totalSize', 1), + # ('done', True), + # ('records', [OrderedDict([ + # ('attributes', OrderedDict([ + # ('type', 'Contact'), + # ('url', '/services/data/v42.0/sobjects/Contact/0035g000003X49iAAC')])), + # ('Id', '0035g000003X49iAAC'), + # ('Email', 'worker2@gmail.com')])])]) \ No newline at end of file From 4009e2e1b6165901e5eff143041e822ba6db51b0 Mon Sep 17 00:00:00 2001 From: Vlad Date: Sat, 15 May 2021 11:29:54 +0300 Subject: [PATCH 033/147] delete get email --- bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot.py b/bot.py index 9cbea2c..c5dd4be 100644 --- a/bot.py +++ b/bot.py @@ -78,7 +78,7 @@ def login(update): user.password = update.message.text user.exist = True user.contact = sf.query("SELECT Id, Email FROM Contact WHERE Email = 'worker2@gmail.com'") - update.message.reply_text('Авторизация прошла успешно ' + str(user.contact['records']['Email'])) + update.message.reply_text('Авторизация прошла успешно ' + str(user.contact['records'])) def createUserIfItNeed(userId): if userId not in usersTelegram: From e77b5fe7ff97161bf20941be6a06c50fecf15723 Mon Sep 17 00:00:00 2001 From: Vlad Date: Sat, 15 May 2021 11:32:34 +0300 Subject: [PATCH 034/147] login function get attributes --- bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot.py b/bot.py index c5dd4be..7d80193 100644 --- a/bot.py +++ b/bot.py @@ -78,7 +78,7 @@ def login(update): user.password = update.message.text user.exist = True user.contact = sf.query("SELECT Id, Email FROM Contact WHERE Email = 'worker2@gmail.com'") - update.message.reply_text('Авторизация прошла успешно ' + str(user.contact['records'])) + update.message.reply_text('Авторизация прошла успешно ' + str(user.contact['records']['attributes'])) def createUserIfItNeed(userId): if userId not in usersTelegram: From 2e2a11b2c7a159a365b2cb6d1dd2977dbde59f54 Mon Sep 17 00:00:00 2001 From: Vlad Date: Sat, 15 May 2021 11:36:32 +0300 Subject: [PATCH 035/147] get one record in login func --- bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot.py b/bot.py index 7d80193..0acdfcb 100644 --- a/bot.py +++ b/bot.py @@ -78,7 +78,7 @@ def login(update): user.password = update.message.text user.exist = True user.contact = sf.query("SELECT Id, Email FROM Contact WHERE Email = 'worker2@gmail.com'") - update.message.reply_text('Авторизация прошла успешно ' + str(user.contact['records']['attributes'])) + update.message.reply_text('Авторизация прошла успешно ' + str(user.contact['records'][0])) def createUserIfItNeed(userId): if userId not in usersTelegram: From 50b0129d0620dfb8328c5e122beeb9fc1bded205 Mon Sep 17 00:00:00 2001 From: Vlad Date: Sat, 15 May 2021 11:42:51 +0300 Subject: [PATCH 036/147] get email in login func --- bot.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/bot.py b/bot.py index 0acdfcb..0652370 100644 --- a/bot.py +++ b/bot.py @@ -78,7 +78,7 @@ def login(update): user.password = update.message.text user.exist = True user.contact = sf.query("SELECT Id, Email FROM Contact WHERE Email = 'worker2@gmail.com'") - update.message.reply_text('Авторизация прошла успешно ' + str(user.contact['records'][0])) + update.message.reply_text('Авторизация прошла успешно ' + str(user.contact['records'][0]['Email'])) def createUserIfItNeed(userId): if userId not in usersTelegram: @@ -126,4 +126,11 @@ def main(): # ('type', 'Contact'), # ('url', '/services/data/v42.0/sobjects/Contact/0035g000003X49iAAC')])), # ('Id', '0035g000003X49iAAC'), - # ('Email', 'worker2@gmail.com')])])]) \ No newline at end of file + # ('Email', 'worker2@gmail.com')])])]) + + # OrderedDict([ + # ('attributes', OrderedDict([ + # ('type', 'Contact'), + # ('url', '/services/data/v42.0/sobjects/Contact/0035g000003X49iAAC')])), + # ('Id', '0035g000003X49iAAC'), + # ('Email', 'worker2@gmail.com')]) \ No newline at end of file From 70eb648edc5a89d0f8fb146ce2babeed4ffa282e Mon Sep 17 00:00:00 2001 From: Vlad Date: Sat, 15 May 2021 12:15:56 +0300 Subject: [PATCH 037/147] change query to incorect --- bot.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/bot.py b/bot.py index 0652370..62549f4 100644 --- a/bot.py +++ b/bot.py @@ -77,8 +77,8 @@ def login(update): else: user.password = update.message.text user.exist = True - user.contact = sf.query("SELECT Id, Email FROM Contact WHERE Email = 'worker2@gmail.com'") - update.message.reply_text('Авторизация прошла успешно ' + str(user.contact['records'][0]['Email'])) + user.contact = sf.query("SELECT Id, Email, FROM Contact WHERE Email = 'workasfaer2@gmail.com'") + update.message.reply_text('Авторизация прошла успешно ' + str(user.contact)) def createUserIfItNeed(userId): if userId not in usersTelegram: From 385ed956caea23025bdae32bbb0ef42715abab9c Mon Sep 17 00:00:00 2001 From: Vlad Date: Sat, 15 May 2021 12:21:17 +0300 Subject: [PATCH 038/147] add reply about incorrect login --- bot.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/bot.py b/bot.py index 62549f4..837891f 100644 --- a/bot.py +++ b/bot.py @@ -78,7 +78,11 @@ def login(update): user.password = update.message.text user.exist = True user.contact = sf.query("SELECT Id, Email, FROM Contact WHERE Email = 'workasfaer2@gmail.com'") - update.message.reply_text('Авторизация прошла успешно ' + str(user.contact)) + x = bool(user.contact) + if bool: + update.message.reply_text('Авторизация прошла успешно ' + str(user.contact)) + else: + update.message.reply_text('Неправильный логин или пароль.Попробуйте Снова') def createUserIfItNeed(userId): if userId not in usersTelegram: From 923498705abd82ff750cd716c701fe8d3a5c5dcb Mon Sep 17 00:00:00 2001 From: Vlad Date: Sat, 15 May 2021 12:25:56 +0300 Subject: [PATCH 039/147] change if else to try except --- bot.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/bot.py b/bot.py index 837891f..eee4ae8 100644 --- a/bot.py +++ b/bot.py @@ -77,12 +77,16 @@ def login(update): else: user.password = update.message.text user.exist = True - user.contact = sf.query("SELECT Id, Email, FROM Contact WHERE Email = 'workasfaer2@gmail.com'") - x = bool(user.contact) - if bool: + try: + user.contact = sf.query("SELECT Id, Email, FROM Contact WHERE Email = 'workasfaer2@gmail.com'") update.message.reply_text('Авторизация прошла успешно ' + str(user.contact)) - else: + except Exception: update.message.reply_text('Неправильный логин или пароль.Попробуйте Снова') + # x = bool(user.contact) + # if bool: + # update.message.reply_text('Авторизация прошла успешно ' + str(user.contact)) + # else: + # update.message.reply_text('Неправильный логин или пароль.Попробуйте Снова') def createUserIfItNeed(userId): if userId not in usersTelegram: From ad7283324ebd7c6e218decfab3325c7b2ab0a165 Mon Sep 17 00:00:00 2001 From: Vlad Date: Sat, 15 May 2021 12:43:12 +0300 Subject: [PATCH 040/147] chage query for login --- bot.py | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/bot.py b/bot.py index eee4ae8..0af0a86 100644 --- a/bot.py +++ b/bot.py @@ -55,7 +55,7 @@ def echo(update, context): message = update.message.text.lower() if usersTelegram[userId].exist == False: - login(update) + login(update, context) elif message == '/bye' or message == '/end': usersTelegram.pop(userId) else: @@ -67,7 +67,7 @@ def error(update, context): """Log Errors caused by Updates.""" logger.warning('Update "%s" caused error "%s"', update, context.error) -def login(update): +def login(update, context): userId = update._effective_user.id user = usersTelegram[userId] @@ -76,12 +76,15 @@ def login(update): update.message.reply_text('Введите пароль') else: user.password = update.message.text - user.exist = True try: - user.contact = sf.query("SELECT Id, Email, FROM Contact WHERE Email = 'workasfaer2@gmail.com'") + user.contact = sf.query(f"SELECT Id, Name, Email, Office__c, Admin__c FROM Contact WHERE Email ='{user.login}' AND Password__c ='{user.password}' LIMIT 1") + user.exist = True update.message.reply_text('Авторизация прошла успешно ' + str(user.contact)) except Exception: update.message.reply_text('Неправильный логин или пароль.Попробуйте Снова') + refreshUser(user) + start(update,context) + return # x = bool(user.contact) # if bool: # update.message.reply_text('Авторизация прошла успешно ' + str(user.contact)) @@ -92,6 +95,12 @@ def createUserIfItNeed(userId): if userId not in usersTelegram: usersTelegram[userId] = UserTelegram(None,None) +def refreshUser(user): + user.login = None + user.password = None + user.exist = False + user.contact = None + def main(): """Start the bot.""" # Create the Updater and pass it your bot's token. From 70f08d608f69c8c1158a61318d81468f7a6e2e3e Mon Sep 17 00:00:00 2001 From: Vlad Date: Sat, 15 May 2021 12:52:45 +0300 Subject: [PATCH 041/147] add throw exception if contact empty --- bot.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/bot.py b/bot.py index 0af0a86..dda31d7 100644 --- a/bot.py +++ b/bot.py @@ -78,6 +78,7 @@ def login(update, context): user.password = update.message.text try: user.contact = sf.query(f"SELECT Id, Name, Email, Office__c, Admin__c FROM Contact WHERE Email ='{user.login}' AND Password__c ='{user.password}' LIMIT 1") + throwExceptionIfContactEmpty(user.contact) user.exist = True update.message.reply_text('Авторизация прошла успешно ' + str(user.contact)) except Exception: @@ -101,6 +102,11 @@ def refreshUser(user): user.exist = False user.contact = None +def throwExceptionIfContactEmpty(contact): + totalSize = int(contact['totalSize']) + if totalSize < 1: + raise Exception('Contact empty') + def main(): """Start the bot.""" # Create the Updater and pass it your bot's token. From b46b18b78ad893aefe443ffab846f2677cad9d75 Mon Sep 17 00:00:00 2001 From: Vlad Date: Sat, 15 May 2021 13:55:05 +0300 Subject: [PATCH 042/147] insert new bot --- bot.py | 417 +++++++++++++++++++++++++++++++++++++++------------------ 1 file changed, 284 insertions(+), 133 deletions(-) diff --git a/bot.py b/bot.py index dda31d7..8758479 100644 --- a/bot.py +++ b/bot.py @@ -1,132 +1,298 @@ +# import logging +# from telegram.ext import Updater, CommandHandler, MessageHandler, Filters +# from simple_salesforce import Salesforce +# import os + +# sf = Salesforce( +# username='max2433186@mindful-impala-acpsha.com', +# password='JKlw124O2kanv5kLLf', +# security_token='') + +# PORT = int(os.environ.get('PORT', 5000)) + +# # Enable logging +# logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', +# level=logging.INFO) + +# logger = logging.getLogger(__name__) +# TOKEN = '1841783209:AAHrDitzlrEGtxSyCUgRr2oSl-vQsgBzPK8' +# bot = '' + +# class UserTelegram: +# def __init__(self, login, password): +# self.login = login +# self.password = password +# self.exist = False +# self.contact = None + +# usersTelegram = {} + +# # Define a few command handlers. These usually take the two arguments update and +# # context. Error handlers also receive the raised TelegramError object in error. + +# def start(update, context): +# """Send a message when the command /start is issued.""" +# userId = update._effective_user.id +# createUserIfItNeed(userId) +# isUserLog = usersTelegram[userId].exist +# if isUserLog: +# update.message.reply_text('Вы уже зарегистрированы!') +# else: +# update.message.reply_text('Введите логин') +# # sf.Contact.create({'LastName':'simple_salesforce','Email':'example@example.com'}) + +# def help(update, context): +# """Send a message when the command /help is issued.""" +# update.message.reply_text('Help!') + +# def echo(update, context): +# """Echo the user message.""" +# userId = update._effective_user.id + +# if userId not in usersTelegram: +# start(update,context) +# return + +# message = update.message.text.lower() +# if usersTelegram[userId].exist == False: +# login(update, context) +# elif message == '/bye' or message == '/end': +# usersTelegram.pop(userId) +# else: +# update.message.reply_text('ты не должен видеть это сообщение') + +# #update.message.reply_text(update.message.text) + +# def error(update, context): +# """Log Errors caused by Updates.""" +# logger.warning('Update "%s" caused error "%s"', update, context.error) + +# def login(update, context): +# userId = update._effective_user.id +# user = usersTelegram[userId] + +# if user.login == None: +# user.login = update.message.text +# update.message.reply_text('Введите пароль') +# else: +# user.password = update.message.text +# try: +# user.contact = sf.query(f"SELECT Id, Name, Email, Office__c, Admin__c FROM Contact WHERE Email ='{user.login}' AND Password__c ='{user.password}' LIMIT 1") +# throwExceptionIfContactEmpty(user.contact) +# user.exist = True +# update.message.reply_text('Авторизация прошла успешно ' + str(user.contact)) +# except Exception: +# update.message.reply_text('Неправильный логин или пароль.Попробуйте Снова') +# refreshUser(user) +# start(update,context) +# return +# # x = bool(user.contact) +# # if bool: +# # update.message.reply_text('Авторизация прошла успешно ' + str(user.contact)) +# # else: +# # update.message.reply_text('Неправильный логин или пароль.Попробуйте Снова') + +# def createUserIfItNeed(userId): +# if userId not in usersTelegram: +# usersTelegram[userId] = UserTelegram(None,None) + +# def refreshUser(user): +# user.login = None +# user.password = None +# user.exist = False +# user.contact = None + +# def throwExceptionIfContactEmpty(contact): +# totalSize = int(contact['totalSize']) +# if totalSize < 1: +# raise Exception('Contact empty') + +# def main(): +# """Start the bot.""" +# # Create the Updater and pass it your bot's token. +# # Make sure to set use_context=True to use the new context based callbacks +# # Post version 12 this will no longer be necessary +# updater = Updater(TOKEN, use_context=True) +# global bot +# bot = updater.bot +# # Get the dispatcher to register handlers +# dp = updater.dispatcher + +# # on different commands - answer in Telegram +# dp.add_handler(CommandHandler("start", start)) +# dp.add_handler(CommandHandler("help", help)) + +# # on noncommand i.e message - echo the message on Telegram +# dp.add_handler(MessageHandler(Filters.text, echo)) + +# # log all errors +# dp.add_error_handler(error) + +# # Start the Bot +# updater.start_webhook(listen="0.0.0.0", +# port=int(PORT), +# url_path=TOKEN) +# updater.bot.setWebhook('https://frozen-scrubland-72051.herokuapp.com/' + TOKEN) + +# # Run the bot until you press Ctrl-C or the process receives SIGINT, +# # SIGTERM or SIGABRT. This should be used most of the time, since +# # start_polling() is non-blocking and will stop the bot gracefully. +# updater.idle() + +# if __name__ == '__main__': +# main() + # OrderedDict([ + # ('totalSize', 1), + # ('done', True), + # ('records', [OrderedDict([ + # ('attributes', OrderedDict([ + # ('type', 'Contact'), + # ('url', '/services/data/v42.0/sobjects/Contact/0035g000003X49iAAC')])), + # ('Id', '0035g000003X49iAAC'), + # ('Email', 'worker2@gmail.com')])])]) + + # OrderedDict([ + # ('attributes', OrderedDict([ + # ('type', 'Contact'), + # ('url', '/services/data/v42.0/sobjects/Contact/0035g000003X49iAAC')])), + # ('Id', '0035g000003X49iAAC'), + # ('Email', 'worker2@gmail.com')]) + + import logging -from telegram.ext import Updater, CommandHandler, MessageHandler, Filters -from simple_salesforce import Salesforce +from typing import Dict import os -sf = Salesforce( -username='max2433186@mindful-impala-acpsha.com', -password='JKlw124O2kanv5kLLf', -security_token='') +from telegram import ReplyKeyboardMarkup, Update, ReplyKeyboardRemove +from telegram.ext import ( + Updater, + CommandHandler, + MessageHandler, + Filters, + ConversationHandler, + CallbackContext, +) + PORT = int(os.environ.get('PORT', 5000)) +TOKEN = '1841783209:AAHrDitzlrEGtxSyCUgRr2oSl-vQsgBzPK8' # Enable logging -logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', - level=logging.INFO) +logging.basicConfig( + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO +) logger = logging.getLogger(__name__) -TOKEN = '1841783209:AAHrDitzlrEGtxSyCUgRr2oSl-vQsgBzPK8' -bot = '' - -class UserTelegram: - def __init__(self, login, password): - self.login = login - self.password = password - self.exist = False - self.contact = None - -usersTelegram = {} - -# Define a few command handlers. These usually take the two arguments update and -# context. Error handlers also receive the raised TelegramError object in error. - -def start(update, context): - """Send a message when the command /start is issued.""" - userId = update._effective_user.id - createUserIfItNeed(userId) - isUserLog = usersTelegram[userId].exist - if isUserLog: - update.message.reply_text('Вы уже зарегистрированы!') - else: - update.message.reply_text('Введите логин') - # sf.Contact.create({'LastName':'simple_salesforce','Email':'example@example.com'}) - -def help(update, context): - """Send a message when the command /help is issued.""" - update.message.reply_text('Help!') - -def echo(update, context): - """Echo the user message.""" - userId = update._effective_user.id - - if userId not in usersTelegram: - start(update,context) - return - - message = update.message.text.lower() - if usersTelegram[userId].exist == False: - login(update, context) - elif message == '/bye' or message == '/end': - usersTelegram.pop(userId) - else: - update.message.reply_text('ты не должен видеть это сообщение') - - #update.message.reply_text(update.message.text) - -def error(update, context): - """Log Errors caused by Updates.""" - logger.warning('Update "%s" caused error "%s"', update, context.error) - -def login(update, context): - userId = update._effective_user.id - user = usersTelegram[userId] - - if user.login == None: - user.login = update.message.text - update.message.reply_text('Введите пароль') - else: - user.password = update.message.text - try: - user.contact = sf.query(f"SELECT Id, Name, Email, Office__c, Admin__c FROM Contact WHERE Email ='{user.login}' AND Password__c ='{user.password}' LIMIT 1") - throwExceptionIfContactEmpty(user.contact) - user.exist = True - update.message.reply_text('Авторизация прошла успешно ' + str(user.contact)) - except Exception: - update.message.reply_text('Неправильный логин или пароль.Попробуйте Снова') - refreshUser(user) - start(update,context) - return - # x = bool(user.contact) - # if bool: - # update.message.reply_text('Авторизация прошла успешно ' + str(user.contact)) - # else: - # update.message.reply_text('Неправильный логин или пароль.Попробуйте Снова') - -def createUserIfItNeed(userId): - if userId not in usersTelegram: - usersTelegram[userId] = UserTelegram(None,None) - -def refreshUser(user): - user.login = None - user.password = None - user.exist = False - user.contact = None - -def throwExceptionIfContactEmpty(contact): - totalSize = int(contact['totalSize']) - if totalSize < 1: - raise Exception('Contact empty') - -def main(): - """Start the bot.""" + +CHOOSING, TYPING_REPLY, TYPING_CHOICE = range(3) + +reply_keyboard = [ + ['Age', 'Favourite colour'], + ['Number of siblings', 'Something else...'], + ['Done'], +] +markup = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True) + + +def facts_to_str(user_data: Dict[str, str]) -> str: + facts = list() + + for key, value in user_data.items(): + facts.append(f'{key} - {value}') + + return "\n".join(facts).join(['\n', '\n']) + + +def start(update: Update, _: CallbackContext) -> int: + update.message.reply_text( + "Hi! My name is Doctor Botter. I will hold a more complex conversation with you. " + "Why don't you tell me something about yourself?", + reply_markup=markup, + ) + + return CHOOSING + + +def regular_choice(update: Update, context: CallbackContext) -> int: + text = update.message.text + context.user_data['choice'] = text + update.message.reply_text(f'Your {text.lower()}? Yes, I would love to hear about that!') + + return TYPING_REPLY + + +def custom_choice(update: Update, _: CallbackContext) -> int: + update.message.reply_text( + 'Alright, please send me the category first, for example "Most impressive skill"' + ) + + return TYPING_CHOICE + + +def received_information(update: Update, context: CallbackContext) -> int: + user_data = context.user_data + text = update.message.text + category = user_data['choice'] + user_data[category] = text + del user_data['choice'] + + update.message.reply_text( + "Neat! Just so you know, this is what you already told me:" + f"{facts_to_str(user_data)} You can tell me more, or change your opinion" + " on something.", + reply_markup=markup, + ) + + return CHOOSING + + +def done(update: Update, context: CallbackContext) -> int: + user_data = context.user_data + if 'choice' in user_data: + del user_data['choice'] + + update.message.reply_text( + f"I learned these facts about you: {facts_to_str(user_data)}Until next time!", + reply_markup=ReplyKeyboardRemove(), + ) + + user_data.clear() + return ConversationHandler.END + + +def main() -> None: # Create the Updater and pass it your bot's token. - # Make sure to set use_context=True to use the new context based callbacks - # Post version 12 this will no longer be necessary - updater = Updater(TOKEN, use_context=True) - global bot - bot = updater.bot - # Get the dispatcher to register handlers - dp = updater.dispatcher + updater = Updater(TOKEN) - # on different commands - answer in Telegram - dp.add_handler(CommandHandler("start", start)) - dp.add_handler(CommandHandler("help", help)) + # Get the dispatcher to register handlers + dispatcher = updater.dispatcher - # on noncommand i.e message - echo the message on Telegram - dp.add_handler(MessageHandler(Filters.text, echo)) + # Add conversation handler with the states CHOOSING, TYPING_CHOICE and TYPING_REPLY + conv_handler = ConversationHandler( + entry_points=[CommandHandler('start', start)], + states={ + CHOOSING: [ + MessageHandler( + Filters.regex('^(Age|Favourite colour|Number of siblings)$'), regular_choice + ), + MessageHandler(Filters.regex('^Something else...$'), custom_choice), + ], + TYPING_CHOICE: [ + MessageHandler( + Filters.text & ~(Filters.command | Filters.regex('^Done$')), regular_choice + ) + ], + TYPING_REPLY: [ + MessageHandler( + Filters.text & ~(Filters.command | Filters.regex('^Done$')), + received_information, + ) + ], + }, + fallbacks=[MessageHandler(Filters.regex('^Done$'), done)], + ) - # log all errors - dp.add_error_handler(error) + dispatcher.add_handler(conv_handler) # Start the Bot updater.start_webhook(listen="0.0.0.0", @@ -139,21 +305,6 @@ def main(): # start_polling() is non-blocking and will stop the bot gracefully. updater.idle() -if __name__ == '__main__': - main() - # OrderedDict([ - # ('totalSize', 1), - # ('done', True), - # ('records', [OrderedDict([ - # ('attributes', OrderedDict([ - # ('type', 'Contact'), - # ('url', '/services/data/v42.0/sobjects/Contact/0035g000003X49iAAC')])), - # ('Id', '0035g000003X49iAAC'), - # ('Email', 'worker2@gmail.com')])])]) - # OrderedDict([ - # ('attributes', OrderedDict([ - # ('type', 'Contact'), - # ('url', '/services/data/v42.0/sobjects/Contact/0035g000003X49iAAC')])), - # ('Id', '0035g000003X49iAAC'), - # ('Email', 'worker2@gmail.com')]) \ No newline at end of file +if __name__ == '__main__': + main() \ No newline at end of file From cfe4c58a755f8e583cb1b64645b94f0b1aa00b5c Mon Sep 17 00:00:00 2001 From: Vlad Date: Sat, 15 May 2021 14:01:13 +0300 Subject: [PATCH 043/147] change place bot --- bot.py | 300 ++++++++++++++++++++++++++++----------------------------- 1 file changed, 150 insertions(+), 150 deletions(-) diff --git a/bot.py b/bot.py index 8758479..430428c 100644 --- a/bot.py +++ b/bot.py @@ -1,3 +1,153 @@ +import logging +from typing import Dict +import os + +from telegram import ReplyKeyboardMarkup, Update, ReplyKeyboardRemove +from telegram.ext import ( + Updater, + CommandHandler, + MessageHandler, + Filters, + ConversationHandler, + CallbackContext, +) + + +PORT = int(os.environ.get('PORT', 5000)) +TOKEN = '1841783209:AAHrDitzlrEGtxSyCUgRr2oSl-vQsgBzPK8' + +# Enable logging +logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + level=logging.INFO) + +logger = logging.getLogger(__name__) + +CHOOSING, TYPING_REPLY, TYPING_CHOICE = range(3) + +reply_keyboard = [ + ['Age', 'Favourite colour'], + ['Number of siblings', 'Something else...'], + ['Done'], +] +markup = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True) + + +def facts_to_str(user_data: Dict[str, str]) -> str: + facts = list() + + for key, value in user_data.items(): + facts.append(f'{key} - {value}') + + return "\n".join(facts).join(['\n', '\n']) + + +def start(update: Update, _: CallbackContext) -> int: + update.message.reply_text( + "Hi! My name is Doctor Botter. I will hold a more complex conversation with you. " + "Why don't you tell me something about yourself?", + reply_markup=markup, + ) + + return CHOOSING + + +def regular_choice(update: Update, context: CallbackContext) -> int: + text = update.message.text + context.user_data['choice'] = text + update.message.reply_text(f'Your {text.lower()}? Yes, I would love to hear about that!') + + return TYPING_REPLY + + +def custom_choice(update: Update, _: CallbackContext) -> int: + update.message.reply_text( + 'Alright, please send me the category first, for example "Most impressive skill"' + ) + + return TYPING_CHOICE + + +def received_information(update: Update, context: CallbackContext) -> int: + user_data = context.user_data + text = update.message.text + category = user_data['choice'] + user_data[category] = text + del user_data['choice'] + + update.message.reply_text( + "Neat! Just so you know, this is what you already told me:" + f"{facts_to_str(user_data)} You can tell me more, or change your opinion" + " on something.", + reply_markup=markup, + ) + + return CHOOSING + + +def done(update: Update, context: CallbackContext) -> int: + user_data = context.user_data + if 'choice' in user_data: + del user_data['choice'] + + update.message.reply_text( + f"I learned these facts about you: {facts_to_str(user_data)}Until next time!", + reply_markup=ReplyKeyboardRemove(), + ) + + user_data.clear() + return ConversationHandler.END + + +def main() -> None: + # Create the Updater and pass it your bot's token. + updater = Updater(TOKEN) + + # Get the dispatcher to register handlers + dispatcher = updater.dispatcher + + # Add conversation handler with the states CHOOSING, TYPING_CHOICE and TYPING_REPLY + conv_handler = ConversationHandler( + entry_points=[CommandHandler('start', start)], + states={ + CHOOSING: [ + MessageHandler( + Filters.regex('^(Age|Favourite colour|Number of siblings)$'), regular_choice + ), + MessageHandler(Filters.regex('^Something else...$'), custom_choice), + ], + TYPING_CHOICE: [ + MessageHandler( + Filters.text & ~(Filters.command | Filters.regex('^Done$')), regular_choice + ) + ], + TYPING_REPLY: [ + MessageHandler( + Filters.text & ~(Filters.command | Filters.regex('^Done$')), + received_information, + ) + ], + }, + fallbacks=[MessageHandler(Filters.regex('^Done$'), done)], + ) + + dispatcher.add_handler(conv_handler) + + # Start the Bot + updater.start_webhook(listen="0.0.0.0", + port=int(PORT), + url_path=TOKEN) + updater.bot.setWebhook('https://frozen-scrubland-72051.herokuapp.com/' + TOKEN) + + # Run the bot until you press Ctrl-C or the process receives SIGINT, + # SIGTERM or SIGABRT. This should be used most of the time, since + # start_polling() is non-blocking and will stop the bot gracefully. + updater.idle() + + +if __name__ == '__main__': + main() + + # import logging # from telegram.ext import Updater, CommandHandler, MessageHandler, Filters # from simple_salesforce import Salesforce @@ -158,153 +308,3 @@ # ('Id', '0035g000003X49iAAC'), # ('Email', 'worker2@gmail.com')]) - -import logging -from typing import Dict -import os - -from telegram import ReplyKeyboardMarkup, Update, ReplyKeyboardRemove -from telegram.ext import ( - Updater, - CommandHandler, - MessageHandler, - Filters, - ConversationHandler, - CallbackContext, -) - - -PORT = int(os.environ.get('PORT', 5000)) -TOKEN = '1841783209:AAHrDitzlrEGtxSyCUgRr2oSl-vQsgBzPK8' - -# Enable logging -logging.basicConfig( - format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO -) - -logger = logging.getLogger(__name__) - -CHOOSING, TYPING_REPLY, TYPING_CHOICE = range(3) - -reply_keyboard = [ - ['Age', 'Favourite colour'], - ['Number of siblings', 'Something else...'], - ['Done'], -] -markup = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True) - - -def facts_to_str(user_data: Dict[str, str]) -> str: - facts = list() - - for key, value in user_data.items(): - facts.append(f'{key} - {value}') - - return "\n".join(facts).join(['\n', '\n']) - - -def start(update: Update, _: CallbackContext) -> int: - update.message.reply_text( - "Hi! My name is Doctor Botter. I will hold a more complex conversation with you. " - "Why don't you tell me something about yourself?", - reply_markup=markup, - ) - - return CHOOSING - - -def regular_choice(update: Update, context: CallbackContext) -> int: - text = update.message.text - context.user_data['choice'] = text - update.message.reply_text(f'Your {text.lower()}? Yes, I would love to hear about that!') - - return TYPING_REPLY - - -def custom_choice(update: Update, _: CallbackContext) -> int: - update.message.reply_text( - 'Alright, please send me the category first, for example "Most impressive skill"' - ) - - return TYPING_CHOICE - - -def received_information(update: Update, context: CallbackContext) -> int: - user_data = context.user_data - text = update.message.text - category = user_data['choice'] - user_data[category] = text - del user_data['choice'] - - update.message.reply_text( - "Neat! Just so you know, this is what you already told me:" - f"{facts_to_str(user_data)} You can tell me more, or change your opinion" - " on something.", - reply_markup=markup, - ) - - return CHOOSING - - -def done(update: Update, context: CallbackContext) -> int: - user_data = context.user_data - if 'choice' in user_data: - del user_data['choice'] - - update.message.reply_text( - f"I learned these facts about you: {facts_to_str(user_data)}Until next time!", - reply_markup=ReplyKeyboardRemove(), - ) - - user_data.clear() - return ConversationHandler.END - - -def main() -> None: - # Create the Updater and pass it your bot's token. - updater = Updater(TOKEN) - - # Get the dispatcher to register handlers - dispatcher = updater.dispatcher - - # Add conversation handler with the states CHOOSING, TYPING_CHOICE and TYPING_REPLY - conv_handler = ConversationHandler( - entry_points=[CommandHandler('start', start)], - states={ - CHOOSING: [ - MessageHandler( - Filters.regex('^(Age|Favourite colour|Number of siblings)$'), regular_choice - ), - MessageHandler(Filters.regex('^Something else...$'), custom_choice), - ], - TYPING_CHOICE: [ - MessageHandler( - Filters.text & ~(Filters.command | Filters.regex('^Done$')), regular_choice - ) - ], - TYPING_REPLY: [ - MessageHandler( - Filters.text & ~(Filters.command | Filters.regex('^Done$')), - received_information, - ) - ], - }, - fallbacks=[MessageHandler(Filters.regex('^Done$'), done)], - ) - - dispatcher.add_handler(conv_handler) - - # Start the Bot - updater.start_webhook(listen="0.0.0.0", - port=int(PORT), - url_path=TOKEN) - updater.bot.setWebhook('https://frozen-scrubland-72051.herokuapp.com/' + TOKEN) - - # Run the bot until you press Ctrl-C or the process receives SIGINT, - # SIGTERM or SIGABRT. This should be used most of the time, since - # start_polling() is non-blocking and will stop the bot gracefully. - updater.idle() - - -if __name__ == '__main__': - main() \ No newline at end of file From 0f2621b8d01208871d1e46bd9c1247382f6850a6 Mon Sep 17 00:00:00 2001 From: Vlad Date: Sat, 15 May 2021 14:04:57 +0300 Subject: [PATCH 044/147] on old bot --- bot.py | 494 +++++++++++++++++++++++++++++---------------------------- 1 file changed, 248 insertions(+), 246 deletions(-) diff --git a/bot.py b/bot.py index 430428c..1f4ec2c 100644 --- a/bot.py +++ b/bot.py @@ -1,296 +1,298 @@ -import logging -from typing import Dict -import os +# import logging +# from typing import Dict +# import os -from telegram import ReplyKeyboardMarkup, Update, ReplyKeyboardRemove -from telegram.ext import ( - Updater, - CommandHandler, - MessageHandler, - Filters, - ConversationHandler, - CallbackContext, -) +# from telegram import ReplyKeyboardMarkup, Update, ReplyKeyboardRemove +# from telegram.ext import ( +# Updater, +# CommandHandler, +# MessageHandler, +# Filters, +# ConversationHandler, +# CallbackContext, +# ) -PORT = int(os.environ.get('PORT', 5000)) -TOKEN = '1841783209:AAHrDitzlrEGtxSyCUgRr2oSl-vQsgBzPK8' +# PORT = int(os.environ.get('PORT', 5000)) +# TOKEN = '1841783209:AAHrDitzlrEGtxSyCUgRr2oSl-vQsgBzPK8' -# Enable logging -logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', - level=logging.INFO) +# # Enable logging +# logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', +# level=logging.INFO) -logger = logging.getLogger(__name__) +# logger = logging.getLogger(__name__) -CHOOSING, TYPING_REPLY, TYPING_CHOICE = range(3) +# CHOOSING, TYPING_REPLY, TYPING_CHOICE = range(3) -reply_keyboard = [ - ['Age', 'Favourite colour'], - ['Number of siblings', 'Something else...'], - ['Done'], -] -markup = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True) +# reply_keyboard = [ +# ['Age', 'Favourite colour'], +# ['Number of siblings', 'Something else...'], +# ['Done'], +# ] +# markup = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True) -def facts_to_str(user_data: Dict[str, str]) -> str: - facts = list() +# def facts_to_str(user_data: Dict[str, str]) -> str: +# facts = list() - for key, value in user_data.items(): - facts.append(f'{key} - {value}') +# for key, value in user_data.items(): +# facts.append(f'{key} - {value}') - return "\n".join(facts).join(['\n', '\n']) +# return "\n".join(facts).join(['\n', '\n']) -def start(update: Update, _: CallbackContext) -> int: - update.message.reply_text( - "Hi! My name is Doctor Botter. I will hold a more complex conversation with you. " - "Why don't you tell me something about yourself?", - reply_markup=markup, - ) +# def start(update: Update, _: CallbackContext) -> int: +# update.message.reply_text( +# "Hi! My name is Doctor Botter. I will hold a more complex conversation with you. " +# "Why don't you tell me something about yourself?", +# reply_markup=markup, +# ) - return CHOOSING +# return CHOOSING -def regular_choice(update: Update, context: CallbackContext) -> int: - text = update.message.text - context.user_data['choice'] = text - update.message.reply_text(f'Your {text.lower()}? Yes, I would love to hear about that!') +# def regular_choice(update: Update, context: CallbackContext) -> int: +# text = update.message.text +# context.user_data['choice'] = text +# update.message.reply_text(f'Your {text.lower()}? Yes, I would love to hear about that!') - return TYPING_REPLY +# return TYPING_REPLY -def custom_choice(update: Update, _: CallbackContext) -> int: - update.message.reply_text( - 'Alright, please send me the category first, for example "Most impressive skill"' - ) +# def custom_choice(update: Update, _: CallbackContext) -> int: +# update.message.reply_text( +# 'Alright, please send me the category first, for example "Most impressive skill"' +# ) - return TYPING_CHOICE +# return TYPING_CHOICE -def received_information(update: Update, context: CallbackContext) -> int: - user_data = context.user_data - text = update.message.text - category = user_data['choice'] - user_data[category] = text - del user_data['choice'] +# def received_information(update: Update, context: CallbackContext) -> int: +# user_data = context.user_data +# text = update.message.text +# category = user_data['choice'] +# user_data[category] = text +# del user_data['choice'] - update.message.reply_text( - "Neat! Just so you know, this is what you already told me:" - f"{facts_to_str(user_data)} You can tell me more, or change your opinion" - " on something.", - reply_markup=markup, - ) +# update.message.reply_text( +# "Neat! Just so you know, this is what you already told me:" +# f"{facts_to_str(user_data)} You can tell me more, or change your opinion" +# " on something.", +# reply_markup=markup, +# ) - return CHOOSING +# return CHOOSING -def done(update: Update, context: CallbackContext) -> int: - user_data = context.user_data - if 'choice' in user_data: - del user_data['choice'] +# def done(update: Update, context: CallbackContext) -> int: +# user_data = context.user_data +# if 'choice' in user_data: +# del user_data['choice'] - update.message.reply_text( - f"I learned these facts about you: {facts_to_str(user_data)}Until next time!", - reply_markup=ReplyKeyboardRemove(), - ) +# update.message.reply_text( +# f"I learned these facts about you: {facts_to_str(user_data)}Until next time!", +# reply_markup=ReplyKeyboardRemove(), +# ) - user_data.clear() - return ConversationHandler.END +# user_data.clear() +# return ConversationHandler.END -def main() -> None: - # Create the Updater and pass it your bot's token. - updater = Updater(TOKEN) +# def main() -> None: +# # Create the Updater and pass it your bot's token. +# updater = Updater(TOKEN) - # Get the dispatcher to register handlers - dispatcher = updater.dispatcher - - # Add conversation handler with the states CHOOSING, TYPING_CHOICE and TYPING_REPLY - conv_handler = ConversationHandler( - entry_points=[CommandHandler('start', start)], - states={ - CHOOSING: [ - MessageHandler( - Filters.regex('^(Age|Favourite colour|Number of siblings)$'), regular_choice - ), - MessageHandler(Filters.regex('^Something else...$'), custom_choice), - ], - TYPING_CHOICE: [ - MessageHandler( - Filters.text & ~(Filters.command | Filters.regex('^Done$')), regular_choice - ) - ], - TYPING_REPLY: [ - MessageHandler( - Filters.text & ~(Filters.command | Filters.regex('^Done$')), - received_information, - ) - ], - }, - fallbacks=[MessageHandler(Filters.regex('^Done$'), done)], - ) - - dispatcher.add_handler(conv_handler) +# # Get the dispatcher to register handlers +# dispatcher = updater.dispatcher + +# # Add conversation handler with the states CHOOSING, TYPING_CHOICE and TYPING_REPLY +# conv_handler = ConversationHandler( +# entry_points=[CommandHandler('start', start)], +# states={ +# CHOOSING: [ +# MessageHandler( +# Filters.regex('^(Age|Favourite colour|Number of siblings)$'), regular_choice +# ), +# MessageHandler(Filters.regex('^Something else...$'), custom_choice), +# ], +# TYPING_CHOICE: [ +# MessageHandler( +# Filters.text & ~(Filters.command | Filters.regex('^Done$')), regular_choice +# ) +# ], +# TYPING_REPLY: [ +# MessageHandler( +# Filters.text & ~(Filters.command | Filters.regex('^Done$')), +# received_information, +# ) +# ], +# }, +# fallbacks=[MessageHandler(Filters.regex('^Done$'), done)], +# ) + +# dispatcher.add_handler(conv_handler) - # Start the Bot - updater.start_webhook(listen="0.0.0.0", - port=int(PORT), - url_path=TOKEN) - updater.bot.setWebhook('https://frozen-scrubland-72051.herokuapp.com/' + TOKEN) +# # Start the Bot +# updater.start_webhook(listen="0.0.0.0", +# port=int(PORT), +# url_path=TOKEN) +# updater.bot.setWebhook('https://frozen-scrubland-72051.herokuapp.com/' + TOKEN) - # Run the bot until you press Ctrl-C or the process receives SIGINT, - # SIGTERM or SIGABRT. This should be used most of the time, since - # start_polling() is non-blocking and will stop the bot gracefully. - updater.idle() +# # Run the bot until you press Ctrl-C or the process receives SIGINT, +# # SIGTERM or SIGABRT. This should be used most of the time, since +# # start_polling() is non-blocking and will stop the bot gracefully. +# updater.idle() -if __name__ == '__main__': - main() +# if __name__ == '__main__': +# main() -# import logging -# from telegram.ext import Updater, CommandHandler, MessageHandler, Filters -# from simple_salesforce import Salesforce -# import os +import logging +from telegram.ext import Updater, CommandHandler, MessageHandler, Filters +from simple_salesforce import Salesforce +import os -# sf = Salesforce( -# username='max2433186@mindful-impala-acpsha.com', -# password='JKlw124O2kanv5kLLf', -# security_token='') +sf = Salesforce( +username='max2433186@mindful-impala-acpsha.com', +password='JKlw124O2kanv5kLLf', +security_token='') -# PORT = int(os.environ.get('PORT', 5000)) +PORT = int(os.environ.get('PORT', 5000)) -# # Enable logging -# logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', -# level=logging.INFO) +# Enable logging +logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + level=logging.INFO) -# logger = logging.getLogger(__name__) -# TOKEN = '1841783209:AAHrDitzlrEGtxSyCUgRr2oSl-vQsgBzPK8' -# bot = '' - -# class UserTelegram: -# def __init__(self, login, password): -# self.login = login -# self.password = password -# self.exist = False -# self.contact = None - -# usersTelegram = {} - -# # Define a few command handlers. These usually take the two arguments update and -# # context. Error handlers also receive the raised TelegramError object in error. - -# def start(update, context): -# """Send a message when the command /start is issued.""" -# userId = update._effective_user.id -# createUserIfItNeed(userId) -# isUserLog = usersTelegram[userId].exist -# if isUserLog: -# update.message.reply_text('Вы уже зарегистрированы!') -# else: -# update.message.reply_text('Введите логин') -# # sf.Contact.create({'LastName':'simple_salesforce','Email':'example@example.com'}) - -# def help(update, context): -# """Send a message when the command /help is issued.""" -# update.message.reply_text('Help!') - -# def echo(update, context): -# """Echo the user message.""" -# userId = update._effective_user.id - -# if userId not in usersTelegram: -# start(update,context) -# return - -# message = update.message.text.lower() -# if usersTelegram[userId].exist == False: -# login(update, context) -# elif message == '/bye' or message == '/end': -# usersTelegram.pop(userId) -# else: -# update.message.reply_text('ты не должен видеть это сообщение') - -# #update.message.reply_text(update.message.text) - -# def error(update, context): -# """Log Errors caused by Updates.""" -# logger.warning('Update "%s" caused error "%s"', update, context.error) - -# def login(update, context): -# userId = update._effective_user.id -# user = usersTelegram[userId] - -# if user.login == None: -# user.login = update.message.text -# update.message.reply_text('Введите пароль') -# else: -# user.password = update.message.text -# try: -# user.contact = sf.query(f"SELECT Id, Name, Email, Office__c, Admin__c FROM Contact WHERE Email ='{user.login}' AND Password__c ='{user.password}' LIMIT 1") -# throwExceptionIfContactEmpty(user.contact) -# user.exist = True -# update.message.reply_text('Авторизация прошла успешно ' + str(user.contact)) -# except Exception: -# update.message.reply_text('Неправильный логин или пароль.Попробуйте Снова') -# refreshUser(user) -# start(update,context) -# return -# # x = bool(user.contact) -# # if bool: -# # update.message.reply_text('Авторизация прошла успешно ' + str(user.contact)) -# # else: -# # update.message.reply_text('Неправильный логин или пароль.Попробуйте Снова') - -# def createUserIfItNeed(userId): -# if userId not in usersTelegram: -# usersTelegram[userId] = UserTelegram(None,None) - -# def refreshUser(user): -# user.login = None -# user.password = None -# user.exist = False -# user.contact = None - -# def throwExceptionIfContactEmpty(contact): -# totalSize = int(contact['totalSize']) -# if totalSize < 1: -# raise Exception('Contact empty') - -# def main(): -# """Start the bot.""" -# # Create the Updater and pass it your bot's token. -# # Make sure to set use_context=True to use the new context based callbacks -# # Post version 12 this will no longer be necessary -# updater = Updater(TOKEN, use_context=True) -# global bot -# bot = updater.bot -# # Get the dispatcher to register handlers -# dp = updater.dispatcher +logger = logging.getLogger(__name__) +TOKEN = '1841783209:AAHrDitzlrEGtxSyCUgRr2oSl-vQsgBzPK8' +bot = '' + +class UserTelegram: + def __init__(self, login, password): + self.login = login + self.password = password + self.exist = False + self.contact = None + +usersTelegram = {} + +# Define a few command handlers. These usually take the two arguments update and +# context. Error handlers also receive the raised TelegramError object in error. + +def start(update, context): + """Send a message when the command /start is issued.""" + userId = update._effective_user.id + createUserIfItNeed(userId) + isUserLog = usersTelegram[userId].exist + if isUserLog: + update.message.reply_text('Вы уже зарегистрированы!') + else: + update.message.reply_text('Введите логин') + # sf.Contact.create({'LastName':'simple_salesforce','Email':'example@example.com'}) + +def help(update, context): + """Send a message when the command /help is issued.""" + update.message.reply_text('Help!') + +def echo(update, context): + """Echo the user message.""" + userId = update._effective_user.id + + if userId not in usersTelegram: + start(update,context) + return + + message = update.message.text.lower() + if usersTelegram[userId].exist == False: + login(update, context) + elif message == '/bye' or message == '/end': + usersTelegram.pop(userId) + else: + update.message.reply_text('ты не должен видеть это сообщение') + + #update.message.reply_text(update.message.text) + +def error(update, context): + """Log Errors caused by Updates.""" + logger.warning('Update "%s" caused error "%s"', update, context.error) + +def login(update, context): + userId = update._effective_user.id + user = usersTelegram[userId] + + if user.login == None: + user.login = update.message.text + update.message.reply_text('Введите пароль') + else: + user.password = update.message.text + try: + user.contact = sf.query(f"SELECT Id, Name, Email, Office__c, Admin__c FROM Contact WHERE Email ='{user.login}' AND Password__c ='{user.password}' LIMIT 1") + throwExceptionIfContactEmpty(user.contact) + user.exist = True + update.message.reply_text('Авторизация прошла успешно ' + str(user.contact)) + except Exception: + update.message.reply_text('Неправильный логин или пароль.Попробуйте Снова') + refreshUser(user) + start(update,context) + return + # x = bool(user.contact) + # if bool: + # update.message.reply_text('Авторизация прошла успешно ' + str(user.contact)) + # else: + # update.message.reply_text('Неправильный логин или пароль.Попробуйте Снова') + +def createUserIfItNeed(userId): + if userId not in usersTelegram: + usersTelegram[userId] = UserTelegram(None,None) + +def refreshUser(user): + user.login = None + user.password = None + user.exist = False + user.contact = None + +def throwExceptionIfContactEmpty(contact): + totalSize = int(contact['totalSize']) + if totalSize < 1: + raise Exception('Contact empty') + +def main(): + """Start the bot.""" + # Create the Updater and pass it your bot's token. + # Make sure to set use_context=True to use the new context based callbacks + # Post version 12 this will no longer be necessary + updater = Updater(TOKEN, use_context=True) + global bot + bot = updater.bot + # Get the dispatcher to register handlers + dp = updater.dispatcher -# # on different commands - answer in Telegram -# dp.add_handler(CommandHandler("start", start)) -# dp.add_handler(CommandHandler("help", help)) + # on different commands - answer in Telegram + dp.add_handler(CommandHandler("start", start)) + dp.add_handler(CommandHandler("help", help)) -# # on noncommand i.e message - echo the message on Telegram -# dp.add_handler(MessageHandler(Filters.text, echo)) + # on noncommand i.e message - echo the message on Telegram + dp.add_handler(MessageHandler(Filters.text, echo)) -# # log all errors -# dp.add_error_handler(error) + # log all errors + dp.add_error_handler(error) -# # Start the Bot -# updater.start_webhook(listen="0.0.0.0", -# port=int(PORT), -# url_path=TOKEN) -# updater.bot.setWebhook('https://frozen-scrubland-72051.herokuapp.com/' + TOKEN) + # Start the Bot + updater.start_webhook(listen="0.0.0.0", + port=int(PORT), + url_path=TOKEN) + updater.bot.setWebhook('https://frozen-scrubland-72051.herokuapp.com/' + TOKEN) -# # Run the bot until you press Ctrl-C or the process receives SIGINT, -# # SIGTERM or SIGABRT. This should be used most of the time, since -# # start_polling() is non-blocking and will stop the bot gracefully. -# updater.idle() + # Run the bot until you press Ctrl-C or the process receives SIGINT, + # SIGTERM or SIGABRT. This should be used most of the time, since + # start_polling() is non-blocking and will stop the bot gracefully. + updater.idle() -# if __name__ == '__main__': -# main() +if __name__ == '__main__': + main() + + # OrderedDict([ # ('totalSize', 1), # ('done', True), From a7ab183226474238049a4a8913075b6f9e57e0b8 Mon Sep 17 00:00:00 2001 From: Vlad Date: Sat, 15 May 2021 14:08:11 +0300 Subject: [PATCH 045/147] add import to old bot --- bot.py | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/bot.py b/bot.py index 1f4ec2c..742c8d5 100644 --- a/bot.py +++ b/bot.py @@ -149,7 +149,16 @@ import logging -from telegram.ext import Updater, CommandHandler, MessageHandler, Filters +from telegram import ReplyKeyboardMarkup, Update, ReplyKeyboardRemove +from telegram.ext import ( + Updater, + CommandHandler, + MessageHandler, + Filters, + ConversationHandler, + CallbackContext, +) + from simple_salesforce import Salesforce import os @@ -292,7 +301,7 @@ def main(): if __name__ == '__main__': main() - + # OrderedDict([ # ('totalSize', 1), # ('done', True), From 01b773aeb429480e37c00ec686e04c59b7935875 Mon Sep 17 00:00:00 2001 From: Vlad Date: Sat, 15 May 2021 14:27:10 +0300 Subject: [PATCH 046/147] add bot in start function --- bot.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/bot.py b/bot.py index 742c8d5..9656ae2 100644 --- a/bot.py +++ b/bot.py @@ -189,7 +189,7 @@ def __init__(self, login, password): # Define a few command handlers. These usually take the two arguments update and # context. Error handlers also receive the raised TelegramError object in error. -def start(update, context): +def start(bot,update, context): """Send a message when the command /start is issued.""" userId = update._effective_user.id createUserIfItNeed(userId) @@ -239,7 +239,7 @@ def login(update, context): user.contact = sf.query(f"SELECT Id, Name, Email, Office__c, Admin__c FROM Contact WHERE Email ='{user.login}' AND Password__c ='{user.password}' LIMIT 1") throwExceptionIfContactEmpty(user.contact) user.exist = True - update.message.reply_text('Авторизация прошла успешно ' + str(user.contact)) + update.message.reply_text('Авторизация прошла успешно ') except Exception: update.message.reply_text('Неправильный логин или пароль.Попробуйте Снова') refreshUser(user) From b632978ce3e5bf75b71da6f367934a6c11a6180c Mon Sep 17 00:00:00 2001 From: Vlad Date: Sat, 15 May 2021 14:56:52 +0300 Subject: [PATCH 047/147] add replyKeyboard --- bot.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/bot.py b/bot.py index 9656ae2..a5c6fae 100644 --- a/bot.py +++ b/bot.py @@ -189,8 +189,9 @@ def __init__(self, login, password): # Define a few command handlers. These usually take the two arguments update and # context. Error handlers also receive the raised TelegramError object in error. -def start(bot,update, context): +def start(update, context): """Send a message when the command /start is issued.""" + userId = update._effective_user.id createUserIfItNeed(userId) isUserLog = usersTelegram[userId].exist @@ -239,7 +240,9 @@ def login(update, context): user.contact = sf.query(f"SELECT Id, Name, Email, Office__c, Admin__c FROM Contact WHERE Email ='{user.login}' AND Password__c ='{user.password}' LIMIT 1") throwExceptionIfContactEmpty(user.contact) user.exist = True - update.message.reply_text('Авторизация прошла успешно ') + reply_keyboard = [['Boy', 'Girl', 'Other']] + update.message.reply_text('Авторизация прошла успешно', + reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True)) except Exception: update.message.reply_text('Неправильный логин или пароль.Попробуйте Снова') refreshUser(user) @@ -251,6 +254,7 @@ def login(update, context): # else: # update.message.reply_text('Неправильный логин или пароль.Попробуйте Снова') + def createUserIfItNeed(userId): if userId not in usersTelegram: usersTelegram[userId] = UserTelegram(None,None) @@ -272,8 +276,6 @@ def main(): # Make sure to set use_context=True to use the new context based callbacks # Post version 12 this will no longer be necessary updater = Updater(TOKEN, use_context=True) - global bot - bot = updater.bot # Get the dispatcher to register handlers dp = updater.dispatcher From 3b3105c9f4230226cddd25d43605f3eb10aa715a Mon Sep 17 00:00:00 2001 From: Vlad Date: Sat, 15 May 2021 15:00:45 +0300 Subject: [PATCH 048/147] change button name --- bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot.py b/bot.py index a5c6fae..0940e2d 100644 --- a/bot.py +++ b/bot.py @@ -240,7 +240,7 @@ def login(update, context): user.contact = sf.query(f"SELECT Id, Name, Email, Office__c, Admin__c FROM Contact WHERE Email ='{user.login}' AND Password__c ='{user.password}' LIMIT 1") throwExceptionIfContactEmpty(user.contact) user.exist = True - reply_keyboard = [['Boy', 'Girl', 'Other']] + reply_keyboard = [['Текущий баланс', 'Создать карточку']] update.message.reply_text('Авторизация прошла успешно', reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True)) except Exception: From 7f5f849e634556500cd04ba0f3a1a0f64f188580 Mon Sep 17 00:00:00 2001 From: Vlad Date: Sat, 15 May 2021 15:24:06 +0300 Subject: [PATCH 049/147] add echoForExistUser --- bot.py | 30 ++++++++++++++++++++---------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/bot.py b/bot.py index 0940e2d..5e6e11d 100644 --- a/bot.py +++ b/bot.py @@ -201,10 +201,6 @@ def start(update, context): update.message.reply_text('Введите логин') # sf.Contact.create({'LastName':'simple_salesforce','Email':'example@example.com'}) -def help(update, context): - """Send a message when the command /help is issued.""" - update.message.reply_text('Help!') - def echo(update, context): """Echo the user message.""" userId = update._effective_user.id @@ -213,20 +209,28 @@ def echo(update, context): start(update,context) return - message = update.message.text.lower() if usersTelegram[userId].exist == False: login(update, context) - elif message == '/bye' or message == '/end': - usersTelegram.pop(userId) else: - update.message.reply_text('ты не должен видеть это сообщение') + echoForExistUser(update,context) #update.message.reply_text(update.message.text) +def echoForExistUser(update,context): + message = update.message.text.lower() + if message == 'текущий баланс': + 'here should be code' + update.message.reply_text('101') + update.message.reply_text('ты не должен видеть это сообщение') + def error(update, context): """Log Errors caused by Updates.""" logger.warning('Update "%s" caused error "%s"', update, context.error) +def end(update, context): + userId = update._effective_user.id + usersTelegram.pop(userId) + def login(update, context): userId = update._effective_user.id user = usersTelegram[userId] @@ -240,7 +244,7 @@ def login(update, context): user.contact = sf.query(f"SELECT Id, Name, Email, Office__c, Admin__c FROM Contact WHERE Email ='{user.login}' AND Password__c ='{user.password}' LIMIT 1") throwExceptionIfContactEmpty(user.contact) user.exist = True - reply_keyboard = [['Текущий баланс', 'Создать карточку']] + reply_keyboard = mainMenuKeyboard() update.message.reply_text('Авторизация прошла успешно', reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True)) except Exception: @@ -254,6 +258,12 @@ def login(update, context): # else: # update.message.reply_text('Неправильный логин или пароль.Попробуйте Снова') +#########################Keyboards############################ +def mainMenuKeyboard(): + return [['Текущий баланс', 'Создать карточку']] + +def createCardKeyboard(): + return [['Сегодня','Календарь','Отмена']] def createUserIfItNeed(userId): if userId not in usersTelegram: @@ -281,7 +291,7 @@ def main(): # on different commands - answer in Telegram dp.add_handler(CommandHandler("start", start)) - dp.add_handler(CommandHandler("help", help)) + dp.add_handler(CommandHandler('end',end)) # on noncommand i.e message - echo the message on Telegram dp.add_handler(MessageHandler(Filters.text, echo)) From a31117ad1c409b733498370910bcb1e57863fdb3 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 10:12:50 +0300 Subject: [PATCH 050/147] add reply text on create card --- bot.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/bot.py b/bot.py index 5e6e11d..a2d248a 100644 --- a/bot.py +++ b/bot.py @@ -221,6 +221,10 @@ def echoForExistUser(update,context): if message == 'текущий баланс': 'here should be code' update.message.reply_text('101') + elif message == 'создать карточку': + reply_keyboard = createCardKeyboard() + update.message.reply_text('На какой день желаете создать карточку?', + reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True)) update.message.reply_text('ты не должен видеть это сообщение') def error(update, context): From 667f016743c9c0487fb96fc626ccc9a973d0296a Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 10:20:58 +0300 Subject: [PATCH 051/147] add reply on cancel message --- bot.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/bot.py b/bot.py index a2d248a..55ef173 100644 --- a/bot.py +++ b/bot.py @@ -225,6 +225,14 @@ def echoForExistUser(update,context): reply_keyboard = createCardKeyboard() update.message.reply_text('На какой день желаете создать карточку?', reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True)) + elif message == 'сегодня': + 'here should be code' + elif message == 'календарь': + 'here should be code' + elif message == 'отмена': + reply_keyboard = mainMenuKeyboard() + update.message.reply_text('', + reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True)) update.message.reply_text('ты не должен видеть это сообщение') def error(update, context): From 56d4c225279acdd1443622d41d4437ac74b296a2 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 10:23:14 +0300 Subject: [PATCH 052/147] update repy on cancel message --- bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot.py b/bot.py index 55ef173..bd1d5dc 100644 --- a/bot.py +++ b/bot.py @@ -231,7 +231,7 @@ def echoForExistUser(update,context): 'here should be code' elif message == 'отмена': reply_keyboard = mainMenuKeyboard() - update.message.reply_text('', + update.message.reply_text('На какой день желаете создать карточку?', reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True)) update.message.reply_text('ты не должен видеть это сообщение') From 19744f0488a19978eda16e6bea6ef4a707e09496 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 10:25:26 +0300 Subject: [PATCH 053/147] update reply on cancel message --- bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot.py b/bot.py index bd1d5dc..1c69cea 100644 --- a/bot.py +++ b/bot.py @@ -231,7 +231,7 @@ def echoForExistUser(update,context): 'here should be code' elif message == 'отмена': reply_keyboard = mainMenuKeyboard() - update.message.reply_text('На какой день желаете создать карточку?', + update.message.reply_text(None, reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True)) update.message.reply_text('ты не должен видеть это сообщение') From ba5ec0ba60883f4ef8a2b786150b129da8282c90 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 10:29:31 +0300 Subject: [PATCH 054/147] update reply on cancel message --- bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot.py b/bot.py index 1c69cea..21de0a2 100644 --- a/bot.py +++ b/bot.py @@ -231,7 +231,7 @@ def echoForExistUser(update,context): 'here should be code' elif message == 'отмена': reply_keyboard = mainMenuKeyboard() - update.message.reply_text(None, + update.message.reply_text( reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True)) update.message.reply_text('ты не должен видеть это сообщение') From 0ba5cd5fe20b073aa169f270d782e6c8790bb08e Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 10:32:29 +0300 Subject: [PATCH 055/147] update reply on cancel message --- bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot.py b/bot.py index 21de0a2..a94a627 100644 --- a/bot.py +++ b/bot.py @@ -231,7 +231,7 @@ def echoForExistUser(update,context): 'here should be code' elif message == 'отмена': reply_keyboard = mainMenuKeyboard() - update.message.reply_text( + update.message.reply_text('Что вы хотите сделать?', reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True)) update.message.reply_text('ты не должен видеть это сообщение') From 380327c8f72099200dc238e29354a4126b1e1123 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 10:44:42 +0300 Subject: [PATCH 056/147] create card class --- bot.py | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/bot.py b/bot.py index a94a627..2a71caf 100644 --- a/bot.py +++ b/bot.py @@ -178,11 +178,19 @@ bot = '' class UserTelegram: - def __init__(self, login, password): - self.login = login - self.password = password + def __init__(self): + self.login = None + self.password = None self.exist = False self.contact = None + self.newCard = None + +class Card: + def __init__(self): + self.date = None + self.amount = None + self.description = None + self.keeper = None usersTelegram = {} @@ -279,7 +287,7 @@ def createCardKeyboard(): def createUserIfItNeed(userId): if userId not in usersTelegram: - usersTelegram[userId] = UserTelegram(None,None) + usersTelegram[userId] = UserTelegram() def refreshUser(user): user.login = None From e1ffe001def147a035b45906f68c428f2fd35114 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 11:05:11 +0300 Subject: [PATCH 057/147] update keyboard markup --- bot.py | 32 ++++++++++++++++++++------------ 1 file changed, 20 insertions(+), 12 deletions(-) diff --git a/bot.py b/bot.py index 2a71caf..700381d 100644 --- a/bot.py +++ b/bot.py @@ -226,22 +226,28 @@ def echo(update, context): def echoForExistUser(update,context): message = update.message.text.lower() + userId = update._effective_user.id if message == 'текущий баланс': - 'here should be code' - update.message.reply_text('101') + update.message.reply_text('101', + reply_markup=mainMenuKeyboard()) elif message == 'создать карточку': - reply_keyboard = createCardKeyboard() + usersTelegram[userId].card = Card() update.message.reply_text('На какой день желаете создать карточку?', - reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True)) - elif message == 'сегодня': + reply_markup=createCardKeyboard()) + elif usersTelegram[userId] != None: + creatingCard(update, context) + + update.message.reply_text('ты не должен видеть это сообщение') + +def creatingCard(update, context): + message = update.message.text.lower() + if message == 'сегодня': 'here should be code' elif message == 'календарь': 'here should be code' elif message == 'отмена': - reply_keyboard = mainMenuKeyboard() update.message.reply_text('Что вы хотите сделать?', - reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True)) - update.message.reply_text('ты не должен видеть это сообщение') + reply_markup=mainMenuKeyboard()) def error(update, context): """Log Errors caused by Updates.""" @@ -264,9 +270,8 @@ def login(update, context): user.contact = sf.query(f"SELECT Id, Name, Email, Office__c, Admin__c FROM Contact WHERE Email ='{user.login}' AND Password__c ='{user.password}' LIMIT 1") throwExceptionIfContactEmpty(user.contact) user.exist = True - reply_keyboard = mainMenuKeyboard() update.message.reply_text('Авторизация прошла успешно', - reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True)) + reply_markup=mainMenuKeyboard()) except Exception: update.message.reply_text('Неправильный логин или пароль.Попробуйте Снова') refreshUser(user) @@ -280,10 +285,13 @@ def login(update, context): #########################Keyboards############################ def mainMenuKeyboard(): - return [['Текущий баланс', 'Создать карточку']] + options = [['Текущий баланс', 'Создать карточку']] + return ReplyKeyboardMarkup(options, one_time_keyboard=True) def createCardKeyboard(): - return [['Сегодня','Календарь','Отмена']] + options = [['Сегодня','Календарь','Отмена']] + return ReplyKeyboardMarkup(options, one_time_keyboard=True) + def createUserIfItNeed(userId): if userId not in usersTelegram: From eb85a522eec949d6ef62b66a009084da8afe3549 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 11:14:41 +0300 Subject: [PATCH 058/147] update reply cancel message --- bot.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/bot.py b/bot.py index 700381d..38bea3e 100644 --- a/bot.py +++ b/bot.py @@ -246,8 +246,7 @@ def creatingCard(update, context): elif message == 'календарь': 'here should be code' elif message == 'отмена': - update.message.reply_text('Что вы хотите сделать?', - reply_markup=mainMenuKeyboard()) + update.message.reply_markup(mainMenuKeyboard()) def error(update, context): """Log Errors caused by Updates.""" From 1e5c2fc8fa14154e5f1f45688eb2a3a9827c8884 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 11:26:10 +0300 Subject: [PATCH 059/147] update replyMarkup --- bot.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/bot.py b/bot.py index 38bea3e..07880da 100644 --- a/bot.py +++ b/bot.py @@ -246,7 +246,8 @@ def creatingCard(update, context): elif message == 'календарь': 'here should be code' elif message == 'отмена': - update.message.reply_markup(mainMenuKeyboard()) + update.message.reply_text('Что вы хотите сделать?', + reply_markup=mainMenuKeyboard()) def error(update, context): """Log Errors caused by Updates.""" @@ -285,7 +286,7 @@ def login(update, context): #########################Keyboards############################ def mainMenuKeyboard(): options = [['Текущий баланс', 'Создать карточку']] - return ReplyKeyboardMarkup(options, one_time_keyboard=True) + return ReplyKeyboardMarkup(options) def createCardKeyboard(): options = [['Сегодня','Календарь','Отмена']] From 1478225e5dfdd9efcc672f49ed40b9e8e545ed0c Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 11:28:12 +0300 Subject: [PATCH 060/147] update reply Markup[ --- bot.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/bot.py b/bot.py index 07880da..dac533d 100644 --- a/bot.py +++ b/bot.py @@ -204,9 +204,9 @@ def start(update, context): createUserIfItNeed(userId) isUserLog = usersTelegram[userId].exist if isUserLog: - update.message.reply_text('Вы уже зарегистрированы!') + update.message.reply_text('Вы уже зарегистрированы!', reply_markup=ReplyKeyboardRemove()) else: - update.message.reply_text('Введите логин') + update.message.reply_text('Введите логин', reply_markup=ReplyKeyboardRemove()) # sf.Contact.create({'LastName':'simple_salesforce','Email':'example@example.com'}) def echo(update, context): @@ -256,6 +256,8 @@ def error(update, context): def end(update, context): userId = update._effective_user.id usersTelegram.pop(userId) + update.message.reply_text('До свидания!', + reply_markup=mainMenuKeyboard()) def login(update, context): userId = update._effective_user.id From 3f897962092a9aafac8593266311b72e9064335b Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 12:16:08 +0300 Subject: [PATCH 061/147] make get current balance --- bot.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/bot.py b/bot.py index dac533d..fe37448 100644 --- a/bot.py +++ b/bot.py @@ -227,14 +227,16 @@ def echo(update, context): def echoForExistUser(update,context): message = update.message.text.lower() userId = update._effective_user.id + user = usersTelegram[userId] if message == 'текущий баланс': + balance = sf.apexecute('Contact/', method='GET') update.message.reply_text('101', reply_markup=mainMenuKeyboard()) elif message == 'создать карточку': - usersTelegram[userId].card = Card() + user.card = Card() update.message.reply_text('На какой день желаете создать карточку?', reply_markup=createCardKeyboard()) - elif usersTelegram[userId] != None: + elif user.card != None: creatingCard(update, context) update.message.reply_text('ты не должен видеть это сообщение') @@ -272,7 +274,7 @@ def login(update, context): user.contact = sf.query(f"SELECT Id, Name, Email, Office__c, Admin__c FROM Contact WHERE Email ='{user.login}' AND Password__c ='{user.password}' LIMIT 1") throwExceptionIfContactEmpty(user.contact) user.exist = True - update.message.reply_text('Авторизация прошла успешно', + update.message.reply_text('Авторизация прошла успешно ' + user.contact, reply_markup=mainMenuKeyboard()) except Exception: update.message.reply_text('Неправильный логин или пароль.Попробуйте Снова') From f5cceefe8d8ba1770cc7d0c5fe402f386b73e1ec Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 12:19:55 +0300 Subject: [PATCH 062/147] update reply about success auth --- bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot.py b/bot.py index fe37448..2f55f1a 100644 --- a/bot.py +++ b/bot.py @@ -274,7 +274,7 @@ def login(update, context): user.contact = sf.query(f"SELECT Id, Name, Email, Office__c, Admin__c FROM Contact WHERE Email ='{user.login}' AND Password__c ='{user.password}' LIMIT 1") throwExceptionIfContactEmpty(user.contact) user.exist = True - update.message.reply_text('Авторизация прошла успешно ' + user.contact, + update.message.reply_text('Авторизация прошла успешно ' + str(user.contact), reply_markup=mainMenuKeyboard()) except Exception: update.message.reply_text('Неправильный логин или пароль.Попробуйте Снова') From cb9f3e461bbc010c1be5364462c39b95d655c1ee Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 12:22:26 +0300 Subject: [PATCH 063/147] update reply success auth --- bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot.py b/bot.py index 2f55f1a..5e3bfe6 100644 --- a/bot.py +++ b/bot.py @@ -274,7 +274,7 @@ def login(update, context): user.contact = sf.query(f"SELECT Id, Name, Email, Office__c, Admin__c FROM Contact WHERE Email ='{user.login}' AND Password__c ='{user.password}' LIMIT 1") throwExceptionIfContactEmpty(user.contact) user.exist = True - update.message.reply_text('Авторизация прошла успешно ' + str(user.contact), + update.message.reply_text('Авторизация прошла успешно ' + str(user.contact['records'][0]['Id']), reply_markup=mainMenuKeyboard()) except Exception: update.message.reply_text('Неправильный логин или пароль.Попробуйте Снова') From e6343efe515785b6d2c36b9ba5735bb5c243cef7 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 12:25:36 +0300 Subject: [PATCH 064/147] update get current balance --- bot.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/bot.py b/bot.py index 5e3bfe6..65e5afd 100644 --- a/bot.py +++ b/bot.py @@ -229,8 +229,9 @@ def echoForExistUser(update,context): userId = update._effective_user.id user = usersTelegram[userId] if message == 'текущий баланс': - balance = sf.apexecute('Contact/', method='GET') - update.message.reply_text('101', + userContactId = user.contact['records'][0]['Id'] + balance = sf.apexecute('Contact/'+userContactId, method='GET') + update.message.reply_text(str(balance), reply_markup=mainMenuKeyboard()) elif message == 'создать карточку': user.card = Card() @@ -274,13 +275,14 @@ def login(update, context): user.contact = sf.query(f"SELECT Id, Name, Email, Office__c, Admin__c FROM Contact WHERE Email ='{user.login}' AND Password__c ='{user.password}' LIMIT 1") throwExceptionIfContactEmpty(user.contact) user.exist = True - update.message.reply_text('Авторизация прошла успешно ' + str(user.contact['records'][0]['Id']), + update.message.reply_text('Авторизация прошла успешно ', reply_markup=mainMenuKeyboard()) except Exception: update.message.reply_text('Неправильный логин или пароль.Попробуйте Снова') refreshUser(user) start(update,context) return + #str(user.contact['records'][0]['Id']) # x = bool(user.contact) # if bool: # update.message.reply_text('Авторизация прошла успешно ' + str(user.contact)) From 38853cafac009f3ba99d22e68dec563d565c9907 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 12:31:25 +0300 Subject: [PATCH 065/147] update reply end message --- bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot.py b/bot.py index 65e5afd..9b1a1dc 100644 --- a/bot.py +++ b/bot.py @@ -260,7 +260,7 @@ def end(update, context): userId = update._effective_user.id usersTelegram.pop(userId) update.message.reply_text('До свидания!', - reply_markup=mainMenuKeyboard()) + reply_markup=ReplyKeyboardRemove()) def login(update, context): userId = update._effective_user.id From 321878f1ecd9ed65a730f596ca8402f9cff688f1 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 13:32:19 +0300 Subject: [PATCH 066/147] create creatingCardDate/Amount/Decription --- bot.py | 170 ++++++--------------------------------------------------- 1 file changed, 16 insertions(+), 154 deletions(-) diff --git a/bot.py b/bot.py index 9b1a1dc..e4cccc0 100644 --- a/bot.py +++ b/bot.py @@ -1,153 +1,3 @@ -# import logging -# from typing import Dict -# import os - -# from telegram import ReplyKeyboardMarkup, Update, ReplyKeyboardRemove -# from telegram.ext import ( -# Updater, -# CommandHandler, -# MessageHandler, -# Filters, -# ConversationHandler, -# CallbackContext, -# ) - - -# PORT = int(os.environ.get('PORT', 5000)) -# TOKEN = '1841783209:AAHrDitzlrEGtxSyCUgRr2oSl-vQsgBzPK8' - -# # Enable logging -# logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', -# level=logging.INFO) - -# logger = logging.getLogger(__name__) - -# CHOOSING, TYPING_REPLY, TYPING_CHOICE = range(3) - -# reply_keyboard = [ -# ['Age', 'Favourite colour'], -# ['Number of siblings', 'Something else...'], -# ['Done'], -# ] -# markup = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True) - - -# def facts_to_str(user_data: Dict[str, str]) -> str: -# facts = list() - -# for key, value in user_data.items(): -# facts.append(f'{key} - {value}') - -# return "\n".join(facts).join(['\n', '\n']) - - -# def start(update: Update, _: CallbackContext) -> int: -# update.message.reply_text( -# "Hi! My name is Doctor Botter. I will hold a more complex conversation with you. " -# "Why don't you tell me something about yourself?", -# reply_markup=markup, -# ) - -# return CHOOSING - - -# def regular_choice(update: Update, context: CallbackContext) -> int: -# text = update.message.text -# context.user_data['choice'] = text -# update.message.reply_text(f'Your {text.lower()}? Yes, I would love to hear about that!') - -# return TYPING_REPLY - - -# def custom_choice(update: Update, _: CallbackContext) -> int: -# update.message.reply_text( -# 'Alright, please send me the category first, for example "Most impressive skill"' -# ) - -# return TYPING_CHOICE - - -# def received_information(update: Update, context: CallbackContext) -> int: -# user_data = context.user_data -# text = update.message.text -# category = user_data['choice'] -# user_data[category] = text -# del user_data['choice'] - -# update.message.reply_text( -# "Neat! Just so you know, this is what you already told me:" -# f"{facts_to_str(user_data)} You can tell me more, or change your opinion" -# " on something.", -# reply_markup=markup, -# ) - -# return CHOOSING - - -# def done(update: Update, context: CallbackContext) -> int: -# user_data = context.user_data -# if 'choice' in user_data: -# del user_data['choice'] - -# update.message.reply_text( -# f"I learned these facts about you: {facts_to_str(user_data)}Until next time!", -# reply_markup=ReplyKeyboardRemove(), -# ) - -# user_data.clear() -# return ConversationHandler.END - - -# def main() -> None: -# # Create the Updater and pass it your bot's token. -# updater = Updater(TOKEN) - -# # Get the dispatcher to register handlers -# dispatcher = updater.dispatcher - -# # Add conversation handler with the states CHOOSING, TYPING_CHOICE and TYPING_REPLY -# conv_handler = ConversationHandler( -# entry_points=[CommandHandler('start', start)], -# states={ -# CHOOSING: [ -# MessageHandler( -# Filters.regex('^(Age|Favourite colour|Number of siblings)$'), regular_choice -# ), -# MessageHandler(Filters.regex('^Something else...$'), custom_choice), -# ], -# TYPING_CHOICE: [ -# MessageHandler( -# Filters.text & ~(Filters.command | Filters.regex('^Done$')), regular_choice -# ) -# ], -# TYPING_REPLY: [ -# MessageHandler( -# Filters.text & ~(Filters.command | Filters.regex('^Done$')), -# received_information, -# ) -# ], -# }, -# fallbacks=[MessageHandler(Filters.regex('^Done$'), done)], -# ) - -# dispatcher.add_handler(conv_handler) - -# # Start the Bot -# updater.start_webhook(listen="0.0.0.0", -# port=int(PORT), -# url_path=TOKEN) -# updater.bot.setWebhook('https://frozen-scrubland-72051.herokuapp.com/' + TOKEN) - -# # Run the bot until you press Ctrl-C or the process receives SIGINT, -# # SIGTERM or SIGABRT. This should be used most of the time, since -# # start_polling() is non-blocking and will stop the bot gracefully. -# updater.idle() - - -# if __name__ == '__main__': -# main() - - import logging from telegram import ReplyKeyboardMarkup, Update, ReplyKeyboardRemove from telegram.ext import ( @@ -238,12 +88,19 @@ def echoForExistUser(update,context): update.message.reply_text('На какой день желаете создать карточку?', reply_markup=createCardKeyboard()) elif user.card != None: - creatingCard(update, context) + creatingCard(update,user,message) update.message.reply_text('ты не должен видеть это сообщение') -def creatingCard(update, context): - message = update.message.text.lower() +def creatingCard(update,user,message): + if user.card.date == None: + creatingCardDate(update,user,message) + elif user.card.amount == None: + creatingCardAmount(update,user,message) + elif user.card.description == None: + creatingCardDecription(update,user,message) + +def creatingCardDate(update,user,message): if message == 'сегодня': 'here should be code' elif message == 'календарь': @@ -252,6 +109,11 @@ def creatingCard(update, context): update.message.reply_text('Что вы хотите сделать?', reply_markup=mainMenuKeyboard()) +def creatingCardAmount(update,user,message): + '' +def creatingCardDecription(update,user,message): + '' + def error(update, context): """Log Errors caused by Updates.""" logger.warning('Update "%s" caused error "%s"', update, context.error) @@ -295,7 +157,7 @@ def mainMenuKeyboard(): return ReplyKeyboardMarkup(options) def createCardKeyboard(): - options = [['Сегодня','Календарь','Отмена']] + options = [['Сегодня','Календарь'],['Отмена']] return ReplyKeyboardMarkup(options, one_time_keyboard=True) From 2ba1880f470b193a02945fd5f0c3841a40432b53 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 13:42:50 +0300 Subject: [PATCH 067/147] update createCardKeyboard --- bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot.py b/bot.py index e4cccc0..8634951 100644 --- a/bot.py +++ b/bot.py @@ -157,7 +157,7 @@ def mainMenuKeyboard(): return ReplyKeyboardMarkup(options) def createCardKeyboard(): - options = [['Сегодня','Календарь'],['Отмена']] + options = [['Сегодня'],['Календарь'],['Отмена']] return ReplyKeyboardMarkup(options, one_time_keyboard=True) From 7575308e758256ac20f832c9db05cd8e33c54c13 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 13:55:25 +0300 Subject: [PATCH 068/147] update mainMenuKeyboard --- bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot.py b/bot.py index 8634951..6ab8ce0 100644 --- a/bot.py +++ b/bot.py @@ -153,7 +153,7 @@ def login(update, context): #########################Keyboards############################ def mainMenuKeyboard(): - options = [['Текущий баланс', 'Создать карточку']] + options = [['Текущий баланс'],['Создать карточку']] return ReplyKeyboardMarkup(options) def createCardKeyboard(): From d125c68fd963c1e8df0a9fd5fdad3e8142a71882 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 14:25:05 +0300 Subject: [PATCH 069/147] create getOptionsForDaysOfMonthKeyboard --- bot.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/bot.py b/bot.py index 6ab8ce0..1c2f50a 100644 --- a/bot.py +++ b/bot.py @@ -1,4 +1,6 @@ import logging +import calendar +import datetime from telegram import ReplyKeyboardMarkup, Update, ReplyKeyboardRemove from telegram.ext import ( Updater, @@ -160,6 +162,31 @@ def createCardKeyboard(): options = [['Сегодня'],['Календарь'],['Отмена']] return ReplyKeyboardMarkup(options, one_time_keyboard=True) +def daysOfMonthKeyboard(): + options = getOptionsForDaysOfMonthKeyboard() + return ReplyKeyboardMarkup(options, one_time_keyboard=True) + +def getOptionsForDaysOfMonthKeyboard(): + options = [] + rowOptions = [] + now = datetime.datetime.now() + daysInMonth = calendar.monthrange(now.year, now.month)[1] + count = 1 + while count <= daysInMonth: + strCount = str(count) + if (count == daysInMonth): + lenOptions = len(options) + options[lenOptions].append(strCount) + elif (len(rowOptions) >= 4): + rowOptions.append(strCount) + options.append(rowOptions) + rowOptions = [] + else: + rowOptions.append(strCount) + count += 1 + return options + + def createUserIfItNeed(userId): if userId not in usersTelegram: From 7df72c3cc65d3e4b342ac5fe6464564897f07678 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 14:30:04 +0300 Subject: [PATCH 070/147] update reply on calendar message --- bot.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/bot.py b/bot.py index 1c2f50a..cf07459 100644 --- a/bot.py +++ b/bot.py @@ -106,7 +106,8 @@ def creatingCardDate(update,user,message): if message == 'сегодня': 'here should be code' elif message == 'календарь': - 'here should be code' + update.message.reply_text('Выберите число', + reply_markup=daysOfMonthKeyboard()) elif message == 'отмена': update.message.reply_text('Что вы хотите сделать?', reply_markup=mainMenuKeyboard()) From 9884d619cd0b3c82920b0b4642c78dabc6d16672 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 14:33:17 +0300 Subject: [PATCH 071/147] update getOptionsForDaysOfMonthKeyboard --- bot.py | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/bot.py b/bot.py index cf07459..ef50895 100644 --- a/bot.py +++ b/bot.py @@ -172,19 +172,20 @@ def getOptionsForDaysOfMonthKeyboard(): rowOptions = [] now = datetime.datetime.now() daysInMonth = calendar.monthrange(now.year, now.month)[1] - count = 1 - while count <= daysInMonth: - strCount = str(count) - if (count == daysInMonth): - lenOptions = len(options) - options[lenOptions].append(strCount) - elif (len(rowOptions) >= 4): - rowOptions.append(strCount) - options.append(rowOptions) - rowOptions = [] - else: - rowOptions.append(strCount) - count += 1 + options.append(str(daysInMonth)) + # count = 1 + # while count <= daysInMonth: + # strCount = str(count) + # if (count == daysInMonth): + # lenOptions = len(options) + # options[lenOptions].append(strCount) + # elif (len(rowOptions) >= 4): + # rowOptions.append(strCount) + # options.append(rowOptions) + # rowOptions = [] + # else: + # rowOptions.append(strCount) + # count += 1 return options From 266b6355a6b8c9d698ed5a0f5374d089a253894b Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 14:37:10 +0300 Subject: [PATCH 072/147] update getOptionsForDaysOfMonthKeyboard --- bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot.py b/bot.py index ef50895..c96eb9e 100644 --- a/bot.py +++ b/bot.py @@ -171,7 +171,7 @@ def getOptionsForDaysOfMonthKeyboard(): options = [] rowOptions = [] now = datetime.datetime.now() - daysInMonth = calendar.monthrange(now.year, now.month)[1] + daysInMonth = calendar.monthrange(now.year, now.month) options.append(str(daysInMonth)) # count = 1 # while count <= daysInMonth: From 845c0bc3e25c894aa3fea4fa3a9bd186c20f5ff4 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 14:40:05 +0300 Subject: [PATCH 073/147] update getOptionsForDaysOfMonthKeyboard --- bot.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/bot.py b/bot.py index c96eb9e..8cc0a06 100644 --- a/bot.py +++ b/bot.py @@ -171,8 +171,9 @@ def getOptionsForDaysOfMonthKeyboard(): options = [] rowOptions = [] now = datetime.datetime.now() - daysInMonth = calendar.monthrange(now.year, now.month) - options.append(str(daysInMonth)) + daysInMonth = calendar.monthrange(now.year, now.month)[1] + strDays = str(daysInMonth) + options.append(strDays) # count = 1 # while count <= daysInMonth: # strCount = str(count) From 7ae431dfffd9a49d42eda93ea9f543bf33617707 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 14:43:35 +0300 Subject: [PATCH 074/147] update creatingCardDate --- bot.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/bot.py b/bot.py index 8cc0a06..ada5658 100644 --- a/bot.py +++ b/bot.py @@ -106,7 +106,10 @@ def creatingCardDate(update,user,message): if message == 'сегодня': 'here should be code' elif message == 'календарь': - update.message.reply_text('Выберите число', + now = datetime.datetime.now() + daysInMonth = calendar.monthrange(now.year, now.month)[1] + strDays = str(daysInMonth) + update.message.reply_text('Выберите число ' + strDays, reply_markup=daysOfMonthKeyboard()) elif message == 'отмена': update.message.reply_text('Что вы хотите сделать?', From 72b9567bf6cbf6dc76629dbc46a1c4a165cdf601 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 14:46:05 +0300 Subject: [PATCH 075/147] update getOptionsForDaysOfMonthKeyboard --- bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot.py b/bot.py index ada5658..9904572 100644 --- a/bot.py +++ b/bot.py @@ -175,7 +175,7 @@ def getOptionsForDaysOfMonthKeyboard(): rowOptions = [] now = datetime.datetime.now() daysInMonth = calendar.monthrange(now.year, now.month)[1] - strDays = str(daysInMonth) + strDays = str(daysInMonth) + '' options.append(strDays) # count = 1 # while count <= daysInMonth: From f39d9c5cc6ef77330293243ef390008393f0d0b2 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 14:47:00 +0300 Subject: [PATCH 076/147] update getOptionsForDaysOfMonthKeyboard --- bot.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/bot.py b/bot.py index 9904572..0059465 100644 --- a/bot.py +++ b/bot.py @@ -175,8 +175,9 @@ def getOptionsForDaysOfMonthKeyboard(): rowOptions = [] now = datetime.datetime.now() daysInMonth = calendar.monthrange(now.year, now.month)[1] - strDays = str(daysInMonth) + '' - options.append(strDays) + strDays = str(daysInMonth) + rowOptions.append(strDays) + options.append(rowOptions) # count = 1 # while count <= daysInMonth: # strCount = str(count) From 432731b1b28772c4490cfa4a3620789d96645272 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 14:50:17 +0300 Subject: [PATCH 077/147] update getOptionsForDaysOfMonthKeyboard --- bot.py | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/bot.py b/bot.py index 0059465..1318884 100644 --- a/bot.py +++ b/bot.py @@ -175,22 +175,22 @@ def getOptionsForDaysOfMonthKeyboard(): rowOptions = [] now = datetime.datetime.now() daysInMonth = calendar.monthrange(now.year, now.month)[1] - strDays = str(daysInMonth) - rowOptions.append(strDays) - options.append(rowOptions) - # count = 1 - # while count <= daysInMonth: - # strCount = str(count) - # if (count == daysInMonth): - # lenOptions = len(options) - # options[lenOptions].append(strCount) - # elif (len(rowOptions) >= 4): - # rowOptions.append(strCount) - # options.append(rowOptions) - # rowOptions = [] - # else: - # rowOptions.append(strCount) - # count += 1 + count = 1 + while count <= daysInMonth: + strCount = str(count) + rowOptions.append(strCount) + options.append(rowOptions) + rowOptions = [] + # if (count == daysInMonth): + # lenOptions = len(options) + # options[lenOptions].append(strCount) + # elif (len(rowOptions) >= 4): + # rowOptions.append(strCount) + # options.append(rowOptions) + # rowOptions = [] + # else: + # rowOptions.append(strCount) + count += 1 return options From f8ef3dbbb3eb3e0f9a1c447a2bbab9a4e16844c8 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 14:53:43 +0300 Subject: [PATCH 078/147] update getOptionsForDaysOfMonthKeyboard --- bot.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/bot.py b/bot.py index 1318884..2070374 100644 --- a/bot.py +++ b/bot.py @@ -175,8 +175,12 @@ def getOptionsForDaysOfMonthKeyboard(): rowOptions = [] now = datetime.datetime.now() daysInMonth = calendar.monthrange(now.year, now.month)[1] + rowOptions.append('1') + rowOptions.append(str(len(rowOptions))) + options.append(rowOptions) count = 1 while count <= daysInMonth: + strCount = str(count) rowOptions.append(strCount) options.append(rowOptions) From b543f4a43ebe72ab4692b01ddfe059b2cfd3a204 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 14:57:18 +0300 Subject: [PATCH 079/147] update getOptionsForDaysOfMonthKeyboard --- bot.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/bot.py b/bot.py index 2070374..2432db2 100644 --- a/bot.py +++ b/bot.py @@ -175,16 +175,16 @@ def getOptionsForDaysOfMonthKeyboard(): rowOptions = [] now = datetime.datetime.now() daysInMonth = calendar.monthrange(now.year, now.month)[1] - rowOptions.append('1') - rowOptions.append(str(len(rowOptions))) options.append(rowOptions) count = 1 while count <= daysInMonth: - strCount = str(count) - rowOptions.append(strCount) - options.append(rowOptions) - rowOptions = [] + if len(rowOptions) >= 4: + rowOptions.append(strCount) + options.append(rowOptions) + rowOptions = [] + else: + rowOptions.append(strCount) # if (count == daysInMonth): # lenOptions = len(options) # options[lenOptions].append(strCount) From 8394c13b53b3096db177f03c9fb25d8fd6cd7bd3 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 15:01:46 +0300 Subject: [PATCH 080/147] update getOptionsForDaysOfMonthKeyboard --- bot.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/bot.py b/bot.py index 2432db2..b0bcc02 100644 --- a/bot.py +++ b/bot.py @@ -175,11 +175,10 @@ def getOptionsForDaysOfMonthKeyboard(): rowOptions = [] now = datetime.datetime.now() daysInMonth = calendar.monthrange(now.year, now.month)[1] - options.append(rowOptions) count = 1 while count <= daysInMonth: strCount = str(count) - if len(rowOptions) >= 4: + if len(rowOptions) >= 4 or count == daysInMonth: rowOptions.append(strCount) options.append(rowOptions) rowOptions = [] From bda28f54e97ccdbce0408c011c444f4be0db83f1 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 15:04:09 +0300 Subject: [PATCH 081/147] update creatingCardDate --- bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot.py b/bot.py index b0bcc02..c235309 100644 --- a/bot.py +++ b/bot.py @@ -109,7 +109,7 @@ def creatingCardDate(update,user,message): now = datetime.datetime.now() daysInMonth = calendar.monthrange(now.year, now.month)[1] strDays = str(daysInMonth) - update.message.reply_text('Выберите число ' + strDays, + update.message.reply_text('Выберите число \n или' + strDays, reply_markup=daysOfMonthKeyboard()) elif message == 'отмена': update.message.reply_text('Что вы хотите сделать?', From c45a43660aed75fb57572ae99e54fec98df41fc3 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 15:09:01 +0300 Subject: [PATCH 082/147] update creatingCardDate --- bot.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/bot.py b/bot.py index c235309..c62aa48 100644 --- a/bot.py +++ b/bot.py @@ -109,7 +109,12 @@ def creatingCardDate(update,user,message): now = datetime.datetime.now() daysInMonth = calendar.monthrange(now.year, now.month)[1] strDays = str(daysInMonth) - update.message.reply_text('Выберите число \n или' + strDays, + replyMessage = """Выберите число + или Введите дату вручную(день-месяц-число) + Пример: + 2021-03-31 + """ + update.message.reply_text('Выберите число \n или Введите дату вручную(день-месяц-число)\n Пример:\n' + strDays, reply_markup=daysOfMonthKeyboard()) elif message == 'отмена': update.message.reply_text('Что вы хотите сделать?', From e07f5ce6f97c342cba64995182d40ae0deb798f6 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 15:09:27 +0300 Subject: [PATCH 083/147] update creatingCardDate --- bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot.py b/bot.py index c62aa48..d30016a 100644 --- a/bot.py +++ b/bot.py @@ -114,7 +114,7 @@ def creatingCardDate(update,user,message): Пример: 2021-03-31 """ - update.message.reply_text('Выберите число \n или Введите дату вручную(день-месяц-число)\n Пример:\n' + strDays, + update.message.reply_text(replyMessage, reply_markup=daysOfMonthKeyboard()) elif message == 'отмена': update.message.reply_text('Что вы хотите сделать?', From b748b056b362963fcbbbb4282a6ec561f8a30f95 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 15:12:09 +0300 Subject: [PATCH 084/147] update creatingCardDate --- bot.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/bot.py b/bot.py index d30016a..96e2179 100644 --- a/bot.py +++ b/bot.py @@ -109,10 +109,10 @@ def creatingCardDate(update,user,message): now = datetime.datetime.now() daysInMonth = calendar.monthrange(now.year, now.month)[1] strDays = str(daysInMonth) - replyMessage = """Выберите число - или Введите дату вручную(день-месяц-число) - Пример: - 2021-03-31 + replyMessage = """Выберите число +или Введите дату вручную(день-месяц-число) +Пример: +2021-03-31 """ update.message.reply_text(replyMessage, reply_markup=daysOfMonthKeyboard()) From 09ef46aa9232b07f8d33dc5279cbaf37ea19a1f2 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 15:16:08 +0300 Subject: [PATCH 085/147] creatingCardDate --- bot.py | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/bot.py b/bot.py index 96e2179..d31387d 100644 --- a/bot.py +++ b/bot.py @@ -106,11 +106,8 @@ def creatingCardDate(update,user,message): if message == 'сегодня': 'here should be code' elif message == 'календарь': - now = datetime.datetime.now() - daysInMonth = calendar.monthrange(now.year, now.month)[1] - strDays = str(daysInMonth) - replyMessage = """Выберите число -или Введите дату вручную(день-месяц-число) + update.message.reply_text('Выберите число') + replyMessage = """Или Введите дату вручную(день-месяц-число) Пример: 2021-03-31 """ From ddab36cb8d23aff4ae242020d0b3f2d50f12bee9 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 15:41:16 +0300 Subject: [PATCH 086/147] create getDateFromString --- bot.py | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/bot.py b/bot.py index d31387d..17810ea 100644 --- a/bot.py +++ b/bot.py @@ -95,14 +95,20 @@ def echoForExistUser(update,context): update.message.reply_text('ты не должен видеть это сообщение') def creatingCard(update,user,message): - if user.card.date == None: + if user.card.date == None or user.card.date == True: creatingCardDate(update,user,message) - elif user.card.amount == None: + elif user.card.amount == None or user.card.amount == True: creatingCardAmount(update,user,message) - elif user.card.description == None: + elif user.card.description == None or user.card.description == True: creatingCardDecription(update,user,message) def creatingCardDate(update,user,message): + if user.card.date == None: + creatingCardDateNone(update,user,message) + elif user.card.date == True: + getDateFromString(update,message) + +def creatingCardDateNone(update,user,message): if message == 'сегодня': 'here should be code' elif message == 'календарь': @@ -116,12 +122,20 @@ def creatingCardDate(update,user,message): elif message == 'отмена': update.message.reply_text('Что вы хотите сделать?', reply_markup=mainMenuKeyboard()) + user.card.date == True def creatingCardAmount(update,user,message): '' def creatingCardDecription(update,user,message): '' +def getDateFromString(update,message): + if len(message) < 3: + now = datetime.datetime.now() + dateStr = str(now.year)+'-'+str(now.month)+'-'+message + update.message.reply_text(dateStr, + reply_markup=ReplyKeyboardRemove()) + def error(update, context): """Log Errors caused by Updates.""" logger.warning('Update "%s" caused error "%s"', update, context.error) From 8fc2ce821d1d199e8942a47c8d3af3e86ede055e Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 15:44:13 +0300 Subject: [PATCH 087/147] update creatingCardDate --- bot.py | 1 + 1 file changed, 1 insertion(+) diff --git a/bot.py b/bot.py index 17810ea..1bfec68 100644 --- a/bot.py +++ b/bot.py @@ -106,6 +106,7 @@ def creatingCardDate(update,user,message): if user.card.date == None: creatingCardDateNone(update,user,message) elif user.card.date == True: + update.message.reply_text('hello') getDateFromString(update,message) def creatingCardDateNone(update,user,message): From 3fd0526aff388832192679126880063d0d7c3f1f Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 15:46:33 +0300 Subject: [PATCH 088/147] debug --- bot.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/bot.py b/bot.py index 1bfec68..ff47170 100644 --- a/bot.py +++ b/bot.py @@ -95,6 +95,7 @@ def echoForExistUser(update,context): update.message.reply_text('ты не должен видеть это сообщение') def creatingCard(update,user,message): + update.message.reply_text('creatingCard') if user.card.date == None or user.card.date == True: creatingCardDate(update,user,message) elif user.card.amount == None or user.card.amount == True: @@ -103,10 +104,11 @@ def creatingCard(update,user,message): creatingCardDecription(update,user,message) def creatingCardDate(update,user,message): + update.message.reply_text('creatingCardDate') if user.card.date == None: creatingCardDateNone(update,user,message) elif user.card.date == True: - update.message.reply_text('hello') + update.message.reply_text('True') getDateFromString(update,message) def creatingCardDateNone(update,user,message): From ba60920d6162f6ea56c7882dcd250aa16c55479f Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 15:48:47 +0300 Subject: [PATCH 089/147] debug --- bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot.py b/bot.py index ff47170..2019fc5 100644 --- a/bot.py +++ b/bot.py @@ -104,7 +104,7 @@ def creatingCard(update,user,message): creatingCardDecription(update,user,message) def creatingCardDate(update,user,message): - update.message.reply_text('creatingCardDate') + update.message.reply_text('creatingCardDate ' + str(user.card.date)) if user.card.date == None: creatingCardDateNone(update,user,message) elif user.card.date == True: From 78632b9eb14763dee56c66b88e43a9b69eba1dc4 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 15:51:03 +0300 Subject: [PATCH 090/147] debug --- bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot.py b/bot.py index 2019fc5..e810c70 100644 --- a/bot.py +++ b/bot.py @@ -125,7 +125,7 @@ def creatingCardDateNone(update,user,message): elif message == 'отмена': update.message.reply_text('Что вы хотите сделать?', reply_markup=mainMenuKeyboard()) - user.card.date == True + user.card.date = True def creatingCardAmount(update,user,message): '' From 728a4272ccbe9bd29341b194208d0ae75e377042 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 15:56:08 +0300 Subject: [PATCH 091/147] update getDateFromString --- bot.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/bot.py b/bot.py index e810c70..27670cd 100644 --- a/bot.py +++ b/bot.py @@ -136,7 +136,8 @@ def getDateFromString(update,message): if len(message) < 3: now = datetime.datetime.now() dateStr = str(now.year)+'-'+str(now.month)+'-'+message - update.message.reply_text(dateStr, + dateObject = datetime.strptime(dateStr, '%Y-%m-%d').date() + update.message.reply_text(str(dateObject), reply_markup=ReplyKeyboardRemove()) def error(update, context): From 61685d31aabafe559fd6acebd6de4da4f04f18ae Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 16:00:36 +0300 Subject: [PATCH 092/147] update getDateFromString --- bot.py | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/bot.py b/bot.py index 27670cd..bec95e0 100644 --- a/bot.py +++ b/bot.py @@ -133,12 +133,15 @@ def creatingCardDecription(update,user,message): '' def getDateFromString(update,message): - if len(message) < 3: - now = datetime.datetime.now() - dateStr = str(now.year)+'-'+str(now.month)+'-'+message - dateObject = datetime.strptime(dateStr, '%Y-%m-%d').date() - update.message.reply_text(str(dateObject), - reply_markup=ReplyKeyboardRemove()) + try: + if len(message) < 3: + now = datetime.datetime.now() + dateStr = str(now.year)+'-'+str(now.month)+'-'+message + dateObject = datetime.strptime(dateStr, '%Y-%m-%d').date() + update.message.reply_text(str(dateObject), + reply_markup=ReplyKeyboardRemove()) + except Exception: + update.message.reply_text(str(Exception)) def error(update, context): """Log Errors caused by Updates.""" From fc19dcd16540d81e3908f39540c7f7f9f5f82f9a Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 16:03:47 +0300 Subject: [PATCH 093/147] update getDateFromString --- bot.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/bot.py b/bot.py index bec95e0..3fc6512 100644 --- a/bot.py +++ b/bot.py @@ -140,8 +140,8 @@ def getDateFromString(update,message): dateObject = datetime.strptime(dateStr, '%Y-%m-%d').date() update.message.reply_text(str(dateObject), reply_markup=ReplyKeyboardRemove()) - except Exception: - update.message.reply_text(str(Exception)) + except Exception as e: + update.message.reply_text(str(e)) def error(update, context): """Log Errors caused by Updates.""" From 516c7dcc2642b899f18f81ebc057276e6e8aaf88 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 16:05:41 +0300 Subject: [PATCH 094/147] update import --- bot.py | 1 + 1 file changed, 1 insertion(+) diff --git a/bot.py b/bot.py index 3fc6512..3f86390 100644 --- a/bot.py +++ b/bot.py @@ -1,5 +1,6 @@ import logging import calendar +from datetime import datetime import datetime from telegram import ReplyKeyboardMarkup, Update, ReplyKeyboardRemove from telegram.ext import ( From 4296ecf4322d59d3e2c90254cb48a6695f29f16c Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 16:10:30 +0300 Subject: [PATCH 095/147] debug getDateFromString --- bot.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/bot.py b/bot.py index 3f86390..02d544e 100644 --- a/bot.py +++ b/bot.py @@ -1,6 +1,5 @@ import logging import calendar -from datetime import datetime import datetime from telegram import ReplyKeyboardMarkup, Update, ReplyKeyboardRemove from telegram.ext import ( @@ -136,10 +135,12 @@ def creatingCardDecription(update,user,message): def getDateFromString(update,message): try: if len(message) < 3: - now = datetime.datetime.now() - dateStr = str(now.year)+'-'+str(now.month)+'-'+message - dateObject = datetime.strptime(dateStr, '%Y-%m-%d').date() - update.message.reply_text(str(dateObject), + # now = datetime.datetime.now() + # dateStr = str(now.year)+'-'+str(now.month)+'-'+message + # dateObject = datetime.strptime(dateStr, '%Y-%m-%d').date() + date_time_str = '2018-06-29 08:15:27.243860' + date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f') + update.message.reply_text(str(date_time_obj), reply_markup=ReplyKeyboardRemove()) except Exception as e: update.message.reply_text(str(e)) From f77fb532a3ba4fa225f1f0cc3c5e1141b191378c Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 16:12:16 +0300 Subject: [PATCH 096/147] debug getDateFromString --- bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot.py b/bot.py index 02d544e..eee5983 100644 --- a/bot.py +++ b/bot.py @@ -138,7 +138,7 @@ def getDateFromString(update,message): # now = datetime.datetime.now() # dateStr = str(now.year)+'-'+str(now.month)+'-'+message # dateObject = datetime.strptime(dateStr, '%Y-%m-%d').date() - date_time_str = '2018-06-29 08:15:27.243860' + date_time_str = '2018-6-29 08:15:27.243860' date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f') update.message.reply_text(str(date_time_obj), reply_markup=ReplyKeyboardRemove()) From 9c1981b9dfc194a5fcee697eb85a630954896e3e Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 16:14:18 +0300 Subject: [PATCH 097/147] debug getDateFromString --- bot.py | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/bot.py b/bot.py index eee5983..4045f2f 100644 --- a/bot.py +++ b/bot.py @@ -135,12 +135,11 @@ def creatingCardDecription(update,user,message): def getDateFromString(update,message): try: if len(message) < 3: - # now = datetime.datetime.now() - # dateStr = str(now.year)+'-'+str(now.month)+'-'+message - # dateObject = datetime.strptime(dateStr, '%Y-%m-%d').date() - date_time_str = '2018-6-29 08:15:27.243860' - date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f') - update.message.reply_text(str(date_time_obj), + now = datetime.datetime.now() + dateStr = str(now.year)+'-'+str(now.month)+'-'+message + #date_str = '2018-6-29 08:15:27.243860' + dateObject = datetime.datetime.strptime(dateStr, '%Y-%m-%d').date + update.message.reply_text(str(dateObject), reply_markup=ReplyKeyboardRemove()) except Exception as e: update.message.reply_text(str(e)) From dbb3506f21961835ea81e03d0dedb9e2b152bda6 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 16:17:15 +0300 Subject: [PATCH 098/147] debug getDateFromString --- bot.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/bot.py b/bot.py index 4045f2f..5130e52 100644 --- a/bot.py +++ b/bot.py @@ -136,10 +136,11 @@ def getDateFromString(update,message): try: if len(message) < 3: now = datetime.datetime.now() - dateStr = str(now.year)+'-'+str(now.month)+'-'+message - #date_str = '2018-6-29 08:15:27.243860' - dateObject = datetime.datetime.strptime(dateStr, '%Y-%m-%d').date - update.message.reply_text(str(dateObject), + # dateStr = str(now.year)+'-'+str(now.month)+'-'+message + # dateObject = datetime.strptime(dateStr, '%Y-%m-%d').date() + date_time_str = '2018-6-29 08:15:27' + date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S') + update.message.reply_text(str(date_time_obj), reply_markup=ReplyKeyboardRemove()) except Exception as e: update.message.reply_text(str(e)) From f5656a737e10088b8e89aadc23e09d98499dd07d Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 16:19:10 +0300 Subject: [PATCH 099/147] debug getDateFromString --- bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot.py b/bot.py index 5130e52..1235863 100644 --- a/bot.py +++ b/bot.py @@ -138,7 +138,7 @@ def getDateFromString(update,message): now = datetime.datetime.now() # dateStr = str(now.year)+'-'+str(now.month)+'-'+message # dateObject = datetime.strptime(dateStr, '%Y-%m-%d').date() - date_time_str = '2018-6-29 08:15:27' + date_time_str = str(now.year)+'-'+str(now.month)+'-'+message + ' 08:15:27' date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S') update.message.reply_text(str(date_time_obj), reply_markup=ReplyKeyboardRemove()) From da452b0c7d59c584d7852d678fc52f6957167c44 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 16:26:03 +0300 Subject: [PATCH 100/147] debug getDateFromString --- bot.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/bot.py b/bot.py index 1235863..0289c6a 100644 --- a/bot.py +++ b/bot.py @@ -138,9 +138,9 @@ def getDateFromString(update,message): now = datetime.datetime.now() # dateStr = str(now.year)+'-'+str(now.month)+'-'+message # dateObject = datetime.strptime(dateStr, '%Y-%m-%d').date() - date_time_str = str(now.year)+'-'+str(now.month)+'-'+message + ' 08:15:27' - date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S') - update.message.reply_text(str(date_time_obj), + dateStr = str(now.year)+'-'+str(now.month)+'-'+message + ' 00:00:00' + dateObject = datetime.datetime.strptime(dateStr, '%Y-%m-%d %H:%M:%S') + update.message.reply_text(str(dateObject), reply_markup=ReplyKeyboardRemove()) except Exception as e: update.message.reply_text(str(e)) From e3ee7776280d4ffe02cc6c3a0f79ed700d809622 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 16:30:10 +0300 Subject: [PATCH 101/147] update getDateFromString --- bot.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/bot.py b/bot.py index 0289c6a..410ab65 100644 --- a/bot.py +++ b/bot.py @@ -95,7 +95,6 @@ def echoForExistUser(update,context): update.message.reply_text('ты не должен видеть это сообщение') def creatingCard(update,user,message): - update.message.reply_text('creatingCard') if user.card.date == None or user.card.date == True: creatingCardDate(update,user,message) elif user.card.amount == None or user.card.amount == True: @@ -104,11 +103,9 @@ def creatingCard(update,user,message): creatingCardDecription(update,user,message) def creatingCardDate(update,user,message): - update.message.reply_text('creatingCardDate ' + str(user.card.date)) if user.card.date == None: creatingCardDateNone(update,user,message) elif user.card.date == True: - update.message.reply_text('True') getDateFromString(update,message) def creatingCardDateNone(update,user,message): @@ -134,14 +131,18 @@ def creatingCardDecription(update,user,message): def getDateFromString(update,message): try: + dateStr = '' if len(message) < 3: now = datetime.datetime.now() - # dateStr = str(now.year)+'-'+str(now.month)+'-'+message - # dateObject = datetime.strptime(dateStr, '%Y-%m-%d').date() dateStr = str(now.year)+'-'+str(now.month)+'-'+message + ' 00:00:00' dateObject = datetime.datetime.strptime(dateStr, '%Y-%m-%d %H:%M:%S') update.message.reply_text(str(dateObject), reply_markup=ReplyKeyboardRemove()) + else: + dateStr = message + dateObject = datetime.datetime.strptime(dateStr, '%Y-%m-%d %H:%M:%S') + update.message.reply_text(str(dateObject), + reply_markup=ReplyKeyboardRemove()) except Exception as e: update.message.reply_text(str(e)) From 9da2a6a977283855f5e2305744220c9fadb54bd7 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 16:33:24 +0300 Subject: [PATCH 102/147] update getDateFromString --- bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot.py b/bot.py index 410ab65..866d0fe 100644 --- a/bot.py +++ b/bot.py @@ -139,7 +139,7 @@ def getDateFromString(update,message): update.message.reply_text(str(dateObject), reply_markup=ReplyKeyboardRemove()) else: - dateStr = message + dateStr = message + ' 00:00:00' dateObject = datetime.datetime.strptime(dateStr, '%Y-%m-%d %H:%M:%S') update.message.reply_text(str(dateObject), reply_markup=ReplyKeyboardRemove()) From a1539c29545ea0700bac01e3c5993bd2fa6f1a6c Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 16:42:19 +0300 Subject: [PATCH 103/147] update getDateFromString --- bot.py | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/bot.py b/bot.py index 866d0fe..10f1928 100644 --- a/bot.py +++ b/bot.py @@ -135,16 +135,15 @@ def getDateFromString(update,message): if len(message) < 3: now = datetime.datetime.now() dateStr = str(now.year)+'-'+str(now.month)+'-'+message + ' 00:00:00' - dateObject = datetime.datetime.strptime(dateStr, '%Y-%m-%d %H:%M:%S') - update.message.reply_text(str(dateObject), - reply_markup=ReplyKeyboardRemove()) else: dateStr = message + ' 00:00:00' - dateObject = datetime.datetime.strptime(dateStr, '%Y-%m-%d %H:%M:%S') - update.message.reply_text(str(dateObject), - reply_markup=ReplyKeyboardRemove()) + + dateObject = datetime.datetime.strptime(dateStr, '%Y-%m-%d %H:%M:%S') + return dateObject.date except Exception as e: - update.message.reply_text(str(e)) + update.message.reply_text('Кажется вы неправильно ввели дату. Попробуйте еще раз или обратитесь к администратору') + return None + #update.message.reply_text(str(e)) def error(update, context): """Log Errors caused by Updates.""" From e1b923a04d946cf72d18cbdcb2fe932a941012f4 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 16:50:00 +0300 Subject: [PATCH 104/147] update creatingCardDate --- bot.py | 35 +++++++++++++++++++---------------- 1 file changed, 19 insertions(+), 16 deletions(-) diff --git a/bot.py b/bot.py index 10f1928..1432002 100644 --- a/bot.py +++ b/bot.py @@ -106,11 +106,17 @@ def creatingCardDate(update,user,message): if user.card.date == None: creatingCardDateNone(update,user,message) elif user.card.date == True: - getDateFromString(update,message) + try: + cardDate = getDateFromString(update,message) + user.card.date = cardDate + except Exception as e: + update.message.reply_text('Кажется вы неправильно ввели дату. Попробуйте еще раз или обратитесь к администратору. Пример: 2021-03-31') + #update.message.reply_text(str(e)) def creatingCardDateNone(update,user,message): if message == 'сегодня': 'here should be code' + user.card.date = True elif message == 'календарь': update.message.reply_text('Выберите число') replyMessage = """Или Введите дату вручную(день-месяц-число) @@ -119,10 +125,11 @@ def creatingCardDateNone(update,user,message): """ update.message.reply_text(replyMessage, reply_markup=daysOfMonthKeyboard()) + user.card.date = True elif message == 'отмена': + user.card = None update.message.reply_text('Что вы хотите сделать?', reply_markup=mainMenuKeyboard()) - user.card.date = True def creatingCardAmount(update,user,message): '' @@ -130,20 +137,16 @@ def creatingCardDecription(update,user,message): '' def getDateFromString(update,message): - try: - dateStr = '' - if len(message) < 3: - now = datetime.datetime.now() - dateStr = str(now.year)+'-'+str(now.month)+'-'+message + ' 00:00:00' - else: - dateStr = message + ' 00:00:00' - - dateObject = datetime.datetime.strptime(dateStr, '%Y-%m-%d %H:%M:%S') - return dateObject.date - except Exception as e: - update.message.reply_text('Кажется вы неправильно ввели дату. Попробуйте еще раз или обратитесь к администратору') - return None - #update.message.reply_text(str(e)) + dateStr = '' + if len(message) < 3: + now = datetime.datetime.now() + dateStr = str(now.year)+'-'+str(now.month)+'-'+message + ' 00:00:00' + else: + dateStr = message + ' 00:00:00' + + dateObject = datetime.datetime.strptime(dateStr, '%Y-%m-%d %H:%M:%S') + return dateObject.date + def error(update, context): """Log Errors caused by Updates.""" From 9cd11f5d40186fcf076af61c866c9178dc709abc Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 16:55:41 +0300 Subject: [PATCH 105/147] update creatingCardDate From 8a83a1e791cf277a1768e317c0e0ed7e657ca5a2 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 17:05:41 +0300 Subject: [PATCH 106/147] create cancel keyboard --- bot.py | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/bot.py b/bot.py index 1432002..f32c652 100644 --- a/bot.py +++ b/bot.py @@ -1,6 +1,8 @@ import logging import calendar import datetime + +from requests.api import options from telegram import ReplyKeyboardMarkup, Update, ReplyKeyboardRemove from telegram.ext import ( Updater, @@ -89,6 +91,8 @@ def echoForExistUser(update,context): user.card = Card() update.message.reply_text('На какой день желаете создать карточку?', reply_markup=createCardKeyboard()) + elif message == 'отмена': + cancelToMainMenu(update,user) elif user.card != None: creatingCard(update,user,message) @@ -110,7 +114,8 @@ def creatingCardDate(update,user,message): cardDate = getDateFromString(update,message) user.card.date = cardDate except Exception as e: - update.message.reply_text('Кажется вы неправильно ввели дату. Попробуйте еще раз или обратитесь к администратору. Пример: 2021-03-31') + update.message.reply_text('Кажется вы неправильно ввели дату. Попробуйте еще раз или обратитесь к администратору. Пример: 2021-03-31', + reply_markup=cancelKeyboard()) #update.message.reply_text(str(e)) def creatingCardDateNone(update,user,message): @@ -126,10 +131,6 @@ def creatingCardDateNone(update,user,message): update.message.reply_text(replyMessage, reply_markup=daysOfMonthKeyboard()) user.card.date = True - elif message == 'отмена': - user.card = None - update.message.reply_text('Что вы хотите сделать?', - reply_markup=mainMenuKeyboard()) def creatingCardAmount(update,user,message): '' @@ -185,11 +186,19 @@ def login(update, context): # else: # update.message.reply_text('Неправильный логин или пароль.Попробуйте Снова') +def cancelToMainMenu(update,user): + user.card = None + update.message.reply_text('Что вы хотите сделать?', + reply_markup=mainMenuKeyboard()) #########################Keyboards############################ def mainMenuKeyboard(): options = [['Текущий баланс'],['Создать карточку']] return ReplyKeyboardMarkup(options) +def cancelKeyboard(): + options = [['Отмена'],[]] + return ReplyKeyboardMarkup(options, one_time_keyboard=True) + def createCardKeyboard(): options = [['Сегодня'],['Календарь'],['Отмена']] return ReplyKeyboardMarkup(options, one_time_keyboard=True) From 554ebc6849272edebe7635bd63f164950d56c836 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 17:19:21 +0300 Subject: [PATCH 107/147] update creatingCardAmount, creatingCardDecription --- bot.py | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/bot.py b/bot.py index f32c652..83b28dc 100644 --- a/bot.py +++ b/bot.py @@ -133,9 +133,21 @@ def creatingCardDateNone(update,user,message): user.card.date = True def creatingCardAmount(update,user,message): - '' + if user.card.date == None: + update.message.reply_text('Введите сумму') + elif user.card.date == True: + try: + cardAmount = float(message) + user.card.amount = cardAmount + except Exception as e: + update.message.reply_text('Кажется вы неправильно ввели сумму. Попробуйте еще раз или обратитесь к администратору. Пример: 5.014', + reply_markup=cancelKeyboard()) + def creatingCardDecription(update,user,message): - '' + if user.card.date == None: + update.message.reply_text('Введите описание') + elif user.card.date == True: + user.card.description = message def getDateFromString(update,message): dateStr = '' From 8c97f8c4ee11223abd2fb0d1891040514b931f3d Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 17:24:58 +0300 Subject: [PATCH 108/147] debug creatingCardAmount --- bot.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/bot.py b/bot.py index 83b28dc..8252897 100644 --- a/bot.py +++ b/bot.py @@ -113,6 +113,7 @@ def creatingCardDate(update,user,message): try: cardDate = getDateFromString(update,message) user.card.date = cardDate + creatingCardAmount(update,user,message) except Exception as e: update.message.reply_text('Кажется вы неправильно ввели дату. Попробуйте еще раз или обратитесь к администратору. Пример: 2021-03-31', reply_markup=cancelKeyboard()) @@ -138,7 +139,8 @@ def creatingCardAmount(update,user,message): elif user.card.date == True: try: cardAmount = float(message) - user.card.amount = cardAmount + update.message.reply_text(cardAmount) + #user.card.amount = cardAmount except Exception as e: update.message.reply_text('Кажется вы неправильно ввели сумму. Попробуйте еще раз или обратитесь к администратору. Пример: 5.014', reply_markup=cancelKeyboard()) From a095cd612ff1666126d6678c4655cf7470e35110 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 17:26:48 +0300 Subject: [PATCH 109/147] debug --- bot.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/bot.py b/bot.py index 8252897..8eff979 100644 --- a/bot.py +++ b/bot.py @@ -134,9 +134,9 @@ def creatingCardDateNone(update,user,message): user.card.date = True def creatingCardAmount(update,user,message): - if user.card.date == None: + if user.card.amount == None: update.message.reply_text('Введите сумму') - elif user.card.date == True: + elif user.card.amount == True: try: cardAmount = float(message) update.message.reply_text(cardAmount) @@ -146,9 +146,9 @@ def creatingCardAmount(update,user,message): reply_markup=cancelKeyboard()) def creatingCardDecription(update,user,message): - if user.card.date == None: + if user.card.description == None: update.message.reply_text('Введите описание') - elif user.card.date == True: + elif user.card.description == True: user.card.description = message def getDateFromString(update,message): From f04fc4a0159f1158d3aa39d70c24121963128b83 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 17:29:25 +0300 Subject: [PATCH 110/147] debug --- bot.py | 1 + 1 file changed, 1 insertion(+) diff --git a/bot.py b/bot.py index 8eff979..77d66ef 100644 --- a/bot.py +++ b/bot.py @@ -136,6 +136,7 @@ def creatingCardDateNone(update,user,message): def creatingCardAmount(update,user,message): if user.card.amount == None: update.message.reply_text('Введите сумму') + user.card.amount = True elif user.card.amount == True: try: cardAmount = float(message) From d67320d4c3ea74e97698feac73135d14726572aa Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 17:55:35 +0300 Subject: [PATCH 111/147] create confirmCreateCard --- bot.py | 34 ++++++++++++++++++++++++++++++---- 1 file changed, 30 insertions(+), 4 deletions(-) diff --git a/bot.py b/bot.py index 77d66ef..f1e5afd 100644 --- a/bot.py +++ b/bot.py @@ -39,12 +39,14 @@ def __init__(self): self.contact = None self.newCard = None + class Card: def __init__(self): self.date = None self.amount = None self.description = None self.keeper = None + self.confirmCreate = None usersTelegram = {} @@ -106,6 +108,9 @@ def creatingCard(update,user,message): elif user.card.description == None or user.card.description == True: creatingCardDecription(update,user,message) + if isinstance(user.card.description,str): + '' + def creatingCardDate(update,user,message): if user.card.date == None: creatingCardDateNone(update,user,message) @@ -140,8 +145,8 @@ def creatingCardAmount(update,user,message): elif user.card.amount == True: try: cardAmount = float(message) - update.message.reply_text(cardAmount) - #user.card.amount = cardAmount + user.card.amount = cardAmount + creatingCardDecription(update,user,message) except Exception as e: update.message.reply_text('Кажется вы неправильно ввели сумму. Попробуйте еще раз или обратитесь к администратору. Пример: 5.014', reply_markup=cancelKeyboard()) @@ -149,8 +154,23 @@ def creatingCardAmount(update,user,message): def creatingCardDecription(update,user,message): if user.card.description == None: update.message.reply_text('Введите описание') + user.card.description = True elif user.card.description == True: - user.card.description = message + user.card.description = str(message) + +def confirmCreateCard(update,user,message): + if user.card.confirmCreate == None: + update.message.reply_text('Вы уверены что хотите создать следующую карточку?') + update.message.reply_text('Дата: ' + str(user.card.date)) + update.message.reply_text('Сумма: ' + str(user.card.amount)) + update.message.reply_text('Описание: ' + str(user.card.description), reply_markup=confirmKeyboard()) + user.card.confirmCreate = True + elif user.card.confirmCreate == True: + createCardInSalesforce(update,user) + user.card = None + +def createCardInSalesforce(update,user): + '' def getDateFromString(update,message): dateStr = '' @@ -211,7 +231,7 @@ def mainMenuKeyboard(): return ReplyKeyboardMarkup(options) def cancelKeyboard(): - options = [['Отмена'],[]] + options = [['Отмена']] return ReplyKeyboardMarkup(options, one_time_keyboard=True) def createCardKeyboard(): @@ -222,6 +242,12 @@ def daysOfMonthKeyboard(): options = getOptionsForDaysOfMonthKeyboard() return ReplyKeyboardMarkup(options, one_time_keyboard=True) +def confirmKeyboard(): + options = [['Да'],['Отмена']] + return ReplyKeyboardMarkup(options, one_time_keyboard=True) + +#########################Keyboards############################ + def getOptionsForDaysOfMonthKeyboard(): options = [] rowOptions = [] From 8b0feccf16fbdcd47bdc839deeb6fc9bdb4384eb Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 18:01:10 +0300 Subject: [PATCH 112/147] UPDATE creatingCard --- bot.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/bot.py b/bot.py index f1e5afd..edcbb87 100644 --- a/bot.py +++ b/bot.py @@ -107,9 +107,9 @@ def creatingCard(update,user,message): creatingCardAmount(update,user,message) elif user.card.description == None or user.card.description == True: creatingCardDecription(update,user,message) - - if isinstance(user.card.description,str): - '' + elif isinstance(user.card.description,str): + confirmCreateCard(update,user,message) + def creatingCardDate(update,user,message): if user.card.date == None: @@ -157,6 +157,7 @@ def creatingCardDecription(update,user,message): user.card.description = True elif user.card.description == True: user.card.description = str(message) + confirmCreateCard(update,user,message) def confirmCreateCard(update,user,message): if user.card.confirmCreate == None: From cbcf3d0f7d0aa5111a538018a681f8c5fc2ffe68 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 18:04:44 +0300 Subject: [PATCH 113/147] update getDateFromString --- bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot.py b/bot.py index edcbb87..75657b7 100644 --- a/bot.py +++ b/bot.py @@ -182,7 +182,7 @@ def getDateFromString(update,message): dateStr = message + ' 00:00:00' dateObject = datetime.datetime.strptime(dateStr, '%Y-%m-%d %H:%M:%S') - return dateObject.date + return dateObject def error(update, context): From 6c1584556dddc6db4345ecbf8f7f2a7974264fa5 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 18:08:49 +0300 Subject: [PATCH 114/147] update creatingCardDecription --- bot.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/bot.py b/bot.py index 75657b7..d80748b 100644 --- a/bot.py +++ b/bot.py @@ -156,13 +156,13 @@ def creatingCardDecription(update,user,message): update.message.reply_text('Введите описание') user.card.description = True elif user.card.description == True: - user.card.description = str(message) + user.card.description = update.message.text confirmCreateCard(update,user,message) def confirmCreateCard(update,user,message): if user.card.confirmCreate == None: update.message.reply_text('Вы уверены что хотите создать следующую карточку?') - update.message.reply_text('Дата: ' + str(user.card.date)) + update.message.reply_text('Дата: ' + str(user.card.date.date)) update.message.reply_text('Сумма: ' + str(user.card.amount)) update.message.reply_text('Описание: ' + str(user.card.description), reply_markup=confirmKeyboard()) user.card.confirmCreate = True From 82992819f61c62928fee4112a16f7e90cfb6ae43 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 18:14:42 +0300 Subject: [PATCH 115/147] update confirmCreateCard --- bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot.py b/bot.py index d80748b..bfb4411 100644 --- a/bot.py +++ b/bot.py @@ -162,7 +162,7 @@ def creatingCardDecription(update,user,message): def confirmCreateCard(update,user,message): if user.card.confirmCreate == None: update.message.reply_text('Вы уверены что хотите создать следующую карточку?') - update.message.reply_text('Дата: ' + str(user.card.date.date)) + update.message.reply_text('Дата: ' + str(user.card.date)) update.message.reply_text('Сумма: ' + str(user.card.amount)) update.message.reply_text('Описание: ' + str(user.card.description), reply_markup=confirmKeyboard()) user.card.confirmCreate = True From 61e2f3b2124a1ea32b1a964936319c7b475d3d92 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 18:20:45 +0300 Subject: [PATCH 116/147] update confirmCreateCard --- bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot.py b/bot.py index bfb4411..5737d55 100644 --- a/bot.py +++ b/bot.py @@ -162,7 +162,7 @@ def creatingCardDecription(update,user,message): def confirmCreateCard(update,user,message): if user.card.confirmCreate == None: update.message.reply_text('Вы уверены что хотите создать следующую карточку?') - update.message.reply_text('Дата: ' + str(user.card.date)) + update.message.reply_text('Дата: ' + str(user.card.date)[:-10]) update.message.reply_text('Сумма: ' + str(user.card.amount)) update.message.reply_text('Описание: ' + str(user.card.description), reply_markup=confirmKeyboard()) user.card.confirmCreate = True From e698761b638203801b216465324a42f4154ce529 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 18:22:33 +0300 Subject: [PATCH 117/147] update confirmCreateCard --- bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot.py b/bot.py index 5737d55..9171dde 100644 --- a/bot.py +++ b/bot.py @@ -162,7 +162,7 @@ def creatingCardDecription(update,user,message): def confirmCreateCard(update,user,message): if user.card.confirmCreate == None: update.message.reply_text('Вы уверены что хотите создать следующую карточку?') - update.message.reply_text('Дата: ' + str(user.card.date)[:-10]) + update.message.reply_text('Дата: ' + str(user.card.date)[:-9]) update.message.reply_text('Сумма: ' + str(user.card.amount)) update.message.reply_text('Описание: ' + str(user.card.description), reply_markup=confirmKeyboard()) user.card.confirmCreate = True From db645cbc81ec1a75e5d8326a3de9adb5e76028ce Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 18:49:12 +0300 Subject: [PATCH 118/147] update createCardInSalesforce --- bot.py | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/bot.py b/bot.py index 9171dde..eb75b10 100644 --- a/bot.py +++ b/bot.py @@ -41,11 +41,11 @@ def __init__(self): class Card: - def __init__(self): + def __init__(self, keeper): self.date = None self.amount = None self.description = None - self.keeper = None + self.keeper = keeper self.confirmCreate = None usersTelegram = {} @@ -84,13 +84,13 @@ def echoForExistUser(update,context): message = update.message.text.lower() userId = update._effective_user.id user = usersTelegram[userId] + userContactId = user.contact['records'][0]['Id'] if message == 'текущий баланс': - userContactId = user.contact['records'][0]['Id'] balance = sf.apexecute('Contact/'+userContactId, method='GET') update.message.reply_text(str(balance), reply_markup=mainMenuKeyboard()) elif message == 'создать карточку': - user.card = Card() + user.card = Card(userContactId) update.message.reply_text('На какой день желаете создать карточку?', reply_markup=createCardKeyboard()) elif message == 'отмена': @@ -164,14 +164,18 @@ def confirmCreateCard(update,user,message): update.message.reply_text('Вы уверены что хотите создать следующую карточку?') update.message.reply_text('Дата: ' + str(user.card.date)[:-9]) update.message.reply_text('Сумма: ' + str(user.card.amount)) - update.message.reply_text('Описание: ' + str(user.card.description), reply_markup=confirmKeyboard()) + update.message.reply_text('Описание: ' + user.card.description, reply_markup=confirmKeyboard()) user.card.confirmCreate = True elif user.card.confirmCreate == True: createCardInSalesforce(update,user) user.card = None def createCardInSalesforce(update,user): - '' + try: + something = sf.Expense_Card__c.create({'CardDate__c': str(user.card.date),'Amount__c':str(user.card.amount),'Description__c':user.card.description,'CardKeeper__c':user.card.keeper}) + update.message.reply_text('Карточка успешно создана!' + str(something)) + except Exception as e: + update.message.reply_text('Извините, карточку не получилось создать' + str(e)) def getDateFromString(update,message): dateStr = '' From 1ca559da0940ba24cc81f4c3f6f488c80ab82ccd Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 19:00:03 +0300 Subject: [PATCH 119/147] update createCardInSalesforce --- bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot.py b/bot.py index eb75b10..b0b3df4 100644 --- a/bot.py +++ b/bot.py @@ -172,7 +172,7 @@ def confirmCreateCard(update,user,message): def createCardInSalesforce(update,user): try: - something = sf.Expense_Card__c.create({'CardDate__c': str(user.card.date),'Amount__c':str(user.card.amount),'Description__c':user.card.description,'CardKeeper__c':user.card.keeper}) + something = sf.Expense_Card__c.create({'CardDate__c': str(user.card.date)[:-9],'Amount__c':str(user.card.amount),'Description__c':user.card.description,'CardKeeper__c':user.card.keeper}) update.message.reply_text('Карточка успешно создана!' + str(something)) except Exception as e: update.message.reply_text('Извините, карточку не получилось создать' + str(e)) From 9a867c0cac084bb6aa8e73bcaba28613a89461a7 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 19:18:31 +0300 Subject: [PATCH 120/147] refactoring all file --- bot.py | 144 ++++++++++++++++++++++++--------------------------------- 1 file changed, 61 insertions(+), 83 deletions(-) diff --git a/bot.py b/bot.py index b0b3df4..5a4a28b 100644 --- a/bot.py +++ b/bot.py @@ -16,6 +16,7 @@ from simple_salesforce import Salesforce import os +#####################################Data##################################### sf = Salesforce( username='max2433186@mindful-impala-acpsha.com', password='JKlw124O2kanv5kLLf', @@ -50,9 +51,10 @@ def __init__(self, keeper): usersTelegram = {} -# Define a few command handlers. These usually take the two arguments update and -# context. Error handlers also receive the raised TelegramError object in error. +#######################################Functions########################################### + +######################################Handlers############################################## def start(update, context): """Send a message when the command /start is issued.""" @@ -80,6 +82,41 @@ def echo(update, context): #update.message.reply_text(update.message.text) +def end(update, context): + userId = update._effective_user.id + usersTelegram.pop(userId) + update.message.reply_text('До свидания!', + reply_markup=ReplyKeyboardRemove()) + +def error(update, context): + """Log Errors caused by Updates.""" + logger.warning('Update "%s" caused error "%s"', update, context.error) + +######################################Handlers############################################## + +######################################Helper handlers############################################## + +def login(update, context): + userId = update._effective_user.id + user = usersTelegram[userId] + + if user.login == None: + user.login = update.message.text + update.message.reply_text('Введите пароль') + else: + user.password = update.message.text + try: + user.contact = sf.query(f"SELECT Id, Name, Email, Office__c, Admin__c FROM Contact WHERE Email ='{user.login}' AND Password__c ='{user.password}' LIMIT 1") + throwExceptionIfContactEmpty(user.contact) + user.exist = True + update.message.reply_text('Авторизация прошла успешно ', + reply_markup=mainMenuKeyboard()) + except Exception: + update.message.reply_text('Неправильный логин или пароль.Попробуйте Снова') + refreshUser(user) + start(update,context) + return + def echoForExistUser(update,context): message = update.message.text.lower() userId = update._effective_user.id @@ -173,63 +210,19 @@ def confirmCreateCard(update,user,message): def createCardInSalesforce(update,user): try: something = sf.Expense_Card__c.create({'CardDate__c': str(user.card.date)[:-9],'Amount__c':str(user.card.amount),'Description__c':user.card.description,'CardKeeper__c':user.card.keeper}) - update.message.reply_text('Карточка успешно создана!' + str(something)) + user.card = None + update.message.reply_text('Карточка успешно создана!', reply_markup=mainMenuKeyboard()) except Exception as e: - update.message.reply_text('Извините, карточку не получилось создать' + str(e)) - -def getDateFromString(update,message): - dateStr = '' - if len(message) < 3: - now = datetime.datetime.now() - dateStr = str(now.year)+'-'+str(now.month)+'-'+message + ' 00:00:00' - else: - dateStr = message + ' 00:00:00' - - dateObject = datetime.datetime.strptime(dateStr, '%Y-%m-%d %H:%M:%S') - return dateObject - - -def error(update, context): - """Log Errors caused by Updates.""" - logger.warning('Update "%s" caused error "%s"', update, context.error) - -def end(update, context): - userId = update._effective_user.id - usersTelegram.pop(userId) - update.message.reply_text('До свидания!', - reply_markup=ReplyKeyboardRemove()) - -def login(update, context): - userId = update._effective_user.id - user = usersTelegram[userId] - - if user.login == None: - user.login = update.message.text - update.message.reply_text('Введите пароль') - else: - user.password = update.message.text - try: - user.contact = sf.query(f"SELECT Id, Name, Email, Office__c, Admin__c FROM Contact WHERE Email ='{user.login}' AND Password__c ='{user.password}' LIMIT 1") - throwExceptionIfContactEmpty(user.contact) - user.exist = True - update.message.reply_text('Авторизация прошла успешно ', - reply_markup=mainMenuKeyboard()) - except Exception: - update.message.reply_text('Неправильный логин или пароль.Попробуйте Снова') - refreshUser(user) - start(update,context) - return - #str(user.contact['records'][0]['Id']) - # x = bool(user.contact) - # if bool: - # update.message.reply_text('Авторизация прошла успешно ' + str(user.contact)) - # else: - # update.message.reply_text('Неправильный логин или пароль.Попробуйте Снова') + update.message.reply_text('Извините, карточку не получилось создать', reply_markup=mainMenuKeyboard()) def cancelToMainMenu(update,user): user.card = None update.message.reply_text('Что вы хотите сделать?', reply_markup=mainMenuKeyboard()) + +######################################Helper handlers############################################## + + #########################Keyboards############################ def mainMenuKeyboard(): options = [['Текущий баланс'],['Создать карточку']] @@ -253,6 +246,7 @@ def confirmKeyboard(): #########################Keyboards############################ +#########################Utils############################ def getOptionsForDaysOfMonthKeyboard(): options = [] rowOptions = [] @@ -267,19 +261,20 @@ def getOptionsForDaysOfMonthKeyboard(): rowOptions = [] else: rowOptions.append(strCount) - # if (count == daysInMonth): - # lenOptions = len(options) - # options[lenOptions].append(strCount) - # elif (len(rowOptions) >= 4): - # rowOptions.append(strCount) - # options.append(rowOptions) - # rowOptions = [] - # else: - # rowOptions.append(strCount) + count += 1 return options - +def getDateFromString(update,message): + dateStr = '' + if len(message) < 3: + now = datetime.datetime.now() + dateStr = str(now.year)+'-'+str(now.month)+'-'+message + ' 00:00:00' + else: + dateStr = message + ' 00:00:00' + + dateObject = datetime.datetime.strptime(dateStr, '%Y-%m-%d %H:%M:%S') + return dateObject def createUserIfItNeed(userId): if userId not in usersTelegram: @@ -296,6 +291,8 @@ def throwExceptionIfContactEmpty(contact): if totalSize < 1: raise Exception('Contact empty') +#########################Utils############################ + def main(): """Start the bot.""" # Create the Updater and pass it your bot's token. @@ -327,23 +324,4 @@ def main(): updater.idle() if __name__ == '__main__': - main() - - - # OrderedDict([ - # ('totalSize', 1), - # ('done', True), - # ('records', [OrderedDict([ - # ('attributes', OrderedDict([ - # ('type', 'Contact'), - # ('url', '/services/data/v42.0/sobjects/Contact/0035g000003X49iAAC')])), - # ('Id', '0035g000003X49iAAC'), - # ('Email', 'worker2@gmail.com')])])]) - - # OrderedDict([ - # ('attributes', OrderedDict([ - # ('type', 'Contact'), - # ('url', '/services/data/v42.0/sobjects/Contact/0035g000003X49iAAC')])), - # ('Id', '0035g000003X49iAAC'), - # ('Email', 'worker2@gmail.com')]) - + main() \ No newline at end of file From bbb6d96041a39620c070f48e3c2e121577812972 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 19:19:51 +0300 Subject: [PATCH 121/147] update start --- bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot.py b/bot.py index 5a4a28b..832215b 100644 --- a/bot.py +++ b/bot.py @@ -62,7 +62,7 @@ def start(update, context): createUserIfItNeed(userId) isUserLog = usersTelegram[userId].exist if isUserLog: - update.message.reply_text('Вы уже зарегистрированы!', reply_markup=ReplyKeyboardRemove()) + update.message.reply_text('Вы уже зарегистрированы!', reply_markup=mainMenuKeyboard()) else: update.message.reply_text('Введите логин', reply_markup=ReplyKeyboardRemove()) # sf.Contact.create({'LastName':'simple_salesforce','Email':'example@example.com'}) From 7051f154b0c486a4a1e163e71ad2a143d5a7ba85 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 19:25:31 +0300 Subject: [PATCH 122/147] =?UTF-8?q?delete=20message=20'=D1=82=D1=8B=20?= =?UTF-8?q?=D0=BD=D0=B5=20=D0=B4=D0=BE=D0=BB=D0=B6=D0=B5=D0=BD=20=D0=B2?= =?UTF-8?q?=D0=B8=D0=B4=D0=B5=D1=82=D1=8C=20=D1=8D=D1=82=D0=BE=20=D1=81?= =?UTF-8?q?=D0=BE=D0=BE=D0=B1=D1=89=D0=B5=D0=BD=D0=B8=D0=B5'?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bot.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/bot.py b/bot.py index 832215b..a14e383 100644 --- a/bot.py +++ b/bot.py @@ -134,8 +134,6 @@ def echoForExistUser(update,context): cancelToMainMenu(update,user) elif user.card != None: creatingCard(update,user,message) - - update.message.reply_text('ты не должен видеть это сообщение') def creatingCard(update,user,message): if user.card.date == None or user.card.date == True: From 52e286bcf0d49a235f95b77b750af592157ceb38 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 19:30:49 +0300 Subject: [PATCH 123/147] update creatingCardDateNone --- bot.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/bot.py b/bot.py index a14e383..51b7a41 100644 --- a/bot.py +++ b/bot.py @@ -161,8 +161,8 @@ def creatingCardDate(update,user,message): def creatingCardDateNone(update,user,message): if message == 'сегодня': - 'here should be code' - user.card.date = True + user.card.date = datetime.datetime.now() + creatingCardAmount(update,user,message) elif message == 'календарь': update.message.reply_text('Выберите число') replyMessage = """Или Введите дату вручную(день-месяц-число) From 3f5b98e2cfe76616b563f308c8c4fda3166e86b9 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 19:35:26 +0300 Subject: [PATCH 124/147] update creatingCardDateNone --- bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot.py b/bot.py index 51b7a41..8e2ec70 100644 --- a/bot.py +++ b/bot.py @@ -161,7 +161,7 @@ def creatingCardDate(update,user,message): def creatingCardDateNone(update,user,message): if message == 'сегодня': - user.card.date = datetime.datetime.now() + user.card.date = datetime.datetime.today() creatingCardAmount(update,user,message) elif message == 'календарь': update.message.reply_text('Выберите число') From 73b10da314688a6afc20ec077422afea11913f40 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 19:36:40 +0300 Subject: [PATCH 125/147] update creatingCardDateNone --- bot.py | 1 + 1 file changed, 1 insertion(+) diff --git a/bot.py b/bot.py index 8e2ec70..a47a99f 100644 --- a/bot.py +++ b/bot.py @@ -163,6 +163,7 @@ def creatingCardDateNone(update,user,message): if message == 'сегодня': user.card.date = datetime.datetime.today() creatingCardAmount(update,user,message) + elif message == 'календарь': update.message.reply_text('Выберите число') replyMessage = """Или Введите дату вручную(день-месяц-число) From 00ae5285473d273aac2e56bb53e50c7ef05133e5 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 19:51:49 +0300 Subject: [PATCH 126/147] update creatingCardDateNone --- bot.py | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/bot.py b/bot.py index a47a99f..4265cad 100644 --- a/bot.py +++ b/bot.py @@ -151,7 +151,7 @@ def creatingCardDate(update,user,message): creatingCardDateNone(update,user,message) elif user.card.date == True: try: - cardDate = getDateFromString(update,message) + cardDate = getStringAsDateAndValidate(message) user.card.date = cardDate creatingCardAmount(update,user,message) except Exception as e: @@ -161,9 +161,10 @@ def creatingCardDate(update,user,message): def creatingCardDateNone(update,user,message): if message == 'сегодня': - user.card.date = datetime.datetime.today() + today = datetime.datetime.today() + user.card.date = getStringAsDateAndValidate(today.day) creatingCardAmount(update,user,message) - + elif message == 'календарь': update.message.reply_text('Выберите число') replyMessage = """Или Введите дату вручную(день-месяц-число) @@ -198,7 +199,7 @@ def creatingCardDecription(update,user,message): def confirmCreateCard(update,user,message): if user.card.confirmCreate == None: update.message.reply_text('Вы уверены что хотите создать следующую карточку?') - update.message.reply_text('Дата: ' + str(user.card.date)[:-9]) + update.message.reply_text('Дата: ' + str(user.card.date)) update.message.reply_text('Сумма: ' + str(user.card.amount)) update.message.reply_text('Описание: ' + user.card.description, reply_markup=confirmKeyboard()) user.card.confirmCreate = True @@ -208,7 +209,7 @@ def confirmCreateCard(update,user,message): def createCardInSalesforce(update,user): try: - something = sf.Expense_Card__c.create({'CardDate__c': str(user.card.date)[:-9],'Amount__c':str(user.card.amount),'Description__c':user.card.description,'CardKeeper__c':user.card.keeper}) + something = sf.Expense_Card__c.create({'CardDate__c': user.card.date,'Amount__c':str(user.card.amount),'Description__c':user.card.description,'CardKeeper__c':user.card.keeper}) user.card = None update.message.reply_text('Карточка успешно создана!', reply_markup=mainMenuKeyboard()) except Exception as e: @@ -264,16 +265,17 @@ def getOptionsForDaysOfMonthKeyboard(): count += 1 return options -def getDateFromString(update,message): - dateStr = '' +def getStringAsDateAndValidate(message): + dateStrResult = '' if len(message) < 3: now = datetime.datetime.now() - dateStr = str(now.year)+'-'+str(now.month)+'-'+message + ' 00:00:00' + dateStr = str(now.year)+'-'+str(now.month)+'-'+message else: - dateStr = message + ' 00:00:00' + dateStr = message - dateObject = datetime.datetime.strptime(dateStr, '%Y-%m-%d %H:%M:%S') - return dateObject + dateStrForValidate = dateStrResult + ' 00:00:00' + dateObject = datetime.datetime.strptime(dateStrForValidate, '%Y-%m-%d %H:%M:%S') + return dateStrResult def createUserIfItNeed(userId): if userId not in usersTelegram: From 63fc2f7546e32898871556ff8129ee7d9b377a4c Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 19:53:44 +0300 Subject: [PATCH 127/147] update createCardInSalesforce --- bot.py | 1 + 1 file changed, 1 insertion(+) diff --git a/bot.py b/bot.py index 4265cad..ee149b8 100644 --- a/bot.py +++ b/bot.py @@ -214,6 +214,7 @@ def createCardInSalesforce(update,user): update.message.reply_text('Карточка успешно создана!', reply_markup=mainMenuKeyboard()) except Exception as e: update.message.reply_text('Извините, карточку не получилось создать', reply_markup=mainMenuKeyboard()) + update.message.reply_text(str(e)) def cancelToMainMenu(update,user): user.card = None From 8b990af7f9d3a06ab4bd17fcb2a1d7f4e0898477 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 19:56:42 +0300 Subject: [PATCH 128/147] debug --- bot.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/bot.py b/bot.py index ee149b8..59aafed 100644 --- a/bot.py +++ b/bot.py @@ -161,10 +161,12 @@ def creatingCardDate(update,user,message): def creatingCardDateNone(update,user,message): if message == 'сегодня': - today = datetime.datetime.today() - user.card.date = getStringAsDateAndValidate(today.day) - creatingCardAmount(update,user,message) - + try: + today = datetime.datetime.today() + user.card.date = getStringAsDateAndValidate(today.day) + creatingCardAmount(update,user,message) + except Exception as e: + update.message.reply_text(str(e)) elif message == 'календарь': update.message.reply_text('Выберите число') replyMessage = """Или Введите дату вручную(день-месяц-число) From 05bd071a5c20de032abcfa55513b798d0b04716c Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 19:58:15 +0300 Subject: [PATCH 129/147] update creatingCardDateNone --- bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot.py b/bot.py index 59aafed..a0e49a1 100644 --- a/bot.py +++ b/bot.py @@ -163,7 +163,7 @@ def creatingCardDateNone(update,user,message): if message == 'сегодня': try: today = datetime.datetime.today() - user.card.date = getStringAsDateAndValidate(today.day) + user.card.date = getStringAsDateAndValidate(str(today.day)) creatingCardAmount(update,user,message) except Exception as e: update.message.reply_text(str(e)) From 01e631af0713ab915c1bf2c6f0277d43e7df7162 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 20:00:22 +0300 Subject: [PATCH 130/147] debug --- bot.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/bot.py b/bot.py index a0e49a1..2c60bf3 100644 --- a/bot.py +++ b/bot.py @@ -163,6 +163,8 @@ def creatingCardDateNone(update,user,message): if message == 'сегодня': try: today = datetime.datetime.today() + update.message.reply_text(str(today)) + update.message.reply_text(str(today.day)) user.card.date = getStringAsDateAndValidate(str(today.day)) creatingCardAmount(update,user,message) except Exception as e: From c2dd514ff6027735ec7bfe9acea5bc0d4b9b3353 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 20:03:33 +0300 Subject: [PATCH 131/147] update getStringAsDateAndValidate --- bot.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/bot.py b/bot.py index 2c60bf3..39bb4a6 100644 --- a/bot.py +++ b/bot.py @@ -274,9 +274,9 @@ def getStringAsDateAndValidate(message): dateStrResult = '' if len(message) < 3: now = datetime.datetime.now() - dateStr = str(now.year)+'-'+str(now.month)+'-'+message + dateStrResult = str(now.year)+'-'+str(now.month)+'-'+message else: - dateStr = message + dateStrResult = message dateStrForValidate = dateStrResult + ' 00:00:00' dateObject = datetime.datetime.strptime(dateStrForValidate, '%Y-%m-%d %H:%M:%S') From 2b63560db2edb9cbfabc401dd07b057f5bd41aaa Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 20:06:30 +0300 Subject: [PATCH 132/147] delete debugs --- bot.py | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/bot.py b/bot.py index 39bb4a6..df02b77 100644 --- a/bot.py +++ b/bot.py @@ -161,14 +161,9 @@ def creatingCardDate(update,user,message): def creatingCardDateNone(update,user,message): if message == 'сегодня': - try: - today = datetime.datetime.today() - update.message.reply_text(str(today)) - update.message.reply_text(str(today.day)) - user.card.date = getStringAsDateAndValidate(str(today.day)) - creatingCardAmount(update,user,message) - except Exception as e: - update.message.reply_text(str(e)) + today = datetime.datetime.today() + user.card.date = getStringAsDateAndValidate(str(today.day)) + creatingCardAmount(update,user,message) elif message == 'календарь': update.message.reply_text('Выберите число') replyMessage = """Или Введите дату вручную(день-месяц-число) From fe6a8844fe6bde21ba5898dab97899c6b08e602b Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 20:11:44 +0300 Subject: [PATCH 133/147] update createCardInSalesforce --- bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot.py b/bot.py index df02b77..6eafa70 100644 --- a/bot.py +++ b/bot.py @@ -213,7 +213,7 @@ def createCardInSalesforce(update,user): update.message.reply_text('Карточка успешно создана!', reply_markup=mainMenuKeyboard()) except Exception as e: update.message.reply_text('Извините, карточку не получилось создать', reply_markup=mainMenuKeyboard()) - update.message.reply_text(str(e)) + update.message.reply_text(str(e.message)) def cancelToMainMenu(update,user): user.card = None From 2031ebb20d42eb0c5de544f1ab1431dae472b46f Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 20:15:55 +0300 Subject: [PATCH 134/147] update createCardInSalesforce --- bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot.py b/bot.py index 6eafa70..d023f5e 100644 --- a/bot.py +++ b/bot.py @@ -213,7 +213,7 @@ def createCardInSalesforce(update,user): update.message.reply_text('Карточка успешно создана!', reply_markup=mainMenuKeyboard()) except Exception as e: update.message.reply_text('Извините, карточку не получилось создать', reply_markup=mainMenuKeyboard()) - update.message.reply_text(str(e.message)) + update.message.reply_text(str(e.message.content)) def cancelToMainMenu(update,user): user.card = None From 5f0f483d7a5296820fd624b027e51f77a1da9bc5 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 20:17:57 +0300 Subject: [PATCH 135/147] update createCardInSalesforce --- bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot.py b/bot.py index d023f5e..df02b77 100644 --- a/bot.py +++ b/bot.py @@ -213,7 +213,7 @@ def createCardInSalesforce(update,user): update.message.reply_text('Карточка успешно создана!', reply_markup=mainMenuKeyboard()) except Exception as e: update.message.reply_text('Извините, карточку не получилось создать', reply_markup=mainMenuKeyboard()) - update.message.reply_text(str(e.message.content)) + update.message.reply_text(str(e)) def cancelToMainMenu(update,user): user.card = None From 86f999343d5246460ce30feb1835c56d84aa8d10 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 20:22:15 +0300 Subject: [PATCH 136/147] debug createCardInSalesforce --- bot.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/bot.py b/bot.py index df02b77..108fd61 100644 --- a/bot.py +++ b/bot.py @@ -213,7 +213,12 @@ def createCardInSalesforce(update,user): update.message.reply_text('Карточка успешно создана!', reply_markup=mainMenuKeyboard()) except Exception as e: update.message.reply_text('Извините, карточку не получилось создать', reply_markup=mainMenuKeyboard()) - update.message.reply_text(str(e)) + update.message.reply_text('0'+str(e[0])) + update.message.reply_text('res con'+str(e.response_content)) + update.message.reply_text('con'+str(e.content)) + update.message.reply_text('mes'+str(e.message)) + update.message.reply_text('mess'+str(e.messages)) + def cancelToMainMenu(update,user): user.card = None From 13c6c14689d2c0f0057d96b11e69ccacbea22c5f Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 20:24:30 +0300 Subject: [PATCH 137/147] debug createCardInSalesforce --- bot.py | 1 - 1 file changed, 1 deletion(-) diff --git a/bot.py b/bot.py index 108fd61..c537dc3 100644 --- a/bot.py +++ b/bot.py @@ -213,7 +213,6 @@ def createCardInSalesforce(update,user): update.message.reply_text('Карточка успешно создана!', reply_markup=mainMenuKeyboard()) except Exception as e: update.message.reply_text('Извините, карточку не получилось создать', reply_markup=mainMenuKeyboard()) - update.message.reply_text('0'+str(e[0])) update.message.reply_text('res con'+str(e.response_content)) update.message.reply_text('con'+str(e.content)) update.message.reply_text('mes'+str(e.message)) From cd2f1e34579bf50b70ad2eab79356f76c898b7ec Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 20:26:05 +0300 Subject: [PATCH 138/147] debug --- bot.py | 1 - 1 file changed, 1 deletion(-) diff --git a/bot.py b/bot.py index c537dc3..85d55ca 100644 --- a/bot.py +++ b/bot.py @@ -213,7 +213,6 @@ def createCardInSalesforce(update,user): update.message.reply_text('Карточка успешно создана!', reply_markup=mainMenuKeyboard()) except Exception as e: update.message.reply_text('Извините, карточку не получилось создать', reply_markup=mainMenuKeyboard()) - update.message.reply_text('res con'+str(e.response_content)) update.message.reply_text('con'+str(e.content)) update.message.reply_text('mes'+str(e.message)) update.message.reply_text('mess'+str(e.messages)) From 264e401522a8af7aae3c49bd638057acd85dfcaa Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 20:28:08 +0300 Subject: [PATCH 139/147] update createCardInSalesforce --- bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot.py b/bot.py index 85d55ca..ab6fc30 100644 --- a/bot.py +++ b/bot.py @@ -213,7 +213,7 @@ def createCardInSalesforce(update,user): update.message.reply_text('Карточка успешно создана!', reply_markup=mainMenuKeyboard()) except Exception as e: update.message.reply_text('Извините, карточку не получилось создать', reply_markup=mainMenuKeyboard()) - update.message.reply_text('con'+str(e.content)) + update.message.reply_text('con'+str(e.content[0])) update.message.reply_text('mes'+str(e.message)) update.message.reply_text('mess'+str(e.messages)) From 262a5bb97b1147f2889226f2f5beefe844cd15bc Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 20:33:26 +0300 Subject: [PATCH 140/147] update createCardInSalesforce --- bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot.py b/bot.py index ab6fc30..fd4a8a9 100644 --- a/bot.py +++ b/bot.py @@ -213,7 +213,7 @@ def createCardInSalesforce(update,user): update.message.reply_text('Карточка успешно создана!', reply_markup=mainMenuKeyboard()) except Exception as e: update.message.reply_text('Извините, карточку не получилось создать', reply_markup=mainMenuKeyboard()) - update.message.reply_text('con'+str(e.content[0])) + update.message.reply_text('con'+str(e.content[0].message)) update.message.reply_text('mes'+str(e.message)) update.message.reply_text('mess'+str(e.messages)) From b514b28292fdd8872beca368d3009afba23eaeb8 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 20:36:00 +0300 Subject: [PATCH 141/147] update createCardInSalesforce --- bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot.py b/bot.py index fd4a8a9..c6ba71f 100644 --- a/bot.py +++ b/bot.py @@ -213,7 +213,7 @@ def createCardInSalesforce(update,user): update.message.reply_text('Карточка успешно создана!', reply_markup=mainMenuKeyboard()) except Exception as e: update.message.reply_text('Извините, карточку не получилось создать', reply_markup=mainMenuKeyboard()) - update.message.reply_text('con'+str(e.content[0].message)) + update.message.reply_text('con'+str(e.content[0]['message'])) update.message.reply_text('mes'+str(e.message)) update.message.reply_text('mess'+str(e.messages)) From 7aad7b65de891e83f1919a8cba4b1d0f1c0d33d3 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 20:40:50 +0300 Subject: [PATCH 142/147] update createCardInSalesforce --- bot.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/bot.py b/bot.py index c6ba71f..9f3905e 100644 --- a/bot.py +++ b/bot.py @@ -213,9 +213,8 @@ def createCardInSalesforce(update,user): update.message.reply_text('Карточка успешно создана!', reply_markup=mainMenuKeyboard()) except Exception as e: update.message.reply_text('Извините, карточку не получилось создать', reply_markup=mainMenuKeyboard()) - update.message.reply_text('con'+str(e.content[0]['message'])) - update.message.reply_text('mes'+str(e.message)) - update.message.reply_text('mess'+str(e.messages)) + for err in e.content: + update.message.reply_text('con'+str(err['message'])) def cancelToMainMenu(update,user): From 6bc996430bc10fe920b5dbb642906ce55203bd57 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 20:42:45 +0300 Subject: [PATCH 143/147] update createCardInSalesforce --- bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot.py b/bot.py index 9f3905e..a18fbe6 100644 --- a/bot.py +++ b/bot.py @@ -214,7 +214,7 @@ def createCardInSalesforce(update,user): except Exception as e: update.message.reply_text('Извините, карточку не получилось создать', reply_markup=mainMenuKeyboard()) for err in e.content: - update.message.reply_text('con'+str(err['message'])) + update.message.reply_text(str(err['message'])) def cancelToMainMenu(update,user): From 922fc70762eb20af91e4ed226d2fba222b39c98a Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 20:52:36 +0300 Subject: [PATCH 144/147] update balance/amount output --- bot.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/bot.py b/bot.py index a18fbe6..164827e 100644 --- a/bot.py +++ b/bot.py @@ -124,7 +124,7 @@ def echoForExistUser(update,context): userContactId = user.contact['records'][0]['Id'] if message == 'текущий баланс': balance = sf.apexecute('Contact/'+userContactId, method='GET') - update.message.reply_text(str(balance), + update.message.reply_text(str(balance)+'$', reply_markup=mainMenuKeyboard()) elif message == 'создать карточку': user.card = Card(userContactId) @@ -199,7 +199,7 @@ def confirmCreateCard(update,user,message): if user.card.confirmCreate == None: update.message.reply_text('Вы уверены что хотите создать следующую карточку?') update.message.reply_text('Дата: ' + str(user.card.date)) - update.message.reply_text('Сумма: ' + str(user.card.amount)) + update.message.reply_text('Сумма: ' + str(user.card.amount)+'$') update.message.reply_text('Описание: ' + user.card.description, reply_markup=confirmKeyboard()) user.card.confirmCreate = True elif user.card.confirmCreate == True: From 71caf31db5eed8395d946d8809858c96136cc27a Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 21:01:48 +0300 Subject: [PATCH 145/147] update readme --- README.md | 59 +------------------------------------------------------ 1 file changed, 1 insertion(+), 58 deletions(-) diff --git a/README.md b/README.md index 90a4b04..a8e4bb5 100644 --- a/README.md +++ b/README.md @@ -1,58 +1 @@ - - -# python-telegram-bot-heroku -A guide to hosting a telegram bot created using the python-telegram-bot library with heroku. -![Deploy your Ember project to Heroku from Github - Philip Mutua ...](https://miro.medium.com/max/3600/1*fIjRtO5P8zc3pjs0E5hYkw.png) -See the full article explaining the steps [here](https://towardsdatascience.com/how-to-deploy-a-telegram-bot-using-heroku-for-free-9436f89575d2). - -## Getting Started -Before you begin, you will need a Telegram bot API token from [BotFather](https://t.me/botfather). - -1. Download the three files in this repo: bot.py (containing your python code for the Telegram bot), requirements.txt (containing the python libraries to be installed), and Procfile (containing the command to execute the python file). -2. Login / [create](https://signup.heroku.com/dc) a Heroku account. -3. Install [Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git). -4. Install the [Heroku CLI](https://devcenter.heroku.com/articles/getting-started-with-python#set-up). -5. Once installed, you can use the _heroku_ command in your terminal / command prompt. Go to the same directory as the files in this repository, and type: - -> heroku login - -A new window will be opened in your browser prompting you to login, so just click on the button. - -6. Once you are logged in, go back to the command line. Type in -> heroku create - -to create your new webapp. Heroku will assign your webapp a name as well as the link to your webapp, which should be of the format [https://{yourherokuappname}.herokuapp.com/.](https://yourherokuappname.herokuapp.com/.) - -7. To the bot.py file, change the TOKEN variable to the API token of your telegram bot, and change the yourherokuappname to the name of your heroku app in the line - -> updater.bot.setWebhook('https://yourherokuappname.herokuapp.com/' + TOKEN) - -8. Next, in your command line, type the following commands in the following order: - -> git init -> git add . -> git commit -m "first commit" - -> heroku git:remote -a YourAppName - -> git push heroku master - -(Make sure to replace YourAppName with the name of your Heroku webapp) - -You should then see the following messages: - -![](https://cdn-images-1.medium.com/max/1000/1*y3JH7a7mY4oYFaAjDCA1Ow.png) - -In particular, it will say that a Python app is detected and it will install the required libraries in the requirements.txt file using pip. Then, it will read the Procfile which specifies that the bot.py file is to be executed. - -9. Go to your conversation with your Telegram bot on Telegram and type /start. The bot should be working now! - -Since you are using the free plan on heroku, the bot will sleep after 30 minutes of inactivity. So do expect the bot to take a few seconds to respond to your /start if you are using it more than 30 minutes after it was previously used. Other than that, the bot will respond almost instantaneously~ - -## What to do if your Bot stops responding -I’ve noticed the bot stops responding after about 24 hours of inactivity (because we are using the free version of Heroku), so if you want to “jolt” the bot awake, one way is to make a change to one of the files (eg. changing the python3 in the procfile to python and vice versa) and then committing the changes with the lines below: -> git add . -> git commit -m "changing python3 to python in Procfile" -> git push heroku master - -You should see again see the messages about a Python app being detected and once it finishes executing, your bot should revive now! +telegram bot nickname: @expenses_salesforce_bot \ No newline at end of file From 974ef0f29d50006470a59b522bbb33f0d8567fdd Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 17 May 2021 21:07:32 +0300 Subject: [PATCH 146/147] update readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a8e4bb5..9da2424 100644 --- a/README.md +++ b/README.md @@ -1 +1 @@ -telegram bot nickname: @expenses_salesforce_bot \ No newline at end of file +telegram bot: https://t.me/expenses_salesforce_bot \ No newline at end of file From 67534529df8ecbacc2958b0617cf9e543285c63c Mon Sep 17 00:00:00 2001 From: Vlad-KVR <62644504+Vlad-KVR@users.noreply.github.com> Date: Mon, 12 Jul 2021 14:17:15 +0300 Subject: [PATCH 147/147] update readme --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 9da2424..f64d0cf 100644 --- a/README.md +++ b/README.md @@ -1 +1,3 @@ -telegram bot: https://t.me/expenses_salesforce_bot \ No newline at end of file +Hello! +Here +telegram bot: https://t.me/expenses_salesforce_bot