190 lines
7.4 KiB
Python
190 lines
7.4 KiB
Python
import telepot
|
|
import datetime
|
|
import time
|
|
import json
|
|
from Queue import Queue
|
|
#import os
|
|
from src import lg,cfg
|
|
#from gevent import spawn
|
|
from telepot.namedtuple import InlineKeyboardMarkup, InlineKeyboardButton
|
|
from telepot.delegate import (
|
|
per_chat_id, pave_event_space, include_callback_query_chat_id, create_open, per_inline_from_id )
|
|
from src.compiler import CrawlUrl
|
|
from gevent import spawn, monkey, Greenlet
|
|
import src.compiler.controller as compiler_controller
|
|
import src.articles.controller as articles_controller
|
|
|
|
def IKB(h):
|
|
return InlineKeyboardButton(text=h["text"], callback_data=h["callback_data"])
|
|
|
|
def IKB2(h):
|
|
return [IKB(h)]
|
|
def IKM(h):
|
|
return InlineKeyboardMarkup(inline_keyboard=[ map(IKB,h)])
|
|
|
|
def IKM2(h):
|
|
return InlineKeyboardMarkup(inline_keyboard= map(IKB2,h))
|
|
|
|
def is_admin(id):
|
|
lg.debug("check admin?"+str(id))
|
|
if str(id) in cfg.is_admin:
|
|
lg.debug("is admin")
|
|
return True
|
|
else:
|
|
return False
|
|
|
|
def query_que_url(url):
|
|
print(json.dumps(url))
|
|
return {"text": url.url, "callback_data":"/urls/"+str(url.id)+"/que"}
|
|
def query_test_url(url):
|
|
print(json.dumps(url))
|
|
return {"text": url.url, "callback_data":"/urls/"+str(url.id)+"/test"}
|
|
|
|
def handle_urls(handler, cmd):
|
|
curls=CrawlUrl.query.all()
|
|
#sent=handler.sender.sendMessage(json.dumps(curls))
|
|
kb_que= IKM2(map(query_que_url,curls))
|
|
kb_test= IKM2(map(query_test_url,curls))
|
|
kb_url=IKM2([{"text": "Que an url", "callback_data":"/urls/que"},
|
|
{"text": "Test an url", "callback_data":"/urls/test"}
|
|
])
|
|
lg.debug(json.dumps(cmd))
|
|
print json.dumps(cmd)
|
|
if len(cmd) >= 4 and cmd[3]=="que":
|
|
sent=handler.sender.sendMessage("I qued url "+ json.dumps(compiler_controller.urls_test(int(cmd[2]))), reply_markup=None)
|
|
elif len(cmd) >= 4 and cmd[3]=="test":
|
|
sent=handler.sender.sendMessage("I tested url: "+ json.dumps(compiler_controller.urls_test(int(cmd[2]))["comp"])[0:399], reply_markup=None)
|
|
elif len(cmd) >= 3 and cmd[2] == "que":
|
|
sent=handler.sender.sendMessage("Which url shoud I que?", reply_markup=kb_que)
|
|
handler._edit_msg_ident = telepot.message_identifier(sent)
|
|
handler._editor = telepot.helper.Editor(handler.bot, sent)
|
|
elif len(cmd) >= 3 and cmd[2] == "test":
|
|
sent=handler.sender.sendMessage("Which url shoud I test?", reply_markup=kb_test)
|
|
handler._edit_msg_ident = telepot.message_identifier(sent)
|
|
handler._editor = telepot.helper.Editor(handler.bot, sent)
|
|
else:
|
|
sent=handler.sender.sendMessage("What do you want to do?", reply_markup=kb_url)
|
|
handler._edit_msg_ident = telepot.message_identifier(sent)
|
|
handler._editor = telepot.helper.Editor(handler.bot, sent)
|
|
|
|
def execute_command(handler,cmd,msg=None, args=[]):
|
|
if cmd[1]=='urls':
|
|
if is_admin(msg["from"]["id"]):
|
|
handle_urls(handler,cmd)
|
|
else:
|
|
handler.sender.sendMessage("Not allowed for "+json.dumps(msg["from"]))
|
|
elif cmd[1] =='articles':
|
|
handler.sender.sendMessage(json.dumps({"args": args, "cmd": cmd}))
|
|
handler.sender.sendMessage(json.dumps(articles_controller.search(args[0])))
|
|
elif cmd[1] =='startworkers':
|
|
if is_admin(msg["from"]["id"]):
|
|
handler.sender.sendMessage(compiler_controller.start_workers())
|
|
|
|
else:
|
|
handler.sender.sendMessage("Sorry, I didn't understand the command!")
|
|
|
|
def handle(handler,msg):
|
|
content_type,chat_type,chat_id = telepot.glance(msg)
|
|
if msg.has_key('text'):
|
|
if msg['text'][0]=='/':
|
|
cmd = msg['text'].split("/")
|
|
args=cmd[-1].split(" ")[1:]
|
|
cmd[-1]=cmd[-1].split(" ")[0]
|
|
execute_command(handler, cmd, msg,args)
|
|
if msg.has_key('data'):
|
|
lg.debug(msg['data'])
|
|
|
|
def make_article_json(art):
|
|
|
|
res={"type":"article", "title":art.title, "id": str(art.id), "url": art.url, "message_text": art.title + " " + art.url}
|
|
if art.image != None:
|
|
lg.debug("http://crawler.fachschaften.at/"+str(art.image))
|
|
res["thumb_url"]="http://crawler.fachschaften.at/"+str(art.image)
|
|
return res
|
|
class InlineHandler(telepot.helper.InlineUserHandler, telepot.helper.AnswererMixin):
|
|
def __init__(self, *args, **kwargs):
|
|
super(InlineHandler, self).__init__(*args, **kwargs)
|
|
|
|
def on_inline_query(self, msg):
|
|
def compute_answer():
|
|
query_id, from_id, query_string = telepot.glance(msg, flavor='inline_query')
|
|
print(self.id, ':', 'Inline Query:', query_id, from_id, query_string)
|
|
articles1=articles_controller.search(query_string)
|
|
|
|
articles = [{'type': 'article',
|
|
'id': 'abc', 'title': query_string, 'message_text': query_string}]
|
|
articles=map(make_article_json,articles1)
|
|
|
|
return articles
|
|
|
|
self.answerer.answer(msg, compute_answer)
|
|
|
|
def on_chosen_inline_result(self, msg):
|
|
from pprint import pprint
|
|
pprint(msg)
|
|
result_id, from_id, query_string = telepot.glance(msg, flavor='chosen_inline_result')
|
|
print(self.id, ':', 'Chosen Inline Result:', result_id, from_id, query_string)
|
|
|
|
|
|
class FetBot(telepot.helper.ChatHandler):
|
|
def __init__(self, *args, **kwargs):
|
|
# super(FetBot,self).__init__(*args,**kwargs)
|
|
super(FetBot,self).__init__( *args,**kwargs)
|
|
|
|
_editor=None
|
|
_edit_msg_ident=None
|
|
keyboard=IKM([{"text":"START","callback_data": "start"},
|
|
{"text":"Don't Start","callback_data":"notstart"}
|
|
])
|
|
keyboard =InlineKeyboardMarkup(
|
|
inline_keyboard=[[
|
|
InlineKeyboardButton(text='START', callback_data='start'),
|
|
InlineKeyboardButton(text='START', callback_data='start')
|
|
]]
|
|
)
|
|
def on_chat_message(self,msg):
|
|
handle(self,msg)
|
|
content_type,chat_type,chat_id = telepot.glance(msg)
|
|
lg.debug(content_type)
|
|
lg.debug(msg)
|
|
if content_type=="photo" or content_type=="sticker":
|
|
lg.debug("try to download %s" % msg[content_type][-1]["file_id"])
|
|
f=self.bot.getFile(msg[content_type][-1]['file_id'])
|
|
lg.debug(f)
|
|
self.bot.download_file(f['file_id'], "dwn/" + f['file_path'])
|
|
# self.bot.getFile(msg['photo'][-1]['file_id']), "dwn")
|
|
#self._cancel_last()
|
|
#sent=self.sender.sendMessage("Hello World", reply_markup=self.keyboard)
|
|
#self._editor = telepot.helper.Editor(self.bot, sent)
|
|
#self._edit_msg_ident = telepot.message_identifier(sent)
|
|
|
|
def on_callback_query(self, msg):
|
|
query_id, from_id, query_data = telepot.glance(msg, flavor='callback_query')
|
|
lg.debug(json.dumps(msg))
|
|
self._cancel_last()
|
|
if query_data[0]=='/':
|
|
cmd = query_data.split("/")
|
|
execute_command(self, cmd, msg)
|
|
|
|
# self.sender.sendMessage("Danke")
|
|
self.bot.answerCallbackQuery(query_id, text='Ok. But I am going to keep asking.')
|
|
#self.bot.answerCallbackQuery(query_id)
|
|
def _cancel_last(self):
|
|
if self._editor:
|
|
self._editor.editMessageReplyMarkup(reply_markup=None)
|
|
self._editor = None
|
|
self._edit_msg_ident = None
|
|
|
|
|
|
|
|
|
|
bot=None
|
|
bot = telepot.DelegatorBot(cfg.token, [include_callback_query_chat_id(pave_event_space())(per_chat_id(),create_open,FetBot,timeout=20),
|
|
pave_event_space()(
|
|
per_inline_from_id(), create_open, InlineHandler, timeout=10),
|
|
])
|
|
|
|
|
|
|
|
|