def bot_iteration(): print('vk iteration...') for event in listen_for_messages(): logger().debug(event) proc = CommandProcessor(api, event.object.peer_id) cmd = try_extract_command(event.object.text) if not cmd: continue pi = event.object.peer_id cmd, *args = cmd.split(' ') if cmd == 'identify': proc.identify(args[0]) elif cmd == 'start': activate(pi, event.object.from_id) elif cmd == 'stop': deactivate(pi) elif cmd == 'subscribe': for a in args: subscribe(pi, a) elif cmd == 'unsubscribe': for a in args: unsubscribe(pi, a) print('twitter iteration...') for author in all_twitters(subscribers): for twit in chunker(new_twits(author), 7): msg = f'\n\n{"-"*10}\n\n'.join(map(str, twit)) for sub, data in subscribers.items(): if author in data['twitters']: send_to(sub, msg)
def tweets_from_web(author): content = requests.get(f'https://mobile.twitter.com/{author}').content open('twitter_last.html', 'w').write(content.decode('utf-8')) twits = tweets_from_string(content, author) if not twits: logger().error('!! SOMETHING BAD HAPPENED WITH TWITTER !!') logger().error('SEE twitter_last.html FILE') return twits
def deactivate(peer_id: int): sp = str(peer_id) if sp not in subscribers: logger().info(f'{peer_id} not activated; ignoring') return del subscribers[sp] with open(SUBFILE, 'w') as f: json.dump(subscribers, f, indent=2) send_to(peer_id, "ok")
def activate(peer_id: int, adder: int): sp = str(peer_id) if sp in subscribers: logger().info(f'{peer_id} already activated; ignoring') return subscribers[sp] = {"admins": [adder], "twitters": []} with open(SUBFILE, 'w') as f: json.dump(subscribers, f, indent=2) send_to(peer_id, "ok")
def subscribe(peer_id: int, twitter: str): sp = str(peer_id) if sp not in subscribers: logger().info(f'{peer_id} not activated; ignoring') return ts = subscribers[sp]['twitters'] if twitter in ts: logger().info(f'{peer_id} already subscribed to {twitter}; ignoring') return ts.append(twitter) with open(SUBFILE, 'w') as f: json.dump(subscribers, f, indent=2) send_to(peer_id, "ok")
def update_last_twit(author: str, twid: int): write = False if author not in last_twits: logger().info(f'No known twits from {author}, adding {twid}') write = True elif twid > last_twits[author]: logger().info( f'{twid} is newer for {author} than {last_twits[author]}, updating' ) write = True if write: last_twits[author] = twid json.dump(last_twits, open('last_twits.json', 'w'), indent=2)
def send_to(peer_id, message): try: api.messages.send(peer_id=peer_id, random_id=get_random_id(), message=f'{BIRB} {message}') except vk.ApiError as e: logger().warning( f'Failed to send "{message[:100]}"... to {peer_id}:\n{e.error}') if e.code == 7: logger().warning( 'Permission denied, seems like bot was removed from this conversation' ) logger().warning(f'Deactivating {peer_id}') deactivate(peer_id)
def main(): init_logger() try: logger().info('Bot starting') if 'owner' in me: for chunk in chunker(list(subscribers.keys()), 20): ss = ', '.join(map(str, chunk)) send_to(me['owner'], f'bot online in {ss}') while True: try: bot_iteration() except Exception as e: logger().error('SOMETHING HAPPENED:') logger().error(traceback.format_exc()) logger().debug("sleeping...") time.sleep(30) print("finishing") except Exception as e: logger().critical('Daizy terminated with an exception:') logger().critical(traceback.format_exc()) sys.exit(1)