def sub_handler(message): troll = tgbot.handle(message, [subscribe])[0] userid = message['from']['id'] if troll != False or troll is None: current_subs = dbactions.get_subscriptions(userid) not_exesting_subs = [ *filter(lambda sub: sub not in current_subs, message['text'].split(' ')) ] valid_names = [*filter(validator, not_exesting_subs)] if valid_names: for new_sub in valid_names: current_subs[new_sub] = tgbot.time.time() dbactions.update(userid, current_subs) succ_sub_message(userid, valid_names, 'установлены') handlers = tgbot.message_handlers try: handlers[handlers.index(sub_handler)] = subscribe except ValueError: pass # called from start function message['text'] = '/cancel' cancel(message) #auto cancel else: tgbot.send_message( userid, '''Вы уже подписаны на этих пользователей или не найдены корректные имена для подписки''')
def dialog(callback): userid = callback['from']['id'] tgbot.delete_message(userid, callback['message']['message_id']) #sending new message with cancel tgbot button cancel_kb = tgbot.Keyboard(inline=False, rows=1, resize_keyboard=True, one_time_keyboard=True) cancel_kb.add_button(0, '/cancel') tgbot.send_message(userid, 'Selected:', cancel_kb) dialog_kb = tgbot.Keyboard(inline=True, rows=2) dialog_kb.add_button(0, 'Просмотр', link='http://reddit.com/user/%s/submitted' % callback['data']) dialog_kb.add_button(1, 'Отписаться', callback='delsub=%s' % callback['data']) #adding inline buttons through new message :c tgbot.send_message(userid, callback['data'], dialog_kb) fsm.set_state('/unsubscribe', '%s' % callback['from']['id'])
def first_step(message): userlist = message['text'].split(' ') userid = str(message['from']['id']) if len(userlist) < 1: tgbot.send_message( userid, 'Список %s пуст' % 'подписок' if message['text'] == '/subscribe' else 'отписок') else: cancel_kb = tgbot.Keyboard(inline=False, rows=1, resize_keyboard=True, one_time_keyboard=True) cancel_kb.add_button(0, '/cancel') tgbot.send_message(userid, 'Теперь введите имена пользователей через пробел', cancel_kb) fsm.set_state('%s' % message['text'], userid) handlers = tgbot.message_handlers if message['text'] == '/subscribe': if sub_handler not in handlers: handlers[handlers.index(subscribe)] = sub_handler return True else: return False elif message['text'] == '/unsubscribe': if unsub_handler not in handlers: handlers[handlers.index(unsubscribe)] = unsub_handler return True else: return False
def send_results(group_id): for player in groups[group_id]['members']: text = 'Дари подарок этому человеку: ' + groups[group_id]['members'][ player]['first_name'] + ' ' + groups[group_id]['members'][player][ 'last_name'] + '!' chat_id = groups[group_id]['members'][player]['secret_santa_chat_id'] tgbot.send_message(chat_id, text)
def subscriptions(message): subs = dbactions.get_subscriptions(message['from']['id']) values = [enumerate(subs)] subs_kb = tgbot.Keyboard(inline=True, rows=len(subs) // 2) row = 0 for x, name in enumerate(subs): subs_kb.add_button(row, caption=name, callback=name) if x % 4 == 0: row += 1 tgbot.send_message(message['from']['id'], 'Ваши подписки', subs_kb)
def _start(userid): hello_kb = tgbot.Keyboard(inline=False, rows=3, resize_keyboard=True, one_time_keyboard=False, selective=True) hello_kb.add_button(0, '/subscribe') hello_kb.add_button(1, '/unsubscribe') hello_kb.add_button(2, '/subscriptions') tgbot.send_message(userid, 'Выберите действие', hello_kb) fsm.set_state('/start', userid)
def check_one(cls): if isinstance(cls, str): for item in CHECK_LIST: if item.__name__ == cls: cls = item break else: raise Exception("Can not found '%s' from CHECK_LIST!" % cls) cls_obj = cls() print("- Checking", cls_obj.fullname, "...", end="") try: cls_obj.do_check() except Exception as error: if isinstance(error, exceptions.ReadTimeout): print("\n! Check failed! Timeout.") write_log_warning("%s check failed! Timeout." % cls_obj.fullname) elif isinstance(error, (exceptions.SSLError, exceptions.ProxyError)): print("\n! Check failed! Proxy error.") write_log_warning("%s check failed! Proxy error." % cls_obj.fullname) elif isinstance(error, ErrorCode): print("\n! Check failed! Error code: %s." % error) write_log_warning("%s check failed! Error code: %s." % (cls_obj.fullname, error)) else: traceback_string = traceback.format_exc() print("\n%s\n! Check failed!" % traceback_string) write_log_warning(*traceback_string.splitlines()) write_log_warning("%s check failed!" % cls_obj.fullname) if DEBUG_ENABLE: if input("* Continue?(Y/N) ").upper() != "Y": _abort_by_user() return False if cls_obj.is_updated() or FORCE_UPDATE: print("\n> New build:", cls_obj.info_dic["LATEST_VERSION"]) write_log_info("%s has updates: %s" % (cls_obj.fullname, cls_obj.info_dic["LATEST_VERSION"])) try: cls_obj.after_check() except: traceback_string = traceback.format_exc() print("\n%s\n! Something wrong when running after_check!" % traceback_string) write_log_warning(*traceback_string.splitlines()) write_log_warning("%s: Something wrong when running after_check!" % cls_obj.fullname) cls_obj.write_to_database() if (ENABLE_SENDMESSAGE and not DONT_POST) or FORCE_UPDATE: send_message(cls_obj.get_print_text()) else: print(" no update") write_log_info("%s no update" % cls_obj.fullname) return True
def start(message): userid = str(message['from']['id']) if len(message['text'].split(' ')) > 1: fsm.set_state('/subscribe', userid) message['text'] = message['text'].split(' ')[1] sub_handler(message) else: if not dbactions.user_exist(userid): dbactions.register(userid) tgbot.send_message(userid, 'Зарегистрированно') _start(userid) else: _start(userid)
def succ_sub_message(userid, subs, status): if type(subs) is not str: info_kb = tgbot.Keyboard(inline=True, rows=len(subs)) for row, value in enumerate(subs): info_kb.add_button(row, value, link='http://reddit.com/user/%s/submitted' % value) else: info_kb = tgbot.Keyboard(inline=True, rows=1) info_kb.add_button(0, subs, link='http://reddit.com/user/%s/submitted' % subs) tgbot.send_message(userid, 'Подписки %s' % status, info_kb)
def recognize(): # convert to wav (for speech recogition) utils.ffmpeg("./rec/ready.mp3", "./rec/current.wav") # convert to ogg (for telegram bot) utils.ffmpeg("./rec/ready.mp3", "./rec/current.ogg") # rename mp3 (for email bot) os.rename("./rec/ready.mp3", "./rec/current.mp3") r = sr.Recognizer() with sr.AudioFile("./rec/current.wav") as source: audio = r.record(source) # delete wav file os.remove("./rec/current.wav") try: rec_text = r.recognize_google(audio, language=data.language) s_print("RECOGNIZED TEXT:\n" + textwrap.fill(rec_text, 80)) # check if result contains one of the keywords found_words = [] for i in keywords: if contains_word(i, rec_text): found_words.append(i) # send string with found words if len(found_words) != 0: # mailbot.send_message(found_words_combined) tgbot.send_message(found_words, rec_text) else: s_print("NO KEYWORDS") except sr.UnknownValueError: s_print("Google Speech Recognition could not understand audio") except sr.RequestError as e: s_print("Could not request results from Google Speech Recognition service; {0}".format(e)) # delete current audio files os.remove("./rec/current.ogg") os.remove("./rec/current.mp3")
def process_update(update): if 'message' in update and 'text' in update['message']: chat_id = str(update['message']['chat']['id']) text = update['message']['text'] if update['message']['chat']['type'] == 'private': splited_text = text.split(' ') if '/start' in splited_text: if len(splited_text) > 1 and splited_text[ 1] in groups and not chat_id in groups[ splited_text[1]]['members']: groups[splited_text[1]]['members'][chat_id] = {} groups[splited_text[1]]['members'][chat_id]['id'] = chat_id groups[splited_text[1]]['members'][chat_id][ 'secret_santa_chat_id'] = None groups[splited_text[1]]['members'][chat_id][ 'first_name'] = update['message']['from']['first_name'] try: groups[splited_text[1]]['members'][chat_id][ 'last_name'] = update['message']['from'][ 'last_name'] except: groups[splited_text[1]]['members'][chat_id][ 'last_name'] = '' try: groups[splited_text[1]]['members'][chat_id][ 'username'] = update['message']['from']['username'] except: groups[splited_text[1]]['members'][chat_id][ 'username'] = '' vacancies_count = groups[ splited_text[1]]['members_count'] - len( groups[splited_text[1]]['members']) msg = groups[splited_text[1]]['members'][chat_id][ 'first_name'] + ' ' + groups[ splited_text[1]]['members'][chat_id][ 'last_name'] + ' участвует. Осталось мест: ' + str( vacancies_count) if groups[splited_text[1]]['members'][chat_id][ 'username'] == 'tfent': msg = 'Я - хороший дедушка мороз. Но вынужден сообщить прискорбные известия: Роман тоже участвует. Кто вообще его позвал? :( Эххх... Осталось мест: ' + str( vacancies_count) tgbot.send_message(splited_text[1], msg) else: tgbot.send_message( chat_id, 'Странно, такого быть не должно. Скорее всего Роман что-то сломал. Маякните Мишгану. Код : 01' ) else: tgbot.send_message( chat_id, 'Странно, такого быть не должно. Скорее всего Роман что-то сломал. Маякните Мишгану. Код : 02' ) elif (update['message']['chat']['type'] == 'group' or update['message']['chat']['type'] == 'supergroup'): if text == '/start@TayniyDedBot' and not chat_id in groups: groups[chat_id] = {} groups[chat_id]['id'] = chat_id groups[chat_id]['title'] = update['message']['chat']['title'] groups[chat_id][ 'members_count'] = tgbot.get_chat_members_count( chat_id) - 1 # 1 - self groups[chat_id]['members'] = {} click_url = 'https://t.me/TayniyDedBot?start=' + chat_id tgbot.send_message( chat_id, 'Кликните ссылку и в открывшемся чате нажмите start. ' + click_url) elif text == '/reset@TayniyDedBot' and chat_id in groups: groups.pop(chat_id) elif text == '/play@TayniyDedBot' and chat_id in groups: if (groups[chat_id]['members_count'] - len(groups[chat_id]['members'])) == 0: tgbot.send_message(chat_id, '*играет_новогодняя_мелодия*') play(chat_id) else: tgbot.send_message(chat_id, 'Рано. Еще есть вакантные места.') else: #channel pass