def end_func(state, survivor): while telegram_bot.send_message( channel_name, 'La Seconda Guerra del Faedo è terminata') is None: time.sleep(1) send_all_floors(state) s = '%s è Campione%s del Faedo!' % (state['rooms'][survivor]['person'], [ '', 'ssa' ][state['rooms'][survivor]['gender']]) while telegram_bot.send_message(channel_name, s) is None: time.sleep(1)
def repeat_state(user, message_obj=None): state = user.state if state is None: restart_user(user) return method = possibles.get(state) if not method: msg = "⚠️ User {} sent to unknown method state: {}".format( user.chat_id, state) report_master(msg) send_message(user, ux.MSG_REFRESH_INTERFACE, sleep=1) restart_user(user) else: method(user, message_obj)
def main(): def get_current_price(): array_price = {} prices = client.get_all_tickers() for coin in prices: symbol = coin['symbol'] price = float(coin['price']) array_price[symbol] = price return array_price client = Client(os.environ['BINANCE_APIKEY'], os.environ['BINANCE_SECRET']) connect = psycopg2.connect(host=os.environ['DB_HOST'], port=5432, database=os.environ['DB_DATABASE'], user=os.environ['DB_USER'], password=os.environ['DB_PASSWORD']) previous = get_current_price() i = 0 while i < 10: messages = [] current = get_current_price() result = 0.0 for key, value in current.items(): if value < previous[key]: result = (value - previous[key]) / previous[key] if result < -0.005: value = key + ': ' + str(current[key]) + ' ' + str(round(result * 100, 2)) + '%' messages.append(value) now = int(time.time()) sql = ("""insert into binance_bot(time, data) values (%s, %s::json)""") cursore = connect.cursor() cursore.execute(sql, (now, json.dumps(current))) connect.commit() print(messages) send_message(messages) time.sleep(10) previous = current i += 1 connect.close() print('exit')
def deal_with_universal_commands(user, text): if text in ['/start', '/help']: restart_user(user) return True if user.is_admin(): if text == '/exception': 1 / 0 return True if text.startswith('/debug') and ' ' in text: on_off = text.lower().split()[1] if on_off in ['on', 'off']: user.debug = on_off == 'on' user.put() msg = "Debug attivato" if user.debug else "Debug disattivato" send_message(user, msg) return True return False
def main(): users = mongo.get_users(collection) for user in users: chat_id = user['user_id'] oauth = user['lepra_oauth'] feed_type = user.get('feed_type', 'main') threshold_rating = user.get('threshold_rating', 'easy') markpost_read = user.get('markpost_read', 'false') feed = get_feed(oauth, feed_type, threshold_rating) if not feed: continue if feed == 'deny': telegram_bot.get_user_oauth(chat_id, client_id, bot) config.logger.error( "Some auth error. User {}, move to prepare".format(chat_id)) mongo.user_to_prepare(chat_id, collection) continue for key in feed: for post in feed[key]: send_to_user = '' post_id = post['id'] config.logger.error("User id: {}".format(chat_id)) config.logger.error("Post id: {}".format(post_id)) read = mongo.check_lepra_post(post_id, chat_id, posts_collection) if read: config.logger.error("User {} already read post: {}".format( chat_id, post_id)) continue for key in post: if key == 'body': data = post[key] data = util.strip_tags(data) send_to_user = send_to_user + data + '\n' elif key == '_links': data = post[key][0]['href'] send_to_user = send_to_user + data if send_to_user: config.logger.error("Send post {} to user {}".format( post_id, chat_id)) time.sleep(1) result = telegram_bot.send_message(send_to_user, 'text', bot, chat_id) if result: config.logger.error("result is: {}".format(result)) if result == 'ban': config.logger.error( "User {} blocked bot, move to prepare".format( chat_id)) mongo.user_to_prepare(chat_id, collection) continue else: mongo.add_to_lepra_posts(post['id'], chat_id, posts_collection) if markpost_read == 'true': markpost_as_read(post_id, oauth)
def begin_func(state): while telegram_bot.send_message( channel_name, 'Sta per cominciare la Seconda Guerra del Faedo: tenetevi pronti!' ) is None: time.sleep(1) while telegram_bot.send_message( channel_name, 'Ecco l\'elenco dei prodi combattenti') is None: time.sleep(1) img = game_graphics.draw_players_list(state) img.save('ProdiCombattenti.png', 'PNG') while telegram_bot.send_document( channel_name, open('ProdiCombattenti.png', 'rb')) is None: time.sleep(1) upload_image_ssh('ProdiCombattenti.png', online_img_file) os.remove('ProdiCombattenti.png') send_all_floors(state) b_time = time.localtime(state['next_iteration']) telegram_bot.send_message( channel_name, 'Le ostilità si apriranno ufficialmente il %s alle ore %s' % (time.strftime('%d/%m/%y', b_time), time.strftime('%H:%M', b_time)))
def check_status(): wakeup_time = tgbot.config.WAKEUP_TIME trigger = tgbot.config.TRIGGER count = 0 print("System checking started") while True: if count == trigger: time_elapsed = trigger * wakeup_time tgbot.send_message("{} is idle for {} minutes {} seconds\n".format( os.uname()[1], time_elapsed // 60, time_elapsed % 60)) count = 0 if mem_active() or cpu_active() or gpu_active(): logging.info("Working") count = 0 else: logging.info("Idle") count += 1 time.sleep(wakeup_time)
def state_CONTINUE(user, message_obj): if message_obj is None: kb = [[ux.BUTTON_YES, ux.BUTTON_NO]] send_message(user, ux.MSG_CONTINUE, kb) else: kb = user.get_keyboard() if message_obj.text: text_input = message_obj.text if text_input in utility.flatten(kb): if text_input == ux.BUTTON_YES: redirect_to_state(user, state_GENERATOR) elif text_input == ux.BUTTON_NO: restart_user(user) else: restart_user_old_keyboard(user) elif ux.text_is_button(text_input): send_message(user, ux.MSG_WRONG_BUTTON_INPUT) else: send_message(user, ux.MSG_WRONG_INPUT_USE_BUTTONS, kb) else: send_message(user, ux.MSG_WRONG_INPUT_USE_BUTTONS, kb)
def main(): # print(collection) users = mongo.get_users(collection) # print(type(bot)) for user in users: # print(user) chat_id = user['user_id'] oauth = user['lepra_oauth'] feed_type = user.get('feed_type', 'main') threshold_rating = user.get('threshold_rating', 'easy') feed = get_feed(oauth, feed_type, threshold_rating) # print(feed) if feed == 'deny': telegram_bot.get_user_oauth(chat_id, client_id, bot) continue for key in feed: # print key for post in feed[key]: send_to_user = '' post_id = post['id'] config.logger.debug("User id: {}".format(chat_id)) config.logger.debug("Post id: {}".format(post_id)) read = mongo.check_lepra_post(post_id, chat_id, posts_collection) if read: config.logger.debug("User {} already read post: {}".format(chat_id, post_id)) continue for key in post: if key == 'body': data = post[key] data = util.strip_tags(data) send_to_user = send_to_user + data + '\n' elif key == '_links': data = post[key][0]['href'] send_to_user = send_to_user + data if send_to_user: result = telegram_bot.send_message(send_to_user, 'text', bot, chat_id) if result: mongo.add_to_lepra_posts(post['id'], chat_id, posts_collection)
def send_to_all_listeners(records): print("Found these new records: ", records) chat_ids = update_chat_ids() for chat_id in chat_ids: for record in records: send_message(generate_message_from_record(record), chat_id)
previous = get_current_price() while True: messages = [] current = get_current_price() result = 0.0 for key, value in current.items(): if value < previous[key]: result = (value - previous[key]) / previous[key] if result < -0.005: value = key + ': ' + str(current[key]) + ' ' + str(round(result * 100, 2)) + '%' messages.append(value) now = int(time.time()) sql = ("""insert into binance_bot(time, data) values (%s, %s::json)""") cursore = connect.cursor() cursore.execute(sql,(now, json.dumps(current))) connect.commit() send_message(messages) time.sleep(35) previous = current connect.close()
def notify_mobile_phone(event, description): """ convenience method to call prowl with a notification """ #prowl_notifier.send_notification('rss_downloader', event, description) telegram_bot.send_message(event + ' ' + description)
def state_INITIAL(user, message_obj): if message_obj is None: kb = [[ux.BUTTON_SOLVER, ux.BUTTON_GENERATOR], [ux.BUTTON_INFO]] if user.is_admin(): kb[1].insert(1, ux.BUTTON_ADMIN) send_message(user, ux.MSG_INTRO, kb) else: text_input = message_obj.text kb = user.get_keyboard() if text_input: if text_input in utility.flatten(kb): if text_input == ux.BUTTON_INFO: send_message(user, ux.MSG_INFO) elif text_input == ux.BUTTON_SOLVER: redirect_to_state(user, state_SOLVER) elif text_input == ux.BUTTON_GENERATOR: redirect_to_state(user, state_GENERATOR) elif text_input == ux.BUTTON_ADMIN: msg = "*User Stats*:\n" for a in ['telegram', 'twitter']: msg += "- {}: {}\n".format(a, ndb_user.get_user_count(a)) send_message(user, msg) else: restart_user_old_keyboard(user) elif ux.text_is_button(text_input): send_message(user, ux.MSG_WRONG_BUTTON_INPUT, kb) else: send_message(user, ux.MSG_WRONG_INPUT_USE_BUTTONS, kb) else: send_message(user, ux.MSG_WRONG_INPUT_USE_BUTTONS, kb)
def restart_user_old_keyboard(user): send_message(user, ux.MSG_WRONG_INPUT_OLD_KEYBOARD) send_typing_action(user, sleep_secs=1) redirect_to_state(user, state_INITIAL, message_obj=None)
def report_master(message): send_message(key.TELEGRAM_BOT_MASTER_ID, message, markdown=False)
def notify_mobile_phone(event, description): """ convenience method to call prowl with a notification """ # prowl_notifier.send_notification('rss_downloader', event, description) telegram_bot.send_message(event + " " + description)
def state_SOLVER(user, message_obj): if message_obj is None: kb = [ [ux.BUTTON_BACK], ] send_message(user, ux.MSG_SOLVER_INTRO, kb) else: kb = user.get_keyboard() if message_obj.text: text_input = message_obj.text if text_input in utility.flatten(kb): if text_input == ux.BUTTON_BACK: restart_user(user) else: restart_user_old_keyboard(user) elif ux.text_is_button(text_input): send_message(user, ux.MSG_WRONG_BUTTON_INPUT, kb) else: reply_text, _ = solver.get_solution_from_text(user, text_input) send_message(user, reply_text) elif message_obj.photo: import vision photo_size = message_obj.photo[-1] # last one is the biggest file_url_suffix = get_url_from_file_id(photo_size.file_id) file_url = key.DIALECT_API_URL_FILE + file_url_suffix logging.debug('TELEGRAM File_url: {}'.format(file_url)) image_content = vision.get_image_content_by_uri(file_url) clues_list = vision.detect_clues(image_content=image_content) reply_text, _ = solver.get_solution_from_image(user, clues_list) send_message(user, reply_text) logging.debug( 'TELEGRAM Reply to message from id={} with photo_url {} -> {}'. format(user.serial_number, file_url, reply_text)) elif message_obj.document: send_message(user, ux.MSG_SEND_PHOTO_NOT_DOCUMENT) else: send_message(user, ux.MSG_WRONG_INPUT_USE_BUTTONS_TEXT_PHOTO, kb)
def state_GENERATOR(user, message_obj): if message_obj is None: kb = [ [ux.BUTTON_SOLUTION], [ux.BUTTON_BACK], ] clues, solution, explanations = generator.get_ghigliottina() user.set_var( 'GHIGLIOTTINA', { 'CLUES': clues, 'SOLUTION': solution, 'EXPLANATIONS': explanations, 'TIME': utility.get_now_seconds() }) msg = ux.MSG_GENERATOR_INTRO.format(', '.join(clues)) send_message(user, msg, kb) else: kb = user.get_keyboard() if message_obj.text: text_input = message_obj.text solution = user.get_var('GHIGLIOTTINA')['SOLUTION'] explanations = '\n'.join( '- {}'.format(e) for e in user.get_var('GHIGLIOTTINA')['EXPLANATIONS']) if text_input in utility.flatten(kb): if text_input == ux.BUTTON_BACK: restart_user(user) elif text_input == ux.BUTTON_SOLUTION: ellapsed_sec = utility.get_now_seconds() - user.get_var( 'GHIGLIOTTINA')['TIME'] if ellapsed_sec < 60: send_message(user, ux.MSG_TOO_EARLY) else: send_message(user, ux.MSG_SOLUTION.format(solution)) send_typing_action(user, sleep_secs=0.5) send_message(user, ux.MSG_EXPLANATIONS.format(explanations)) send_typing_action(user, sleep_secs=1) redirect_to_state(user, state_CONTINUE) else: restart_user_old_keyboard(user) elif ux.text_is_button(text_input): send_message(user, ux.MSG_WRONG_BUTTON_INPUT) else: correct = text_input.upper() == solution msg = ux.MSG_GUESS_OK if correct else ux.MSG_GUESS_KO send_message(user, msg) if correct: send_typing_action(user, sleep_secs=0.5) send_message(user, ux.MSG_EXPLANATIONS.format(explanations), remove_keyboard=True) send_typing_action(user, sleep_secs=1) redirect_to_state(user, state_CONTINUE) else: send_message(user, ux.MSG_WRONG_INPUT_USE_BUTTONS, kb)