Skip to content
This repository has been archived by the owner on Nov 3, 2020. It is now read-only.

Adicionando comandos para tag e alterando consulta de questões #8

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
54 changes: 45 additions & 9 deletions src/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,52 @@

logger = logging.getLogger(__name__)

mytags = ["python"]

def start(bot, update):
"""Mensagem inicial do comando /start"""
update.message.reply_text('Iniciar configuração - mostrar lista de comandos')


def ver_perguntas(bot, update):
# reply_keyboard = [['python', 'php', 'javascript']]

# buscar questao da lista de mais recentes da tag 'python'(intervalo de 1 dia)
questoes = buscar_questoes()
update.message.reply_text(questoes[0])

def tagsToString():
return "\n".join(str(x) for x in mytags)

def myTag(bot, update):
if mytags:
update.message.reply_text("Minhas tags:\n\n" + tagsToString())
else:
update.message.reply_text("Você não possui nenhuma tag adicionada")

def addTag(bot, update, args):
if args:
mytags.extend(args)
mytags = list(set(mytags))
update.message.reply_text("Minhas tags:\n\n" + tagsToString())
else:
update.message.reply_text("É necessário passar o nome da tag que deseja adicionar")

def deleteTag(bot, update, args):
if args:
if args[0] in mytags:
mytags.remove(args[0])
update.message.reply_text("Tag " + args[0] + " deletada")
else:
update.message.reply_text(args[0] + " não é uma de suas tags")
myTag(bot, update)
else:
update.message.reply_text("É necessário passar o nome da tag que deseja remover")

def ver_perguntas(bot, update, args):
max_default = 10

if args:
max_default = int(args[0])
#reply_keyboard = [['python', 'php', 'javascript']]

#buscar questao da lista de mais recentes da tag 'python'(intervalo de 1 dia)
questoes = buscar_questoes(mytags)
total = len(questoes)
for i in range(0, max_default if total > max_default else total):
update.message.reply_text(questoes[i])

def help(bot, update):
update.message.reply_text("""
Expand Down Expand Up @@ -52,7 +85,10 @@ def main():
# comandos habilitados
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", help))
dp.add_handler(CommandHandler("buscar", ver_perguntas))
dp.add_handler(CommandHandler("buscar", ver_perguntas, pass_args=True))
dp.add_handler(CommandHandler("mytag", myTag))
dp.add_handler(CommandHandler("addtag", addTag, pass_args=True))
dp.add_handler(CommandHandler("deletetag", deleteTag, pass_args=True))

# p/ comandos não reconhecidos
dp.add_handler(MessageHandler(Filters.text, echo))
Expand Down
54 changes: 33 additions & 21 deletions src/sopt.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,36 @@
from stackapi import StackAPI
import html
from datetime import datetime, timedelta
#import datetime
#import time


hoje = datetime.today()
inicio = hoje - timedelta(days=1)
#hoje = datetime.today()
#inicio = hoje - timedelta(days=1)

tsHoje = str(hoje.timestamp()).split(".")[0]
tsInicio = str(inicio.timestamp()).split(".")[0]


# as datas sao usadas em timestamp, precisa converter.
#as datas sao usadas em timestamp, precisa converter.
# Ex de entrada: mes-dia-ano
# def timestamp_data(data):
# return datetime.datetime.fromtimestamp(data)
#def timestamp_data(data):
# return datetime.datetime.fromtimestamp(data)

#inserir no formato: datetime.datetime(2018, 8, 18, 6, 00, 0, 000000)
#def data_timestamp(data):
# return int(datetime.datetime(2018, 8, 18, 6, 00, 0, 000000)).strftime("%s")

# inserir no formato: datetime.datetime(2018, 8, 18, 6, 00, 0, 000000)
# def data_timestamp(data):
# return int(datetime.datetime(2018, 8, 18, 6, 00, 0, 000000)).strftime("%s")
def buscar_questoes(tags):
#definicao do pt.stackoverflow
sopt = StackAPI("pt.stackoverflow")

def buscar_questoes(tag="python"):
# definicao do pt.stackoverflow
sopt = StackAPI("pt.stackoverflow")

#conf de numero de resultados
#sopt.page_size = 100
#sopt.max_pages = 1
#resultado = []
#busca por questoes/tag de acordo com intervalo de tempo(atualmente de 1 dia)
#ts = int(time.time())
#questoes_python = sopt.fetch('questions', min=1, fromdate=ts - 54000, todate=ts)

# conf de numero de resultados
sopt.page_size = 100
Expand All @@ -33,11 +42,14 @@ def buscar_questoes(tag="python"):
questoes_python = sopt.fetch('questions', min=1, fromdate=tsInicio, todate=tsHoje, tagged=tag)
# return str(html.unescape(questoes_python['items'][0]['title']))

for i in range(0, len(questoes_python['items'])):
resultado.append("""
Titulo: {}
Link: {}
Criacao: {}
""".format(html.unescape(questoes_python['items'][i]['title']), questoes_python['items'][i]['link'],
questoes_python['items'][i]['creation_date']))
return resultado

for i in range(0, len(questoes_python['items'])):
for value in tags:
if value in questoes_python['items'][i]['tags']:
resultado.append("""
Titulo: {}
Link: {}
Criacao: {}
""".format(html.unescape(questoes_python['items'][i]['title']),questoes_python['items'][i]['link'],
questoes_python['items'][i]['creation_date'] ))
return resultado