From 9e83a6cacabcd9f8b253e7f695037d945a834289 Mon Sep 17 00:00:00 2001 From: Andrea Date: Thu, 1 Nov 2018 18:58:39 +0100 Subject: [PATCH 01/89] Admin by username insted of ID --- scienzati_bot.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index 0ef33b6..20feb53 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -9,7 +9,7 @@ class Settings: TelegramApiKey = "676490981:AAELlmTlQLD4_1HojhzWIX4yISDrVU5qDmA" - SupremeAdmins = [14092073] + SupremeAdmins = ["pandry","andreaidini"]#Lowercase username! ITGroup = 0 OTGroup = -1001176680738 subscriptionRows = 7 @@ -508,7 +508,7 @@ def setBio(message): #Creazione di una nuova lista @bot.message_handler(commands=['newlist', 'nuovalista']) def newList(message): - if message.from_user.id in Settings.SupremeAdmins or UserPermission.IsAdmin(GetUserPermissionsValue(message.from_user.id)) or UserPermission.CanCreateList(GetUserPermissionsValue(message.from_user.id)): + if message.from_user.username.lower() in Settings.SupremeAdmins or UserPermission.IsAdmin(GetUserPermissionsValue(message.from_user.id)) or UserPermission.CanCreateList(GetUserPermissionsValue(message.from_user.id)): if not message.from_user.is_bot and message.text != "" : # Gets info about the user user = GetUser(message.from_user.id) From 7eb94f4f6b298165d83ec405057a503b48fc0e9c Mon Sep 17 00:00:00 2001 From: Andrea Date: Thu, 1 Nov 2018 19:14:23 +0100 Subject: [PATCH 02/89] Added requirements via 'pip3 freeze > requirements.txt' --- requirements.txt | Bin 0 -> 1640 bytes 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 requirements.txt diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..2e154ca801ca32493bfcc785bd596c9dc7f881d8 GIT binary patch literal 1640 zcmZ8hT~FIU5ZvcV{V5>qP-q_d&_=3MsX)~52Z*slsK0P7f#k=xo!PzhxyT{}c5Y^N zcF%wRJV+spl=217g`7(+89p=lC?DiOcGBW|A%h&Hmmu8)cM06Zhzr1UvXw_gkmCwJ zms(#>7^pK-1+Ny+>7hjS7EaFO6+A7NI(*wHA5YMo@fAP~z^{P_6GzFpBeqh3i<&vk zXYx5J^BX%XPMpXc`|&m_e%EYYp*Ex zp6S%A&RMpxuYAa_0`PUrX#6753IgKS_~#HMmZwoB_q&N~9m~R}Z#M-X>?r zXd77L{|!#kAGPSiDmP&JjdQHH&b9W%%7EG)%qx7a{_CGk8Ypw?*0EygI&%Zo0_QzZ zRxOcUnK|w4s7*(7X08mu3?6|E_#J@t`(;=<=%GERg7uotA91dXThG3Di=3M^yOBOG z%fuLuaGmsx-SVr;aM@FOL%>riSAd7*BRSI#{B53lEDp5&BCL;n_Pl zC~UzO?-_sJn=kgAHd9;wnyf*=6Z-2=4njSc?F8^&@?mNaUyJUPUxO< uImd={*v1~8eAD`rxkYJ*6S|bcI}~%Xt`o|(g>U2vF8JnUAI>?`6#oHL5a)0J literal 0 HcmV?d00001 From 72c47321ea36bf2e9a2227c61915d7e155396843 Mon Sep 17 00:00:00 2001 From: Andrea Date: Thu, 1 Nov 2018 19:16:17 +0100 Subject: [PATCH 03/89] Added Dockerfile --- Dockerfile | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 Dockerfile diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..a903a06 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,10 @@ +FROM python:3 + +WORKDIR /usr/src/app + +COPY requirements.txt ./ +RUN pip install --no-cache-dir -r requirements.txt + +COPY . . + +CMD [ "python", "./scienzati_bot.py" ] From 20c03352344913a556b81ad7843826e77a58d3ff Mon Sep 17 00:00:00 2001 From: Andrea Date: Thu, 1 Nov 2018 19:18:23 +0100 Subject: [PATCH 04/89] Updateg group values --- scienzati_bot.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index 20feb53..338d1e1 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -10,8 +10,8 @@ class Settings: TelegramApiKey = "676490981:AAELlmTlQLD4_1HojhzWIX4yISDrVU5qDmA" SupremeAdmins = ["pandry","andreaidini"]#Lowercase username! - ITGroup = 0 - OTGroup = -1001176680738 + ITGroup = -1001068546876 + OTGroup = -1001218814107 subscriptionRows = 7 From aec8c3b6560be11e6ce0bdb192a87642b4187a46 Mon Sep 17 00:00:00 2001 From: Andrea Date: Thu, 1 Nov 2018 19:32:38 +0100 Subject: [PATCH 05/89] Copy only the script --- Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index a903a06..635b229 100644 --- a/Dockerfile +++ b/Dockerfile @@ -5,6 +5,6 @@ WORKDIR /usr/src/app COPY requirements.txt ./ RUN pip install --no-cache-dir -r requirements.txt -COPY . . +COPY scienzati_bot.py . CMD [ "python", "./scienzati_bot.py" ] From 3d40067e49f14c794e1d1b827bad5841a04dae70 Mon Sep 17 00:00:00 2001 From: Andrea Date: Fri, 2 Nov 2018 01:25:00 +0100 Subject: [PATCH 06/89] Fixed Bug: random crash --- scienzati_bot.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index 338d1e1..c527677 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -708,7 +708,7 @@ def callback_query(call): #Check if is to abort bio if call.data == "aBio": #Check if the guy who pressed is the same who asked to set the bio - if call.from_user.id == call.message.reply_to_message.from_user.id: + if call.message.reply_to_message != None and call.from_user.id == call.message.reply_to_message.from_user.id: #Check that the user needs to set the bio if user["Status"] == UserStatus.WAITING_FOR_BIOGRAPHY : success = abortNewBio(call.from_user.id) @@ -720,7 +720,7 @@ def callback_query(call): #Check if is to abort list creation elif call.data == "aList": #Check if the guy who pressed is the same who asked to set the bio - if call.from_user.id == call.message.reply_to_message.from_user.id: + if call.message.reply_to_message != None and call.from_user.id == call.message.reply_to_message.from_user.id: #Check that the user needs to set the bio if user["Status"] == UserStatus.WAITING_FOR_LIST : @@ -731,7 +731,7 @@ def callback_query(call): else: bot.delete_message(call.message.chat.id , call.message.message_id) elif "ousub-" in call.data: - if call.from_user.id == call.message.reply_to_message.from_user.id: + if call.message.reply_to_message != None and call.from_user.id == call.message.reply_to_message.from_user.id: if user["Status"] == UserStatus.ACTIVE : #Show next n rows + offset, osub-{offset} #Safe data checks @@ -768,7 +768,7 @@ def callback_query(call): bot.answer_callback_query(call.id, text="Just go away", show_alert=False, cache_time=999999) elif "cusub-" in call.data: - if call.from_user.id == call.message.reply_to_message.from_user.id: + if call.message.reply_to_message != None and call.from_user.id == call.message.reply_to_message.from_user.id: if user["Status"] == UserStatus.ACTIVE : splittedString = call.data.split('-') if len(splittedString) == 2: @@ -806,7 +806,7 @@ def callback_query(call): elif "usub-" in call.data: - if call.from_user.id == call.message.reply_to_message.from_user.id: + if call.message.reply_to_message != None and call.from_user.id == call.message.reply_to_message.from_user.id: if user["Status"] == UserStatus.ACTIVE : #Show next n rows + offset, osub-{offset} #Safe data checks @@ -824,7 +824,7 @@ def callback_query(call): return bot.answer_callback_query(call.id, text="Just go away", show_alert=False, cache_time=999999) elif "osub-" in call.data: - if call.from_user.id == call.message.reply_to_message.from_user.id: + if call.message.reply_to_message != None and call.from_user.id == call.message.reply_to_message.from_user.id: if user["Status"] == UserStatus.ACTIVE : #Show next n rows + offset, osub-{offset} #Safe data checks @@ -862,7 +862,7 @@ def callback_query(call): elif "sub-" in call.data: #Subscribe to list sub-{id} - if call.from_user.id == call.message.reply_to_message.from_user.id: + if call.message.reply_to_message != None and call.from_user.id == call.message.reply_to_message.from_user.id: if user["Status"] == UserStatus.ACTIVE : #Show next n rows + offset, osub-{offset} #Safe data checks From ae3e408b4375776ac948bba5f419a715ec938d60 Mon Sep 17 00:00:00 2001 From: Andrea Date: Fri, 2 Nov 2018 01:59:00 +0100 Subject: [PATCH 07/89] Added 'CanAddAdmin' permission and permissions helper --- scienzati_bot.py | 43 ++++++++++++++++++++++++++++++++++++------- 1 file changed, 36 insertions(+), 7 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index c527677..d5814fa 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -87,9 +87,10 @@ class constResources: intro_mex = """Questo e' il bot del gruppo @scienza, /iscrivi iscriviti al database di utenti e a liste di interessi - /modifica visiona e modifica la propria descrizione + /bio modifica la propria biografia /liste consulta le attuali liste di interessi - /nuovalista crea nuove liste + /nuovalista crea nuove liste - solo per amministratori + /gdpr Consulta le norme sul GDPR /privs elenca i privilegi utente""" privs_mex = """privs =-1 -> utente non registrato @@ -167,27 +168,55 @@ def CanEnterBio(status): # class UserPermission: #Siply do an AND with the permission ADMIN=int('1', 2) - CHANNEL=int('10', 2) - CREATE_LIST=int('100', 2) + CAN_ADD_ADMIN=int('10', 2) + CHANNEL=int('100', 2) + CREATE_LIST=int('1000', 2) def IsAdmin(permission): if (permission & UserPermission.ADMIN) == UserPermission.ADMIN: return True return False + def SetAdminPermission(permission): + return permission | UserPermission.ADMIN + + def RemoveAdminPermission(permission): + return permission & (not(UserPermission.ADMIN)) + + def CanAddAdmin(permission): + if (permission & UserPermission.CAN_ADD_ADMIN) == UserPermission.CAN_ADD_ADMIN: + return True + return False + + def SetCanAddAdmin(permission): + return permission | UserPermission.CAN_ADD_ADMIN + + def RemoveCanAddAdmin(permission): + return permission & (not(UserPermission.CAN_ADD_ADMIN)) + def CanForwardToChannel(permission): if (permission & UserPermission.CHANNEL) == UserPermission.CHANNEL: return True return False + def SetForwardToChannel(permission): + return permission | UserPermission.CHANNEL + + def RemoveForwardToChannel(permission): + return permission & (not(UserPermission.CHANNEL)) + def CanCreateList(permission): if (permission & UserPermission.CREATE_LIST) == UserPermission.CREATE_LIST: return True return False - - - + def SetCanCreateList(permission): + return permission | UserPermission.CREATE_LIST + + def RemoveCanCreateList(permission): + return permission & (not(UserPermission.CREATE_LIST)) + + ### From e31cd5cf5686f6179696e60c08d8e2070a4883a5 Mon Sep 17 00:00:00 2001 From: Andrea Date: Fri, 2 Nov 2018 03:11:10 +0100 Subject: [PATCH 08/89] Added permission to add list grant and removal --- scienzati_bot.py | 187 ++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 176 insertions(+), 11 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index d5814fa..e10eeac 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -169,8 +169,9 @@ def CanEnterBio(status): class UserPermission: #Siply do an AND with the permission ADMIN=int('1', 2) CAN_ADD_ADMIN=int('10', 2) - CHANNEL=int('100', 2) - CREATE_LIST=int('1000', 2) + CAN_REMOVE_ADMIN=int('100', 2) + CHANNEL=int('1000', 2) + CREATE_LIST=int('10000', 2) def IsAdmin(permission): if (permission & UserPermission.ADMIN) == UserPermission.ADMIN: @@ -193,6 +194,17 @@ def SetCanAddAdmin(permission): def RemoveCanAddAdmin(permission): return permission & (not(UserPermission.CAN_ADD_ADMIN)) + + def CanRemoveAdmin(permission): + if (permission & UserPermission.CAN_REMOVE_ADMIN) == UserPermission.CAN_REMOVE_ADMIN: + return True + return False + + def SetCanRemoveAdmin(permission): + return permission | UserPermission.CAN_REMOVE_ADMIN + + def RemoveCanRemoveAdmin(permission): + return permission & (not(UserPermission.CAN_REMOVE_ADMIN)) def CanForwardToChannel(permission): if (permission & UserPermission.CHANNEL) == UserPermission.CHANNEL: @@ -265,6 +277,15 @@ def GetUserPermissionsValue(userID): #No user exist, returning Flase for now return False +# GetUserPermissionsValue takes the userID as input and returns the permission value (int) direclty from the database +def SetUserPermissionsValue(userID,newPermission): + dbC = dbConnection.cursor() + res = dbC.execute('UPDATE Users SET Permissions=? WHERE ID = ?', (newPermission, userID,) ) + if res: + CommitDb() + return True + return False + def GetUserStatusValue(userID): user = GetUser(userID) if user != False: @@ -444,6 +465,27 @@ def getUsersIdLike(userNick): return res return False +def getUserId(userNick): + dbC = dbConnection.cursor() + dbC.execute('SELECT `ID` FROM Users WHERE `Nickname`= ?;', (userNick,)) + res = dbC.fetchone() + if res != None: + return res[0] + return False + +def setNewUserStatus(userdID, statusID): + dbC = dbConnection.cursor() + #res = dbC.execute('UPDATE Users SET Status=? WHERE ID = ?;', (UserStatus.WAITING_FOR_BIOGRAPHY , message.from_user.id,) ) + res = dbC.execute('UPDATE Users SET Status=? WHERE ID = ?', (statusID , userdID,) ) + if res: + CommitDb() + return True + return False + + +def IsUserSuperadmin(userNick): + return userNick.lower() in Settings.SupremeAdmins + ### # Bot functions @@ -513,10 +555,8 @@ def setBio(message): #Check if the user needs to set a biography if UserStatus.CanEnterBio(user["Status"]): #Asks for the bio - dbC = dbConnection.cursor() - #res = dbC.execute('UPDATE Users SET Status=? WHERE ID = ?;', (UserStatus.WAITING_FOR_BIOGRAPHY , message.from_user.id,) ) - res = dbC.execute('UPDATE Users SET Status=? WHERE ID = ?', (UserStatus.WAITING_FOR_BIOGRAPHY , message.from_user.id,) ) #res = dbC.execute('UPDATE Users SET Status=?, Biography=? WHERE employeeid = ?;', (0, message.text, message.from_user.id,) ) + res = setNewUserStatus(message.from_user.id, UserStatus.WAITING_FOR_BIOGRAPHY) #Tries to force the user to reply to the message #markup = telebot.types.ForceReply(selective=False) markup = telebot.types.InlineKeyboardMarkup() @@ -537,7 +577,7 @@ def setBio(message): #Creazione di una nuova lista @bot.message_handler(commands=['newlist', 'nuovalista']) def newList(message): - if message.from_user.username.lower() in Settings.SupremeAdmins or UserPermission.IsAdmin(GetUserPermissionsValue(message.from_user.id)) or UserPermission.CanCreateList(GetUserPermissionsValue(message.from_user.id)): + if IsUserSuperadmin(message.from_user.username) or UserPermission.IsAdmin(GetUserPermissionsValue(message.from_user.id)) or UserPermission.CanCreateList(GetUserPermissionsValue(message.from_user.id)): if not message.from_user.is_bot and message.text != "" : # Gets info about the user user = GetUser(message.from_user.id) @@ -547,8 +587,7 @@ def newList(message): msg = bot.reply_to(message, "Something's wrong here. error code: #R747") else: #Asks for the bio - dbC = dbConnection.cursor() - res = dbC.execute('UPDATE Users SET Status=? WHERE ID = ?', (UserStatus.WAITING_FOR_LIST , message.from_user.id,) ) + res = setNewUserStatus(message.from_user.id,UserStatus.WAITING_FOR_LIST ) markup = telebot.types.InlineKeyboardMarkup() markup.row_width = 1 markup.add(telebot.types.InlineKeyboardButton('❌ Annulla', callback_data=f"aList")) @@ -640,6 +679,132 @@ def unsubscribeUserListHandler(message): else: bot.reply_to(message, "Sarebbe opportuno registrarsi prima, tu non credi?\nPuoi farlo attraverso il comando /iscrivi") + +@bot.message_handler(commands=['setadmin']) +def setAdminPermissionHandler(message): + user = GetUser(message.from_user.id) + if user != False: + userPermission = GetUserPermissionsValue(message.from_user.id) + if IsUserSuperadmin(message.from_user.username) or (UserPermission.IsAdmin(userPermission) and UserPermission.CanAddAdmin(userPermission)): + args = message.text.split(' ') + if len(args) == 2: + newAdminNickname = args[1].replace('@','').lower() + newAdminId = getUserId(newAdminNickname) + if newAdminId == False: + #It looks like there's no user called this way + bot.reply_to(message, "❌ Sembra che l'utente non sia registrato.\nÈ opportuno farlo registrare prima di promuoverlo ad amministratore!") + return + newAdminpermission = GetUserPermissionsValue(newAdminId) + newAdminpermission = UserPermission.SetAdminPermission(newAdminpermission) + res = SetUserPermissionsValue(newAdminId, newAdminpermission) + if res == True: + #Say OK + bot.reply_to(message, "✅ Admin impostato con successo!\nLode al nuovo admin, @" + newAdminNickname + "!") + else: + #not ok + bot.reply_to(message, "❌ Impossibile impostare l'amministratore!") + return + else: + bot.reply_to(message, "❌ Utilizzo: /setadmin {@}username") + return + bot.reply_to(message, "❌ Error 403 - Unauthorized") + +@bot.message_handler(commands=['unsetadmin', 'removeadmin']) +def unsetAdminPermissionHandler(message): + user = GetUser(message.from_user.id) + if user != False: + userPermission = GetUserPermissionsValue(message.from_user.id) + if IsUserSuperadmin(message.from_user.username) or (UserPermission.IsAdmin(userPermission) and UserPermission.CanRemoveAdmin(userPermission)): + args = message.text.split(' ') + if len(args) == 2: + oldAdminNickname = args[1].replace('@','').lower() + oldAdminId = getUserId(oldAdminNickname) + if oldAdminId == False: + #It looks like there's no user called this way + bot.reply_to(message, "❌ Sembra che l'utente non sia registrato.\nÈ opportuno farlo registrare prima di promuoverlo ad amministratore!") + return + oldAdminpermission = GetUserPermissionsValue(oldAdminId) + if not UserPermission.IsAdmin(oldAdminpermission): + bot.reply_to(message, "❌ Sembra che l'utente non sia amministratore!") + return + oldAdminpermission = UserPermission.RemoveAdminPermission(oldAdminpermission) + res = SetUserPermissionsValue(oldAdminId, oldAdminpermission) + if res == True: + #Say OK + bot.reply_to(message, "✅ Admin congedato con successo!") + else: + #not ok + bot.reply_to(message, "❌ Impossibile congedare l'amministratore!") + return + else: + bot.reply_to(message, "❌ Utilizzo: /removeadmin {@}username") + return + bot.reply_to(message, "❌ Error 403 - Unauthorized") + + +@bot.message_handler(commands=['grantlist']) +def grantListCreationPermissionHandler(message): + user = GetUser(message.from_user.id) + if user != False: + userPermission = GetUserPermissionsValue(message.from_user.id) + if IsUserSuperadmin(message.from_user.username) or UserPermission.IsAdmin(userPermission): + args = message.text.split(' ') + if len(args) == 2: + newUserNickname = args[1].replace('@','').lower() + newUserId = getUserId(newUserNickname) + if newUserId == False: + #It looks like there's no user called this way + bot.reply_to(message, "❌ Sembra che l'utente non sia registrato.\nÈ opportuno farlo registrare prima di promuoverlo e permettergli di creare liste!") + return + newUserpermission = GetUserPermissionsValue(newUserId) + newUserpermission = UserPermission.SetCanCreateList(newUserpermission) + res = SetUserPermissionsValue(newUserId, newUserpermission) + if res == True: + #Say OK + bot.reply_to(message, "✅ Permesso di creazione liste assegnato!") + else: + #not ok + bot.reply_to(message, "❌ Impossibile impostare il permesso!") + return + else: + bot.reply_to(message, "❌ Utilizzo: /grantlist {@}username") + return + bot.reply_to(message, "❌ Error 403 - Unauthorized") + +@bot.message_handler(commands=['revokelist']) +def revokeListCreationPermissionHandler(message): + user = GetUser(message.from_user.id) + if user != False: + userPermission = GetUserPermissionsValue(message.from_user.id) + if IsUserSuperadmin(message.from_user.username) or UserPermission.IsAdmin(userPermission) : + args = message.text.split(' ') + if len(args) == 2: + oldUserNickname = args[1].replace('@','').lower() + oldUserId = getUserId(oldUserNickname) + if oldUserId == False: + #It looks like there's no user called this way + bot.reply_to(message, "❌ Sembra che l'utente non sia registrato.\nÈ opportuno farlo registrare prima di promuoverlo ad amministratore!") + return + oldUserpermission = GetUserPermissionsValue(oldUserId) + oldUserpermission = UserPermission.RemoveCanCreateList(oldUserpermission) + res = SetUserPermissionsValue(oldUserId, oldUserpermission) + if res == True: + #Say OK + #If was creating list, abort + oldstatus = GetUserStatusValue(oldUserId) + if oldstatus == UserStatus.WAITING_FOR_LIST: + setNewUserStatus(oldUserId,UserStatus.ACTIVE) + bot.reply_to(message, "✅ Permesso revocato con successo!") + else: + #not ok + bot.reply_to(message, "❌ Impossibile revocare il permesso!") + return + else: + bot.reply_to(message, "❌ Utilizzo: /revokelist {@}username") + return + bot.reply_to(message, "❌ Error 403 - Unauthorized") + + @bot.message_handler(func=lambda m: True) def genericMessageHandler(message): #get info about the user @@ -657,7 +822,7 @@ def genericMessageHandler(message): msg = bot.reply_to(message, "✅ Biografia impostata con successo!") #Tries to force the user to reply to the message #TODO: Not sure about the order - needs to be checked - elif message.chat.type == "group" or message.chat.type == "supergroup" and message.reply_to_message != None and message.reply_to_message.from_user.id == botInfo.id: + elif (message.chat.type == "group" or message.chat.type == "supergroup") and message.reply_to_message != None and message.reply_to_message.from_user.id == botInfo.id: dbC = dbConnection.cursor() res = dbC.execute('UPDATE Users SET Status=?, Biography=? WHERE ID = ?', (UserStatus.ACTIVE, message.text, message.from_user.id,) ) msg = bot.reply_to(message, "✅ Biografia impostata con successo!") @@ -679,7 +844,7 @@ def genericMessageHandler(message): #Tries to force the user to reply to the message #TODO: Not sure about the order - needs to be checked - elif message.chat.type == "group" or message.chat.type == "supergroup" and message.reply_to_message != None and message.reply_to_message.from_user.id == botInfo.id: + elif (message.chat.type == "group" or message.chat.type == "supergroup") and message.reply_to_message != None and message.reply_to_message.from_user.id == botInfo.id: success = CreateNewList(listName) if success: msg = bot.reply_to(message, "Lista creata con successo!") @@ -696,7 +861,7 @@ def genericMessageHandler(message): #https://stackoverflow.com/a/12400584 time.localtime(message.date))) - if message.chat.type == "group" or message.chat.type == "supergroup" and not message.from_user.is_bot and message.text != "": + if (message.chat.type == "group" or message.chat.type == "supergroup") and not message.from_user.is_bot and message.text != "": if message.text[0] == "#" or message.text[0] == "@" or message.text[0] == "." or message.text[0] == "!": listName = message.text.strip()[1:].lower() if ListExists(listName): From 08acb67896247c59e212010617b94282c5c486d3 Mon Sep 17 00:00:00 2001 From: Andrea Date: Fri, 2 Nov 2018 04:00:37 +0100 Subject: [PATCH 09/89] Fixed various listing issues --- scienzati_bot.py | 48 ++++++++++++++++++++++++++++-------------------- 1 file changed, 28 insertions(+), 20 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index e10eeac..823d42c 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -45,6 +45,8 @@ class Settings: #This part of the code is used to initalize the database. #It runs the "seed" query #This is the query that is used to initialize the SQLite3 database + +#TODO: add referencing message to make the bot statful initQuery= """CREATE TABLE IF NOT EXISTS `Users` ( `ID` INTEGER NOT NULL UNIQUE, `Nickname` TEXT NOT NULL, @@ -944,7 +946,8 @@ def callback_query(call): # sub-{id} => subscript to list {id} markup.row(telebot.types.InlineKeyboardButton(ulist["Name"], callback_data="usub-"+str(ulist["ID"]))) #If there are still lists, print the page delimiter - if len(lists) > Settings.subscriptionRows-1: + #if len(lists) > Settings.subscriptionRows-1: + if SubscribedLists(call.from_user.id, limit=1, offset=int(Settings.subscriptionRows-1)) != False: previousArrow = telebot.types.InlineKeyboardButton(f"⬅️", callback_data=f"ousub-"+str(int(actualOffset) - Settings.subscriptionRows+1)) nextArrow = telebot.types.InlineKeyboardButton(f"➡️", callback_data=f"ousub-"+str(int(actualOffset) + Settings.subscriptionRows-1)) emptyArrow = telebot.types.InlineKeyboardButton(" ", callback_data="ignore") @@ -954,7 +957,8 @@ def callback_query(call): rightButton = nextArrow if actualOffset - Settings.subscriptionRows +2 > 0: leftButton = previousArrow - markup.row(leftButton, rightButton) + if leftButton != rightButton: + markup.row(leftButton, rightButton) #msg = bot.reply_to(message, msg, reply_markup=markup) bot.edit_message_text("Ecco un elenco delle liste attualmente alle quali sei iscritto al momento:\n(Per rimuovere la sottoscrizione, è sufficiente \"tapparla\" e confermare)" , call.message.chat.id , call.message.message_id, call.id, reply_markup=markup) return @@ -978,8 +982,9 @@ def callback_query(call): lists = SubscribedLists(call.from_user.id) markup = telebot.types.InlineKeyboardMarkup() #Print the lists as inline buttons - if len(lists) == 0: + if lists == False: bot.edit_message_reply_markup(call.message.chat.id , call.message.message_id, call.id) + return for ulist in lists: # sub-{id} => subscript to list {id} markup.row(telebot.types.InlineKeyboardButton(ulist["Name"], callback_data="usub-"+str(ulist["ID"]))) @@ -1037,16 +1042,17 @@ def callback_query(call): # sub-{id} => subscript to list {id} markup.row(telebot.types.InlineKeyboardButton(ulist["Name"], callback_data="sub-"+str(ulist["ID"]))) #If there are still lists, print the page delimiter - if len(lists) > Settings.subscriptionRows-1: - previousArrow = telebot.types.InlineKeyboardButton(f"⬅️", callback_data=f"osub-"+str(int(actualOffset) - Settings.subscriptionRows+1)) - nextArrow = telebot.types.InlineKeyboardButton(f"➡️", callback_data=f"osub-"+str(int(actualOffset) + Settings.subscriptionRows-1)) - emptyArrow = telebot.types.InlineKeyboardButton(" ", callback_data="ignore") - leftButton, rightButton = emptyArrow,emptyArrow - #Check if there are more list - if AvailableListsToUser(call.from_user.id, limit=1, offset=int(actualOffset+Settings.subscriptionRows)) != False: - rightButton = nextArrow - if actualOffset - Settings.subscriptionRows +2 > 0: - leftButton = previousArrow + #if len(lists) > Settings.subscriptionRows-1: + previousArrow = telebot.types.InlineKeyboardButton(f"⬅️", callback_data=f"osub-"+str(int(actualOffset) - Settings.subscriptionRows+1)) + nextArrow = telebot.types.InlineKeyboardButton(f"➡️", callback_data=f"osub-"+str(int(actualOffset) + Settings.subscriptionRows-1)) + emptyArrow = telebot.types.InlineKeyboardButton(" ", callback_data="ignore") + leftButton, rightButton = emptyArrow,emptyArrow + #Check if there are more list + if AvailableListsToUser(call.from_user.id, limit=1, offset=int(actualOffset+Settings.subscriptionRows)) != False: + rightButton = nextArrow + if actualOffset - Settings.subscriptionRows +2 > 0: + leftButton = previousArrow + if leftButton != rightButton: markup.row(leftButton, rightButton) #msg = bot.reply_to(message, msg, reply_markup=markup) bot.edit_message_reply_markup(call.message.chat.id , call.message.message_id, call.id, reply_markup=markup) @@ -1077,13 +1083,15 @@ def callback_query(call): # sub-{id} => subscript to list {id} markup.row(telebot.types.InlineKeyboardButton(ulist["Name"], callback_data="sub-"+str(ulist["ID"]))) #If there are still lists, print the page delimiter - nextArrow = telebot.types.InlineKeyboardButton(f"➡️", callback_data=f"osub-"+str(Settings.subscriptionRows-1)) - emptyArrow = telebot.types.InlineKeyboardButton(" ", callback_data="ignore") - leftButton, rightButton = emptyArrow,emptyArrow - #Check if there are more list - if AvailableListsToUser(call.from_user.id, limit=1, offset=Settings.subscriptionRows-1) != False: - rightButton = nextArrow - markup.row(leftButton, rightButton) + if AvailableListsToUser(call.from_user.id, limit=1, offset=int(Settings.subscriptionRows-1)) != False: + nextArrow = telebot.types.InlineKeyboardButton(f"➡️", callback_data=f"osub-"+str(Settings.subscriptionRows-1)) + emptyArrow = telebot.types.InlineKeyboardButton(" ", callback_data="ignore") + leftButton, rightButton = emptyArrow,emptyArrow + #Check if there are more list + if AvailableListsToUser(call.from_user.id, limit=1, offset=Settings.subscriptionRows-1) != False: + rightButton = nextArrow + if leftButton != rightButton: + markup.row(leftButton, rightButton) #msg = bot.reply_to(message, msg, reply_markup=markup) bot.edit_message_reply_markup(call.message.chat.id , call.message.message_id, call.id, reply_markup=markup) return From c628cee3f99f5e518f8f53237277500693f08329 Mon Sep 17 00:00:00 2001 From: Andrea Date: Fri, 2 Nov 2018 04:02:25 +0100 Subject: [PATCH 10/89] Ingore SQL viewer program bin file --- .gitignore | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index a828f5e..d673f0a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ __pycache__ .vscode/ -database.sqlitedb \ No newline at end of file +database.sqlitedb +database.sqlitedb-journal \ No newline at end of file From e5497516fd8db8234d150d5acffc64b900d2ef31 Mon Sep 17 00:00:00 2001 From: Andrea Date: Fri, 2 Nov 2018 04:18:56 +0100 Subject: [PATCH 11/89] Updated dockerfile and removed unused depencecies - Download size from ~300MiBs to 80MiBs --- Dockerfile | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index 635b229..fece950 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,9 +1,35 @@ -FROM python:3 +FROM python:3-alpine WORKDIR /usr/src/app COPY requirements.txt ./ + +# +# The compilation of lxml (a library required and installed by pip) requires more than 1GiB of RAM memory. +# Since I had only 1 GiB of RAM, as a workaround I made a 2GiB swap file +# THIS IS A THING TO AVOID AS MUSH AS POSSIBLE +# Commands executed: +# +# 1. dd if=/dev/zero of=/swapfile bs=2048 count=1M +# 2. chmod 0600 /swapfile +# 3. mkswap /swapfile +# 4. echo "/swapfile swap swap sw 0 0" >>/etc/fstab +# 5. swapon /swapfile +# +# 1. Creates a swapfile and fill it of 0s +# 2. Set permissions for a swap file +# 3. Sets the file a file usable as a swap file +# 4. sets the swap on startup +# 5. enables the swap "hotplugged" + + +RUN apk add py3-pip openssl py3-lxml \ + && apk add --virtual build-dependencies python3-dev build-base wget libffi-dev openssl-dev libxml2-dev libxslt-dev \ + && rm -rf /var/cache/apk/* + RUN pip install --no-cache-dir -r requirements.txt +RUN apk del build-dependencies + COPY scienzati_bot.py . From 6116457426cc23c104f8eda38c6cac947e312a17 Mon Sep 17 00:00:00 2001 From: Andrea Date: Fri, 2 Nov 2018 04:25:56 +0100 Subject: [PATCH 12/89] Aded ping function --- scienzati_bot.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/scienzati_bot.py b/scienzati_bot.py index 823d42c..5e92bb0 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -807,6 +807,12 @@ def revokeListCreationPermissionHandler(message): bot.reply_to(message, "❌ Error 403 - Unauthorized") +@bot.message_handler(commands=['ping']) +def pingHandler(message): + bot.reply_to(message, "🏓 Pong!") + + + @bot.message_handler(func=lambda m: True) def genericMessageHandler(message): #get info about the user From bf32d6614f7901933044fe2c8ba86a3d3014adca Mon Sep 17 00:00:00 2001 From: Andrea Date: Fri, 2 Nov 2018 04:28:00 +0100 Subject: [PATCH 13/89] Added ping function reply only to admins --- scienzati_bot.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index 5e92bb0..cd4b27c 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -809,7 +809,8 @@ def revokeListCreationPermissionHandler(message): @bot.message_handler(commands=['ping']) def pingHandler(message): - bot.reply_to(message, "🏓 Pong!") + if IsUserSuperadmin(message.from_user.username) or (GetUser(message.from_user.id) != False and UserPermission.IsAdmin(GetUserPermissionsValue(message.from_user.id))): + bot.reply_to(message, "🏓 Pong!") From 999894c275b32a424a49c11dab73a35ca9be87f5 Mon Sep 17 00:00:00 2001 From: Andrea Date: Fri, 2 Nov 2018 11:23:25 +0100 Subject: [PATCH 14/89] Added empty list check --- scienzati_bot.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/scienzati_bot.py b/scienzati_bot.py index cd4b27c..4f21c63 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -1086,6 +1086,9 @@ def callback_query(call): lists = AvailableListsToUser(call.from_user.id) markup = telebot.types.InlineKeyboardMarkup() #Print the lists as inline buttons + if len(lists) == 0: + bot.edit_message_text("Al momento non è presente nessuna lista" , call.message.chat.id , call.message.message_id, call.id) + return for ulist in lists: # sub-{id} => subscript to list {id} markup.row(telebot.types.InlineKeyboardButton(ulist["Name"], callback_data="sub-"+str(ulist["ID"]))) From bd7528a8c1224a5201061f57d1d89be021eafbe8 Mon Sep 17 00:00:00 2001 From: Andrea Date: Fri, 2 Nov 2018 11:26:15 +0100 Subject: [PATCH 15/89] Added missing commits --- scienzati_bot.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index 4f21c63..b1ba67f 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -338,6 +338,7 @@ def CreateNewList(name): try: res = dbC.execute('INSERT INTO Lists (Name) VALUES (?)', (name,) ) if res: + CommitDb() return True return False except: @@ -361,6 +362,7 @@ def SubscribeUserToList(userID, listID): dbC.execute('INSERT INTO Subscriptions (User, List) VALUES (?,?)', (userID, listID)) res = dbC.fetchall() if res != None: + CommitDb() return True return False @@ -370,7 +372,7 @@ def UnubscribeUserFromList(userID, listID): dbC.execute('DELETE FROM Subscriptions WHERE User=? AND List=?', (userID, listID)) res = dbC.fetchall() if res != None: - #User already subscribed + CommitDb() return True return False @@ -431,7 +433,11 @@ def GetListSubscribers(listID): def UpdateNickname(userID, nickname): dbC = dbConnection.cursor() - dbC.execute('UPDATE Users SET Nickname=? WHERE ID = ?', (nickname, userID, )) + res = dbC.execute('UPDATE Users SET Nickname=? WHERE ID = ?', (nickname, userID, )) + if res: + CommitDb() + return True + return False #Abort the inserting process of a new Bio #WARNING: CHECK IF USER IS BANNED BEFORE, OR HE WILL GET UNBANNED From 59b661ded080ae213a59c5f89538cd92659bc04d Mon Sep 17 00:00:00 2001 From: Andrea Date: Fri, 2 Nov 2018 12:30:23 +0100 Subject: [PATCH 16/89] Various Bugfixes --- scienzati_bot.py | 108 ++++++++++++++++------------------------------- 1 file changed, 36 insertions(+), 72 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index b1ba67f..ab71170 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -625,18 +625,19 @@ def subscribeUserListHandler(message): lists = AvailableListsToUser(message.from_user.id) markup = telebot.types.InlineKeyboardMarkup() #Print the lists as inline buttons - if len(lists) == 0: + if lists == False: msg = "Al momento non è presente nessuna lista.\nSi prega di riprovare in seguito." - for ulist in lists: - # sub-{id} => subscript to list {id} - markup.row(telebot.types.InlineKeyboardButton(ulist["Name"], callback_data="sub-"+str(ulist["ID"]))) - #If there are still lists, print the page delimiter - #if len(lists) > Settings.subscriptionRows-1: - if AvailableListsToUser(message.from_user.id, limit=1, offset=int(Settings.subscriptionRows)) != False: - # osub-{n} => offest subscription, needed for pagination, - #Teels the offset to set to correctly display the pages - markup.row(telebot.types.InlineKeyboardButton(" ", callback_data="ignore"), telebot.types.InlineKeyboardButton(f"➡️", callback_data=f"osub-"+str(Settings.subscriptionRows-1))) - #⬅️ ➡️ + else: + for ulist in lists: + # sub-{id} => subscript to list {id} + markup.row(telebot.types.InlineKeyboardButton(ulist["Name"], callback_data="sub-"+str(ulist["ID"]))) + #If there are still lists, print the page delimiter + #if len(lists) > Settings.subscriptionRows-1: + if AvailableListsToUser(message.from_user.id, limit=1, offset=int(Settings.subscriptionRows-1)) != False: + # osub-{n} => offest subscription, needed for pagination, + #Teels the offset to set to correctly display the pages + markup.row(telebot.types.InlineKeyboardButton(" ", callback_data="ignore"), telebot.types.InlineKeyboardButton(f"➡️", callback_data=f"osub-"+str(Settings.subscriptionRows-1))) + #⬅️ ➡️ msg = bot.reply_to(message, msg, reply_markup=markup) #SubscribeUserToList() @@ -670,7 +671,7 @@ def unsubscribeUserListHandler(message): markup.row(telebot.types.InlineKeyboardButton(ulist["Name"], callback_data="usub-"+str(ulist["ID"]))) #If there are still lists, print the page delimiter #if len(lists) > Settings.subscriptionRows-1: - if SubscribedLists(message.from_user.id, limit=1, offset=int(Settings.subscriptionRows)) != False: + if SubscribedLists(message.from_user.id, limit=1, offset=int(Settings.subscriptionRows-1)) != False: # osub-{n} => offest subscription, needed for pagination, #Teels the offset to set to correctly display the pages markup.row(telebot.types.InlineKeyboardButton(" ", callback_data="ignore"), telebot.types.InlineKeyboardButton(f"➡️", callback_data=f"ousub-"+str(Settings.subscriptionRows-1))) @@ -951,7 +952,7 @@ def callback_query(call): if actualOffset%(Settings.subscriptionRows-1) == 0: lists = SubscribedLists(call.from_user.id, offset=int(actualOffset)) markup = telebot.types.InlineKeyboardMarkup() - if len(lists) == 0: + if lists == False: bot.edit_message_text("Non sei iscritto a nessuna lista" , call.message.chat.id , call.message.message_id, call.id) return #Print the lists as inline buttons @@ -959,14 +960,13 @@ def callback_query(call): # sub-{id} => subscript to list {id} markup.row(telebot.types.InlineKeyboardButton(ulist["Name"], callback_data="usub-"+str(ulist["ID"]))) #If there are still lists, print the page delimiter - #if len(lists) > Settings.subscriptionRows-1: - if SubscribedLists(call.from_user.id, limit=1, offset=int(Settings.subscriptionRows-1)) != False: + if int(actualOffset) >=Settings.subscriptionRows -1 or SubscribedLists(call.from_user.id, limit=1, offset=int(actualOffset + Settings.subscriptionRows-1)) != False: previousArrow = telebot.types.InlineKeyboardButton(f"⬅️", callback_data=f"ousub-"+str(int(actualOffset) - Settings.subscriptionRows+1)) nextArrow = telebot.types.InlineKeyboardButton(f"➡️", callback_data=f"ousub-"+str(int(actualOffset) + Settings.subscriptionRows-1)) emptyArrow = telebot.types.InlineKeyboardButton(" ", callback_data="ignore") leftButton, rightButton = emptyArrow,emptyArrow #Check if there are more list - if SubscribedLists(call.from_user.id, limit=1, offset=int(actualOffset+Settings.subscriptionRows)) != False: + if SubscribedLists(call.from_user.id, limit=1, offset=int(actualOffset + Settings.subscriptionRows-1)) != False: rightButton = nextArrow if actualOffset - Settings.subscriptionRows +2 > 0: leftButton = previousArrow @@ -992,31 +992,12 @@ def callback_query(call): else: bot.answer_callback_query(call.id, text="❌ Si è verificato un errore", show_alert=False) #Edit message back to list - lists = SubscribedLists(call.from_user.id) - markup = telebot.types.InlineKeyboardMarkup() - #Print the lists as inline buttons - if lists == False: - bot.edit_message_reply_markup(call.message.chat.id , call.message.message_id, call.id) - return - for ulist in lists: - # sub-{id} => subscript to list {id} - markup.row(telebot.types.InlineKeyboardButton(ulist["Name"], callback_data="usub-"+str(ulist["ID"]))) - #If there are still lists, print the page delimiter - if len(lists) > Settings.subscriptionRows-1: - previousArrow = telebot.types.InlineKeyboardButton(f"⬅️", callback_data=f"ousub-"+str(int(actualOffset) - Settings.subscriptionRows+1)) - nextArrow = telebot.types.InlineKeyboardButton(f"➡️", callback_data=f"ousub-"+str(int(actualOffset) + Settings.subscriptionRows-1)) - emptyArrow = telebot.types.InlineKeyboardButton(" ", callback_data="ignore") - leftButton, rightButton = emptyArrow,emptyArrow - #Check if there are more list - if SubscribedLists(call.from_user.id, limit=1, offset=int(Settings.subscriptionRows)) != False: - rightButton = nextArrow - markup.row(leftButton, rightButton) - #msg = bot.reply_to(message, msg, reply_markup=markup) - bot.edit_message_reply_markup(call.message.chat.id , call.message.message_id, call.id, reply_markup=markup) - return + nc = call + nc.data = "ousub-0" + callback_query(nc) + return bot.answer_callback_query(call.id, text="Just go away", show_alert=False, cache_time=999999) - elif "usub-" in call.data: if call.message.reply_to_message != None and call.from_user.id == call.message.reply_to_message.from_user.id: if user["Status"] == UserStatus.ACTIVE : @@ -1048,7 +1029,7 @@ def callback_query(call): lists = AvailableListsToUser(call.from_user.id, offset=int(actualOffset)) markup = telebot.types.InlineKeyboardMarkup() #Print the lists as inline buttons - if len(lists) == 0: + if lists == False: bot.edit_message_text("Al momento non è presente nessuna lista" , call.message.chat.id , call.message.message_id, call.id) return for ulist in lists: @@ -1056,17 +1037,18 @@ def callback_query(call): markup.row(telebot.types.InlineKeyboardButton(ulist["Name"], callback_data="sub-"+str(ulist["ID"]))) #If there are still lists, print the page delimiter #if len(lists) > Settings.subscriptionRows-1: - previousArrow = telebot.types.InlineKeyboardButton(f"⬅️", callback_data=f"osub-"+str(int(actualOffset) - Settings.subscriptionRows+1)) - nextArrow = telebot.types.InlineKeyboardButton(f"➡️", callback_data=f"osub-"+str(int(actualOffset) + Settings.subscriptionRows-1)) - emptyArrow = telebot.types.InlineKeyboardButton(" ", callback_data="ignore") - leftButton, rightButton = emptyArrow,emptyArrow - #Check if there are more list - if AvailableListsToUser(call.from_user.id, limit=1, offset=int(actualOffset+Settings.subscriptionRows)) != False: - rightButton = nextArrow - if actualOffset - Settings.subscriptionRows +2 > 0: - leftButton = previousArrow - if leftButton != rightButton: - markup.row(leftButton, rightButton) + if int(actualOffset) >=Settings.subscriptionRows -1 or AvailableListsToUser(call.from_user.id, limit=1, offset=int( actualOffset + Settings.subscriptionRows-1)) != False: + previousArrow = telebot.types.InlineKeyboardButton(f"⬅️", callback_data=f"osub-"+str(int(actualOffset) - Settings.subscriptionRows+1)) + nextArrow = telebot.types.InlineKeyboardButton(f"➡️", callback_data=f"osub-"+str(int(actualOffset) + Settings.subscriptionRows-1)) + emptyArrow = telebot.types.InlineKeyboardButton(" ", callback_data="ignore") + leftButton, rightButton = emptyArrow,emptyArrow + #Check if there are more list + if AvailableListsToUser(call.from_user.id, limit=1, offset=int(actualOffset + Settings.subscriptionRows-1)) != False: + rightButton = nextArrow + if actualOffset - Settings.subscriptionRows +2 > 0: + leftButton = previousArrow + if leftButton != rightButton: + markup.row(leftButton, rightButton) #msg = bot.reply_to(message, msg, reply_markup=markup) bot.edit_message_reply_markup(call.message.chat.id , call.message.message_id, call.id, reply_markup=markup) return @@ -1089,27 +1071,9 @@ def callback_query(call): else: bot.answer_callback_query(call.id, text="❌ Si è verificato un errore", show_alert=False) #update message - lists = AvailableListsToUser(call.from_user.id) - markup = telebot.types.InlineKeyboardMarkup() - #Print the lists as inline buttons - if len(lists) == 0: - bot.edit_message_text("Al momento non è presente nessuna lista" , call.message.chat.id , call.message.message_id, call.id) - return - for ulist in lists: - # sub-{id} => subscript to list {id} - markup.row(telebot.types.InlineKeyboardButton(ulist["Name"], callback_data="sub-"+str(ulist["ID"]))) - #If there are still lists, print the page delimiter - if AvailableListsToUser(call.from_user.id, limit=1, offset=int(Settings.subscriptionRows-1)) != False: - nextArrow = telebot.types.InlineKeyboardButton(f"➡️", callback_data=f"osub-"+str(Settings.subscriptionRows-1)) - emptyArrow = telebot.types.InlineKeyboardButton(" ", callback_data="ignore") - leftButton, rightButton = emptyArrow,emptyArrow - #Check if there are more list - if AvailableListsToUser(call.from_user.id, limit=1, offset=Settings.subscriptionRows-1) != False: - rightButton = nextArrow - if leftButton != rightButton: - markup.row(leftButton, rightButton) - #msg = bot.reply_to(message, msg, reply_markup=markup) - bot.edit_message_reply_markup(call.message.chat.id , call.message.message_id, call.id, reply_markup=markup) + nc = call + nc.data = "osub-0" + callback_query(nc) return @bot.inline_handler(func=lambda chosen_inline_result: True) From 993d1dcb6790fa418a4bc77a703fe1055221e61e Mon Sep 17 00:00:00 2001 From: Andrea Date: Fri, 2 Nov 2018 12:33:26 +0100 Subject: [PATCH 17/89] Added die function - (actually restarts inside docker) --- scienzati_bot.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index ab71170..bf3f69e 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -4,6 +4,7 @@ import sqlite3 import random import re +import sys #Settings class @@ -819,7 +820,11 @@ def pingHandler(message): if IsUserSuperadmin(message.from_user.username) or (GetUser(message.from_user.id) != False and UserPermission.IsAdmin(GetUserPermissionsValue(message.from_user.id))): bot.reply_to(message, "🏓 Pong!") - +@bot.message_handler(commands=['die', 'crash']) +def pingHandler(message): + if IsUserSuperadmin(message.from_user.username) or (GetUser(message.from_user.id) != False and UserPermission.IsAdmin(GetUserPermissionsValue(message.from_user.id))): + bot.reply_to(message, "Autodestruction sequence initialized... \n💥 Poof! ✨") + sys.exit(0) @bot.message_handler(func=lambda m: True) def genericMessageHandler(message): From 82d7389209d512c31221d778e63ccd938af74b4d Mon Sep 17 00:00:00 2001 From: Andrea Date: Fri, 2 Nov 2018 19:48:02 +0100 Subject: [PATCH 18/89] Added aliases to commands --- scienzati_bot.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index bf3f69e..5d26ddf 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -549,7 +549,7 @@ def start_user_registration(message): ### Aggioramento/ impostaizone bio -@bot.message_handler(commands=['bio']) +@bot.message_handler(commands=['bio', 'setbio']) def setBio(message): if not message.from_user.is_bot and message.text != "" : # Gets info about the user @@ -609,11 +609,14 @@ def newList(message): @bot.message_handler(commands=['lists', 'liste']) def showLists(message): msg = "Ecco le liste esistenti al momento:\n" - for list in GetLists(): + liste = GetLists() + for list in liste: msg = msg + list[0] + "\n" + if len(liste) == 0: + msg = "Al momento non sono presenti liste" bot.reply_to(message, msg) -@bot.message_handler(commands=['subscribe', 'join', 'registrati']) +@bot.message_handler(commands=['subscribe', 'join', 'registrati', 'partecipa', 'aderisci', 'sottoscrivi']) def subscribeUserListHandler(message): user = GetUser(message.from_user.id) if user != False: @@ -651,7 +654,7 @@ def subscribeUserListHandler(message): else: bot.reply_to(message, "Sarebbe opportuno registrarsi prima, tu non credi?\nPuoi farlo attraverso il comando /iscrivi") -@bot.message_handler(commands=['subscribedto', 'joinedto', 'inscriptions', 'iscrizioni', 'disiscriviti', 'rimuovi']) +@bot.message_handler(commands=['subscribedto', 'joinedto', 'inscriptions', 'iscrizioni','disiscrivi', 'disiscriviti', 'rimuovi', 'esci']) def unsubscribeUserListHandler(message): user = GetUser(message.from_user.id) if user != False: From 38f6d0efba3fb473289301a901bb47a5b20d6da0 Mon Sep 17 00:00:00 2001 From: Andrea Date: Fri, 2 Nov 2018 19:50:04 +0100 Subject: [PATCH 19/89] Added @RagazzaSmarties' help message --- scienzati_bot.py | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index 5d26ddf..5407116 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -88,13 +88,18 @@ class Settings: class constResources: - intro_mex = """Questo e' il bot del gruppo @scienza, - /iscrivi iscriviti al database di utenti e a liste di interessi - /bio modifica la propria biografia - /liste consulta le attuali liste di interessi - /nuovalista crea nuove liste - solo per amministratori - /gdpr Consulta le norme sul GDPR - /privs elenca i privilegi utente""" + intro_mex = """Ciao 😁 +Sei confuso? +Questo è il bot del gruppo @scienza e permette di usufruire di queste funzioni: +/iscriviti per iscriverti al database di utenti e per partecipare alle liste sugli interessi +/aderisci per iscriverti ad una lista, puoi usare anche: /partecipa e /sottoscrivi +/bio per scrivere qualcosa su di te +/liste per scoprire le liste già presenti +/nuovalista per aggiungere una nuova lista (si deve avere il permesso) +/registrati per registrarti in una lista +/gdpr consulta le norme sul GDPR +/privs elenca i privilegi utente +/disiscrivi per cancellarti da una lista alla quale hai aderito, puoi usare pure: /esci, /rimuovi, /iscrizioni e /aderenze""" privs_mex = """privs =-1 -> utente non registrato = 0 -> utente normale From 40570d67aa3d938d01f63c63ea0d8710cdbbb454 Mon Sep 17 00:00:00 2001 From: Andrea Date: Sat, 3 Nov 2018 18:09:38 +0100 Subject: [PATCH 20/89] added list delletaion and various fixes --- scienzati_bot.py | 203 ++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 181 insertions(+), 22 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index 5407116..a51bcfe 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -95,12 +95,24 @@ class constResources: /aderisci per iscriverti ad una lista, puoi usare anche: /partecipa e /sottoscrivi /bio per scrivere qualcosa su di te /liste per scoprire le liste già presenti -/nuovalista per aggiungere una nuova lista (si deve avere il permesso) /registrati per registrarti in una lista /gdpr consulta le norme sul GDPR /privs elenca i privilegi utente /disiscrivi per cancellarti da una lista alla quale hai aderito, puoi usare pure: /esci, /rimuovi, /iscrizioni e /aderenze""" + admin_help = """Comandi admin... blabla + /nuovalista + /rimuovilista + === CA$TA THINGS === + /setadmin + /unsetadmin + /grantlist + /revokelist + """ + + version = "α0.1.2.I dev" + + privs_mex = """privs =-1 -> utente non registrato = 0 -> utente normale = 1 -> utente abituale @@ -179,7 +191,7 @@ class UserPermission: #Siply do an AND with the permission CAN_ADD_ADMIN=int('10', 2) CAN_REMOVE_ADMIN=int('100', 2) CHANNEL=int('1000', 2) - CREATE_LIST=int('10000', 2) + LIST=int('10000', 2) def IsAdmin(permission): if (permission & UserPermission.ADMIN) == UserPermission.ADMIN: @@ -225,16 +237,16 @@ def SetForwardToChannel(permission): def RemoveForwardToChannel(permission): return permission & (not(UserPermission.CHANNEL)) - def CanCreateList(permission): - if (permission & UserPermission.CREATE_LIST) == UserPermission.CREATE_LIST: + def ListPermission(permission): + if (permission & UserPermission.LIST) == UserPermission.LIST: return True return False - def SetCanCreateList(permission): - return permission | UserPermission.CREATE_LIST + def SetListPermission(permission): + return permission | UserPermission.LIST - def RemoveCanCreateList(permission): - return permission & (not(UserPermission.CREATE_LIST)) + def RemoveListPermission(permission): + return permission & (not(UserPermission.LIST)) @@ -350,9 +362,24 @@ def CreateNewList(name): except: return False -def GetLists(): +def GetLists(limit = Settings.subscriptionRows-1, offset=0): dbC = dbConnection.cursor() - dbC.execute('SELECT `Name` FROM Lists') + if limit == None: + dbC.execute('SELECT * FROM Lists') + else: + dbC.execute('SELECT * FROM Lists LIMIT ? OFFSET ?', (limit, offset,)) + res = dbC.fetchall() + if len(res) >0: + return res + return False + + +def GetListsNames(limit = Settings.subscriptionRows-1, offset=0): + dbC = dbConnection.cursor() + if limit == None: + dbC.execute('SELECT `Name` FROM Lists') + else: + dbC.execute('SELECT `Name` FROM Lists LIMIT ? OFFSET ?', (limit, offset,)) return dbC.fetchall() def SubscribeUserToList(userID, listID): @@ -385,7 +412,10 @@ def UnubscribeUserFromList(userID, listID): def AvailableListsToUser(userID, limit=Settings.subscriptionRows-1, offset=0): #If user is not in the list dbC = dbConnection.cursor() - dbC.execute('SELECT ID, Name FROM Lists WHERE Lists.ID NOT IN (SELECT List FROM Subscriptions WHERE User=?) LIMIT ? OFFSET ?', (userID, limit,offset)) + if limit == None: + dbC.execute('SELECT ID, Name FROM Lists WHERE Lists.ID NOT IN (SELECT List FROM Subscriptions WHERE User=?)') + else: + dbC.execute('SELECT ID, Name FROM Lists WHERE Lists.ID NOT IN (SELECT List FROM Subscriptions WHERE User=?) LIMIT ? OFFSET ?', (userID, limit,offset)) res = dbC.fetchall() if len(res) >0: #User already subscribed @@ -396,7 +426,10 @@ def AvailableListsToUser(userID, limit=Settings.subscriptionRows-1, offset=0): def SubscribedLists(userID, limit=Settings.subscriptionRows-1, offset=0): #If user is not in the list dbC = dbConnection.cursor() - dbC.execute('SELECT Lists.ID, Lists.Name FROM Lists INNER JOIN Subscriptions ON Subscriptions.List = Lists.ID WHERE Subscriptions.User=? LIMIT ? OFFSET ?', (userID, limit,offset)) + if limit == None: + dbC.execute('SELECT Lists.ID, Lists.Name FROM Lists INNER JOIN Subscriptions ON Subscriptions.List = Lists.ID WHERE Subscriptions.User=?', (userID,)) + else: + dbC.execute('SELECT Lists.ID, Lists.Name FROM Lists INNER JOIN Subscriptions ON Subscriptions.List = Lists.ID WHERE Subscriptions.User=? LIMIT ? OFFSET ?', (userID, limit,offset)) res = dbC.fetchall() if len(res) >0: #User already subscribed @@ -437,6 +470,15 @@ def GetListSubscribers(listID): return res return False +def DeleteList(listID): + #If user is not in the list + dbC = dbConnection.cursor() + res =dbC.execute('DELETE FROM Lists WHERE ID=?', (listID,)) + if res != None: + CommitDb() + return True + return False + def UpdateNickname(userID, nickname): dbC = dbConnection.cursor() res = dbC.execute('UPDATE Users SET Nickname=? WHERE ID = ?', (nickname, userID, )) @@ -511,6 +553,14 @@ def IsUserSuperadmin(userNick): def send_welcome(message): bot.reply_to(message, constResources.intro_mex) +@bot.message_handler(commands=['adminhelp']) +def send_admhelp(message): + bot.reply_to(message, constResources.admin_help) + +@bot.message_handler(commands=['v', 'version']) +def send_version(message): + bot.reply_to(message, "V: " + constResources.version) + # Replies with the static message before @bot.message_handler(commands=['privs']) def send_privs(message): @@ -568,8 +618,6 @@ def setBio(message): #There's only one user, as it's supposed to be #Check if the user needs to set a biography if UserStatus.CanEnterBio(user["Status"]): - #Asks for the bio - #res = dbC.execute('UPDATE Users SET Status=?, Biography=? WHERE employeeid = ?;', (0, message.text, message.from_user.id,) ) res = setNewUserStatus(message.from_user.id, UserStatus.WAITING_FOR_BIOGRAPHY) #Tries to force the user to reply to the message #markup = telebot.types.ForceReply(selective=False) @@ -591,30 +639,62 @@ def setBio(message): #Creazione di una nuova lista @bot.message_handler(commands=['newlist', 'nuovalista']) def newList(message): - if IsUserSuperadmin(message.from_user.username) or UserPermission.IsAdmin(GetUserPermissionsValue(message.from_user.id)) or UserPermission.CanCreateList(GetUserPermissionsValue(message.from_user.id)): + if IsUserSuperadmin(message.from_user.username) or UserPermission.IsAdmin(GetUserPermissionsValue(message.from_user.id)) or UserPermission.ListPermission(GetUserPermissionsValue(message.from_user.id)): if not message.from_user.is_bot and message.text != "" : # Gets info about the user user = GetUser(message.from_user.id) #Check if the user exists if user == False: #the user does not exist - msg = bot.reply_to(message, "Something's wrong here. error code: #R747") + bot.reply_to(message, "Something's wrong here. error code: #Q534") else: - #Asks for the bio res = setNewUserStatus(message.from_user.id,UserStatus.WAITING_FOR_LIST ) markup = telebot.types.InlineKeyboardMarkup() markup.row_width = 1 markup.add(telebot.types.InlineKeyboardButton('❌ Annulla', callback_data=f"aList")) msg = bot.reply_to(message, "Per creare una nuova lista, scrivi il nome in chat privata o in un messaggio che mi risponda rispondendomi", reply_markup=markup) dbConnection.commit() + else: + bot.reply_to(message, "Error 403 - ❌ Unauthorized") + +#Creazione di una nuova lista +@bot.message_handler(commands=['deletelist', 'removelist', 'rimuovilista', 'eliminalista']) +def deleteListHandler(message): + if IsUserSuperadmin(message.from_user.username) or UserPermission.IsAdmin(GetUserPermissionsValue(message.from_user.id)) or UserPermission.ListPermission(GetUserPermissionsValue(message.from_user.id)): + if not message.from_user.is_bot and message.text != "" : + # Gets info about the user + user = GetUser(message.from_user.id) + #Check if the user exists + if user == False: + #the user does not exist + msg = bot.reply_to(message, "Something's wrong here. error code: #J258") + else: + #Asks for the bio + #need to send message with a list + liste = GetLists() + markup = telebot.types.InlineKeyboardMarkup() + #Print the lists as inline buttons + msg = "Random message padding" + if liste == False:#TODO test + msg = "Al momento non è presente nessuna lista.\nSi prega di riprovare in seguito." + else: + for ulist in liste: + markup.row(telebot.types.InlineKeyboardButton(ulist["Name"], callback_data="rlist-"+str(ulist["ID"]))) + + if AvailableListsToUser(message.from_user.id, limit=1, offset=int(Settings.subscriptionRows-1)) != False: + markup.row(telebot.types.InlineKeyboardButton(" ", callback_data="ignore"), telebot.types.InlineKeyboardButton(f"➡️", callback_data=f"orlist-"+str(Settings.subscriptionRows-1))) + #⬅️ ➡️ + msg = bot.reply_to(message, msg, reply_markup=markup) + #SubscribeUserToList() + else: msg = bot.reply_to(message, "Error 403 - ❌ Unauthorized") #Lista delle liste @bot.message_handler(commands=['lists', 'liste']) def showLists(message): - msg = "Ecco le liste esistenti al momento:\n" - liste = GetLists() + liste = GetListsNames(limit=None) + msg = "Al momento esistono " + str(len(liste))+ " liste; eccole qui:\n" for list in liste: msg = msg + list[0] + "\n" if len(liste) == 0: @@ -775,7 +855,7 @@ def grantListCreationPermissionHandler(message): bot.reply_to(message, "❌ Sembra che l'utente non sia registrato.\nÈ opportuno farlo registrare prima di promuoverlo e permettergli di creare liste!") return newUserpermission = GetUserPermissionsValue(newUserId) - newUserpermission = UserPermission.SetCanCreateList(newUserpermission) + newUserpermission = UserPermission.SetListPermission(newUserpermission) res = SetUserPermissionsValue(newUserId, newUserpermission) if res == True: #Say OK @@ -804,7 +884,7 @@ def revokeListCreationPermissionHandler(message): bot.reply_to(message, "❌ Sembra che l'utente non sia registrato.\nÈ opportuno farlo registrare prima di promuoverlo ad amministratore!") return oldUserpermission = GetUserPermissionsValue(oldUserId) - oldUserpermission = UserPermission.RemoveCanCreateList(oldUserpermission) + oldUserpermission = UserPermission.RemoveListPermission(oldUserpermission) res = SetUserPermissionsValue(oldUserId, oldUserpermission) if res == True: #Say OK @@ -832,7 +912,7 @@ def pingHandler(message): def pingHandler(message): if IsUserSuperadmin(message.from_user.username) or (GetUser(message.from_user.id) != False and UserPermission.IsAdmin(GetUserPermissionsValue(message.from_user.id))): bot.reply_to(message, "Autodestruction sequence initialized... \n💥 Poof! ✨") - sys.exit(0) + sys.exit(10) @bot.message_handler(func=lambda m: True) def genericMessageHandler(message): @@ -991,6 +1071,85 @@ def callback_query(call): #Just go away bot.answer_callback_query(call.id, text="Just go away", show_alert=False, cache_time=999999) + elif "orlist-" in call.data: + if call.message.reply_to_message != None and call.from_user.id == call.message.reply_to_message.from_user.id: + if user["Status"] == UserStatus.ACTIVE : + #Show next n rows + offset, osub-{offset} + #Safe data checks + splittedString = call.data.split('-') + if len(splittedString) == 2: + if splittedString[1].isdigit(): + actualOffset=int(splittedString[1]) + if actualOffset%(Settings.subscriptionRows-1) == 0: + + + liste = GetLists(offset=int(actualOffset)) + markup = telebot.types.InlineKeyboardMarkup() + #Print the lists as inline buttons + msg = "Random message padding" + if liste == False:#TODO test + msg = "Al momento non è presente nessuna lista.\nSi prega di riprovare in seguito." + else: + for ulist in liste: + markup.row(telebot.types.InlineKeyboardButton(ulist["Name"], callback_data="rlist-"+str(ulist["ID"]))) + + if int(actualOffset) >=Settings.subscriptionRows -1 or GetLists(limit=1, offset=int(actualOffset + Settings.subscriptionRows-1)) != False: + previousArrow = telebot.types.InlineKeyboardButton(f"⬅️", callback_data=f"orlist-"+str(int(actualOffset) - Settings.subscriptionRows+1)) + nextArrow = telebot.types.InlineKeyboardButton(f"➡️", callback_data=f"orlist-"+str(int(actualOffset) + Settings.subscriptionRows-1)) + emptyArrow = telebot.types.InlineKeyboardButton(" ", callback_data="ignore") + leftButton, rightButton = emptyArrow,emptyArrow + #Check if there are more list + if GetLists(limit=1, offset=int(actualOffset + Settings.subscriptionRows-1)) != False: + rightButton = nextArrow + if actualOffset - Settings.subscriptionRows +2 > 0: + leftButton = previousArrow + if leftButton != rightButton: + markup.row(leftButton, rightButton) + #msg = bot.edit_message_reply_markup(call, msg, reply_markup=markup) + bot.edit_message_text(msg , call.message.chat.id , call.message.message_id, call.id, reply_markup=markup) + return + #Just go away + bot.answer_callback_query(call.id, text="Just go away", show_alert=False, cache_time=999999) + + elif "crlist-" in call.data: + if call.message.reply_to_message != None and call.from_user.id == call.message.reply_to_message.from_user.id: + if user["Status"] == UserStatus.ACTIVE : + splittedString = call.data.split('-') + if len(splittedString) == 2: + if splittedString[1].isdigit(): + listID=int(splittedString[1]) + #Remove subscription + success = DeleteList(listID) + if success: + bot.answer_callback_query(call.id, text="✅ Eliminata", show_alert=False) + else: + bot.answer_callback_query(call.id, text="❌ Si è verificato un errore", show_alert=False) + #Edit message back to list + nc = call + nc.data = "orlist-0" + callback_query(nc) + return + bot.answer_callback_query(call.id, text="Just go away", show_alert=False, cache_time=999999) + + + elif "rlist-" in call.data: + if call.message.reply_to_message != None and call.from_user.id == call.message.reply_to_message.from_user.id: + if user["Status"] == UserStatus.ACTIVE : + #Show next n rows + offset, osub-{offset} + #Safe data checks + splittedString = call.data.split('-') + if len(splittedString) == 2: + if splittedString[1].isdigit(): + listID=int(splittedString[1]) + msg="Sei sicuro di voler eliminare definitivamente la lista \"" + GetListName(listID) + "\"?" + markup = telebot.types.InlineKeyboardMarkup() + markup.row( + telebot.types.InlineKeyboardButton(f"⬅️ No", callback_data=f"orlist-0"), + telebot.types.InlineKeyboardButton(f"🗑 Elimina", callback_data=f"crlist-"+str(listID)) + ) + bot.edit_message_text(msg , call.message.chat.id , call.message.message_id, call.id, reply_markup=markup) + return + elif "cusub-" in call.data: if call.message.reply_to_message != None and call.from_user.id == call.message.reply_to_message.from_user.id: if user["Status"] == UserStatus.ACTIVE : From 745b8c42531582c1f19ea8ddc3ca40740f342dd1 Mon Sep 17 00:00:00 2001 From: Andrea Date: Sat, 3 Nov 2018 18:14:48 +0100 Subject: [PATCH 21/89] fixed code version --- scienzati_bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index a51bcfe..004600e 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -110,7 +110,7 @@ class constResources: /revokelist """ - version = "α0.1.2.I dev" + version = "α0.1.2.0" privs_mex = """privs =-1 -> utente non registrato From dbc8a9dece2408dd8c295ef4a1f60b2e38de477b Mon Sep 17 00:00:00 2001 From: Andrea Date: Sat, 3 Nov 2018 18:32:00 +0100 Subject: [PATCH 22/89] Aggiunto tasto chiudi per i messsaggi - elimina il messaggio del bot per 'pulire' la chat --- scienzati_bot.py | 94 +++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 82 insertions(+), 12 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index 004600e..e80093e 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -110,7 +110,7 @@ class constResources: /revokelist """ - version = "α0.1.2.0" + version = "α0.1.2.1D dev" privs_mex = """privs =-1 -> utente non registrato @@ -725,7 +725,7 @@ def subscribeUserListHandler(message): if AvailableListsToUser(message.from_user.id, limit=1, offset=int(Settings.subscriptionRows-1)) != False: # osub-{n} => offest subscription, needed for pagination, #Teels the offset to set to correctly display the pages - markup.row(telebot.types.InlineKeyboardButton(" ", callback_data="ignore"), telebot.types.InlineKeyboardButton(f"➡️", callback_data=f"osub-"+str(Settings.subscriptionRows-1))) + markup.row(telebot.types.InlineKeyboardButton("❌ Chiudi", callback_data="deleteDis"), telebot.types.InlineKeyboardButton(f"➡️", callback_data=f"osub-"+str(Settings.subscriptionRows-1))) #⬅️ ➡️ msg = bot.reply_to(message, msg, reply_markup=markup) #SubscribeUserToList() @@ -763,7 +763,8 @@ def unsubscribeUserListHandler(message): if SubscribedLists(message.from_user.id, limit=1, offset=int(Settings.subscriptionRows-1)) != False: # osub-{n} => offest subscription, needed for pagination, #Teels the offset to set to correctly display the pages - markup.row(telebot.types.InlineKeyboardButton(" ", callback_data="ignore"), telebot.types.InlineKeyboardButton(f"➡️", callback_data=f"ousub-"+str(Settings.subscriptionRows-1))) + #markup.row(telebot.types.InlineKeyboardButton(" ", callback_data="ignore"), telebot.types.InlineKeyboardButton(f"➡️", callback_data=f"ousub-"+str(Settings.subscriptionRows-1))) + markup.row(telebot.types.InlineKeyboardButton("❌ Chiudi", callback_data="deleteDis"), telebot.types.InlineKeyboardButton(f"➡️", callback_data=f"ousub-"+str(Settings.subscriptionRows-1))) #⬅️ ➡️ msg = bot.reply_to(message, msg, reply_markup=markup) #SubscribeUserToList() @@ -1033,6 +1034,10 @@ def callback_query(call): bot.edit_message_text("Annullato." , call.message.chat.id , call.message.message_id, call.id, reply_markup=markup) else: bot.delete_message(call.message.chat.id , call.message.message_id) + elif "deleteDis" in call.data: + if call.message.reply_to_message != None and call.from_user.id == call.message.reply_to_message.from_user.id: + bot.delete_message(call.message.chat.id , call.message.message_id) + elif "ousub-" in call.data: if call.message.reply_to_message != None and call.from_user.id == call.message.reply_to_message.from_user.id: if user["Status"] == UserStatus.ACTIVE : @@ -1053,11 +1058,33 @@ def callback_query(call): # sub-{id} => subscript to list {id} markup.row(telebot.types.InlineKeyboardButton(ulist["Name"], callback_data="usub-"+str(ulist["ID"]))) #If there are still lists, print the page delimiter + + previousArrow = telebot.types.InlineKeyboardButton(f"⬅️", callback_data=f"ousub-"+str(int(actualOffset) - Settings.subscriptionRows+1)) + nextArrow = telebot.types.InlineKeyboardButton(f"➡️", callback_data=f"ousub-"+str(int(actualOffset) + Settings.subscriptionRows-1)) + emptyArrow = telebot.types.InlineKeyboardButton(" ", callback_data="ignore") + deletePagination = telebot.types.InlineKeyboardButton("❌ Chiudi", callback_data="deleteDis") + leftButton, rightButton = deletePagination,emptyArrow + if int(actualOffset) >=Settings.subscriptionRows -1 or SubscribedLists(call.from_user.id, limit=1, offset=int(actualOffset + Settings.subscriptionRows-1)) != False: + #Check if there are more list + if SubscribedLists(call.from_user.id, limit=1, offset=int(actualOffset + Settings.subscriptionRows-1)) != False: + rightButton = nextArrow + if actualOffset - Settings.subscriptionRows +2 > 0: + leftButton = previousArrow + markup.row(leftButton, rightButton) + bot.edit_message_text("Ecco un elenco delle liste attualmente alle quali sei iscritto al momento:\n(Per rimuovere la sottoscrizione, è sufficiente \"tapparla\" e confermare)" , call.message.chat.id , call.message.message_id, call.id, reply_markup=markup) + return + + + + + + """ if int(actualOffset) >=Settings.subscriptionRows -1 or SubscribedLists(call.from_user.id, limit=1, offset=int(actualOffset + Settings.subscriptionRows-1)) != False: previousArrow = telebot.types.InlineKeyboardButton(f"⬅️", callback_data=f"ousub-"+str(int(actualOffset) - Settings.subscriptionRows+1)) nextArrow = telebot.types.InlineKeyboardButton(f"➡️", callback_data=f"ousub-"+str(int(actualOffset) + Settings.subscriptionRows-1)) emptyArrow = telebot.types.InlineKeyboardButton(" ", callback_data="ignore") - leftButton, rightButton = emptyArrow,emptyArrow + deletePagination = telebot.types.InlineKeyboardButton("❌ Chiudi", callback_data="deleteDis") + leftButton, rightButton = deletePagination,emptyArrow #Check if there are more list if SubscribedLists(call.from_user.id, limit=1, offset=int(actualOffset + Settings.subscriptionRows-1)) != False: rightButton = nextArrow @@ -1068,6 +1095,7 @@ def callback_query(call): #msg = bot.reply_to(message, msg, reply_markup=markup) bot.edit_message_text("Ecco un elenco delle liste attualmente alle quali sei iscritto al momento:\n(Per rimuovere la sottoscrizione, è sufficiente \"tapparla\" e confermare)" , call.message.chat.id , call.message.message_id, call.id, reply_markup=markup) return + """ #Just go away bot.answer_callback_query(call.id, text="Just go away", show_alert=False, cache_time=999999) @@ -1092,19 +1120,39 @@ def callback_query(call): else: for ulist in liste: markup.row(telebot.types.InlineKeyboardButton(ulist["Name"], callback_data="rlist-"+str(ulist["ID"]))) - + + + + + + + previousArrow = telebot.types.InlineKeyboardButton(f"⬅️", callback_data=f"orlist-"+str(int(actualOffset) - Settings.subscriptionRows+1)) + nextArrow = telebot.types.InlineKeyboardButton(f"➡️", callback_data=f"orlist-"+str(int(actualOffset) + Settings.subscriptionRows-1)) + emptyArrow = telebot.types.InlineKeyboardButton(" ", callback_data="ignore") + deletePagination = telebot.types.InlineKeyboardButton("❌ Chiudi", callback_data="deleteDis") + leftButton, rightButton = deletePagination,emptyArrow if int(actualOffset) >=Settings.subscriptionRows -1 or GetLists(limit=1, offset=int(actualOffset + Settings.subscriptionRows-1)) != False: - previousArrow = telebot.types.InlineKeyboardButton(f"⬅️", callback_data=f"orlist-"+str(int(actualOffset) - Settings.subscriptionRows+1)) - nextArrow = telebot.types.InlineKeyboardButton(f"➡️", callback_data=f"orlist-"+str(int(actualOffset) + Settings.subscriptionRows-1)) - emptyArrow = telebot.types.InlineKeyboardButton(" ", callback_data="ignore") - leftButton, rightButton = emptyArrow,emptyArrow #Check if there are more list if GetLists(limit=1, offset=int(actualOffset + Settings.subscriptionRows-1)) != False: rightButton = nextArrow if actualOffset - Settings.subscriptionRows +2 > 0: leftButton = previousArrow - if leftButton != rightButton: - markup.row(leftButton, rightButton) + markup.row(leftButton, rightButton) + + """ + previousArrow = telebot.types.InlineKeyboardButton(f"⬅️", callback_data=f"orlist-"+str(int(actualOffset) - Settings.subscriptionRows+1)) + nextArrow = telebot.types.InlineKeyboardButton(f"➡️", callback_data=f"orlist-"+str(int(actualOffset) + Settings.subscriptionRows-1)) + emptyArrow = telebot.types.InlineKeyboardButton(" ", callback_data="ignore") + deletePagination = telebot.types.InlineKeyboardButton("❌ Chiudi", callback_data="deleteDis") + leftButton, rightButton = deletePagination,emptyArrow + if int(actualOffset) >=Settings.subscriptionRows -1 or GetLists(limit=1, offset=int(actualOffset + Settings.subscriptionRows-1)) != False: + #Check if there are more list + if GetLists(limit=1, offset=int(actualOffset + Settings.subscriptionRows-1)) != False: + rightButton = nextArrow + if actualOffset - Settings.subscriptionRows +2 > 0: + leftButton = previousArrow + markup.row(leftButton, rightButton) + """ #msg = bot.edit_message_reply_markup(call, msg, reply_markup=markup) bot.edit_message_text(msg , call.message.chat.id , call.message.message_id, call.id, reply_markup=markup) return @@ -1209,11 +1257,32 @@ def callback_query(call): markup.row(telebot.types.InlineKeyboardButton(ulist["Name"], callback_data="sub-"+str(ulist["ID"]))) #If there are still lists, print the page delimiter #if len(lists) > Settings.subscriptionRows-1: + previousArrow = telebot.types.InlineKeyboardButton(f"⬅️", callback_data=f"osub-"+str(int(actualOffset) - Settings.subscriptionRows+1)) + nextArrow = telebot.types.InlineKeyboardButton(f"➡️", callback_data=f"osub-"+str(int(actualOffset) + Settings.subscriptionRows-1)) + emptyArrow = telebot.types.InlineKeyboardButton(" ", callback_data="ignore") + deletePagination = telebot.types.InlineKeyboardButton("❌ Chiudi", callback_data="deleteDis") + leftButton, rightButton = deletePagination,emptyArrow + if int(actualOffset) >=Settings.subscriptionRows -1 or AvailableListsToUser(call.from_user.id, limit=1, offset=int( actualOffset + Settings.subscriptionRows-1)) != False: + #Check if there are more list + if AvailableListsToUser(call.from_user.id, limit=1, offset=int(actualOffset + Settings.subscriptionRows-1)) != False: + rightButton = nextArrow + if actualOffset - Settings.subscriptionRows +2 > 0: + leftButton = previousArrow + markup.row(leftButton, rightButton) + + + + + + + + """ if int(actualOffset) >=Settings.subscriptionRows -1 or AvailableListsToUser(call.from_user.id, limit=1, offset=int( actualOffset + Settings.subscriptionRows-1)) != False: previousArrow = telebot.types.InlineKeyboardButton(f"⬅️", callback_data=f"osub-"+str(int(actualOffset) - Settings.subscriptionRows+1)) nextArrow = telebot.types.InlineKeyboardButton(f"➡️", callback_data=f"osub-"+str(int(actualOffset) + Settings.subscriptionRows-1)) emptyArrow = telebot.types.InlineKeyboardButton(" ", callback_data="ignore") - leftButton, rightButton = emptyArrow,emptyArrow + deletePagination = telebot.types.InlineKeyboardButton("❌ Chiudi", callback_data="deleteDis") + leftButton, rightButton = deletePagination,emptyArrow #Check if there are more list if AvailableListsToUser(call.from_user.id, limit=1, offset=int(actualOffset + Settings.subscriptionRows-1)) != False: rightButton = nextArrow @@ -1221,6 +1290,7 @@ def callback_query(call): leftButton = previousArrow if leftButton != rightButton: markup.row(leftButton, rightButton) + """ #msg = bot.reply_to(message, msg, reply_markup=markup) bot.edit_message_reply_markup(call.message.chat.id , call.message.message_id, call.id, reply_markup=markup) return From 56a67613b539a49316d50a6cc5570ef61aa083cf Mon Sep 17 00:00:00 2001 From: Andrea Date: Sat, 3 Nov 2018 18:33:12 +0100 Subject: [PATCH 23/89] Cleanup --- scienzati_bot.py | 70 ------------------------------------------------ 1 file changed, 70 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index e80093e..4fe7b35 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -596,13 +596,10 @@ def start_user_registration(message): else: msg = bot.reply_to(message, "Errore nella creazione del record") - # this is to define step-by-step subscription #bot.register_next_step_handler(msg, first_registration) - - ### Aggioramento/ impostaizone bio @bot.message_handler(commands=['bio', 'setbio']) def setBio(message): @@ -994,7 +991,6 @@ def genericMessageHandler(message): elif message.chat.id == Settings.OTGroup: #Increment OT group messages cunt IncrOTGroupMessagesCount(message.from_user.id) - dbConnection.commit() @@ -1073,29 +1069,6 @@ def callback_query(call): markup.row(leftButton, rightButton) bot.edit_message_text("Ecco un elenco delle liste attualmente alle quali sei iscritto al momento:\n(Per rimuovere la sottoscrizione, è sufficiente \"tapparla\" e confermare)" , call.message.chat.id , call.message.message_id, call.id, reply_markup=markup) return - - - - - - """ - if int(actualOffset) >=Settings.subscriptionRows -1 or SubscribedLists(call.from_user.id, limit=1, offset=int(actualOffset + Settings.subscriptionRows-1)) != False: - previousArrow = telebot.types.InlineKeyboardButton(f"⬅️", callback_data=f"ousub-"+str(int(actualOffset) - Settings.subscriptionRows+1)) - nextArrow = telebot.types.InlineKeyboardButton(f"➡️", callback_data=f"ousub-"+str(int(actualOffset) + Settings.subscriptionRows-1)) - emptyArrow = telebot.types.InlineKeyboardButton(" ", callback_data="ignore") - deletePagination = telebot.types.InlineKeyboardButton("❌ Chiudi", callback_data="deleteDis") - leftButton, rightButton = deletePagination,emptyArrow - #Check if there are more list - if SubscribedLists(call.from_user.id, limit=1, offset=int(actualOffset + Settings.subscriptionRows-1)) != False: - rightButton = nextArrow - if actualOffset - Settings.subscriptionRows +2 > 0: - leftButton = previousArrow - if leftButton != rightButton: - markup.row(leftButton, rightButton) - #msg = bot.reply_to(message, msg, reply_markup=markup) - bot.edit_message_text("Ecco un elenco delle liste attualmente alle quali sei iscritto al momento:\n(Per rimuovere la sottoscrizione, è sufficiente \"tapparla\" e confermare)" , call.message.chat.id , call.message.message_id, call.id, reply_markup=markup) - return - """ #Just go away bot.answer_callback_query(call.id, text="Just go away", show_alert=False, cache_time=999999) @@ -1120,26 +1093,6 @@ def callback_query(call): else: for ulist in liste: markup.row(telebot.types.InlineKeyboardButton(ulist["Name"], callback_data="rlist-"+str(ulist["ID"]))) - - - - - - - previousArrow = telebot.types.InlineKeyboardButton(f"⬅️", callback_data=f"orlist-"+str(int(actualOffset) - Settings.subscriptionRows+1)) - nextArrow = telebot.types.InlineKeyboardButton(f"➡️", callback_data=f"orlist-"+str(int(actualOffset) + Settings.subscriptionRows-1)) - emptyArrow = telebot.types.InlineKeyboardButton(" ", callback_data="ignore") - deletePagination = telebot.types.InlineKeyboardButton("❌ Chiudi", callback_data="deleteDis") - leftButton, rightButton = deletePagination,emptyArrow - if int(actualOffset) >=Settings.subscriptionRows -1 or GetLists(limit=1, offset=int(actualOffset + Settings.subscriptionRows-1)) != False: - #Check if there are more list - if GetLists(limit=1, offset=int(actualOffset + Settings.subscriptionRows-1)) != False: - rightButton = nextArrow - if actualOffset - Settings.subscriptionRows +2 > 0: - leftButton = previousArrow - markup.row(leftButton, rightButton) - - """ previousArrow = telebot.types.InlineKeyboardButton(f"⬅️", callback_data=f"orlist-"+str(int(actualOffset) - Settings.subscriptionRows+1)) nextArrow = telebot.types.InlineKeyboardButton(f"➡️", callback_data=f"orlist-"+str(int(actualOffset) + Settings.subscriptionRows-1)) emptyArrow = telebot.types.InlineKeyboardButton(" ", callback_data="ignore") @@ -1152,7 +1105,6 @@ def callback_query(call): if actualOffset - Settings.subscriptionRows +2 > 0: leftButton = previousArrow markup.row(leftButton, rightButton) - """ #msg = bot.edit_message_reply_markup(call, msg, reply_markup=markup) bot.edit_message_text(msg , call.message.chat.id , call.message.message_id, call.id, reply_markup=markup) return @@ -1269,28 +1221,6 @@ def callback_query(call): if actualOffset - Settings.subscriptionRows +2 > 0: leftButton = previousArrow markup.row(leftButton, rightButton) - - - - - - - - """ - if int(actualOffset) >=Settings.subscriptionRows -1 or AvailableListsToUser(call.from_user.id, limit=1, offset=int( actualOffset + Settings.subscriptionRows-1)) != False: - previousArrow = telebot.types.InlineKeyboardButton(f"⬅️", callback_data=f"osub-"+str(int(actualOffset) - Settings.subscriptionRows+1)) - nextArrow = telebot.types.InlineKeyboardButton(f"➡️", callback_data=f"osub-"+str(int(actualOffset) + Settings.subscriptionRows-1)) - emptyArrow = telebot.types.InlineKeyboardButton(" ", callback_data="ignore") - deletePagination = telebot.types.InlineKeyboardButton("❌ Chiudi", callback_data="deleteDis") - leftButton, rightButton = deletePagination,emptyArrow - #Check if there are more list - if AvailableListsToUser(call.from_user.id, limit=1, offset=int(actualOffset + Settings.subscriptionRows-1)) != False: - rightButton = nextArrow - if actualOffset - Settings.subscriptionRows +2 > 0: - leftButton = previousArrow - if leftButton != rightButton: - markup.row(leftButton, rightButton) - """ #msg = bot.reply_to(message, msg, reply_markup=markup) bot.edit_message_reply_markup(call.message.chat.id , call.message.message_id, call.id, reply_markup=markup) return From 7c884b51c60cc35fa5bb174376aa8373428328f2 Mon Sep 17 00:00:00 2001 From: Andrea Date: Sat, 3 Nov 2018 18:47:16 +0100 Subject: [PATCH 24/89] Biography autoclean --- scienzati_bot.py | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index 4fe7b35..aefef52 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -110,7 +110,7 @@ class constResources: /revokelist """ - version = "α0.1.2.1D dev" + version = "α0.1.2.1" privs_mex = """privs =-1 -> utente non registrato @@ -927,12 +927,23 @@ def genericMessageHandler(message): dbC = dbConnection.cursor() res = dbC.execute('UPDATE Users SET Status=?, Biography=? WHERE ID = ?', (UserStatus.ACTIVE, message.text, message.from_user.id,) ) msg = bot.reply_to(message, "✅ Biografia impostata con successo!") + bot.delete_message(message.chat.id , message.reply_to_message.message_id) + #Tries to force the user to reply to the message #TODO: Not sure about the order - needs to be checked elif (message.chat.type == "group" or message.chat.type == "supergroup") and message.reply_to_message != None and message.reply_to_message.from_user.id == botInfo.id: dbC = dbConnection.cursor() res = dbC.execute('UPDATE Users SET Status=?, Biography=? WHERE ID = ?', (UserStatus.ACTIVE, message.text, message.from_user.id,) ) msg = bot.reply_to(message, "✅ Biografia impostata con successo!") + bot.delete_message(message.chat.id , message.reply_to_message.message_id) + + + + + + + + #Check for list elif user["Status"] == UserStatus.WAITING_FOR_LIST: #User is creating a new list @@ -1014,7 +1025,9 @@ def callback_query(call): success = abortNewBio(call.from_user.id) if success: markup = telebot.types.InlineKeyboardMarkup() - bot.edit_message_text("Annullato." , call.message.chat.id , call.message.message_id, call.id, reply_markup=markup) + bot.answer_callback_query(call.id, text="❌ Annullato", show_alert=True) + bot.delete_message(call.message.chat.id , call.message.message_id) + #bot.edit_message_text("Annullato." , call.message.chat.id , call.message.message_id, call.id, reply_markup=markup) else: bot.delete_message(call.message.chat.id , call.message.message_id) #Check if is to abort list creation @@ -1022,12 +1035,13 @@ def callback_query(call): #Check if the guy who pressed is the same who asked to set the bio if call.message.reply_to_message != None and call.from_user.id == call.message.reply_to_message.from_user.id: #Check that the user needs to set the bio - if user["Status"] == UserStatus.WAITING_FOR_LIST : success = abortNewList(call.from_user.id) if success: markup = telebot.types.InlineKeyboardMarkup() - bot.edit_message_text("Annullato." , call.message.chat.id , call.message.message_id, call.id, reply_markup=markup) + bot.answer_callback_query(call.id, text="❌ Annullato", show_alert=True) + bot.delete_message(call.message.chat.id , call.message.message_id) + #bot.edit_message_text("Annullato." , call.message.chat.id , call.message.message_id, call.id, reply_markup=markup) else: bot.delete_message(call.message.chat.id , call.message.message_id) elif "deleteDis" in call.data: From 0404e2c1283f867b113834456d60d63469eb3408 Mon Sep 17 00:00:00 2001 From: Andrea Date: Sat, 3 Nov 2018 19:20:00 +0100 Subject: [PATCH 25/89] Added privilege message --- scienzati_bot.py | 71 ++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 57 insertions(+), 14 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index aefef52..8e9b13a 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -110,16 +110,7 @@ class constResources: /revokelist """ - version = "α0.1.2.1" - - - privs_mex = """privs =-1 -> utente non registrato - = 0 -> utente normale - = 1 -> utente abituale - = 2 -> utente assiduo - = 3 -> utente storico (puo' inoltrare al canale, puo' creare nuove liste) - = 4 -> amministratore - = 5 -> fondatore""" + version = "α0.1.2.2B dev" gdpr_message = "Raccogliamo il numero di messaggi, nickname, ID e ultima volta che l'utente ha scritto. Per richiedere l'eliminazione dei propri dati contattare un amministratore ed uscire dal gruppo" @@ -551,20 +542,72 @@ def IsUserSuperadmin(userNick): # This is the function called when the bot is started or the help commands are sent @bot.message_handler(commands=['start', 'help']) def send_welcome(message): - bot.reply_to(message, constResources.intro_mex) + markup = telebot.types.InlineKeyboardMarkup() + markup.row(telebot.types.InlineKeyboardButton("❌ Chiudi", callback_data="deleteDis")) + bot.reply_to(message, constResources.intro_mex, reply_markup=markup) @bot.message_handler(commands=['adminhelp']) def send_admhelp(message): - bot.reply_to(message, constResources.admin_help) + markup = telebot.types.InlineKeyboardMarkup() + markup.row(telebot.types.InlineKeyboardButton("❌ Chiudi", callback_data="deleteDis")) + bot.reply_to(message, constResources.admin_help, reply_markup=markup) @bot.message_handler(commands=['v', 'version']) def send_version(message): - bot.reply_to(message, "V: " + constResources.version) + markup = telebot.types.InlineKeyboardMarkup() + markup.row(telebot.types.InlineKeyboardButton("❌ Chiudi", callback_data="deleteDis")) + bot.reply_to(message, "V: " + constResources.version, reply_markup=markup) # Replies with the static message before @bot.message_handler(commands=['privs']) def send_privs(message): - bot.reply_to(message, constResources.privs_mex) + markup = telebot.types.InlineKeyboardMarkup() + userPermission = GetUserPermissionsValue(message.from_user.id) + msg = "⚙️ Ranks\nSupreme admin: " + if IsUserSuperadmin(message.from_user.username): + msg = msg + "✅ Sì" + else: + msg = msg + "❌ Nope" + msg = msg + "\n" + + msg = msg + "Admin: " + if UserPermission.IsAdmin(userPermission): + msg = msg + "✅ Sì" + else: + msg = msg + "❌ Nope" + msg = msg + "\n" + + msg = msg + "\n📝Privileges\n" + msg = msg + "Gestione liste: " + if UserPermission.ListPermission(userPermission): + msg = msg + "✅ Sì" + else: + msg = msg + "❌ Nope" + msg = msg + "\n" + + msg = msg + "Aggiunta amministratori: " + if UserPermission.CanAddAdmin(userPermission): + msg = msg + "✅ Sì" + else: + msg = msg + "❌ Nope" + msg = msg + "\n" + + msg = msg + "Eliminazione amministratori: " + if UserPermission.CanRemoveAdmin(userPermission): + msg = msg + "✅ Sì" + else: + msg = msg + "❌ Nope" + msg = msg + "\n" + + msg = msg + "Inoltro al canale: " + if UserPermission.CanForwardToChannel(userPermission): + msg = msg + "✅ Sì" + else: + msg = msg + "❌ Nope" + + + markup.row(telebot.types.InlineKeyboardButton("❌ Chiudi", callback_data="deleteDis")) + bot.reply_to(message, msg, reply_markup=markup) # Replies with the static message before @bot.message_handler(commands=['gdpr']) From 4db86eddd1a5c1c0b41c94f6069d45f1e17cd68f Mon Sep 17 00:00:00 2001 From: Andrea Date: Sat, 3 Nov 2018 19:46:11 +0100 Subject: [PATCH 26/89] Added user selection on privilege message --- scienzati_bot.py | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index 8e9b13a..6dce8fe 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -110,7 +110,7 @@ class constResources: /revokelist """ - version = "α0.1.2.2B dev" + version = "α0.1.2.2E dev" gdpr_message = "Raccogliamo il numero di messaggi, nickname, ID e ultima volta che l'utente ha scritto. Per richiedere l'eliminazione dei propri dati contattare un amministratore ed uscire dal gruppo" @@ -513,6 +513,7 @@ def getUsersIdLike(userNick): return False def getUserId(userNick): + userNick = userNick.replace('@','').lower() dbC = dbConnection.cursor() dbC.execute('SELECT `ID` FROM Users WHERE `Nickname`= ?;', (userNick,)) res = dbC.fetchone() @@ -561,9 +562,16 @@ def send_version(message): # Replies with the static message before @bot.message_handler(commands=['privs']) def send_privs(message): + args = message.text.split(' ') + userid = message.from_user.id + if len(args) == 2: + reqUserid = getUserId(args[1]) + if reqUserid != False: + userid = reqUserid + + userPermission = GetUserPermissionsValue(userid) markup = telebot.types.InlineKeyboardMarkup() - userPermission = GetUserPermissionsValue(message.from_user.id) - msg = "⚙️ Ranks\nSupreme admin: " + msg = "Ecco i privilegi dell'utente @" + GetUserNickname(userid) + ":\n ⚙️ Ranks\nSupreme admin: " if IsUserSuperadmin(message.from_user.username): msg = msg + "✅ Sì" else: @@ -889,7 +897,7 @@ def grantListCreationPermissionHandler(message): if IsUserSuperadmin(message.from_user.username) or UserPermission.IsAdmin(userPermission): args = message.text.split(' ') if len(args) == 2: - newUserNickname = args[1].replace('@','').lower() + newUserNickname = userNickname newUserId = getUserId(newUserNickname) if newUserId == False: #It looks like there's no user called this way From c0aa5d7c15466c3390c21763856c2e7dbc5a0b96 Mon Sep 17 00:00:00 2001 From: Andrea Date: Sat, 3 Nov 2018 19:46:38 +0100 Subject: [PATCH 27/89] Added message delation on list listing function --- scienzati_bot.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index 6dce8fe..b97ad9a 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -741,13 +741,15 @@ def deleteListHandler(message): #Lista delle liste @bot.message_handler(commands=['lists', 'liste']) def showLists(message): + markup = telebot.types.InlineKeyboardMarkup() + markup.row(telebot.types.InlineKeyboardButton("❌ Chiudi", callback_data="deleteDis")) liste = GetListsNames(limit=None) msg = "Al momento esistono " + str(len(liste))+ " liste; eccole qui:\n" for list in liste: msg = msg + list[0] + "\n" if len(liste) == 0: msg = "Al momento non sono presenti liste" - bot.reply_to(message, msg) + bot.reply_to(message, msg, reply_markup=markup) @bot.message_handler(commands=['subscribe', 'join', 'registrati', 'partecipa', 'aderisci', 'sottoscrivi']) def subscribeUserListHandler(message): From 1528965efea1ee386fb36d2e18aa60c4384a1d64 Mon Sep 17 00:00:00 2001 From: Andrea Date: Sat, 3 Nov 2018 19:58:53 +0100 Subject: [PATCH 28/89] Added close message and provided message on user not found --- scienzati_bot.py | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index b97ad9a..14650a9 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -110,7 +110,7 @@ class constResources: /revokelist """ - version = "α0.1.2.2E dev" + version = "α0.1.2.2G dev" gdpr_message = "Raccogliamo il numero di messaggi, nickname, ID e ultima volta che l'utente ha scritto. Per richiedere l'eliminazione dei propri dati contattare un amministratore ed uscire dal gruppo" @@ -564,15 +564,26 @@ def send_version(message): def send_privs(message): args = message.text.split(' ') userid = message.from_user.id + markup = telebot.types.InlineKeyboardMarkup() + markup.row(telebot.types.InlineKeyboardButton("❌ Chiudi", callback_data="deleteDis")) + if len(args) == 2: reqUserid = getUserId(args[1]) if reqUserid != False: userid = reqUserid + else: + bot.reply_to(message, "L'utente inserito non è stato trovato in database", reply_markup=markup) + elif len(args) > 2: + bot.reply_to(message, "Sono stati inseriti troppi parametri", reply_markup=markup) + + if GetUser(userid) == False: + bot.reply_to(message, "Non sei presente in database, perciò non è possibile conoscere il tuo livello di privilegi.", reply_markup=markup) + return userPermission = GetUserPermissionsValue(userid) markup = telebot.types.InlineKeyboardMarkup() msg = "Ecco i privilegi dell'utente @" + GetUserNickname(userid) + ":\n ⚙️ Ranks\nSupreme admin: " - if IsUserSuperadmin(message.from_user.username): + if IsUserSuperadmin(GetUserNickname(userid)): msg = msg + "✅ Sì" else: msg = msg + "❌ Nope" @@ -614,7 +625,6 @@ def send_privs(message): msg = msg + "❌ Nope" - markup.row(telebot.types.InlineKeyboardButton("❌ Chiudi", callback_data="deleteDis")) bot.reply_to(message, msg, reply_markup=markup) # Replies with the static message before From 029e45fa48c9c710ffafb870bb84f9412bc6650f Mon Sep 17 00:00:00 2001 From: Andrea Date: Sat, 3 Nov 2018 20:00:15 +0100 Subject: [PATCH 29/89] Added close button on ping reponse --- scienzati_bot.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index 14650a9..f23fef3 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -967,7 +967,10 @@ def revokeListCreationPermissionHandler(message): @bot.message_handler(commands=['ping']) def pingHandler(message): if IsUserSuperadmin(message.from_user.username) or (GetUser(message.from_user.id) != False and UserPermission.IsAdmin(GetUserPermissionsValue(message.from_user.id))): - bot.reply_to(message, "🏓 Pong!") + + markup = telebot.types.InlineKeyboardMarkup() + markup.row(telebot.types.InlineKeyboardButton("❌ Chiudi", callback_data="deleteDis")) + bot.reply_to(message, "🏓 Pong!", reply_markup=markup ) @bot.message_handler(commands=['die', 'crash']) def pingHandler(message): From ddc3581bfdb2106524107ca85bf4a45875841c08 Mon Sep 17 00:00:00 2001 From: Andrea Date: Sat, 3 Nov 2018 20:01:56 +0100 Subject: [PATCH 30/89] Fixed help message --- scienzati_bot.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index f23fef3..1edb218 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -92,10 +92,9 @@ class constResources: Sei confuso? Questo è il bot del gruppo @scienza e permette di usufruire di queste funzioni: /iscriviti per iscriverti al database di utenti e per partecipare alle liste sugli interessi -/aderisci per iscriverti ad una lista, puoi usare anche: /partecipa e /sottoscrivi +/aderisci per iscriverti ad una lista, puoi usare anche: /partecipa, /registrati e /sottoscrivi /bio per scrivere qualcosa su di te /liste per scoprire le liste già presenti -/registrati per registrarti in una lista /gdpr consulta le norme sul GDPR /privs elenca i privilegi utente /disiscrivi per cancellarti da una lista alla quale hai aderito, puoi usare pure: /esci, /rimuovi, /iscrizioni e /aderenze""" From f77b7ed560ddfb0c0d8d0fcd87452e9f5f835ecd Mon Sep 17 00:00:00 2001 From: Andrea Date: Sat, 3 Nov 2018 20:52:36 +0100 Subject: [PATCH 31/89] Fixed missing close message on privs --- scienzati_bot.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index 1edb218..6dc6dd3 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -109,7 +109,7 @@ class constResources: /revokelist """ - version = "α0.1.2.2G dev" + version = "α0.1.2.2K dev" gdpr_message = "Raccogliamo il numero di messaggi, nickname, ID e ultima volta che l'utente ha scritto. Per richiedere l'eliminazione dei propri dati contattare un amministratore ed uscire dal gruppo" @@ -580,7 +580,6 @@ def send_privs(message): return userPermission = GetUserPermissionsValue(userid) - markup = telebot.types.InlineKeyboardMarkup() msg = "Ecco i privilegi dell'utente @" + GetUserNickname(userid) + ":\n ⚙️ Ranks\nSupreme admin: " if IsUserSuperadmin(GetUserNickname(userid)): msg = msg + "✅ Sì" From 52c4c6d4c365765f8c5adbec318f9524615290e8 Mon Sep 17 00:00:00 2001 From: Andrea Date: Sat, 3 Nov 2018 21:30:14 +0100 Subject: [PATCH 32/89] Bugfixes + admins can delete any message --- scienzati_bot.py | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index 6dc6dd3..6275a2a 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -907,7 +907,7 @@ def grantListCreationPermissionHandler(message): if IsUserSuperadmin(message.from_user.username) or UserPermission.IsAdmin(userPermission): args = message.text.split(' ') if len(args) == 2: - newUserNickname = userNickname + newUserNickname = args[1] newUserId = getUserId(newUserNickname) if newUserId == False: #It looks like there's no user called this way @@ -971,7 +971,7 @@ def pingHandler(message): bot.reply_to(message, "🏓 Pong!", reply_markup=markup ) @bot.message_handler(commands=['die', 'crash']) -def pingHandler(message): +def dieHandler(message): if IsUserSuperadmin(message.from_user.username) or (GetUser(message.from_user.id) != False and UserPermission.IsAdmin(GetUserPermissionsValue(message.from_user.id))): bot.reply_to(message, "Autodestruction sequence initialized... \n💥 Poof! ✨") sys.exit(10) @@ -1014,10 +1014,10 @@ def genericMessageHandler(message): #TODO check for ASCII ONLY (RegEx?), replace spaces with underscores, listName = message.text.lower() p = re.compile(r'[a-z0-9_\-]+', re.IGNORECASE) - if not p.match(listName): - bot.reply_to(message, "Qualcosa è andato storto :c\n Il nome sembra contenre caratteri non permessi. Sono permesse solo lettere, numeri, underscores(_) e trattini") - return if message.chat.type == "private": + if not p.match(listName): + bot.reply_to(message, "Qualcosa è andato storto :c\n Il nome sembra contenre caratteri non permessi. Sono permesse solo lettere, numeri, underscores(_) e trattini") + return success = CreateNewList(listName) if success: msg = bot.reply_to(message, "Lista creata con successo!") @@ -1025,8 +1025,10 @@ def genericMessageHandler(message): msg = bot.reply_to(message, "Qualcosa è andato storto :c\n Sei sicuro che non esista già una lista con lo stesso nome?") #Tries to force the user to reply to the message - #TODO: Not sure about the order - needs to be checked elif (message.chat.type == "group" or message.chat.type == "supergroup") and message.reply_to_message != None and message.reply_to_message.from_user.id == botInfo.id: + if not p.match(listName): + bot.reply_to(message, "Qualcosa è andato storto :c\n Il nome sembra contenre caratteri non permessi. Sono permesse solo lettere, numeri, underscores(_) e trattini") + return success = CreateNewList(listName) if success: msg = bot.reply_to(message, "Lista creata con successo!") @@ -1109,7 +1111,8 @@ def callback_query(call): else: bot.delete_message(call.message.chat.id , call.message.message_id) elif "deleteDis" in call.data: - if call.message.reply_to_message != None and call.from_user.id == call.message.reply_to_message.from_user.id: + userPerm = GetUserPermissionsValue(call.from_user.id) + if (IsUserSuperadmin(call.from_user.username) or UserPermission.IsAdmin(userPerm)) or call.message.reply_to_message != None and call.from_user.id == call.message.reply_to_message.from_user.id: bot.delete_message(call.message.chat.id , call.message.message_id) elif "ousub-" in call.data: From 2001c5812f4f371c5425318a833a433f49678fa6 Mon Sep 17 00:00:00 2001 From: Andrea Date: Sat, 3 Nov 2018 21:31:56 +0100 Subject: [PATCH 33/89] Updated version number to correct one --- scienzati_bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index 6275a2a..e73cbb1 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -109,7 +109,7 @@ class constResources: /revokelist """ - version = "α0.1.2.2K dev" + version = "α0.1.2.3" gdpr_message = "Raccogliamo il numero di messaggi, nickname, ID e ultima volta che l'utente ha scritto. Per richiedere l'eliminazione dei propri dati contattare un amministratore ed uscire dal gruppo" From d2fcb62e0c581a5bff7bf33cfbb7cdd7182fa1b9 Mon Sep 17 00:00:00 2001 From: Andrea Date: Sat, 3 Nov 2018 21:35:30 +0100 Subject: [PATCH 34/89] Added close on deletion list --- scienzati_bot.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index e73cbb1..987d76f 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -734,11 +734,13 @@ def deleteListHandler(message): if liste == False:#TODO test msg = "Al momento non è presente nessuna lista.\nSi prega di riprovare in seguito." else: + for ulist in liste: markup.row(telebot.types.InlineKeyboardButton(ulist["Name"], callback_data="rlist-"+str(ulist["ID"]))) - + rightbutton = telebot.types.InlineKeyboardButton(" ", callback_data="ignore") if AvailableListsToUser(message.from_user.id, limit=1, offset=int(Settings.subscriptionRows-1)) != False: - markup.row(telebot.types.InlineKeyboardButton(" ", callback_data="ignore"), telebot.types.InlineKeyboardButton(f"➡️", callback_data=f"orlist-"+str(Settings.subscriptionRows-1))) + rightbutton = telebot.types.InlineKeyboardButton(f"➡️", callback_data=f"orlist-"+str(Settings.subscriptionRows-1)) + markup.row(telebot.types.InlineKeyboardButton("❌ Chiudi", callback_data="deleteDis"), rightbutton) #⬅️ ➡️ msg = bot.reply_to(message, msg, reply_markup=markup) #SubscribeUserToList() From 290c2cbe6e7de0d9d2fb1a744c0e09d3c71420a6 Mon Sep 17 00:00:00 2001 From: Andrea Date: Sat, 3 Nov 2018 21:40:11 +0100 Subject: [PATCH 35/89] Added bot delete functio nad improves nickname saving function --- scienzati_bot.py | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index 987d76f..d90439b 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -471,7 +471,7 @@ def DeleteList(listID): def UpdateNickname(userID, nickname): dbC = dbConnection.cursor() - res = dbC.execute('UPDATE Users SET Nickname=? WHERE ID = ?', (nickname, userID, )) + res = dbC.execute('UPDATE Users SET Nickname=? WHERE ID = ?', (nickname.lower().replace('@',''), userID, )) if res: CommitDb() return True @@ -748,6 +748,14 @@ def deleteListHandler(message): else: msg = bot.reply_to(message, "Error 403 - ❌ Unauthorized") +@bot.message_handler(commands=['del', 'delete']) +def deleteBotMessage(message): + userPerm = GetUserPermissionsValue(message.from_user.id) + if IsUserSuperadmin(message.from_user.username) or UserPermission.IsAdmin(userPerm): + if message.reply_to_message != None and message.reply_to_message.from_user.id == botInfo.id: + bot.delete_message(message.chat.id , message.message_id) + + #Lista delle liste @bot.message_handler(commands=['lists', 'liste']) def showLists(message): @@ -1003,13 +1011,6 @@ def genericMessageHandler(message): msg = bot.reply_to(message, "✅ Biografia impostata con successo!") bot.delete_message(message.chat.id , message.reply_to_message.message_id) - - - - - - - #Check for list elif user["Status"] == UserStatus.WAITING_FOR_LIST: #User is creating a new list From 1c5f15ad24448068aa6ce8f9b5697cdc66358a62 Mon Sep 17 00:00:00 2001 From: Andrea Date: Sat, 3 Nov 2018 21:40:30 +0100 Subject: [PATCH 36/89] Version bumo --- scienzati_bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index d90439b..8839ef3 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -109,7 +109,7 @@ class constResources: /revokelist """ - version = "α0.1.2.3" + version = "α0.1.2.4" gdpr_message = "Raccogliamo il numero di messaggi, nickname, ID e ultima volta che l'utente ha scritto. Per richiedere l'eliminazione dei propri dati contattare un amministratore ed uscire dal gruppo" From 47df52c9166dfa7aba6bf73dab08144ffe081a5b Mon Sep 17 00:00:00 2001 From: Andrea Date: Sat, 3 Nov 2018 21:45:05 +0100 Subject: [PATCH 37/89] /del function bugfix --- scienzati_bot.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index 8839ef3..75fa239 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -102,6 +102,7 @@ class constResources: admin_help = """Comandi admin... blabla /nuovalista /rimuovilista + /del delete bot message === CA$TA THINGS === /setadmin /unsetadmin @@ -109,7 +110,7 @@ class constResources: /revokelist """ - version = "α0.1.2.4" + version = "α0.1.2.5" gdpr_message = "Raccogliamo il numero di messaggi, nickname, ID e ultima volta che l'utente ha scritto. Per richiedere l'eliminazione dei propri dati contattare un amministratore ed uscire dal gruppo" @@ -751,9 +752,9 @@ def deleteListHandler(message): @bot.message_handler(commands=['del', 'delete']) def deleteBotMessage(message): userPerm = GetUserPermissionsValue(message.from_user.id) - if IsUserSuperadmin(message.from_user.username) or UserPermission.IsAdmin(userPerm): + if userPerm != False and (IsUserSuperadmin(message.from_user.username) or UserPermission.IsAdmin(userPerm)): if message.reply_to_message != None and message.reply_to_message.from_user.id == botInfo.id: - bot.delete_message(message.chat.id , message.message_id) + bot.delete_message(message.chat.id , message.reply_to_message.message_id) #Lista delle liste From 16963e5ae47b8b92ffaf50de993d8ef8edd9753b Mon Sep 17 00:00:00 2001 From: Andrea Date: Sat, 3 Nov 2018 22:05:51 +0100 Subject: [PATCH 38/89] permissions text obtained by a function and added permissions to inline query --- scienzati_bot.py | 104 ++++++++++++++++++++++++++--------------------- 1 file changed, 57 insertions(+), 47 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index 75fa239..03899b6 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -535,6 +535,51 @@ def IsUserSuperadmin(userNick): return userNick.lower() in Settings.SupremeAdmins +def getUserPermissionText(userid): + userPermission = GetUserPermissionsValue(userid) + msg = "Ecco i privilegi dell'utente @" + GetUserNickname(userid) + ":\n ⚙️ Ranks\nSupreme admin: " + if IsUserSuperadmin(GetUserNickname(userid)): + msg = msg + "✅ Sì" + else: + msg = msg + "❌ Nope" + msg = msg + "\n" + + msg = msg + "Admin: " + if UserPermission.IsAdmin(userPermission): + msg = msg + "✅ Sì" + else: + msg = msg + "❌ Nope" + msg = msg + "\n" + + msg = msg + "\n📝Privileges\n" + msg = msg + "Gestione liste: " + if UserPermission.ListPermission(userPermission): + msg = msg + "✅ Sì" + else: + msg = msg + "❌ Nope" + msg = msg + "\n" + + msg = msg + "Aggiunta amministratori: " + if UserPermission.CanAddAdmin(userPermission): + msg = msg + "✅ Sì" + else: + msg = msg + "❌ Nope" + msg = msg + "\n" + + msg = msg + "Eliminazione amministratori: " + if UserPermission.CanRemoveAdmin(userPermission): + msg = msg + "✅ Sì" + else: + msg = msg + "❌ Nope" + msg = msg + "\n" + + msg = msg + "Inoltro al canale: " + if UserPermission.CanForwardToChannel(userPermission): + msg = msg + "✅ Sì" + else: + msg = msg + "❌ Nope" + return msg + ### # Bot functions ### @@ -579,52 +624,8 @@ def send_privs(message): if GetUser(userid) == False: bot.reply_to(message, "Non sei presente in database, perciò non è possibile conoscere il tuo livello di privilegi.", reply_markup=markup) return - - userPermission = GetUserPermissionsValue(userid) - msg = "Ecco i privilegi dell'utente @" + GetUserNickname(userid) + ":\n ⚙️ Ranks\nSupreme admin: " - if IsUserSuperadmin(GetUserNickname(userid)): - msg = msg + "✅ Sì" - else: - msg = msg + "❌ Nope" - msg = msg + "\n" - - msg = msg + "Admin: " - if UserPermission.IsAdmin(userPermission): - msg = msg + "✅ Sì" - else: - msg = msg + "❌ Nope" - msg = msg + "\n" - - msg = msg + "\n📝Privileges\n" - msg = msg + "Gestione liste: " - if UserPermission.ListPermission(userPermission): - msg = msg + "✅ Sì" - else: - msg = msg + "❌ Nope" - msg = msg + "\n" - - msg = msg + "Aggiunta amministratori: " - if UserPermission.CanAddAdmin(userPermission): - msg = msg + "✅ Sì" - else: - msg = msg + "❌ Nope" - msg = msg + "\n" - - msg = msg + "Eliminazione amministratori: " - if UserPermission.CanRemoveAdmin(userPermission): - msg = msg + "✅ Sì" - else: - msg = msg + "❌ Nope" - msg = msg + "\n" - - msg = msg + "Inoltro al canale: " - if UserPermission.CanForwardToChannel(userPermission): - msg = msg + "✅ Sì" - else: - msg = msg + "❌ Nope" - - bot.reply_to(message, msg, reply_markup=markup) + bot.reply_to(message, getUserPermissionText(userid), reply_markup=markup) # Replies with the static message before @bot.message_handler(commands=['gdpr']) @@ -1340,9 +1341,18 @@ def getUserBioInlineQuery(inline_query): usersIDs = getUsersIdLike(user) for userid in usersIDs: userNick = GetUserNickname(userid[0]) + userBio = GetUserBio(userid[0]) + if userBio != None: + responses.append( + telebot.types.InlineQueryResultArticle(len(responses)+1, userNick[0].upper() + userNick[1:] + "'s Bio: " + userBio, + telebot.types.InputTextMessageContent(userNick[0].upper() + userNick[1:] + "'s Biography is \"" +userBio + "\"")) + ) responses.append( - telebot.types.InlineQueryResultArticle(len(responses)+1, userNick[0].upper() + userNick[1:] + "'s Bio: " + GetUserBio(userid[0]), telebot.types.InputTextMessageContent(userNick[0].upper() + userNick[1:] + "'s Biography is \"" +GetUserBio(userid[0]) + "\"")) - ) + telebot.types.InlineQueryResultArticle(len(responses)+1, userNick[0].upper() + userNick[1:] + "'s permissions", + telebot.types.InputTextMessageContent(getUserPermissionText(userid[0]))) + ) + + bot.answer_inline_query(inline_query.id, responses) # Query message is text ### From ae621de2ba6139e72b8c09417f6f2b51026f0ac7 Mon Sep 17 00:00:00 2001 From: Andrea Date: Sat, 3 Nov 2018 22:06:14 +0100 Subject: [PATCH 39/89] bump version --- scienzati_bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index 03899b6..e0fcb23 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -110,7 +110,7 @@ class constResources: /revokelist """ - version = "α0.1.2.5" + version = "α0.1.2.6" gdpr_message = "Raccogliamo il numero di messaggi, nickname, ID e ultima volta che l'utente ha scritto. Per richiedere l'eliminazione dei propri dati contattare un amministratore ed uscire dal gruppo" From ce42c0008d8fc98c924873064f0de09c8ab33d64 Mon Sep 17 00:00:00 2001 From: Andrea Date: Sat, 3 Nov 2018 22:18:15 +0100 Subject: [PATCH 40/89] usage of str.startswith istead of checking if str is contained --- scienzati_bot.py | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index e0fcb23..b02f28a 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -5,6 +5,7 @@ import random import re import sys +import str #Settings class @@ -1088,7 +1089,7 @@ def callback_query(call): user = GetUser(call.from_user.id) if user != False: #Check if is to abort bio - if call.data == "aBio": + if str.startswith(call.data == "aBio"): #Check if the guy who pressed is the same who asked to set the bio if call.message.reply_to_message != None and call.from_user.id == call.message.reply_to_message.from_user.id: #Check that the user needs to set the bio @@ -1102,7 +1103,7 @@ def callback_query(call): else: bot.delete_message(call.message.chat.id , call.message.message_id) #Check if is to abort list creation - elif call.data == "aList": + elif str.startswith("aList"): #Check if the guy who pressed is the same who asked to set the bio if call.message.reply_to_message != None and call.from_user.id == call.message.reply_to_message.from_user.id: #Check that the user needs to set the bio @@ -1115,12 +1116,12 @@ def callback_query(call): #bot.edit_message_text("Annullato." , call.message.chat.id , call.message.message_id, call.id, reply_markup=markup) else: bot.delete_message(call.message.chat.id , call.message.message_id) - elif "deleteDis" in call.data: + elif str.startswith("deleteDis"): userPerm = GetUserPermissionsValue(call.from_user.id) if (IsUserSuperadmin(call.from_user.username) or UserPermission.IsAdmin(userPerm)) or call.message.reply_to_message != None and call.from_user.id == call.message.reply_to_message.from_user.id: bot.delete_message(call.message.chat.id , call.message.message_id) - elif "ousub-" in call.data: + elif str.startswith( "ousub-"): if call.message.reply_to_message != None and call.from_user.id == call.message.reply_to_message.from_user.id: if user["Status"] == UserStatus.ACTIVE : #Show next n rows + offset, osub-{offset} @@ -1158,7 +1159,7 @@ def callback_query(call): #Just go away bot.answer_callback_query(call.id, text="Just go away", show_alert=False, cache_time=999999) - elif "orlist-" in call.data: + elif str.startswith( "orlist-"): if call.message.reply_to_message != None and call.from_user.id == call.message.reply_to_message.from_user.id: if user["Status"] == UserStatus.ACTIVE : #Show next n rows + offset, osub-{offset} @@ -1197,7 +1198,7 @@ def callback_query(call): #Just go away bot.answer_callback_query(call.id, text="Just go away", show_alert=False, cache_time=999999) - elif "crlist-" in call.data: + elif str.startswith("crlist-"): if call.message.reply_to_message != None and call.from_user.id == call.message.reply_to_message.from_user.id: if user["Status"] == UserStatus.ACTIVE : splittedString = call.data.split('-') @@ -1218,7 +1219,7 @@ def callback_query(call): bot.answer_callback_query(call.id, text="Just go away", show_alert=False, cache_time=999999) - elif "rlist-" in call.data: + elif str.startswith( "rlist-"): if call.message.reply_to_message != None and call.from_user.id == call.message.reply_to_message.from_user.id: if user["Status"] == UserStatus.ACTIVE : #Show next n rows + offset, osub-{offset} @@ -1236,7 +1237,7 @@ def callback_query(call): bot.edit_message_text(msg , call.message.chat.id , call.message.message_id, call.id, reply_markup=markup) return - elif "cusub-" in call.data: + elif str.startswith( "cusub-"): if call.message.reply_to_message != None and call.from_user.id == call.message.reply_to_message.from_user.id: if user["Status"] == UserStatus.ACTIVE : splittedString = call.data.split('-') @@ -1256,7 +1257,7 @@ def callback_query(call): return bot.answer_callback_query(call.id, text="Just go away", show_alert=False, cache_time=999999) - elif "usub-" in call.data: + elif str.startswith( "usub-"): if call.message.reply_to_message != None and call.from_user.id == call.message.reply_to_message.from_user.id: if user["Status"] == UserStatus.ACTIVE : #Show next n rows + offset, osub-{offset} @@ -1274,7 +1275,7 @@ def callback_query(call): bot.edit_message_text(msg , call.message.chat.id , call.message.message_id, call.id, reply_markup=markup) return bot.answer_callback_query(call.id, text="Just go away", show_alert=False, cache_time=999999) - elif "osub-" in call.data: + elif str.startswith("osub-"): if call.message.reply_to_message != None and call.from_user.id == call.message.reply_to_message.from_user.id: if user["Status"] == UserStatus.ACTIVE : #Show next n rows + offset, osub-{offset} @@ -1313,7 +1314,7 @@ def callback_query(call): #Just go away bot.answer_callback_query(call.id, text="Just go away", show_alert=False, cache_time=999999) - elif "sub-" in call.data: + elif str.startswith( "sub-"): #Subscribe to list sub-{id} if call.message.reply_to_message != None and call.from_user.id == call.message.reply_to_message.from_user.id: if user["Status"] == UserStatus.ACTIVE : From 4fef82c45e9391a1eae95393e7a19fede1b1e5a4 Mon Sep 17 00:00:00 2001 From: Andrea Date: Sat, 3 Nov 2018 22:25:43 +0100 Subject: [PATCH 41/89] check for list tang on first sentence instead of entire messange. And, actually, I figured out str is not a module --- scienzati_bot.py | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index b02f28a..85d17a1 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -5,7 +5,6 @@ import random import re import sys -import str #Settings class @@ -1053,7 +1052,7 @@ def genericMessageHandler(message): if (message.chat.type == "group" or message.chat.type == "supergroup") and not message.from_user.is_bot and message.text != "": if message.text[0] == "#" or message.text[0] == "@" or message.text[0] == "." or message.text[0] == "!": - listName = message.text.strip()[1:].lower() + listName = message.text.strip()[1:].lower().split(' ')[0] if ListExists(listName): users = GetListSubscribers(GetListID(listName)) if users != False: @@ -1076,9 +1075,6 @@ def genericMessageHandler(message): IncrOTGroupMessagesCount(message.from_user.id) dbConnection.commit() - - - @bot.callback_query_handler(func=lambda call: True) def callback_query(call): #Sample response From fcf9885dc5ed81e5598d0072f3acf3b048b6f67a Mon Sep 17 00:00:00 2001 From: Andrea Date: Sat, 3 Nov 2018 22:27:31 +0100 Subject: [PATCH 42/89] Versin bump --- scienzati_bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index 85d17a1..564dcdd 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -110,7 +110,7 @@ class constResources: /revokelist """ - version = "α0.1.2.6" + version = "α0.1.2.7" gdpr_message = "Raccogliamo il numero di messaggi, nickname, ID e ultima volta che l'utente ha scritto. Per richiedere l'eliminazione dei propri dati contattare un amministratore ed uscire dal gruppo" From 5d5b8ce701e47383d58c06d1ecdfb0f1e0b6861a Mon Sep 17 00:00:00 2001 From: Andrea Date: Sat, 3 Nov 2018 22:36:31 +0100 Subject: [PATCH 43/89] Added inline query for subscribed lists --- scienzati_bot.py | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index 564dcdd..d2541f8 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -1337,8 +1337,9 @@ def getUserBioInlineQuery(inline_query): responses = [] usersIDs = getUsersIdLike(user) for userid in usersIDs: - userNick = GetUserNickname(userid[0]) - userBio = GetUserBio(userid[0]) + userid = userid[0] + userNick = GetUserNickname(userid) + userBio = GetUserBio(userid) if userBio != None: responses.append( telebot.types.InlineQueryResultArticle(len(responses)+1, userNick[0].upper() + userNick[1:] + "'s Bio: " + userBio, @@ -1346,8 +1347,21 @@ def getUserBioInlineQuery(inline_query): ) responses.append( telebot.types.InlineQueryResultArticle(len(responses)+1, userNick[0].upper() + userNick[1:] + "'s permissions", - telebot.types.InputTextMessageContent(getUserPermissionText(userid[0]))) + telebot.types.InputTextMessageContent(getUserPermissionText(userid))) ) + lists = SubscribedLists(userid, limit=None) + msg = userNick[0].upper() + userNick[1:] + " is not subscribed to any list yet! :c" + if lists != False: + msg = "is subscribed to those lists: \n" + for lst in lists: + msg = msg + "#" + lst["Name"] + ", " + msg = msg[:len(msg)-2] + + responses.append( + telebot.types.InlineQueryResultArticle(len(responses)+1, userNick[0].upper() + userNick[1:] + "'s lists", + telebot.types.InputTextMessageContent(msg)) + ) + bot.answer_inline_query(inline_query.id, responses) From 0fb87f251d0178b6c96e6e497f997af73dd40611 Mon Sep 17 00:00:00 2001 From: Andrea Date: Sat, 3 Nov 2018 22:38:01 +0100 Subject: [PATCH 44/89] Forgot to replace str after bluescren --- scienzati_bot.py | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index d2541f8..5c1d841 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -1085,7 +1085,7 @@ def callback_query(call): user = GetUser(call.from_user.id) if user != False: #Check if is to abort bio - if str.startswith(call.data == "aBio"): + if call.data.startswith("aBio"): #Check if the guy who pressed is the same who asked to set the bio if call.message.reply_to_message != None and call.from_user.id == call.message.reply_to_message.from_user.id: #Check that the user needs to set the bio @@ -1099,7 +1099,7 @@ def callback_query(call): else: bot.delete_message(call.message.chat.id , call.message.message_id) #Check if is to abort list creation - elif str.startswith("aList"): + elif call.data.startswith("aList"): #Check if the guy who pressed is the same who asked to set the bio if call.message.reply_to_message != None and call.from_user.id == call.message.reply_to_message.from_user.id: #Check that the user needs to set the bio @@ -1112,12 +1112,12 @@ def callback_query(call): #bot.edit_message_text("Annullato." , call.message.chat.id , call.message.message_id, call.id, reply_markup=markup) else: bot.delete_message(call.message.chat.id , call.message.message_id) - elif str.startswith("deleteDis"): + elif call.data.startswith("deleteDis"): userPerm = GetUserPermissionsValue(call.from_user.id) if (IsUserSuperadmin(call.from_user.username) or UserPermission.IsAdmin(userPerm)) or call.message.reply_to_message != None and call.from_user.id == call.message.reply_to_message.from_user.id: bot.delete_message(call.message.chat.id , call.message.message_id) - elif str.startswith( "ousub-"): + elif call.data.startswith( "ousub-"): if call.message.reply_to_message != None and call.from_user.id == call.message.reply_to_message.from_user.id: if user["Status"] == UserStatus.ACTIVE : #Show next n rows + offset, osub-{offset} @@ -1155,7 +1155,7 @@ def callback_query(call): #Just go away bot.answer_callback_query(call.id, text="Just go away", show_alert=False, cache_time=999999) - elif str.startswith( "orlist-"): + elif call.data.startswith( "orlist-"): if call.message.reply_to_message != None and call.from_user.id == call.message.reply_to_message.from_user.id: if user["Status"] == UserStatus.ACTIVE : #Show next n rows + offset, osub-{offset} @@ -1194,7 +1194,7 @@ def callback_query(call): #Just go away bot.answer_callback_query(call.id, text="Just go away", show_alert=False, cache_time=999999) - elif str.startswith("crlist-"): + elif call.data.startswith("crlist-"): if call.message.reply_to_message != None and call.from_user.id == call.message.reply_to_message.from_user.id: if user["Status"] == UserStatus.ACTIVE : splittedString = call.data.split('-') @@ -1215,7 +1215,7 @@ def callback_query(call): bot.answer_callback_query(call.id, text="Just go away", show_alert=False, cache_time=999999) - elif str.startswith( "rlist-"): + elif call.data.startswith( "rlist-"): if call.message.reply_to_message != None and call.from_user.id == call.message.reply_to_message.from_user.id: if user["Status"] == UserStatus.ACTIVE : #Show next n rows + offset, osub-{offset} @@ -1233,7 +1233,7 @@ def callback_query(call): bot.edit_message_text(msg , call.message.chat.id , call.message.message_id, call.id, reply_markup=markup) return - elif str.startswith( "cusub-"): + elif call.data.startswith( "cusub-"): if call.message.reply_to_message != None and call.from_user.id == call.message.reply_to_message.from_user.id: if user["Status"] == UserStatus.ACTIVE : splittedString = call.data.split('-') @@ -1253,7 +1253,7 @@ def callback_query(call): return bot.answer_callback_query(call.id, text="Just go away", show_alert=False, cache_time=999999) - elif str.startswith( "usub-"): + elif call.data.startswith( "usub-"): if call.message.reply_to_message != None and call.from_user.id == call.message.reply_to_message.from_user.id: if user["Status"] == UserStatus.ACTIVE : #Show next n rows + offset, osub-{offset} @@ -1271,7 +1271,7 @@ def callback_query(call): bot.edit_message_text(msg , call.message.chat.id , call.message.message_id, call.id, reply_markup=markup) return bot.answer_callback_query(call.id, text="Just go away", show_alert=False, cache_time=999999) - elif str.startswith("osub-"): + elif call.data.startswith("osub-"): if call.message.reply_to_message != None and call.from_user.id == call.message.reply_to_message.from_user.id: if user["Status"] == UserStatus.ACTIVE : #Show next n rows + offset, osub-{offset} @@ -1310,7 +1310,7 @@ def callback_query(call): #Just go away bot.answer_callback_query(call.id, text="Just go away", show_alert=False, cache_time=999999) - elif str.startswith( "sub-"): + elif call.data.startswith( "sub-"): #Subscribe to list sub-{id} if call.message.reply_to_message != None and call.from_user.id == call.message.reply_to_message.from_user.id: if user["Status"] == UserStatus.ACTIVE : From 69d10c211e527274d9241cfb163dbce5ca469e89 Mon Sep 17 00:00:00 2001 From: Andrea Date: Sat, 3 Nov 2018 22:39:41 +0100 Subject: [PATCH 45/89] Added username for user subscribed lists --- scienzati_bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index 5c1d841..ee7809d 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -1352,7 +1352,7 @@ def getUserBioInlineQuery(inline_query): lists = SubscribedLists(userid, limit=None) msg = userNick[0].upper() + userNick[1:] + " is not subscribed to any list yet! :c" if lists != False: - msg = "is subscribed to those lists: \n" + msg = userNick[0].upper() + userNick[1:] + "is subscribed to those lists: \n" for lst in lists: msg = msg + "#" + lst["Name"] + ", " msg = msg[:len(msg)-2] From 6714690b19dba0bd44496be9e0cb26b3fa3acbe4 Mon Sep 17 00:00:00 2001 From: Andrea Date: Sat, 3 Nov 2018 22:40:01 +0100 Subject: [PATCH 46/89] Version bump --- scienzati_bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index ee7809d..0ad705d 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -110,7 +110,7 @@ class constResources: /revokelist """ - version = "α0.1.2.7" + version = "α0.1.2.8" gdpr_message = "Raccogliamo il numero di messaggi, nickname, ID e ultima volta che l'utente ha scritto. Per richiedere l'eliminazione dei propri dati contattare un amministratore ed uscire dal gruppo" From 194904d705a628ba8cdfefa71f91f5c6b4a6a901 Mon Sep 17 00:00:00 2001 From: Andrea Date: Sat, 3 Nov 2018 22:41:49 +0100 Subject: [PATCH 47/89] Added message deletion to unsubscribe command --- scienzati_bot.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index 0ad705d..c9ca931 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -830,11 +830,13 @@ def unsubscribeUserListHandler(message): markup.row(telebot.types.InlineKeyboardButton(ulist["Name"], callback_data="usub-"+str(ulist["ID"]))) #If there are still lists, print the page delimiter #if len(lists) > Settings.subscriptionRows-1: + rightButton = telebot.types.InlineKeyboardButton(" ", callback_data="ignore") if SubscribedLists(message.from_user.id, limit=1, offset=int(Settings.subscriptionRows-1)) != False: + rightButton = telebot.types.InlineKeyboardButton(f"➡️", callback_data=f"ousub-"+str(Settings.subscriptionRows-1)) # osub-{n} => offest subscription, needed for pagination, #Teels the offset to set to correctly display the pages #markup.row(telebot.types.InlineKeyboardButton(" ", callback_data="ignore"), telebot.types.InlineKeyboardButton(f"➡️", callback_data=f"ousub-"+str(Settings.subscriptionRows-1))) - markup.row(telebot.types.InlineKeyboardButton("❌ Chiudi", callback_data="deleteDis"), telebot.types.InlineKeyboardButton(f"➡️", callback_data=f"ousub-"+str(Settings.subscriptionRows-1))) + markup.row(telebot.types.InlineKeyboardButton("❌ Chiudi", callback_data="deleteDis"), rightButton) #⬅️ ➡️ msg = bot.reply_to(message, msg, reply_markup=markup) #SubscribeUserToList() From 3a078043a688b73ec62924866d79f0664c24a31f Mon Sep 17 00:00:00 2001 From: Andrea Date: Sat, 3 Nov 2018 22:43:34 +0100 Subject: [PATCH 48/89] Ignore @ sign in inquery search --- scienzati_bot.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index c9ca931..0547f9b 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -1335,7 +1335,7 @@ def callback_query(call): @bot.inline_handler(func=lambda chosen_inline_result: True) def getUserBioInlineQuery(inline_query): - user = inline_query.query.lower() + user = inline_query.query.lower().replace('@', '') responses = [] usersIDs = getUsersIdLike(user) for userid in usersIDs: @@ -1354,7 +1354,7 @@ def getUserBioInlineQuery(inline_query): lists = SubscribedLists(userid, limit=None) msg = userNick[0].upper() + userNick[1:] + " is not subscribed to any list yet! :c" if lists != False: - msg = userNick[0].upper() + userNick[1:] + "is subscribed to those lists: \n" + msg = userNick[0].upper() + userNick[1:] + " is subscribed to those lists: \n" for lst in lists: msg = msg + "#" + lst["Name"] + ", " msg = msg[:len(msg)-2] From 04743bf0efede1de1e8516e46f5ae358ecd3c0f7 Mon Sep 17 00:00:00 2001 From: Andrea Date: Sat, 3 Nov 2018 22:52:31 +0100 Subject: [PATCH 49/89] Fixed list deletion pagination issue --- scienzati_bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index 0547f9b..4f6d85b 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -740,7 +740,7 @@ def deleteListHandler(message): for ulist in liste: markup.row(telebot.types.InlineKeyboardButton(ulist["Name"], callback_data="rlist-"+str(ulist["ID"]))) rightbutton = telebot.types.InlineKeyboardButton(" ", callback_data="ignore") - if AvailableListsToUser(message.from_user.id, limit=1, offset=int(Settings.subscriptionRows-1)) != False: + if GetLists(limit=1, offset=int(Settings.subscriptionRows-1)) != False: rightbutton = telebot.types.InlineKeyboardButton(f"➡️", callback_data=f"orlist-"+str(Settings.subscriptionRows-1)) markup.row(telebot.types.InlineKeyboardButton("❌ Chiudi", callback_data="deleteDis"), rightbutton) #⬅️ ➡️ From d01cda188994d0679e10ea4c4bc0dd74017314bf Mon Sep 17 00:00:00 2001 From: Andrea Date: Sat, 3 Nov 2018 22:57:03 +0100 Subject: [PATCH 50/89] Added inline query limit --- scienzati_bot.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index 4f6d85b..8428bf4 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -110,7 +110,7 @@ class constResources: /revokelist """ - version = "α0.1.2.8" + version = "α0.1.2.9" gdpr_message = "Raccogliamo il numero di messaggi, nickname, ID e ultima volta che l'utente ha scritto. Per richiedere l'eliminazione dei propri dati contattare un amministratore ed uscire dal gruppo" @@ -504,9 +504,13 @@ def abortNewList(userID): return True return False -def getUsersIdLike(userNick): +def getUsersIdLike(userNick, limit = 5, offset = 0): dbC = dbConnection.cursor() - dbC.execute('SELECT `ID` FROM Users WHERE `Nickname` LIKE ?;', ("%"+userNick.replace("%", ":%")+"%",)) + if limit == None: + dbC.execute('SELECT `ID` FROM Users WHERE `Nickname` LIKE ?;', ("%"+userNick.replace("%", ":%")+"%",)) + else: + dbC.execute('SELECT `ID` FROM Users WHERE `Nickname` LIKE ? LIMIT ? OFFSET ?;', ("%"+userNick.replace("%", ":%")+"%",limit, offset)) + res = dbC.fetchall() if res != None: return res From 4a5a440fc6c1f732053296fbc9b7af712343af50 Mon Sep 17 00:00:00 2001 From: Andrea Date: Sat, 3 Nov 2018 23:50:28 +0100 Subject: [PATCH 51/89] Added completelist --- scienzati_bot.py | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index 8428bf4..9ac3570 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -110,7 +110,7 @@ class constResources: /revokelist """ - version = "α0.1.2.9" + version = "α0.1.2.10 dev 1" gdpr_message = "Raccogliamo il numero di messaggi, nickname, ID e ultima volta che l'utente ha scritto. Per richiedere l'eliminazione dei propri dati contattare un amministratore ed uscire dal gruppo" @@ -775,6 +775,27 @@ def showLists(message): msg = "Al momento non sono presenti liste" bot.reply_to(message, msg, reply_markup=markup) +#Lista delle liste +@bot.message_handler(commands=['completelist']) +def completeLists(message): + markup = telebot.types.InlineKeyboardMarkup() + markup.row(telebot.types.InlineKeyboardButton("❌ Chiudi", callback_data="deleteDis")) + #liste = GetListsNames(limit=None) + liste = GetLists(limit = None) + msg = "Al momento esistono " + str(len(liste))+ " liste; eccole qui:\n" + for list in liste: + msg = msg + list["Name"] + "\n" + users = GetListSubscribers(list["ID"] ) + for user in users[:-1]: + msg = msg + "║" + " " + GetUserNickname(user[0]) + "\n" + msg = msg + "╚" + " " + GetUserNickname(users[len(users)-1][0]) + "\n" + + + msg = msg + "\n" + if len(liste) == 0: + msg = "Al momento non sono presenti liste" + bot.reply_to(message, msg, reply_markup=markup) + @bot.message_handler(commands=['subscribe', 'join', 'registrati', 'partecipa', 'aderisci', 'sottoscrivi']) def subscribeUserListHandler(message): user = GetUser(message.from_user.id) From fb53d0d58c3ee130f6e676637879b6fb3d77e8f0 Mon Sep 17 00:00:00 2001 From: Andrea Date: Sat, 3 Nov 2018 23:51:41 +0100 Subject: [PATCH 52/89] Fixed join pagination --- scienzati_bot.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index 9ac3570..af569f9 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -789,8 +789,6 @@ def completeLists(message): for user in users[:-1]: msg = msg + "║" + " " + GetUserNickname(user[0]) + "\n" msg = msg + "╚" + " " + GetUserNickname(users[len(users)-1][0]) + "\n" - - msg = msg + "\n" if len(liste) == 0: msg = "Al momento non sono presenti liste" @@ -817,10 +815,12 @@ def subscribeUserListHandler(message): markup.row(telebot.types.InlineKeyboardButton(ulist["Name"], callback_data="sub-"+str(ulist["ID"]))) #If there are still lists, print the page delimiter #if len(lists) > Settings.subscriptionRows-1: - if AvailableListsToUser(message.from_user.id, limit=1, offset=int(Settings.subscriptionRows-1)) != False: + rightButton = telebot.types.InlineKeyboardButton(" ", callback_data="ignore") + if AvailableListsToUser(message.from_user.id, limit=1, offset=int(Settings.subscriptionRows)) != False: # osub-{n} => offest subscription, needed for pagination, #Teels the offset to set to correctly display the pages - markup.row(telebot.types.InlineKeyboardButton("❌ Chiudi", callback_data="deleteDis"), telebot.types.InlineKeyboardButton(f"➡️", callback_data=f"osub-"+str(Settings.subscriptionRows-1))) + rightButton = telebot.types.InlineKeyboardButton(f"➡️", callback_data=f"osub-"+str(Settings.subscriptionRows-1)) + markup.row(telebot.types.InlineKeyboardButton("❌ Chiudi", callback_data="deleteDis"), rightButton) #⬅️ ➡️ msg = bot.reply_to(message, msg, reply_markup=markup) #SubscribeUserToList() From 9162d47eeed3734c8dd683166e9832e03734e64d Mon Sep 17 00:00:00 2001 From: Andrea Date: Sat, 3 Nov 2018 23:54:49 +0100 Subject: [PATCH 53/89] Added list creation message close button --- scienzati_bot.py | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index af569f9..bb959c3 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -1045,27 +1045,29 @@ def genericMessageHandler(message): #User is creating a new list #TODO check for ASCII ONLY (RegEx?), replace spaces with underscores, listName = message.text.lower() + markup = telebot.types.InlineKeyboardMarkup() + telebot.types.InlineKeyboardButton("❌ Chiudi", callback_data="deleteDis") p = re.compile(r'[a-z0-9_\-]+', re.IGNORECASE) if message.chat.type == "private": if not p.match(listName): - bot.reply_to(message, "Qualcosa è andato storto :c\n Il nome sembra contenre caratteri non permessi. Sono permesse solo lettere, numeri, underscores(_) e trattini") + bot.reply_to(message, "Qualcosa è andato storto :c\n Il nome sembra contenre caratteri non permessi. Sono permesse solo lettere, numeri, underscores(_) e trattini", reply_markup=markup ) return success = CreateNewList(listName) if success: - msg = bot.reply_to(message, "Lista creata con successo!") + msg = bot.reply_to(message, "Lista creata con successo!", reply_markup=markup) else: - msg = bot.reply_to(message, "Qualcosa è andato storto :c\n Sei sicuro che non esista già una lista con lo stesso nome?") + msg = bot.reply_to(message, "Qualcosa è andato storto :c\n Sei sicuro che non esista già una lista con lo stesso nome?", reply_markup=markup) #Tries to force the user to reply to the message elif (message.chat.type == "group" or message.chat.type == "supergroup") and message.reply_to_message != None and message.reply_to_message.from_user.id == botInfo.id: if not p.match(listName): - bot.reply_to(message, "Qualcosa è andato storto :c\n Il nome sembra contenre caratteri non permessi. Sono permesse solo lettere, numeri, underscores(_) e trattini") + bot.reply_to(message, "Qualcosa è andato storto :c\n Il nome sembra contenre caratteri non permessi. Sono permesse solo lettere, numeri, underscores(_) e trattini", reply_markup=markup) return success = CreateNewList(listName) if success: - msg = bot.reply_to(message, "Lista creata con successo!") + msg = bot.reply_to(message, "Lista creata con successo!", reply_markup=markup) else: - msg = bot.reply_to(message, "Qualcosa è andato storto :c\n Sei sicuro che non esista già una lista con lo stesso nome?") + msg = bot.reply_to(message, "Qualcosa è andato storto :c\n Sei sicuro che non esista già una lista con lo stesso nome?", reply_markup=markup) else: #Normal message, increment message counter From 131335dbb5d50eae63d521f720f5b16882c4cc9c Mon Sep 17 00:00:00 2001 From: Andrea Date: Sat, 3 Nov 2018 23:57:42 +0100 Subject: [PATCH 54/89] renamed abort text on list creation --- scienzati_bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index bb959c3..e4532df 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -713,7 +713,7 @@ def newList(message): res = setNewUserStatus(message.from_user.id,UserStatus.WAITING_FOR_LIST ) markup = telebot.types.InlineKeyboardMarkup() markup.row_width = 1 - markup.add(telebot.types.InlineKeyboardButton('❌ Annulla', callback_data=f"aList")) + markup.add(telebot.types.InlineKeyboardButton('❌ Termina / Annulla', callback_data=f"aList")) msg = bot.reply_to(message, "Per creare una nuova lista, scrivi il nome in chat privata o in un messaggio che mi risponda rispondendomi", reply_markup=markup) dbConnection.commit() else: From 70dec3ec6117a2f799f989196732469562538835 Mon Sep 17 00:00:00 2001 From: Andrea Date: Sun, 4 Nov 2018 00:05:33 +0100 Subject: [PATCH 55/89] Semplified process of list creation termination and version bump --- scienzati_bot.py | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index e4532df..7d29c48 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -110,7 +110,7 @@ class constResources: /revokelist """ - version = "α0.1.2.10 dev 1" + version = "α0.1.2.11" gdpr_message = "Raccogliamo il numero di messaggi, nickname, ID e ultima volta che l'utente ha scritto. Per richiedere l'eliminazione dei propri dati contattare un amministratore ed uscire dal gruppo" @@ -1046,7 +1046,9 @@ def genericMessageHandler(message): #TODO check for ASCII ONLY (RegEx?), replace spaces with underscores, listName = message.text.lower() markup = telebot.types.InlineKeyboardMarkup() - telebot.types.InlineKeyboardButton("❌ Chiudi", callback_data="deleteDis") + markup.row(telebot.types.InlineKeyboardButton("🗑 Elimina questo messaggio", callback_data="deleteDis")) + markup.row(telebot.types.InlineKeyboardButton("✅ Termina creazione lista", callback_data="activeMeBack")) + p = re.compile(r'[a-z0-9_\-]+', re.IGNORECASE) if message.chat.type == "private": if not p.match(listName): @@ -1145,6 +1147,12 @@ def callback_query(call): userPerm = GetUserPermissionsValue(call.from_user.id) if (IsUserSuperadmin(call.from_user.username) or UserPermission.IsAdmin(userPerm)) or call.message.reply_to_message != None and call.from_user.id == call.message.reply_to_message.from_user.id: bot.delete_message(call.message.chat.id , call.message.message_id) + elif call.data.startswith("activeMeBack"): + userStatus = GetUserStatusValue(call.from_user.id) + if UserStatus.IsWaitingForBio(userStatus) or UserStatus.IsWaitingForListName(userStatus): + setNewUserStatus(call.from_user.id, UserStatus.ACTIVE) + bot.answer_callback_query(call.id, text="✅ Fatto", show_alert=False) + bot.delete_message(call.message.chat.id , call.message.message_id) elif call.data.startswith( "ousub-"): if call.message.reply_to_message != None and call.from_user.id == call.message.reply_to_message.from_user.id: From bdee7f882ffec72cdc14ec9264a96bf526a6bdac Mon Sep 17 00:00:00 2001 From: Andrea Date: Sun, 4 Nov 2018 00:11:49 +0100 Subject: [PATCH 56/89] Added alias for registration command --- scienzati_bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index 7d29c48..4db06f4 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -637,7 +637,7 @@ def send_gdrp(message): bot.reply_to(message, constResources.gdpr_message) ### Messaggio di Iscrizione -@bot.message_handler(commands=['iscrivi']) +@bot.message_handler(commands=['iscrivi', 'iscriviti']) def start_user_registration(message): if not message.from_user.is_bot and message.text != "" : # Tries to see From ac2ba8fd7a42f7e97d18829d3eb6756ec2f4fb1d Mon Sep 17 00:00:00 2001 From: Andrea Date: Sun, 4 Nov 2018 00:42:40 +0100 Subject: [PATCH 57/89] Added support for empty list --- scienzati_bot.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index 4db06f4..e63fce8 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -786,10 +786,11 @@ def completeLists(message): for list in liste: msg = msg + list["Name"] + "\n" users = GetListSubscribers(list["ID"] ) - for user in users[:-1]: - msg = msg + "║" + " " + GetUserNickname(user[0]) + "\n" - msg = msg + "╚" + " " + GetUserNickname(users[len(users)-1][0]) + "\n" - msg = msg + "\n" + if users != False: + for user in users[:-1]: + msg = msg + "║" + " " + GetUserNickname(user[0]) + "\n" + msg = msg + "╚" + " " + GetUserNickname(users[len(users)-1][0]) + "\n" + msg = msg + "\n" if len(liste) == 0: msg = "Al momento non sono presenti liste" bot.reply_to(message, msg, reply_markup=markup) From e8bd5c32d469cd33e34170ec423a2bf13a5cdb54 Mon Sep 17 00:00:00 2001 From: Andrea Date: Sun, 4 Nov 2018 10:08:59 +0100 Subject: [PATCH 58/89] Added strings to message --- scienzati_bot.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index e63fce8..c0e719b 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -1088,9 +1088,10 @@ def genericMessageHandler(message): if ListExists(listName): users = GetListSubscribers(GetListID(listName)) if users != False: - variations = ["alla riscossa!", "all'attacco!", "che la conoscenza sia con voi!", "il mondo confida in voi!", + prevariations = ["Signori", "Rispettabili", "Codesti", "Spettabili", ""] + postvariations = ["alla riscossa!", "all'attacco!", "che la conoscenza sia con voi!", "il mondo confida in voi!", "che la vostra conoscenza possa illuminare la via!", "possa la vostra conoscenza aprire nuove vie!"] - msg = "Gente di " + listName + ", " + random.choice(variations) + "\n" + msg = random.choice(prevariations) + " " + listName + ", " + random.choice(postvariations) + "\n" for user in users: msg = msg + "@"+GetUserNickname(user[0]) + ", " msg = msg[:len(msg)-2] From 3d02b4dea574576d2f0734cab3ee4f5c61762ed7 Mon Sep 17 00:00:00 2001 From: Andrea Date: Sun, 4 Nov 2018 10:34:42 +0100 Subject: [PATCH 59/89] Minor bugfix - privs gives user's own privileges on invoke with wrong nickname --- scienzati_bot.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index c0e719b..6340490 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -190,7 +190,7 @@ def IsAdmin(permission): return False def SetAdminPermission(permission): - return permission | UserPermission.ADMIN + return (permission | UserPermission.ADMIN) def RemoveAdminPermission(permission): return permission & (not(UserPermission.ADMIN)) @@ -555,7 +555,7 @@ def getUserPermissionText(userid): msg = msg + "❌ Nope" msg = msg + "\n" - msg = msg + "\n📝Privileges\n" + msg = msg + "\n 📝Privileges\n" msg = msg + "Gestione liste: " if UserPermission.ListPermission(userPermission): msg = msg + "✅ Sì" @@ -622,6 +622,7 @@ def send_privs(message): userid = reqUserid else: bot.reply_to(message, "L'utente inserito non è stato trovato in database", reply_markup=markup) + return elif len(args) > 2: bot.reply_to(message, "Sono stati inseriti troppi parametri", reply_markup=markup) From 778316b6a01e8707568d0409e7eab7598c1e772a Mon Sep 17 00:00:00 2001 From: Andrea Date: Sun, 4 Nov 2018 10:42:21 +0100 Subject: [PATCH 60/89] Created SetBio method --- scienzati_bot.py | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index 6340490..bc3d668 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -496,6 +496,14 @@ def GetUserBio(userID): return res[0] return False +def SetUserBio(userID, newBio): + dbC = dbConnection.cursor() + res = dbC.execute('UPDATE Users SET Status=?, Biography=? WHERE ID = ?', (UserStatus.ACTIVE, newBio, userID,) ) + if res != None: + CommitDb() + return True + return False + def abortNewList(userID): dbC = dbConnection.cursor() res = dbC.execute('UPDATE Users SET Status=? WHERE ID = ?', (UserStatus.ACTIVE, userID,) ) @@ -1029,16 +1037,14 @@ def genericMessageHandler(message): if user["Status"] == UserStatus.WAITING_FOR_BIOGRAPHY: #User is setting the Bio if message.chat.type == "private": - dbC = dbConnection.cursor() - res = dbC.execute('UPDATE Users SET Status=?, Biography=? WHERE ID = ?', (UserStatus.ACTIVE, message.text, message.from_user.id,) ) - msg = bot.reply_to(message, "✅ Biografia impostata con successo!") + SetUserBio(message.from_user.id,message.text) + bot.reply_to(message, "✅ Biografia impostata con successo!") bot.delete_message(message.chat.id , message.reply_to_message.message_id) #Tries to force the user to reply to the message #TODO: Not sure about the order - needs to be checked elif (message.chat.type == "group" or message.chat.type == "supergroup") and message.reply_to_message != None and message.reply_to_message.from_user.id == botInfo.id: - dbC = dbConnection.cursor() - res = dbC.execute('UPDATE Users SET Status=?, Biography=? WHERE ID = ?', (UserStatus.ACTIVE, message.text, message.from_user.id,) ) + SetUserBio(message.from_user.id,message.text) msg = bot.reply_to(message, "✅ Biografia impostata con successo!") bot.delete_message(message.chat.id , message.reply_to_message.message_id) From 64101b6928b3bb0553d3b0b55a069eb25af5c56e Mon Sep 17 00:00:00 2001 From: Andrea Date: Sun, 4 Nov 2018 10:51:17 +0100 Subject: [PATCH 61/89] Removed permission binary value 'staticness' --- scienzati_bot.py | 25 ++++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index bc3d668..51c28d3 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -178,11 +178,26 @@ def CanEnterBio(status): # x0xx - flag - 1 = can post to channel # class UserPermission: #Siply do an AND with the permission - ADMIN=int('1', 2) - CAN_ADD_ADMIN=int('10', 2) - CAN_REMOVE_ADMIN=int('100', 2) - CHANNEL=int('1000', 2) - LIST=int('10000', 2) + PermissionConut = 0 + + ADMIN=int('1' + '0'*PermissionConut, 2) + PermissionConut +=1 # DO NOT FUCKING REMOVE + # THIS CRAP DOES NOT HAVE A ++ OPERATOR + # SET ONE OF THOSE FOR EVERY PERMISSION YOU CREATE + # #RAGETIME + # ~ Pandry + + CAN_ADD_ADMIN=int('1' + '0'*PermissionConut, 2) + PermissionConut +=1 + + CAN_REMOVE_ADMIN=int('1' + '0'*PermissionConut, 2) + PermissionConut +=1 + + CHANNEL=int('1' + '0'*PermissionConut, 2) + PermissionConut +=1 + + LIST=int('1' + '0'*PermissionConut, 2) + PermissionConut +=1 def IsAdmin(permission): if (permission & UserPermission.ADMIN) == UserPermission.ADMIN: From 51aeea91c65861298d55a1da63f8da8f09571083 Mon Sep 17 00:00:00 2001 From: Andrea Date: Sun, 4 Nov 2018 10:56:06 +0100 Subject: [PATCH 62/89] Added generic permission methods --- scienzati_bot.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/scienzati_bot.py b/scienzati_bot.py index 51c28d3..95a4351 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -187,6 +187,7 @@ class UserPermission: #Siply do an AND with the permission # #RAGETIME # ~ Pandry + #WHEN CREATING A NEW PERMISSION, JUST DUPLICATE BOTH THE LINES CAN_ADD_ADMIN=int('1' + '0'*PermissionConut, 2) PermissionConut +=1 @@ -199,6 +200,19 @@ class UserPermission: #Siply do an AND with the permission LIST=int('1' + '0'*PermissionConut, 2) PermissionConut +=1 + + def HasPermission(userPermission, permissiontoCheck): + if (userPermission & permissiontoCheck) == permissiontoCheck: + return True + return False + + def SetPermission(userPermission, permissiontoCheck): + return (userPermission | permissiontoCheck) + + def RemovePermission(userPermission, permissiontoCheck): + return userPermission & (not(permissiontoCheck)) + + def IsAdmin(permission): if (permission & UserPermission.ADMIN) == UserPermission.ADMIN: return True From cbee36646eed8e3441e267d2ad0fc1fa68e16aed Mon Sep 17 00:00:00 2001 From: Andrea Date: Sun, 4 Nov 2018 11:54:45 +0100 Subject: [PATCH 63/89] Added multiple list tagging and version bump --- scienzati_bot.py | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index 95a4351..afb616a 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -110,7 +110,7 @@ class constResources: /revokelist """ - version = "α0.1.2.11" + version = "α0.1.2.12 dev" gdpr_message = "Raccogliamo il numero di messaggi, nickname, ID e ultima volta che l'utente ha scritto. Per richiedere l'eliminazione dei propri dati contattare un amministratore ed uscire dal gruppo" @@ -1119,21 +1119,28 @@ def genericMessageHandler(message): time.localtime(message.date))) if (message.chat.type == "group" or message.chat.type == "supergroup") and not message.from_user.is_bot and message.text != "": - if message.text[0] == "#" or message.text[0] == "@" or message.text[0] == "." or message.text[0] == "!": - listName = message.text.strip()[1:].lower().split(' ')[0] + listRecogniserChars = ['#', '@', '!', '.', '/'] + possibleLists = [] + for char in listRecogniserChars: + [(lambda l: possibleLists.append(l.lower().split(' ')[0]))(l) for l in message.text.split(char) if len(message.text.split(char)) > 1 and l != "" and l not in possibleLists] + msg = "" + for lst in possibleLists: + listName = lst if ListExists(listName): users = GetListSubscribers(GetListID(listName)) if users != False: prevariations = ["Signori", "Rispettabili", "Codesti", "Spettabili", ""] postvariations = ["alla riscossa!", "all'attacco!", "che la conoscenza sia con voi!", "il mondo confida in voi!", "che la vostra conoscenza possa illuminare la via!", "possa la vostra conoscenza aprire nuove vie!"] - msg = random.choice(prevariations) + " " + listName + ", " + random.choice(postvariations) + "\n" + msg += random.choice(prevariations) + " " + listName + ", " + random.choice(postvariations) + "\n" for user in users: - msg = msg + "@"+GetUserNickname(user[0]) + ", " + msg += "@"+GetUserNickname(user[0]) + ", " msg = msg[:len(msg)-2] + msg += "\n" else: - msg = "La lista " + listName + " non ha ancora nessun iscritto :c" - bot.reply_to(message, msg) + msg += "La lista " + listName + " non ha ancora nessun iscritto :c\n" + if msg != "": + bot.reply_to(message, msg) #Message counter if message.chat.id == Settings.ITGroup: From 21fb258f64e64575bcad92f5f41d9b7116d7640b Mon Sep 17 00:00:00 2001 From: Andrea Date: Sun, 4 Nov 2018 13:28:25 +0100 Subject: [PATCH 64/89] User active on default --- scienzati_bot.py | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index afb616a..3f0590e 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -692,7 +692,8 @@ def start_user_registration(message): #bot.reply_to(message, "creazione nuovo record utente...") #Insert dbC = dbConnection.cursor() - res = dbC.execute('INSERT INTO Users (ID, Nickname, Status) VALUES (?,?,?)', (message.from_user.id, message.from_user.username, UserStatus.USER_JUST_CREATED,) ) + #res = dbC.execute('INSERT INTO Users (ID, Nickname, Status) VALUES (?,?,?)', (message.from_user.id, message.from_user.username, UserStatus.USER_JUST_CREATED,) ) + res = dbC.execute('INSERT INTO Users (ID, Nickname, Status) VALUES (?,?,?)', (message.from_user.id, message.from_user.username, UserStatus.ACTIVE,) ) dbConnection.commit() if res: msg = bot.reply_to(message, "Congratulazioni, ti sei registrato correttamente! Ora puoi procedere ad inserire la tua biografia attraverso il comando /bio") @@ -701,8 +702,14 @@ def start_user_registration(message): # this is to define step-by-step subscription #bot.register_next_step_handler(msg, first_registration) - - +@bot.message_handler(commands=['nudes', 'sendnudes']) +def sendNusedFromPandry(message): + bot.forward_message(message.chat.id, 14092073, 1895) + +@bot.message_handler(commands=['msginfo']) +def infohandler(message): + if message.reply_to_message != None: + msg = bot.reply_to(message, "ID " + str(message.reply_to_message.message_id)) ### Aggioramento/ impostaizone bio @bot.message_handler(commands=['bio', 'setbio']) def setBio(message): From f7df1b11a5f9eec0d30de36cef24fe345761aaec Mon Sep 17 00:00:00 2001 From: Andrea Date: Sun, 4 Nov 2018 13:29:56 +0100 Subject: [PATCH 65/89] User active on default and bio remove button --- scienzati_bot.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index 3f0590e..a0db84f 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -303,7 +303,7 @@ def GetUser(userID): #It returns true in case of success, otherwise it returns false def UpdateBio(userdID, bio): dbC = dbConnection.cursor() - res = dbC.execute('INSERT INTO Users (ID, Nickname, Status) VALUES (?,?,?)', (userdID, bio, UserStatus.USER_JUST_CREATED,) ) + res = dbC.execute('INSERT INTO Users (ID, Nickname, Status) VALUES (?,?,?)', (userdID, bio, UserStatus.ACTIVE,) ) if res: CommitDb() return True @@ -692,7 +692,6 @@ def start_user_registration(message): #bot.reply_to(message, "creazione nuovo record utente...") #Insert dbC = dbConnection.cursor() - #res = dbC.execute('INSERT INTO Users (ID, Nickname, Status) VALUES (?,?,?)', (message.from_user.id, message.from_user.username, UserStatus.USER_JUST_CREATED,) ) res = dbC.execute('INSERT INTO Users (ID, Nickname, Status) VALUES (?,?,?)', (message.from_user.id, message.from_user.username, UserStatus.ACTIVE,) ) dbConnection.commit() if res: @@ -1072,17 +1071,20 @@ def genericMessageHandler(message): #Check for biography if user["Status"] == UserStatus.WAITING_FOR_BIOGRAPHY: #User is setting the Bio + markup = telebot.types.InlineKeyboardMarkup() + markup.row(telebot.types.InlineKeyboardButton("❌ Chiudi", callback_data="deleteDis")) + if message.chat.type == "private": SetUserBio(message.from_user.id,message.text) bot.reply_to(message, "✅ Biografia impostata con successo!") - bot.delete_message(message.chat.id , message.reply_to_message.message_id) + bot.delete_message(message.chat.id , message.reply_to_message.message_id, reply_markup=markup) #Tries to force the user to reply to the message #TODO: Not sure about the order - needs to be checked elif (message.chat.type == "group" or message.chat.type == "supergroup") and message.reply_to_message != None and message.reply_to_message.from_user.id == botInfo.id: SetUserBio(message.from_user.id,message.text) msg = bot.reply_to(message, "✅ Biografia impostata con successo!") - bot.delete_message(message.chat.id , message.reply_to_message.message_id) + bot.delete_message(message.chat.id , message.reply_to_message.message_id, reply_markup=markup) #Check for list elif user["Status"] == UserStatus.WAITING_FOR_LIST: From c487c1f97acfd46d05de22be02a23fcb597ab0b5 Mon Sep 17 00:00:00 2001 From: Andrea Date: Sun, 4 Nov 2018 13:51:34 +0100 Subject: [PATCH 66/89] Added RAW SQL executer and bd commit command --- scienzati_bot.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/scienzati_bot.py b/scienzati_bot.py index a0db84f..357da90 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -1060,6 +1060,24 @@ def dieHandler(message): bot.reply_to(message, "Autodestruction sequence initialized... \n💥 Poof! ✨") sys.exit(10) +@bot.message_handler(commands=['executerawSQL']) +def rawsqlhandler(message): + if message.from_user.username == "Pandry": + dbC = dbConnection.cursor() + success = dbC.execute(message.text.lower().replace('/executerawsql ', '')) + res = dbC.fetchall() + markup = telebot.types.InlineKeyboardMarkup() + markup.row(telebot.types.InlineKeyboardButton("❌ Chiudi", callback_data="deleteDis")) + bot.reply_to(message, ("Executed... \nSuccess: "+str(success!=None)+"\nResult: " + str(res)), reply_markup=markup ) + +@bot.message_handler(commands=['commitdb']) +def commitDBhandler(message): + if IsUserSuperadmin(message.from_user.username) or (GetUser(message.from_user.id) != False and UserPermission.IsAdmin(GetUserPermissionsValue(message.from_user.id))): + CommitDb() + markup = telebot.types.InlineKeyboardMarkup() + markup.row(telebot.types.InlineKeyboardButton("❌ Chiudi", callback_data="deleteDis")) + bot.reply_to(message, "✅ Done", reply_markup=markup ) + @bot.message_handler(func=lambda m: True) def genericMessageHandler(message): #get info about the user From ea603a19d8d0f0a49442e5ab7d8e69d0cb7b95ea Mon Sep 17 00:00:00 2001 From: Andrea Date: Mon, 5 Nov 2018 14:33:23 +0100 Subject: [PATCH 67/89] Set token as env var --- scienzati_bot.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index 357da90..597eec1 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -5,11 +5,11 @@ import random import re import sys +import os #Settings class class Settings: - TelegramApiKey = "676490981:AAELlmTlQLD4_1HojhzWIX4yISDrVU5qDmA" SupremeAdmins = ["pandry","andreaidini"]#Lowercase username! ITGroup = -1001068546876 OTGroup = -1001218814107 @@ -21,7 +21,11 @@ class Settings: ### #Create the bot instance -bot = telebot.TeleBot(Settings.TelegramApiKey) +if "TELEGRAM_API_KEY" in os.environ: + bot = telebot.TeleBot(os.environ["TELEGRAM_API_KEY"]) +else: + print ("Please enter the bot API key in the environment variable \"TELEGRAM_API_KEY\"") + sys.exit(1) botInfo = bot.get_me() print("Authorized on @" + botInfo.username) From 1ee39f94b63e571bd9b37c9152699a239ed46d61 Mon Sep 17 00:00:00 2001 From: Andrea Date: Mon, 5 Nov 2018 14:44:40 +0100 Subject: [PATCH 68/89] Forces user to set nickname --- scienzati_bot.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/scienzati_bot.py b/scienzati_bot.py index 597eec1..590e25e 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -695,6 +695,12 @@ def start_user_registration(message): #The user needs to be created #bot.reply_to(message, "creazione nuovo record utente...") #Insert + if message.from_user.username == None or message.from_user.username == "": + markup = telebot.types.InlineKeyboardMarkup() + markup.row(telebot.types.InlineKeyboardButton("❌ Chiudi", callback_data="deleteDis")) + bot.reply_to(message, "Errore nella registrazione: è necessario avere un username.\nImposta un username e ritenta.", reply_markup=markup) + return + dbC = dbConnection.cursor() res = dbC.execute('INSERT INTO Users (ID, Nickname, Status) VALUES (?,?,?)', (message.from_user.id, message.from_user.username, UserStatus.ACTIVE,) ) dbConnection.commit() From 3c82d3d2d677fb67ad92b6bcfe74b76bc24c1d89 Mon Sep 17 00:00:00 2001 From: Andrea Date: Wed, 7 Nov 2018 22:32:11 +0100 Subject: [PATCH 69/89] Little bugfix --- scienzati_bot.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index 590e25e..68cf26d 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -114,7 +114,7 @@ class constResources: /revokelist """ - version = "α0.1.2.12 dev" + version = "α0.1.2.12 dev A" gdpr_message = "Raccogliamo il numero di messaggi, nickname, ID e ultima volta che l'utente ha scritto. Per richiedere l'eliminazione dei propri dati contattare un amministratore ed uscire dal gruppo" @@ -871,7 +871,7 @@ def subscribeUserListHandler(message): #If there are still lists, print the page delimiter #if len(lists) > Settings.subscriptionRows-1: rightButton = telebot.types.InlineKeyboardButton(" ", callback_data="ignore") - if AvailableListsToUser(message.from_user.id, limit=1, offset=int(Settings.subscriptionRows)) != False: + if AvailableListsToUser(message.from_user.id, limit=1, offset=int(Settings.subscriptionRows-1)) != False: # osub-{n} => offest subscription, needed for pagination, #Teels the offset to set to correctly display the pages rightButton = telebot.types.InlineKeyboardButton(f"➡️", callback_data=f"osub-"+str(Settings.subscriptionRows-1)) @@ -1105,14 +1105,16 @@ def genericMessageHandler(message): if message.chat.type == "private": SetUserBio(message.from_user.id,message.text) bot.reply_to(message, "✅ Biografia impostata con successo!") - bot.delete_message(message.chat.id , message.reply_to_message.message_id, reply_markup=markup) + if message.reply_to_message.message_id != None + bot.delete_message(message.chat.id , message.reply_to_message.message_id) #Tries to force the user to reply to the message #TODO: Not sure about the order - needs to be checked elif (message.chat.type == "group" or message.chat.type == "supergroup") and message.reply_to_message != None and message.reply_to_message.from_user.id == botInfo.id: SetUserBio(message.from_user.id,message.text) msg = bot.reply_to(message, "✅ Biografia impostata con successo!") - bot.delete_message(message.chat.id , message.reply_to_message.message_id, reply_markup=markup) + if message.reply_to_message.message_id != None + bot.delete_message(message.chat.id , message.reply_to_message.message_id) #Check for list elif user["Status"] == UserStatus.WAITING_FOR_LIST: From 567ce2527aec9275eb9457bcc5423a7866fb25fd Mon Sep 17 00:00:00 2001 From: Andrea Date: Wed, 7 Nov 2018 22:37:52 +0100 Subject: [PATCH 70/89] Updated help message --- scienzati_bot.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index 68cf26d..b3c8163 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -101,7 +101,13 @@ class constResources: /liste per scoprire le liste già presenti /gdpr consulta le norme sul GDPR /privs elenca i privilegi utente -/disiscrivi per cancellarti da una lista alla quale hai aderito, puoi usare pure: /esci, /rimuovi, /iscrizioni e /aderenze""" +/disiscrivi per cancellarti da una lista alla quale hai aderito, puoi usare pure: /esci, /rimuovi, /iscrizioni e /aderenze + +In caso di problemi invece, sei pregato di conttattare @Pandry, in quanto sviluppatore del bot. +Report di problemi, come ad esempio liste non presenti, bot non responsivo ecc sono assolutamente gradite; O anche solo per proporre qualche idea e conversarne a riguardo. +A tal proposito, esiste un gruppo dedicato ai programmi scritti in comune tra i membri di @Scienza. +Chiedi ad un amministratore per ulteriori informazioni a riguardo. +Buona continuazione su @Scienza""" admin_help = """Comandi admin... blabla /nuovalista From 514493da85343c7aa17d31fa00c8958da19be89c Mon Sep 17 00:00:00 2001 From: Andrea Date: Wed, 7 Nov 2018 22:42:30 +0100 Subject: [PATCH 71/89] Added intro message --- scienzati_bot.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/scienzati_bot.py b/scienzati_bot.py index b3c8163..9cf2788 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -109,6 +109,13 @@ class constResources: Chiedi ad un amministratore per ulteriori informazioni a riguardo. Buona continuazione su @Scienza""" + welcome_message = """Benvenuto/a 😊 +Presentati se ti va +Hai interessi particolari e vuoi essere avvisato quando se ne parla nel gruppo? Utilizza il nostro bot @scienzati_bot per iscriverti e registrarti nelle liste che ti interessano. +Al fine di non "intasare" la chat con messaggi da parte mia, sei inviatato ad avviarmi in privato. +In caso di dubbi, il comando /help o /aiuto sarà a tua disposizione. +Buona permanenza dallo staff di @Scienza😁""" + admin_help = """Comandi admin... blabla /nuovalista /rimuovilista From 26724c7a8a71ca1048a40e098be6fce6a3370f64 Mon Sep 17 00:00:00 2001 From: Andrea Date: Wed, 7 Nov 2018 22:59:21 +0100 Subject: [PATCH 72/89] Added on-join message and forgot colon on if condition --- scienzati_bot.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index 9cf2788..8201832 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -1101,6 +1101,12 @@ def commitDBhandler(message): markup.row(telebot.types.InlineKeyboardButton("❌ Chiudi", callback_data="deleteDis")) bot.reply_to(message, "✅ Done", reply_markup=markup ) +@bot.message_handler(content_types=['new_chat_member', 'new_chat_members']) +def welcomeMessage(message): + markup = telebot.types.InlineKeyboardMarkup() + markup.row(telebot.types.InlineKeyboardButton("❌ Chiudi", callback_data="deleteDis")) + bot.reply_to(message, constResources.welcome_message, reply_markup=markup ) + @bot.message_handler(func=lambda m: True) def genericMessageHandler(message): #get info about the user @@ -1118,7 +1124,7 @@ def genericMessageHandler(message): if message.chat.type == "private": SetUserBio(message.from_user.id,message.text) bot.reply_to(message, "✅ Biografia impostata con successo!") - if message.reply_to_message.message_id != None + if message.reply_to_message.message_id != None: bot.delete_message(message.chat.id , message.reply_to_message.message_id) #Tries to force the user to reply to the message @@ -1126,7 +1132,7 @@ def genericMessageHandler(message): elif (message.chat.type == "group" or message.chat.type == "supergroup") and message.reply_to_message != None and message.reply_to_message.from_user.id == botInfo.id: SetUserBio(message.from_user.id,message.text) msg = bot.reply_to(message, "✅ Biografia impostata con successo!") - if message.reply_to_message.message_id != None + if message.reply_to_message.message_id != None: bot.delete_message(message.chat.id , message.reply_to_message.message_id) #Check for list From 775ae42b9853c102215f8c54d95481d456e8beef Mon Sep 17 00:00:00 2001 From: Andrea Date: Wed, 7 Nov 2018 23:05:41 +0100 Subject: [PATCH 73/89] Added bio command --- scienzati_bot.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/scienzati_bot.py b/scienzati_bot.py index 8201832..f0bef1c 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -1101,6 +1101,25 @@ def commitDBhandler(message): markup.row(telebot.types.InlineKeyboardButton("❌ Chiudi", callback_data="deleteDis")) bot.reply_to(message, "✅ Done", reply_markup=markup ) +@bot.message_handler(commands=['bio']) +def getUserBio(message): + args = message.text.split(' ') + if len(args) == 2: + userNickname = args[1].replace('@', '') + userID = getUserId(userNickname) + if userID != False: + userBio = GetUserBio(userid) + markup = telebot.types.InlineKeyboardMarkup() + markup.row(telebot.types.InlineKeyboardButton("❌ Chiudi", callback_data="deleteDis")) + bot.reply_to(message, "La biografia dell'utente @" + userNickname + "è:\n"+userBio, reply_markup=markup ) + else: + markup = telebot.types.InlineKeyboardMarkup() + markup.row(telebot.types.InlineKeyboardButton("❌ Chiudi", callback_data="deleteDis")) + bot.reply_to(message, "L'utente non è stato trovato", reply_markup=markup ) + + + + @bot.message_handler(content_types=['new_chat_member', 'new_chat_members']) def welcomeMessage(message): markup = telebot.types.InlineKeyboardMarkup() From 6ef1b1218d1ab711ba0817bba9c66ce054390cd4 Mon Sep 17 00:00:00 2001 From: Andrea Date: Wed, 7 Nov 2018 23:06:09 +0100 Subject: [PATCH 74/89] Added bio alias and fixed wrong variable name --- scienzati_bot.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index f0bef1c..d53fde8 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -1101,14 +1101,14 @@ def commitDBhandler(message): markup.row(telebot.types.InlineKeyboardButton("❌ Chiudi", callback_data="deleteDis")) bot.reply_to(message, "✅ Done", reply_markup=markup ) -@bot.message_handler(commands=['bio']) +@bot.message_handler(commands=['bio', 'getbio', 'biografia']) def getUserBio(message): args = message.text.split(' ') if len(args) == 2: userNickname = args[1].replace('@', '') userID = getUserId(userNickname) if userID != False: - userBio = GetUserBio(userid) + userBio = GetUserBio(userID) markup = telebot.types.InlineKeyboardMarkup() markup.row(telebot.types.InlineKeyboardButton("❌ Chiudi", callback_data="deleteDis")) bot.reply_to(message, "La biografia dell'utente @" + userNickname + "è:\n"+userBio, reply_markup=markup ) From d1959461c3a31f30adfc579148ac5b9687917c1d Mon Sep 17 00:00:00 2001 From: Andrea Date: Wed, 7 Nov 2018 23:16:21 +0100 Subject: [PATCH 75/89] Made inline and bio commands available onmly to registred users. --- scienzati_bot.py | 61 +++++++++++++++++++++++++++--------------------- 1 file changed, 35 insertions(+), 26 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index d53fde8..18fd19b 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -1103,6 +1103,11 @@ def commitDBhandler(message): @bot.message_handler(commands=['bio', 'getbio', 'biografia']) def getUserBio(message): + requiringUser = GetUser(message.from_user.id) + if requiringUser == False: + markup = telebot.types.InlineKeyboardMarkup() + markup.row(telebot.types.InlineKeyboardButton("❌ Chiudi", callback_data="deleteDis")) + bot.reply_to(message, "Devi essere registrato per poter far uso per queste funzioni", reply_markup=markup ) args = message.text.split(' ') if len(args) == 2: userNickname = args[1].replace('@', '') @@ -1492,36 +1497,40 @@ def callback_query(call): @bot.inline_handler(func=lambda chosen_inline_result: True) def getUserBioInlineQuery(inline_query): - user = inline_query.query.lower().replace('@', '') + requiringUser = GetUser(inline_query.from_user.id) responses = [] - usersIDs = getUsersIdLike(user) - for userid in usersIDs: - userid = userid[0] - userNick = GetUserNickname(userid) - userBio = GetUserBio(userid) - if userBio != None: + if requiringUser == False: + responses = [telebot.types.InlineQueryResultArticle(1, "Devi essere registrato per poter far uso per queste funzioni.", telebot.types.InputTextMessageContent("Non sei autorizzato ad usare il bot."))] + else: + user = inline_query.query.lower().replace('@', '') + usersIDs = getUsersIdLike(user) + for userid in usersIDs: + userid = userid[0] + userNick = GetUserNickname(userid) + userBio = GetUserBio(userid) + if userBio != None: + responses.append( + telebot.types.InlineQueryResultArticle(len(responses)+1, userNick[0].upper() + userNick[1:] + "'s Bio: " + userBio, + telebot.types.InputTextMessageContent(userNick[0].upper() + userNick[1:] + "'s Biography is \"" +userBio + "\"")) + ) responses.append( - telebot.types.InlineQueryResultArticle(len(responses)+1, userNick[0].upper() + userNick[1:] + "'s Bio: " + userBio, - telebot.types.InputTextMessageContent(userNick[0].upper() + userNick[1:] + "'s Biography is \"" +userBio + "\"")) + telebot.types.InlineQueryResultArticle(len(responses)+1, userNick[0].upper() + userNick[1:] + "'s permissions", + telebot.types.InputTextMessageContent(getUserPermissionText(userid))) ) - responses.append( - telebot.types.InlineQueryResultArticle(len(responses)+1, userNick[0].upper() + userNick[1:] + "'s permissions", - telebot.types.InputTextMessageContent(getUserPermissionText(userid))) - ) - lists = SubscribedLists(userid, limit=None) - msg = userNick[0].upper() + userNick[1:] + " is not subscribed to any list yet! :c" - if lists != False: - msg = userNick[0].upper() + userNick[1:] + " is subscribed to those lists: \n" - for lst in lists: - msg = msg + "#" + lst["Name"] + ", " - msg = msg[:len(msg)-2] - - responses.append( - telebot.types.InlineQueryResultArticle(len(responses)+1, userNick[0].upper() + userNick[1:] + "'s lists", - telebot.types.InputTextMessageContent(msg)) - ) + lists = SubscribedLists(userid, limit=None) + msg = userNick[0].upper() + userNick[1:] + " is not subscribed to any list yet! :c" + if lists != False: + msg = userNick[0].upper() + userNick[1:] + " is subscribed to those lists: \n" + for lst in lists: + msg = msg + "#" + lst["Name"] + ", " + msg = msg[:len(msg)-2] - + responses.append( + telebot.types.InlineQueryResultArticle(len(responses)+1, userNick[0].upper() + userNick[1:] + "'s lists", + telebot.types.InputTextMessageContent(msg)) + ) + + bot.answer_inline_query(inline_query.id, responses) # Query message is text From 5ef672e1cc6192acc543bb6d7e573129d86e92a5 Mon Sep 17 00:00:00 2001 From: Andrea Date: Wed, 7 Nov 2018 23:21:56 +0100 Subject: [PATCH 76/89] Translated user messages to italian --- scienzati_bot.py | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index 18fd19b..de7d953 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -762,7 +762,7 @@ def setBio(message): dbConnection.commit() else: #Nothing to do here - msg = bot.reply_to(message, "You can't enter a bio.") + msg = bot.reply_to(message, "Non puoi inrerire una biografia.") #Creazione di una nuova lista @@ -775,7 +775,7 @@ def newList(message): #Check if the user exists if user == False: #the user does not exist - bot.reply_to(message, "Something's wrong here. error code: #Q534") + bot.reply_to(message, "Oh no! Qualcosa è andato storto. Codice di errore: #Q534") else: res = setNewUserStatus(message.from_user.id,UserStatus.WAITING_FOR_LIST ) markup = telebot.types.InlineKeyboardMarkup() @@ -784,7 +784,7 @@ def newList(message): msg = bot.reply_to(message, "Per creare una nuova lista, scrivi il nome in chat privata o in un messaggio che mi risponda rispondendomi", reply_markup=markup) dbConnection.commit() else: - bot.reply_to(message, "Error 403 - ❌ Unauthorized") + bot.reply_to(message, "❌ Errore 403 - Permessi insufficienti per eseguire l'azione") #Creazione di una nuova lista @bot.message_handler(commands=['deletelist', 'removelist', 'rimuovilista', 'eliminalista']) @@ -796,14 +796,14 @@ def deleteListHandler(message): #Check if the user exists if user == False: #the user does not exist - msg = bot.reply_to(message, "Something's wrong here. error code: #J258") + msg = bot.reply_to(message, "Oh no! Qualcosa è andato storto. Codice di errore: #J258") else: #Asks for the bio #need to send message with a list liste = GetLists() markup = telebot.types.InlineKeyboardMarkup() #Print the lists as inline buttons - msg = "Random message padding" + msg = "Ecco le liste esistenti al momento:" if liste == False:#TODO test msg = "Al momento non è presente nessuna lista.\nSi prega di riprovare in seguito." else: @@ -819,7 +819,7 @@ def deleteListHandler(message): #SubscribeUserToList() else: - msg = bot.reply_to(message, "Error 403 - ❌ Unauthorized") + msg = bot.reply_to(message, "❌ Errore 403 - Permessi insufficienti per eseguire l'azione") @bot.message_handler(commands=['del', 'delete']) def deleteBotMessage(message): @@ -895,7 +895,7 @@ def subscribeUserListHandler(message): elif UserStatus.IsBanned(userStatus): #banned, not much you can do right now - bot.reply_to(message, "Error 403 - ❌ Unauthorized") + bot.reply_to(message, "❌ Errore 403 - Permessi insufficienti per eseguire l'azione") else: #User in another activity (like creating list) bot.reply_to(message, "Sembra che tu sia occupato in un'altra azione (come impostare una biografia).\n Sarebbe opportuno terminare quell'azione prima di cercare di intraprenderne altre") @@ -936,7 +936,7 @@ def unsubscribeUserListHandler(message): elif UserStatus.IsBanned(userStatus): #banned, not much you can do right now - bot.reply_to(message, "Error 403 - ❌ Unauthorized") + bot.reply_to(message, "❌ Errore 403 - Permessi insufficienti per eseguire l'azione") else: #User in another activity (like creating list) bot.reply_to(message, "Sembra che tu sia occupato in un'altra azione (come impostare una biografia).\n Sarebbe opportuno terminare quell'azione prima di cercare di intraprenderne altre") @@ -971,7 +971,7 @@ def setAdminPermissionHandler(message): else: bot.reply_to(message, "❌ Utilizzo: /setadmin {@}username") return - bot.reply_to(message, "❌ Error 403 - Unauthorized") + bot.reply_to(message, "❌ Errore 403 - Permessi insufficienti per eseguire l'azione") @bot.message_handler(commands=['unsetadmin', 'removeadmin']) def unsetAdminPermissionHandler(message): @@ -1003,7 +1003,7 @@ def unsetAdminPermissionHandler(message): else: bot.reply_to(message, "❌ Utilizzo: /removeadmin {@}username") return - bot.reply_to(message, "❌ Error 403 - Unauthorized") + bot.reply_to(message, "❌ Errore 403 - Permessi insufficienti per eseguire l'azione") @bot.message_handler(commands=['grantlist']) @@ -1033,7 +1033,7 @@ def grantListCreationPermissionHandler(message): else: bot.reply_to(message, "❌ Utilizzo: /grantlist {@}username") return - bot.reply_to(message, "❌ Error 403 - Unauthorized") + bot.reply_to(message, "❌ Errore 403 - Permessi insufficienti per eseguire l'azione") @bot.message_handler(commands=['revokelist']) def revokeListCreationPermissionHandler(message): @@ -1066,7 +1066,7 @@ def revokeListCreationPermissionHandler(message): else: bot.reply_to(message, "❌ Utilizzo: /revokelist {@}username") return - bot.reply_to(message, "❌ Error 403 - Unauthorized") + bot.reply_to(message, "❌ Errore 403 - Permessi insufficienti per eseguire l'azione") @bot.message_handler(commands=['ping']) @@ -1518,15 +1518,15 @@ def getUserBioInlineQuery(inline_query): telebot.types.InputTextMessageContent(getUserPermissionText(userid))) ) lists = SubscribedLists(userid, limit=None) - msg = userNick[0].upper() + userNick[1:] + " is not subscribed to any list yet! :c" + msg = userNick[0].upper() + userNick[1:] + " non è ancora iscritto a nessuna lista! :c" if lists != False: - msg = userNick[0].upper() + userNick[1:] + " is subscribed to those lists: \n" + msg = userNick[0].upper() + userNick[1:] + " è iscritto a queste liste: \n" for lst in lists: msg = msg + "#" + lst["Name"] + ", " msg = msg[:len(msg)-2] responses.append( - telebot.types.InlineQueryResultArticle(len(responses)+1, userNick[0].upper() + userNick[1:] + "'s lists", + telebot.types.InlineQueryResultArticle(len(responses)+1, "Ecco le liste a cui è iscritto @" + userNick[0].upper() + userNick[1:], telebot.types.InputTextMessageContent(msg)) ) From a075cc471b4e5d42b7ba5c63435a35a1b9137d38 Mon Sep 17 00:00:00 2001 From: Andrea Date: Wed, 7 Nov 2018 23:30:43 +0100 Subject: [PATCH 77/89] Different sign for completelist to indicate all users excapt last one --- scienzati_bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index de7d953..20f985a 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -855,7 +855,7 @@ def completeLists(message): users = GetListSubscribers(list["ID"] ) if users != False: for user in users[:-1]: - msg = msg + "║" + " " + GetUserNickname(user[0]) + "\n" + msg = msg + "╠" + " " + GetUserNickname(user[0]) + "\n" msg = msg + "╚" + " " + GetUserNickname(users[len(users)-1][0]) + "\n" msg = msg + "\n" if len(liste) == 0: From a3fe83629c93358f877e9fcdc74a1d4ad7141003 Mon Sep 17 00:00:00 2001 From: Andrea Date: Wed, 7 Nov 2018 23:37:32 +0100 Subject: [PATCH 78/89] Imoproved subscribed lists format --- scienzati_bot.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index 20f985a..4a23b0c 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -1521,9 +1521,9 @@ def getUserBioInlineQuery(inline_query): msg = userNick[0].upper() + userNick[1:] + " non è ancora iscritto a nessuna lista! :c" if lists != False: msg = userNick[0].upper() + userNick[1:] + " è iscritto a queste liste: \n" - for lst in lists: - msg = msg + "#" + lst["Name"] + ", " - msg = msg[:len(msg)-2] + for lst in lists[:-1]: + msg = msg + "╠" + " " + lst["Name"] + "\n" + msg = msg + "╚" + " " + lists[len(lists)-1]["Name"] responses.append( telebot.types.InlineQueryResultArticle(len(responses)+1, "Ecco le liste a cui è iscritto @" + userNick[0].upper() + userNick[1:], From 6895a4589c83ab98f85e072f64129e1cd239c19a Mon Sep 17 00:00:00 2001 From: Andrea Date: Wed, 7 Nov 2018 23:42:02 +0100 Subject: [PATCH 79/89] Translated inline results --- scienzati_bot.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index 4a23b0c..e911c4e 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -1510,11 +1510,11 @@ def getUserBioInlineQuery(inline_query): userBio = GetUserBio(userid) if userBio != None: responses.append( - telebot.types.InlineQueryResultArticle(len(responses)+1, userNick[0].upper() + userNick[1:] + "'s Bio: " + userBio, - telebot.types.InputTextMessageContent(userNick[0].upper() + userNick[1:] + "'s Biography is \"" +userBio + "\"")) + telebot.types.InlineQueryResultArticle(len(responses)+1, "Biografia di @" + userNick[0].upper() + userNick[1:], + telebot.types.InputTextMessageContent("Questa è la biografia di @" + userNick[0].upper() + userNick[1:] + ":\n" + userBio)) ) responses.append( - telebot.types.InlineQueryResultArticle(len(responses)+1, userNick[0].upper() + userNick[1:] + "'s permissions", + telebot.types.InlineQueryResultArticle(len(responses)+1, "Permessi di @" + userNick[0].upper() + userNick[1:], telebot.types.InputTextMessageContent(getUserPermissionText(userid))) ) lists = SubscribedLists(userid, limit=None) From 3fe57d4739e5f1dbce7079fb5ca4552772618fb6 Mon Sep 17 00:00:00 2001 From: Andrea Date: Wed, 7 Nov 2018 23:45:53 +0100 Subject: [PATCH 80/89] Improved help message --- scienzati_bot.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index e911c4e..54f00f6 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -110,11 +110,12 @@ class constResources: Buona continuazione su @Scienza""" welcome_message = """Benvenuto/a 😊 -Presentati se ti va -Hai interessi particolari e vuoi essere avvisato quando se ne parla nel gruppo? Utilizza il nostro bot @scienzati_bot per iscriverti e registrarti nelle liste che ti interessano. -Al fine di non "intasare" la chat con messaggi da parte mia, sei inviatato ad avviarmi in privato. +Presentati se ti va (se possibile evidenzia le tue passioni scientifiche e/o i tuoi studi), ci farebbe piacere ☺️. + +Hai interessi particolari e vuoi essere avvisato quando se ne parla nel gruppo? Utilizza il nostro bot @scienzati_bot per iscriverti e registrarti nelle liste che ti interessano! +Al fine di non "intasare" la chat con messaggi da parte mia, sei inviatata/o ad avviarmi in privato. In caso di dubbi, il comando /help o /aiuto sarà a tua disposizione. -Buona permanenza dallo staff di @Scienza😁""" +Buona permanenza dallo staff di @Scienza 😁""" admin_help = """Comandi admin... blabla /nuovalista From bb94c5b547551c2d5bc9069c063c6064457b27a2 Mon Sep 17 00:00:00 2001 From: Andrea Date: Wed, 7 Nov 2018 23:46:13 +0100 Subject: [PATCH 81/89] Added help aliases --- scienzati_bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index 54f00f6..d230da5 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -645,7 +645,7 @@ def getUserPermissionText(userid): #Start command. # This is the function called when the bot is started or the help commands are sent -@bot.message_handler(commands=['start', 'help']) +@bot.message_handler(commands=['start', 'help', 'aiuto']) def send_welcome(message): markup = telebot.types.InlineKeyboardMarkup() markup.row(telebot.types.InlineKeyboardButton("❌ Chiudi", callback_data="deleteDis")) From 856614fe57ec0c53fd50132ad34a76910b32d942 Mon Sep 17 00:00:00 2001 From: Andrea Date: Wed, 7 Nov 2018 23:52:20 +0100 Subject: [PATCH 82/89] Added help message --- scienzati_bot.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/scienzati_bot.py b/scienzati_bot.py index d230da5..5a7345e 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -117,6 +117,18 @@ class constResources: In caso di dubbi, il comando /help o /aiuto sarà a tua disposizione. Buona permanenza dallo staff di @Scienza 😁""" + info_message = """Ciao! +Questo è il bot del gruppo @Scienza! +Questo bot è stato sviluppato da alcuni membri del gruppo @Scienza (@AndreaIdini, @Pandry) con lo scopo di agevolare la richiesta di persone competenti in un determinato campo con lo scopo di soddisfare le domande poste nel gruppo. +Il bot è OSS (Open Source Software) ed è possibile trovare il codice sorgente a questo indirizzo: + +https://github.com/Scienza/scienziati_bot + +La persona che al momento si occupa dello sviluppo attivo del bot e si occupa di mantenerlo operativo è @Pandry. +Puoi contattarlo in privato per qualunque questione, tuttavia ti chiedo di contattarlo in caso di questioni riguardati problemi con me o nel caso tu voglia qualche funzionalità aggiuntiva ad esempio. + + """ + admin_help = """Comandi admin... blabla /nuovalista /rimuovilista @@ -651,6 +663,12 @@ def send_welcome(message): markup.row(telebot.types.InlineKeyboardButton("❌ Chiudi", callback_data="deleteDis")) bot.reply_to(message, constResources.intro_mex, reply_markup=markup) +@bot.message_handler(commands=['info', 'informazioni', 'about']) +def send_welcome(message): + markup = telebot.types.InlineKeyboardMarkup() + markup.row(telebot.types.InlineKeyboardButton("❌ Chiudi", callback_data="deleteDis")) + bot.reply_to(message, constResources.intro_mex, reply_markup=markup) + @bot.message_handler(commands=['adminhelp']) def send_admhelp(message): markup = telebot.types.InlineKeyboardMarkup() From 3d4fcf5ce0d3fe7ec610f8e808d1968e615e730c Mon Sep 17 00:00:00 2001 From: Andrea Date: Wed, 7 Nov 2018 23:56:58 +0100 Subject: [PATCH 83/89] Added commands to help and resolved bio command aliases conflict --- scienzati_bot.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index 5a7345e..abed45d 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -100,9 +100,12 @@ class constResources: /bio per scrivere qualcosa su di te /liste per scoprire le liste già presenti /gdpr consulta le norme sul GDPR -/privs elenca i privilegi utente +/privs elenca i privilegi di un utente (richiesto come argomento) +/biografia mostra la biografia di un utente (richiesto come argomento) /disiscrivi per cancellarti da una lista alla quale hai aderito, puoi usare pure: /esci, /rimuovi, /iscrizioni e /aderenze +Puoi anche usare il bot in modalità "inline": sarà sufficiente scrivere @scienziati_bot per avere informazioni riguardo l'utente + In caso di problemi invece, sei pregato di conttattare @Pandry, in quanto sviluppatore del bot. Report di problemi, come ad esempio liste non presenti, bot non responsivo ecc sono assolutamente gradite; O anche solo per proporre qualche idea e conversarne a riguardo. A tal proposito, esiste un gruppo dedicato ai programmi scritti in comune tra i membri di @Scienza. @@ -752,7 +755,7 @@ def infohandler(message): if message.reply_to_message != None: msg = bot.reply_to(message, "ID " + str(message.reply_to_message.message_id)) ### Aggioramento/ impostaizone bio -@bot.message_handler(commands=['bio', 'setbio']) +@bot.message_handler(commands=['bio', 'setbio', 'impostabio', 'impostabiografia']) def setBio(message): if not message.from_user.is_bot and message.text != "" : # Gets info about the user @@ -1120,7 +1123,7 @@ def commitDBhandler(message): markup.row(telebot.types.InlineKeyboardButton("❌ Chiudi", callback_data="deleteDis")) bot.reply_to(message, "✅ Done", reply_markup=markup ) -@bot.message_handler(commands=['bio', 'getbio', 'biografia']) +@bot.message_handler(commands=['getbio', 'biografia']) def getUserBio(message): requiringUser = GetUser(message.from_user.id) if requiringUser == False: From a9e8de13248b273c98f3dcabb96e729db8f68fb9 Mon Sep 17 00:00:00 2001 From: Andrea Date: Wed, 7 Nov 2018 23:58:47 +0100 Subject: [PATCH 84/89] Returning correct message on /info command and fixed method name conflict --- scienzati_bot.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index abed45d..2263566 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -667,10 +667,10 @@ def send_welcome(message): bot.reply_to(message, constResources.intro_mex, reply_markup=markup) @bot.message_handler(commands=['info', 'informazioni', 'about']) -def send_welcome(message): +def send_info(message): markup = telebot.types.InlineKeyboardMarkup() markup.row(telebot.types.InlineKeyboardButton("❌ Chiudi", callback_data="deleteDis")) - bot.reply_to(message, constResources.intro_mex, reply_markup=markup) + bot.reply_to(message, constResources.info_message, reply_markup=markup) @bot.message_handler(commands=['adminhelp']) def send_admhelp(message): From 820a50c28874356e9f846653035b06116b640e77 Mon Sep 17 00:00:00 2001 From: Andrea Date: Thu, 8 Nov 2018 00:01:01 +0100 Subject: [PATCH 85/89] Improved info message --- scienzati_bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index 2263566..6c9881f 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -122,7 +122,7 @@ class constResources: info_message = """Ciao! Questo è il bot del gruppo @Scienza! -Questo bot è stato sviluppato da alcuni membri del gruppo @Scienza (@AndreaIdini, @Pandry) con lo scopo di agevolare la richiesta di persone competenti in un determinato campo con lo scopo di soddisfare le domande poste nel gruppo. +Questo bot è stato sviluppato da alcuni membri del gruppo @Scienza (@AndreaIdini, @Pandry) con lo scopo di agevolare l'intervento di persone competenti in un determinato campo e richiedere il loro aiuto riguardo le questioni e le domande poste nel gruppo. Il bot è OSS (Open Source Software) ed è possibile trovare il codice sorgente a questo indirizzo: https://github.com/Scienza/scienziati_bot From b83cce0922e9ed1411e2e3c1172bd38ff7cd96ae Mon Sep 17 00:00:00 2001 From: Andrea Date: Thu, 8 Nov 2018 00:01:38 +0100 Subject: [PATCH 86/89] Version bump --- scienzati_bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index 6c9881f..200c030 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -143,7 +143,7 @@ class constResources: /revokelist """ - version = "α0.1.2.12 dev A" + version = "α0.1.2.14" gdpr_message = "Raccogliamo il numero di messaggi, nickname, ID e ultima volta che l'utente ha scritto. Per richiedere l'eliminazione dei propri dati contattare un amministratore ed uscire dal gruppo" From 9f0cba5247048840d960419d0c999ba8a59354a3 Mon Sep 17 00:00:00 2001 From: Andrea Date: Thu, 8 Nov 2018 00:03:26 +0100 Subject: [PATCH 87/89] Added info command to help message text --- scienzati_bot.py | 1 + 1 file changed, 1 insertion(+) diff --git a/scienzati_bot.py b/scienzati_bot.py index 200c030..1452619 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -103,6 +103,7 @@ class constResources: /privs elenca i privilegi di un utente (richiesto come argomento) /biografia mostra la biografia di un utente (richiesto come argomento) /disiscrivi per cancellarti da una lista alla quale hai aderito, puoi usare pure: /esci, /rimuovi, /iscrizioni e /aderenze +/info Ottieni informazioni su di me Puoi anche usare il bot in modalità "inline": sarà sufficiente scrivere @scienziati_bot per avere informazioni riguardo l'utente From f9c3e97b6dd46094ab2dd67060692ca11f2caddc Mon Sep 17 00:00:00 2001 From: Andrea Date: Wed, 14 Nov 2018 21:36:56 +0100 Subject: [PATCH 88/89] Added welcome message only on IT group --- scienzati_bot.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/scienzati_bot.py b/scienzati_bot.py index 1452619..728cc1a 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -1150,9 +1150,10 @@ def getUserBio(message): @bot.message_handler(content_types=['new_chat_member', 'new_chat_members']) def welcomeMessage(message): - markup = telebot.types.InlineKeyboardMarkup() - markup.row(telebot.types.InlineKeyboardButton("❌ Chiudi", callback_data="deleteDis")) - bot.reply_to(message, constResources.welcome_message, reply_markup=markup ) + if message.chat.id == Settings.ITGroup: + markup = telebot.types.InlineKeyboardMarkup() + markup.row(telebot.types.InlineKeyboardButton("❌ Chiudi", callback_data="deleteDis")) + bot.reply_to(message, constResources.welcome_message, reply_markup=markup ) @bot.message_handler(func=lambda m: True) def genericMessageHandler(message): From 8b3562a412e017a6debc7eb30d8657ff070ec85b Mon Sep 17 00:00:00 2001 From: Andrea Date: Fri, 7 Dec 2018 15:22:29 +0100 Subject: [PATCH 89/89] =?UTF-8?q?Sei=20pi=C3=B9=20felice=20ora=20Behz=3F?= =?UTF-8?q?=20:P?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- database.sqlitedb-journal | Bin 4616 -> 0 bytes scienzati_bot.py | 2 +- 2 files changed, 1 insertion(+), 1 deletion(-) delete mode 100644 database.sqlitedb-journal diff --git a/database.sqlitedb-journal b/database.sqlitedb-journal deleted file mode 100644 index 89bd3cd02780ab92b73e7ad8973233fb3f124bc7..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 4616 zcmZQzK!A9$om+rBb_NC}ASHm17-bFT5Mbg3`i_zR0s|0@g3%Bd4S~@R7!85Z5Eu=C z(GVC7fzc2c4S~@R7!85Z5Eu=CArb=GZFl-KIT`p>896u@jSYkI^YRsnON#RIs`CG_ a8W|W`=o%X68XGDY8Cw|{S{WLF#(e<)T@oz- diff --git a/scienzati_bot.py b/scienzati_bot.py index 728cc1a..a02537d 100644 --- a/scienzati_bot.py +++ b/scienzati_bot.py @@ -117,7 +117,7 @@ class constResources: Presentati se ti va (se possibile evidenzia le tue passioni scientifiche e/o i tuoi studi), ci farebbe piacere ☺️. Hai interessi particolari e vuoi essere avvisato quando se ne parla nel gruppo? Utilizza il nostro bot @scienzati_bot per iscriverti e registrarti nelle liste che ti interessano! -Al fine di non "intasare" la chat con messaggi da parte mia, sei inviatata/o ad avviarmi in privato. +Al fine di non "intasare" la chat con messaggi da parte mia, sei invitata/o ad avviarmi in privato. In caso di dubbi, il comando /help o /aiuto sarà a tua disposizione. Buona permanenza dallo staff di @Scienza 😁"""