Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

First functional beta #9

Open
wants to merge 86 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
86 commits
Select commit Hold shift + click to select a range
3cefe69
Configparser library added; now the config.ini file contains the conf…
JaviBF92 Nov 14, 2016
5cf614c
Added to DB new tables and initialization for future permission roles
JaviBF92 Nov 15, 2016
d3da1a9
Code modularization. Now repository.py will contain the DataBase func…
JaviBF92 Nov 18, 2016
dddc7fb
Name of function add_to changed; wrong module import changed
JaviBF92 Nov 20, 2016
0d9f067
Function empty_event edited to accept date as an optional parameter
JaviBF92 Nov 23, 2016
1ef2ec3
Modularized code to messaging & ancillary_methods
ManuelLR Nov 24, 2016
909dc63
Added permission check to execute messages
ManuelLR Nov 24, 2016
1e33e62
Permissions group handling (list, create and help)
ManuelLR Nov 24, 2016
74fab26
Added class conversation_session
ManuelLR Nov 25, 2016
408dd85
periodicCheck now uses empty_event function
JaviBF92 Dec 1, 2016
f0972c0
Merge branch 'Develop' of https://github.com/SUGUS-GNULinux/SugusBot …
JaviBF92 Dec 1, 2016
ac09e7c
periodicCheck function fixed
JaviBF92 Dec 2, 2016
c08424d
log file edition fixed
JaviBF92 Dec 2, 2016
fe60717
Addition of spaces and some names changed
JaviBF92 Dec 2, 2016
3e93bf8
Function add_user_permission added to repository.py; changes in datab…
JaviBF92 Dec 2, 2016
e14dde2
Events commands added & optimizations in sugusbot.py
JaviBF92 Dec 2, 2016
128afc7
auxiliar function show_list simplified
JaviBF92 Dec 12, 2016
176d909
Deprecated emojis changed for emoji library
JaviBF92 Dec 14, 2016
9eb4293
emoji library added to requirements
JaviBF92 Dec 14, 2016
968289f
Added ban users with no username to be added to a list (Solved issue #2)
ManuelLR Dec 16, 2016
bc4eac7
added to show_list function one-value list treatment
JaviBF92 Dec 17, 2016
9ef5a04
Parameters of some show_list callings changed (issue #6 fixed)
JaviBF92 Dec 17, 2016
376ba86
Added rel_user_event
ManuelLR Dec 17, 2016
c8aa08f
Merge branch 'Develop'
ManuelLR Dec 17, 2016
97b1513
Improve show_list
ManuelLR Dec 17, 2016
fee0d91
Update remove_from_event
ManuelLR Dec 17, 2016
78b01ef
Empty_event & periodic_check updated
ManuelLR Dec 17, 2016
e18e24f
Added Auto update user data
ManuelLR Dec 17, 2016
66dfa9d
Merge pull request #7 from SUGUS-GNULinux/rel_user_event
JaviBF92 Dec 22, 2016
4de732e
Some fixes included
JaviBF92 Jan 7, 2017
fc11170
Functions for delete and create events added; some warning messages c…
JaviBF92 Jan 13, 2017
47a7662
Writing permissions in log modified
JaviBF92 Jan 25, 2017
017f6e0
URL change
ManuelLR Feb 8, 2017
0a7752e
Function /addevent
ManuelLR Feb 8, 2017
df50253
Function /addtogroup
ManuelLR Feb 8, 2017
edd6670
Now check_type_and_text_start support multiple perm_required
ManuelLR Feb 8, 2017
d7c8918
check_date only permit future event
ManuelLR Feb 8, 2017
71d6bf2
Merge branch 'master' into Develop
ManuelLR Feb 8, 2017
da3b2fe
Merge remote-tracking branch 'origin/master' into Develop
ManuelLR Feb 8, 2017
e8e1cf2
Add emoji package
robertohueso Feb 10, 2017
23aa1e1
Improve check_user_permission
JaviBF92 Feb 12, 2017
7a48e44
Addition of remove_from_group
JaviBF92 Feb 13, 2017
25c059c
Import changes
JaviBF92 Feb 14, 2017
089ceeb
Log writing permission fixed
JaviBF92 Feb 14, 2017
c12a4de
Changes in commands
JaviBF92 Feb 14, 2017
bb47afc
Import changes
JaviBF92 Feb 15, 2017
66835bb
Addition of delfromgroup command
JaviBF92 Feb 15, 2017
d6e7692
Addition of delfromgroup command
JaviBF92 Feb 15, 2017
1cf3650
addevent command permissions
JaviBF92 Feb 23, 2017
ca4bf54
addition of removeevent command
JaviBF92 Feb 23, 2017
f8552ec
fixes in addevent command
JaviBF92 Feb 23, 2017
4c02fbb
Changes in removeevent command
JaviBF92 Feb 23, 2017
a66d90c
auxilliary_methods function check_date improved
JaviBF92 Feb 23, 2017
b513d0b
Redundant code deleted
JaviBF92 Feb 23, 2017
3c2df8c
Changes in events command
JaviBF92 Feb 23, 2017
ec2b7b8
Changes in /addevent message
JaviBF92 Feb 23, 2017
281d07b
Log messages improved
JaviBF92 Feb 28, 2017
e21f2ec
Capturando error al obtener usuarios
ManuelLR May 15, 2017
ddb3790
Debug no se vacia comida automáticamente
ManuelLR May 19, 2017
c6fea05
Capturando más detalladamente los errores del archivo
ManuelLR May 19, 2017
ad67695
Posible Fix autoborrado evento comida
ManuelLR May 19, 2017
360bfaa
Changed detach call
robgc Jun 30, 2017
e8b9f4a
Removed detach call for testing
robgc Jun 30, 2017
296e181
Commented out buggy print
robgc Jun 30, 2017
3e2c2cd
Modified prints
robgc Jun 30, 2017
8f846bb
Added editor folders to gitignore
robgc Jul 4, 2017
f43cda2
Print functions removed in main
robgc Jul 4, 2017
a24b1f8
New main loop using library DRY extension
robgc Jul 4, 2017
5604dfc
Fixed SQLite thread error and others
robgc Jul 16, 2017
b1048b7
Modified import of repository module
robgc Jul 25, 2017
57eb690
Improved imports in handlers module
robgc Jul 25, 2017
b6f5855
Improves gitignore
robertohueso Oct 3, 2017
1f5429a
Add comida inline buttons
robertohueso Oct 3, 2017
9e0b528
Implement quien_come
robertohueso Oct 4, 2017
04e9c83
Replace sugusbot.py
robertohueso Oct 5, 2017
46f0c38
Implement no_como
robertohueso Oct 5, 2017
37de759
Implement help
robertohueso Oct 5, 2017
1439d46
Create config_sample.ini
robertohueso Oct 5, 2017
9e45ffe
Implement join_to_event
robertohueso Oct 6, 2017
1cffef0
Implement leave_event
robertohueso Oct 6, 2017
5eb963a
Implement participants
robertohueso Oct 7, 2017
9807558
Implement remove_event
robertohueso Oct 7, 2017
c4e919a
Add new user when /start
robertohueso Oct 7, 2017
a1cbaba
Multiple improves
ManuelLR Nov 22, 2017
2d5a528
Adding auto-clean comida event every day
ManuelLR Nov 22, 2017
febcda6
Fix como and join_to_event
rarellano Dec 13, 2017
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
193 changes: 192 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,195 @@
token
config.ini
log
*.pyc
*.db
.idea
.vscode

# Created by https://www.gitignore.io/api/linux,emacs,python

### Emacs ###
# -*- mode: gitignore; -*-
*~
\#*\#
/.emacs.desktop
/.emacs.desktop.lock
*.elc
auto-save-list
tramp
.\#*

# Org-mode
.org-id-locations
*_archive

# flymake-mode
*_flymake.*

# eshell files
/eshell/history
/eshell/lastdir

# elpa packages
/elpa/

# reftex files
*.rel

# AUCTeX auto folder
/auto/

# cask packages
.cask/
dist/

# Flycheck
flycheck_*.el

# server auth directory
/server/

# projectiles files
.projectile
projectile-bookmarks.eld

# directory configuration
.dir-locals.el

# saveplace
places

# url cache
url/cache/

# cedet
ede-projects.el

# smex
smex-items

# company-statistics
company-statistics-cache.el

# anaconda-mode
anaconda-mode/

### Linux ###

# temporary files which can be created if a process still has a handle open of a deleted file
.fuse_hidden*

# KDE directory preferences
.directory

# Linux trash folder which might appear on any partition or disk
.Trash-*

# .nfs files are created when an open file is removed but is still being accessed
.nfs*

### Python ###
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
target/

# Jupyter Notebook
.ipynb_checkpoints

# pyenv
.python-version

# celery beat schedule file
celerybeat-schedule

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/

bin/
include/
pip-selfcheck.json

2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@ Es necesario tener el archivo "token" para enviar mensajes con el bot.
Es necesario instalar la librería [python-telegram-bot](https://github.com/leandrotoledo/python-telegram-bot), junto con algunos paquetes adicionales:

# apt-get install python-libxml2
# pip install python-telegram-bot pyquery cssselect lxml
# pip install python-telegram-bot pyquery cssselect lxml emoji
112 changes: 112 additions & 0 deletions auxilliary_methods.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
#!/usr/bin/python3.5
# -*- coding: utf-8 -*-

from urllib.request import urlopen
from pyquery import PyQuery
import telegram
from repository import find_user_by_telegram_user_id, check_user_permission
from emoji import emojize
from datetime import datetime
import time
import schedule
import threading


def get_who():

while True:
try:
url = 'https://sugus.eii.us.es/en_sugus.html'
#html = AssertionErrorurlopen(url).read()
html = urlopen(url).read()
pq = PyQuery(html)
break
except:
raise

ul = pq('ul.usuarios > li')
who = [w.text() for w in ul.items() if w.text() != "Parece que no hay nadie."]

return who


def check_type_and_text_start(aText = None,
aUName = None,
cText = None,
aType = None,
cType = None,
cUId = None,
perm_required=None):
# Si perm_required es None y cUId no es None entonces se busca que el usuario esté en cualquier grupo

result = True

if cType is not None:
result = aType == cType
if cUId is not None:
if perm_required is None: # Comprobar solo usuario y permiso
result = result and find_user_by_telegram_user_id(cUId)
else: # Comprobar usuario y permisos
for a in perm_required:
if check_user_permission(cUId, a):
result = result and True
if cText is not None:
result = result and aText.startswith(cText)

return result

def check_permissions(user_id, required_perm):
return all([check_user_permission(user_id, perm) for perm in required_perm])

def show_list(header, contains, positions = None):

result = [header + "\n"]

if contains:
if positions:
for a in contains:
a_ordered = [str(a[i]) for i in positions]
result.append("{} {}\n".format(emojize(":small_blue_diamond:", use_aliases=True), " ".join(a_ordered)))
else:
if isinstance(contains[0], str):
rows = ["{} {}\n".format(emojize(":small_blue_diamond:", use_aliases=True) ,a) for a in contains]
else:
rows = ["{} {}\n".format(emojize(":small_blue_diamond:", use_aliases=True) ," ".join(a)) for a in contains]
result += rows

return "".join(result)


def check_date(date):
res = True

try:
if datetime.strptime(date, '%d-%m-%Y').date() < datetime.today().date():
res = False
except ValueError:
res = False
return res

def extract_user_from_update(update):
try:
user = update.callback_query.from_user
except AttributeError:
user = update.message.from_user

return user


def init_scheduler():
cease_continuous_run = threading.Event()

class ScheduleThread(threading.Thread):
@classmethod
def run(cls):
while not cease_continuous_run.is_set():
schedule.run_pending()
time.sleep(1)

continuous_thread = ScheduleThread()
continuous_thread.start()

return cease_continuous_run
5 changes: 5 additions & 0 deletions config_sample.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
[Database]
route = sugusBotDB.db
[Telegram]
token = XXXX
id_admin = XXXX
67 changes: 67 additions & 0 deletions conversation_session.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
#!/usr/bin/python3.5
# -*- coding: utf-8 -*-


class conversation_session():
def __init__(self):
self.__inConversation = {}

@staticmethod
def __g_key(act_user, conversation_id=None):
# Generate the key based on actUser and conversationId
if conversation_id is None:
conversation_id = act_user.id

return str(act_user.id) + "-" + str(conversation_id)

def __add(self, key, options):
self.__inConversation[key] = options

def add_option(self, act_user, option, value, conversation_id=None):
"""Añade el par de valores (option, value) para el usuario"""
key = self.__g_key(act_user, conversation_id)
if not self.get(act_user):
self.__inConversation[key] = {option: value}
else:
self.__inConversation[key][option] = value

def del_option(self, act_user, option, conversation_id=None):
"""Elimina la opción 'option' del usuario"""
key = self.__g_key(act_user, conversation_id)
del self.__inConversation[key][option]

def empty(self, act_user, conversation_id=None):
"""Elimina todas las opciones para el usuario"""
key = self.__g_key(act_user, conversation_id)
del self.__inConversation[key]

def get(self, act_user, conversation_id=None):
"""Devuelve todas las opciones del usuario"""
key = self.__g_key(act_user, conversation_id)
try:
result = self.__inConversation[key]
except KeyError as error:
result = []
pass
return result

def contain_option(self, act_user, option, conversation_id=None, c_opt_value=None):
"""Comprueba si existe la opción 'option' para el usuario"""
options = self.get(act_user, conversation_id)
if option in options:
if c_opt_value == options[option]:
return True
elif c_opt_value == None:
return True
else:
return False
else:
return False

def status(self, act_user, conversation_id=None):
"""Dice si el usuario tiene alguna sesión en curso"""
key = self.__g_key(act_user, conversation_id)
if key in self.__inConversation:
return True
else:
return False
Loading