def check_payload(event, key): if type(key) is dict: # is button key = Buttons.get_key(key) elif type(key) is list: keys = [ Buttons.get_key(single_key) if type(key) is dict else single_key for single_key in key ] return hasattr(event, 'payload') and literal_eval( event.payload).get('command') in keys return hasattr(event, 'payload') and literal_eval( event.payload).get('command') == key
def process_new_message(self, event): try: user = self.db.session.query(User).filter( User.user_id == event.user_id).first() if not user: user = self.db.add(User(event.user_id)) else: self.db.update(user, {User.last_interaction_date: datetime.today()}) if event.user_id in Config.admin_ids or \ Settings.bot and not user.banned: handlers = self.handlers if user.path == Buttons.get_key(Buttons.call_admin): handlers = self.special_handlers coincidence = next( (rule for rule in handlers if rule['condition'](self.vk, event, user) and ( 'main' in rule or 'admin' in rule and event.user_id in Config.admin_ids))) if coincidence: if 'admin' in coincidence and event.user_id in Config.admin_ids: coincidence['admin'](self.vk, event, user) elif 'main' in coincidence: coincidence['main'](self.vk, event, user) except StopIteration: return None except Exception as e: self.write_error_message(event.user_id) self.write_log(self.vk, event.message_id, e) self.db.session.rollback()
def get_status(self): if self.banned: return 'Забанен' elif self.apologies_count > 0: return 'Извиняется' elif self.path == Buttons.get_key(Buttons.call_admin): return 'Активно разговаривает с админом' return 'Активен'
def get_essay_button(self, vk, event, user): if self.db.session.query(Essay).filter( Essay.user_id == event.user_id, Essay.processed_text == None).first(): vk.send(event.user_id, self.reject_message) else: self.db.update(user, {User.path: Buttons.get_key(Buttons.essay)}) vk.send( event.user_id, 'давай свой текст, прочту его за тебя и в кратце расскажу в чем суть', [[Buttons.to_main]])
def process_unread_messages(self): count = 200 while count == 200: conversations, count = self.vk.get_unread_conversations() for conversation in conversations: user = self.db.session.query(User).filter( User.user_id == conversation['conversation']['peer'] ['id']).first() if user.path != Buttons.get_key( Buttons.call_admin) and not user.banned: self.vk.send(user.user_id, [ 'что-то я залип на некоторое время, можешь повторить что ты там говорил?', 'извини, что не отвечал, делал свои дела. ну ты знаешь, дела обычного бота бедрока: ' 'банил всяких гандонов и генерировал мемы. так на чем мы остановились?' ])
class Drums(object): def __init__(self): print 'Starting up drums!' self._buttons = Buttons() self._led = LEDS() self._sequenceQueue = [] self._play = False self._last_key_time = datetime.now() self._led.test() def run(self): while True: now = datetime.now() if not self._buttons.has_keys() and (now - self._last_key_time).total_seconds() > STOP_PLAYING_THRESHOLD: print 'sequence ended. going to sleep (kinda!)' self._play = False if self._buttons.has_keys(): if not self._play: print 'start playing!' self._play = True self._last_key_time = now self._process_key(self._buttons.get_key()) if not self._play: time.sleep(1) continue time.sleep(0.05) def _process_key(self, key): print 'processing key %s' % key self._led.set_color_for_button(key, 0xFF)
def call_admin(self, vk, event, user): self.db.update(user, {User.path: Buttons.get_key(Buttons.call_admin)}) vk.send( event.user_id, 'понял, позову админа. если захочешь снова разговаривать с бездушным роботом пиши "вызываю бота"' )
def set_scores_button(self, vk, event, user): self.db.update(user, {User.path: Buttons.get_key(Buttons.jokes_set_scores)}) vk.send(event.user_id, 'сколько баллов поставишь шутнику?', [[Buttons.jokes_refresh]])
def make_admin_laugh_button(self, vk, event, user): self.db.update(user, {User.path: Buttons.get_key(Buttons.make_joke)}) message = 'присылай шутку, передам её админу и он оценит' if any(user.jokes): message = [message, 'шути'] vk.send(event.user_id, message, [[Buttons.to_main]])
def action_with_user_button(self, vk, event, admin): self.db.update(admin, {User.path: Buttons.get_key(Buttons.action_with_user)}) vk.send(event.user_id, f'вводи id в формате "id{event.user_id}"', [[Buttons.to_main]])
def need_process_message(user): return user.path not in [ Buttons.get_key(Buttons.make_joke), Buttons.get_key(Buttons.essay) ]
def compare_path(self, path, in_arg=False): if type(path) is dict: # is button path = Buttons.get_key(path) return self.path == path if not in_arg else path in self.path