Files
fachschaften/bot/bot.py
Andreas Stephanides 8955bf17f5 init commit
2017-01-14 12:23:04 +01:00

141 lines
4.9 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
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 query_que_url(url):
print(json.dumps(url))
return {"text": url.url, "callback_data":"/urls/"+str(url.id)+"/que"}
def handle_urls(handler, cmd):
curls=CrawlUrl.query.all()
#sent=handler.sender.sendMessage(json.dumps(curls))
kb= IKM2(map(query_que_url,curls))
print json.dumps(cmd)
if len(cmd) >= 4 and cmd[3]=="que":
sent=handler.sender.sendMessage("I qued url "+str(cmd[2]), reply_markup=None)
else:
sent=handler.sender.sendMessage("que?", reply_markup=kb)
handler._edit_msg_ident = telepot.message_identifier(sent)
handler._editor = telepot.helper.Editor(handler.bot, sent)
def execute_command(handler,cmd,msg=None):
if cmd[1]=='urls':
handle_urls(handler,cmd)
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("/")
execute_command(handler, cmd, msg)
if msg.has_key('data'):
lg.debug(msg['data'])
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)
articles = [{'type': 'article',
'id': 'abc', 'title': query_string, 'message_text': query_string}]
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)
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),
])