def update_chat_db(message): with db_session: chat = Chat.get(chat_id=message.chat.id) if chat == None: chat = Chat(chat_id=message.chat.id, user_id=message.from_user.id, open_date=datetime.now(), \ last_message_date=datetime.now(), username=message.from_user.username, \ first_name=message.from_user.first_name, last_name=message.from_user.last_name, \ silent_mode=False, deleted=False) else: chat.last_message_date = datetime.now() chat.username = message.from_user.username if message.text == STOP_CMD: chat.silent_mode = True elif message.left_chat_participant != None: if message.left_chat_participant.id == BOT_ID: chat.deleted = True elif message.new_chat_participant != None: if message.new_chat_participant.id == BOT_ID: chat.deleted = False elif message.text == START_CMD: chat.silent_mode = False chat.deleted = False return chat.primary_id
def send_message(bot, message): with db_session: cmd = text = '' primary_id = 0 params = message.text.split(' ', 2) if len(params) > 0: cmd = params[0] if len(params) > 1: try: primary_id = int(params[1]) except ValueError: bot.sendMessage(chat_id=message.chat_id, text='cannot find user') return False if len(params) > 2: text = params[2] if primary_id == 0: bot.sendMessage(chat_id=message.chat_id, text='cannot send message to empty user') elif len(text) == 0: bot.sendMessage(chat_id=message.chat_id, text='cannot send empty message') else: chat = Chat.get(primary_id=primary_id) if chat == None: bot.sendMessage(chat_id=message.chat_id, text='cannot find user') elif chat.deleted: bot.sendMessage(chat_id=message.chat_id, text='this user marked as deleted') else: bot.sendMessage(chat_id=chat.chat_id, text=text)
def update_chat_db(message): with db_session: chat = Chat.get(chat_id=message.chat.id) if chat == None: chat = Chat(chat_id=message.chat.id, user_id=message.from_user.id, open_date=datetime.now(), \ last_message_date=datetime.now(), username=message.from_user.username, \ first_name=message.from_user.first_name, last_name=message.from_user.last_name, \ silent_mode=False, deleted=False, group_id="nobody", state="REGISTER_STATE", \ realname="", contacts="", places="1", masterskaya="", gender="male") else: chat.last_message_date = datetime.now() chat.username = message.from_user.username chat.first_name = message.from_user.first_name chat.last_name = message.from_user.last_name return chat
def update_chat_db(message): with db_session: chat = Chat.get(chat_id=message.chat.id) if chat == None: chat = Chat(chat_id=message.chat.id, user_id=message.from_user.id, open_date=datetime.now(), \ last_message_date=datetime.now(), username=message.from_user.username, \ first_name=message.from_user.first_name, last_name=message.from_user.last_name, \ silent_mode=False, deleted=False, group_id="nobody", state="REGISTER_STATE", \ realname="") else: chat.last_message_date = datetime.now() chat.username = message.from_user.username chat.first_name = message.from_user.first_name chat.last_name = message.from_user.last_name return chat
def unsubscribe_chat(chat_id: int) -> None: Chat.get(chat_id=chat_id).subscribed = False
def subscribe_chat(chat_id: int) -> None: Chat.get(chat_id=chat_id).subscribed = True
def run(bot, logfile): global LAST_UPDATE_ID for update in bot.getUpdates(offset=LAST_UPDATE_ID, timeout=10): message = update.message chat = update_chat_db(message) primary_id, group_id, state, silent_mode, deleted, realname, contacts, username, places, gender, masterskaya = \ chat.primary_id, chat.group_id, chat.state, chat.silent_mode, chat.deleted, \ chat.realname, chat.contacts, chat.username, chat.places, chat.gender, chat.masterskaya log_update(update, logfile) #automata_step(message, chat) #if group_id == "admin": # reply_markup = '{"keyboard" : [["/user_list"]], "resize_keyboard" : true, "one_time_keyboard" : true}' #else: # reply_markup = telegram.ReplyKeyboardHide() print(u"State: {}. Message: {}".format(state, message.text)) if state.startswith("REGISTER_STATE"): if len(state.split()) == 1: text = u"Привет! Вы попали в бот, распределяющий людей по палаткам." bot.sendMessage(chat_id=message.chat_id, text=text) if not username: reply_markup = '{"keyboard" : [["/continue"]], "resize_keyboard" : true, "one_time_keyboard" : true}' text = u"Пожалуйста, установите username в настройках (Settings) Телеграма, чтобы остальные могли с Вами связаться" bot.sendMessage(chat_id=message.chat_id, text=text, reply_markup=reply_markup) else: reply_markup = '{"keyboard" : [["/continue"]], "resize_keyboard" : true, "one_time_keyboard" : true}' text = u"По username @{} с Вами могут связываться остальные. Введите свой телефон для связи или нажмите /continue:".format(username) bot.sendMessage(chat_id=message.chat_id, text=text, reply_markup=reply_markup) state = "REGISTER_STATE contacts" elif len(state.split()) == 2: if message.text != "/continue": contacts = message.text text = u"Вы готовы предоставить место в палатке (/give) или Вам оно нужно (/need)?" reply_markup = '{"keyboard" : [["/give", "/need"]], "resize_keyboard" : true, "one_time_keyboard" : true}' bot.sendMessage(chat_id=message.chat_id, text=text, reply_markup=reply_markup) state = "REGISTER_STATE contacts group" elif len(state.split()) == 3: if message.text == "/give": state = "REGISTER_STATE contacts group give" group_id = "give" text = u"Сколько мест в палатке Вы можете предоставить?" reply_markup = '{"keyboard" : [["1", "2", "3"]], "resize_keyboard" : true, "one_time_keyboard" : true}' bot.sendMessage(chat_id=message.chat_id, text=text, reply_markup=reply_markup) elif message.text == "/need": state = "REGISTER_STATE contacts group need" group_id = "need" text = u"Из какой Вы мастерской?" bot.sendMessage(chat_id=message.chat_id, text=text, reply_markup=telegram.ReplyKeyboardHide()) else: pass elif state.split()[3] == "give": if len(state.split()) == 4: places = message.text reply_markup = '{"keyboard" : [["/female", "/male"]], "resize_keyboard" : true}' text = u'Введите Ваш пол ("/female", "/male"):' bot.sendMessage(chat_id=message.chat_id, text=text, reply_markup=reply_markup) state = "REGISTER_STATE contacts group give gender" elif len(state.split()) == 5: if message.text == "/male": gender = "male" elif message.text == "/female": gender = "female" else: gender = message.text reply_markup = '{"keyboard" : [["/register", "/unregister"]], "resize_keyboard" : true}' text = u"Ваша заявка зарегистрирована! Нажмите /register для перерегистрации или /unregister, если Ваша больше не актуальна." bot.sendMessage(chat_id=message.chat_id, text=text, reply_markup=reply_markup) state = "MAIN_STATE" elif state.split()[3] == "need": if len(state.split()) == 4: masterskaya = message.text reply_markup = '{"keyboard" : [["/female", "/male"]], "resize_keyboard" : true}' text = u'Введите Ваш пол ("/female", "/male"):' bot.sendMessage(chat_id=message.chat_id, text=text, reply_markup=reply_markup) state = "REGISTER_STATE contacts group need gender" elif len(state.split()) == 5: if message.text == "/male": gender = "male" elif message.text == "/female": gender = "female" else: gender = message.text reply_markup = '{"keyboard" : [["/register", "/unregister"]], "resize_keyboard" : true}' text = u"Ваша заявка зарегистрирована! Нажмите /register для перерегистрации или /unregister, если Ваша больше не актуальна." bot.sendMessage(chat_id=message.chat_id, text=text, reply_markup=reply_markup) state = "MAIN_STATE" elif state.startswith("MAIN_STATE"): if message.text == "I am god": group_id += "_admin" reply_markup = '{"keyboard" : [["/user_list", "/register", "/unregister"]], "resize_keyboard" : true}' bot.sendMessage(chat_id=message.chat_id, text="Вы админ! Вам доступен /user_list", reply_markup=reply_markup) elif message.left_chat_member != None: if message.left_chat_member.id == BOT_ID: deleted = True elif message.new_chat_member != None: if message.new_chat_member.id == BOT_ID: deleted = False elif message.text == "/unregister": if "admin" in group_id: group_id = "admin" else: group_id = "done" reply_markup = '{"keyboard" : [["/register"]], "resize_keyboard" : true}' text = u"Ваша заявка больше не актуальна! Нажмите /register для новой регистрации." bot.sendMessage(chat_id=message.chat_id, text=text, reply_markup=reply_markup) elif message.text == "/register": reply_markup = '{"keyboard" : [["/continue"]], "resize_keyboard" : true, "one_time_keyboard" : true}' text = u"По username @{} с Вами могут связываться остальные. Введите свой телефон для связи или нажмите /continue:".format(username) bot.sendMessage(chat_id=message.chat_id, text=text, reply_markup=reply_markup) state = "REGISTER_STATE contacts" elif message.text == USER_LIST_CMD: print_userlist(bot, message) elif "admin" in group_id and message.text == "/killme": exit() else: pass with db_session: chat = Chat.get(chat_id=message.chat.id) chat.primary_id, chat.group_id, chat.state, chat.silent_mode, chat.deleted, \ chat.realname, chat.contacts, chat.username, chat.places, chat.gender, chat.masterskaya = \ primary_id, group_id, state, silent_mode, deleted, realname, contacts, username, places, gender, masterskaya LAST_UPDATE_ID = update.update_id + 1
def add_chat(_bot: Bot, update: Update) -> None: chat_id = update.effective_chat.id if not Chat.exists(chat_id=chat_id): Chat(chat_id=chat_id, name=update.effective_chat.title) Chat.get(chat_id=chat_id).name = update.effective_chat.title
def run(bot, logfile, slackbot): global LAST_UPDATE_ID for update in bot.getUpdates(offset=LAST_UPDATE_ID, timeout=10): message = update.message chat = update_chat_db(message) primary_id, group_id, state, silent_mode, deleted, realname, news = \ chat.primary_id, chat.group_id, chat.state, chat.silent_mode, chat.deleted, chat.realname, chat.news log_update(update, logfile, slackbot, primary_id) #automata_step(message, chat) reply_markup = MAIN_KEYBOARD_ADMIN if ((group_id == "admin") or (group_id == 'teacher')) else MAIN_KEYBOARD print(u"State: {}. Message: {}".format(state, message.text)) if state.startswith("REGISTER_STATE"): if len(state.split()) == 1: reply_markup = u'{{"keyboard" : [["{}"]], "resize_keyboard" : true, "one_time_keyboard" : true}}'.format(CONFIRM_CMD) realname = u"{} {}".format(message.from_user.first_name, message.from_user.last_name) text = u'Ваше имя и фамилия в Телеграме: {}. Подтвердите его (нажмите или наберите "{}") или введите Вашe имя и фамилию для использования в этом боте:'.format(realname, CONFIRM_CMD) bot.sendMessage(chat_id=message.chat_id, text=text, reply_markup=reply_markup) state = "REGISTER_STATE password" elif len(state.split()) == 2: if message.text != CONFIRM_CMD: realname = message.text bot.sendMessage(chat_id=message.chat_id, text=u"Ваше имя: {}".format(realname), reply_markup=telegram.ReplyKeyboardHide()) #bot.sendMessage(chat_id=message.chat_id, text=REGISTER_TEXT) #state = "REGISTER_STATE password realname" bot.sendMessage(chat_id=message.chat_id, text=u'Вы в группе 1! Выберите команду:', reply_markup=reply_markup) state = "MAIN_STATE" elif len(state.split()) == 3: password = message.text if password == "umbrella": group_id = "group1" bot.sendMessage(chat_id=message.chat_id, text="Спасибо, вы в группе 1!", reply_markup=MAIN_KEYBOARD) state = "MAIN_STATE" elif password == "butterfly": group_id = "group2" bot.sendMessage(chat_id=message.chat_id, text="Спасибо, вы в группе 2!", reply_markup=MAIN_KEYBOARD) state = "MAIN_STATE" elif password == "god": group_id = "teacher" bot.sendMessage(chat_id=message.chat_id, text="Вы учитель!", reply_markup=MAIN_KEYBOARD_ADMIN) state = "MAIN_STATE" elif password == "boss": group_id = "admin" bot.sendMessage(chat_id=message.chat_id, text="Вы администратор!", reply_markup=MAIN_KEYBOARD_ADMIN) state = "MAIN_STATE" else: bot.sendMessage(chat_id=message.chat_id, text="Кодовое слово мне неизвестно :(") bot.sendMessage(chat_id=message.chat_id, text=REGISTER_TEXT) elif state == "MAIN_STATE": if message.left_chat_member != None: if message.left_chat_member.id == bot.getMe().id: deleted = True elif message.new_chat_member != None: if message.new_chat_member.id == bot.getMe().id: deleted = False elif message.text == HELP_CMD: bot.sendMessage(chat_id=message.chat_id, \ text=HELP_ADMIN_TEXT if ((group_id == "admin") or (group_id == 'teacher')) else HELP_TEXT) bot.sendMessage(chat_id=message.chat_id, text=HELP_MORE_TEXT) # elif message.text == START_CMD: # silent_mode = False # deleted = False # bot.sendMessage(chat_id=message.chat_id, text=MESSAGE_START, reply_markup=reply_markup) # elif message.text == STOP_CMD: # silent_mode = True # bot.sendMessage(chat_id=message.chat_id, text=MESSAGE_STOP, reply_markup=reply_markup) elif message.text == GROUP_CHAT_CMD: if group_id == 'group1': bot.sendMessage(chat_id=message.chat_id, text=GROUP1_CHAT_LINK, reply_markup=reply_markup) elif group_id == 'group2': bot.sendMessage(chat_id=message.chat_id, text=GROUP2_CHAT_LINK, reply_markup=reply_markup) elif group_id == 'admin' or group_id == 'teacher': bot.sendMessage(chat_id=message.chat_id, text=GROUP1_CHAT_LINK, reply_markup=reply_markup) bot.sendMessage(chat_id=message.chat_id, text=GROUP2_CHAT_LINK, reply_markup=reply_markup) elif message.text == ADMIN_PASS: bot.sendMessage(chat_id=message.chat_id, text=u'Вы администратор!', reply_markup=MAIN_KEYBOARD_ADMIN) group_id = 'admin' elif message.text == NEWS_CMD: #news_message = get_news_message() if news == '': bot.sendMessage(chat_id=message.chat_id, text=u"Пока никаких новостей...", reply_markup=reply_markup) else: from_chat_id, message_id = map(int, news.split()) try: bot.forwardMessage(chat_id=message.chat_id, from_chat_id=from_chat_id, message_id=message_id) except telegram.TelegramError as error: print "TelegramError", error elif message.text == TEACHER_CMD: bot.sendMessage(chat_id=message.chat_id, text=TEACHER_TEXT, reply_markup=reply_markup) elif message.text == HOMEWORK_CMD: bot.sendMessage(chat_id=message.chat_id, text=HOMEWORK_TEXT, reply_markup=reply_markup) elif message.text == RESULTS_CMD: bot.sendMessage(chat_id=message.chat_id, text=RESULTS_TEXT, reply_markup=reply_markup) elif message.text == CARD_CMD: bot.sendMessage(chat_id=message.chat_id, text=u'Номер карты: 4276 5500 6960 1089, получатель: Климовская Динара Омирхановна. Сбербанк.\nПожалуйста, скиньте скрин платежа Яне (@yasaukova), как отправите перевод)', reply_markup=reply_markup) elif message.text == CHINESE_POD_CMD: bot.sendMessage(chat_id=message.chat_id, text=u'Доступ к Chinese Pod:\nlogin - [email protected]\npassword - lagou', reply_markup=reply_markup) elif message.text == STUFF_CMD: reply_markup = u'{{"keyboard" : [["{}", "{}", "{}"], ["{}", "{}"]], "resize_keyboard" : true}}'.\ format(STUFF_PIMSLER_CMD, STUFF_VIDEO_CMD, STUFF_RESOURCES_CMD, STUFF_BOOK_CMD, BACK_CMD) bot.sendMessage(chat_id=message.chat_id, text=u'Выберите материал:', reply_markup=reply_markup) state = 'STUFF_STATE' elif message.text == SCHEDULE_CMD: #bot.sendMessage(chat_id=message.chat_id, text="Расписание не установлено", reply_markup=reply_markup) #if group_id == "group1": # bot.sendMessage(chat_id=message.chat_id, text="Расписание не установлено", reply_markup=reply_markup) #elif group_id == "group2": # bot.sendMessage(chat_id=message.chat_id, text="Среда, с 19:30 до 20:00", reply_markup=reply_markup) #else: # schedule_message = get_schedule_message() # bot.sendMessage(chat_id=message.chat_id, text=schedule_message, reply_markup=reply_markup) schedule_message = get_schedule_message() bot.sendMessage(chat_id=message.chat_id, text=schedule_message, reply_markup=reply_markup) elif (group_id == "admin" or group_id == "teacher") and message.text == SEND_CMD: state = "SEND_STATE" reply_markup = u'{{"keyboard" : [["{}", "{}"]], "resize_keyboard" : true}}'.format(NEWS_CMD, CANCEL_CMD) bot.sendMessage(chat_id=message.chat_id, text=u"Отослать новость?", reply_markup=reply_markup) elif ((group_id == "admin") or (group_id == 'teacher')) and message.text == USER_LIST_CMD: print_userlist(bot, message) elif ((group_id == "admin") or (group_id == 'teacher')) and message.text == GOOGLE_SHEET_CMD: bot.sendMessage(chat_id=message.chat_id, text=u'Ссылка на гуглшит: {}'.format(GOOGLE_SHEET), reply_markup=reply_markup) else: pass elif state.startswith("SEND_STATE"): if message.text == CANCEL_CMD: bot.sendMessage(chat_id=message.chat_id, text=u"Рассылка отменена", reply_markup=reply_markup) state = "MAIN_STATE" elif len(state.split()) == 1: if message.text == NEWS_CMD: state += " news" reply_markup = u'{{"keyboard" : [["{}", "{}", "{}"]], "resize_keyboard" : true}}'.format(GROUP1_CMD, ALL_CMD, CANCEL_CMD) bot.sendMessage(chat_id=message.chat_id, text=u"Выберите группу для рассылки:", reply_markup=reply_markup) elif message.text == HOMEWORK_CMD: state += " homework" reply_markup = u'{{"keyboard" : [["{}", "{}", "{}"]], "resize_keyboard" : true}}'.format(GROUP1_CMD, ALL_CMD, CANCEL_CMD) bot.sendMessage(chat_id=message.chat_id, text=u"Выберите группу для рассылки:", reply_markup=reply_markup) else: reply_markup = u'{{"keyboard" : [["{}", "{}"]], "resize_keyboard" : true}}'.format(NEWS_CMD, CANCEL_CMD) bot.sendMessage(chat_id=message.chat_id, text=u'Отослать новость', reply_markup=reply_markup) elif len(state.split()) == 2: if message.text == GROUP1_CMD: state += " group1" reply_markup = u'{{"keyboard" : [["{}"]], "resize_keyboard" : true}}'.format(CANCEL_CMD) bot.sendMessage(chat_id=message.chat_id, text=u"Введите сообщение для рассылки (или файл/картинку):", reply_markup=reply_markup) elif message.text == GROUP2_CMD: state += " group2" reply_markup = u'{{"keyboard" : [["{}"]], "resize_keyboard" : true}}'.format(CANCEL_CMD) bot.sendMessage(chat_id=message.chat_id, text=u"Введите сообщение для рассылки (или файл/картинку):", reply_markup=reply_markup) elif message.text == ALL_CMD: state += " all" reply_markup = u'{{"keyboard" : [["{}"]], "resize_keyboard" : true}}'.format(CANCEL_CMD) bot.sendMessage(chat_id=message.chat_id, text=u"Введите сообщение для рассылки (или файл/картинку):", reply_markup=reply_markup) else: reply_markup = u'{{"keyboard" : [["{}", "{}", "{}"]], "resize_keyboard" : true}}'.format(GROUP1_CMD, ALL_CMD, CANCEL_CMD) bot.sendMessage(chat_id=message.chat_id, text=u"Выберите группу для рассылки:", reply_markup=reply_markup) elif len(state.split()) == 3: state += " " + str(message.message_id) reply_markup = u'{{"keyboard" : [["{}", "{}"]], "resize_keyboard" : true}}'.format(CONFIRM_CMD, CANCEL_CMD) bot.sendMessage(chat_id=message.chat_id, text=u"Подтвердите отправку:", reply_markup=reply_markup) elif len(state.split()) == 4: if message.text == CONFIRM_CMD: _, _, group, message_id = state.split() forward_broad(bot, from_chat_id=message.chat_id, message_id=message_id, group=group) # Update news after broadcasting with db_session: chat = Chat.get(chat_id=message.chat.id) news = chat.news bot.sendMessage(chat_id=message.chat_id, text=u"Отправлено!", reply_markup=reply_markup) state = "MAIN_STATE" else: reply_markup = u'{"keyboard" : [["{}", "{}"]], "resize_keyboard" : true}'.format(CONFIRM_CMD, CANCEL_CMD) bot.sendMessage(chat_id=message.chat_id, text="Подтвердите отправку:", reply_markup=reply_markup) elif state.startswith('STUFF_STATE'): if message.text == STUFF_PIMSLER_CMD: reply_markup = u'{{"keyboard" : [["{}", "{}", "{}"], ["{}", "{}"]], "resize_keyboard" : true}}'.\ format(STUFF_PIMSLER_CMD, STUFF_VIDEO_CMD, STUFF_RESOURCES_CMD, STUFF_BOOK_CMD, BACK_CMD) bot.sendMessage(chat_id=message.chat_id, text=u'Пимслер -- https://yadi.sk/d/7E_5aVZLt5Nwf', reply_markup=reply_markup) elif message.text == STUFF_VIDEO_CMD: reply_markup = u'{{"keyboard" : [["{}", "{}", "{}"], ["{}", "{}"]], "resize_keyboard" : true}}'.\ format(STUFF_PIMSLER_CMD, STUFF_VIDEO_CMD, STUFF_RESOURCES_CMD, STUFF_BOOK_CMD, BACK_CMD) bot.sendMessage(chat_id=message.chat_id, text=u'Видео: \n https://yadi.sk/d/UZQt40fKtDLpW -- уровень 1\n https://yadi.sk/d/NvR0AXDhsM7iK -- уровень 2', reply_markup=reply_markup) elif message.text == STUFF_RESOURCES_CMD: reply_markup = u'{{"keyboard" : [["{}", "{}", "{}"], ["{}", "{}"]], "resize_keyboard" : true}}'.\ format(STUFF_PIMSLER_CMD, STUFF_VIDEO_CMD, STUFF_RESOURCES_CMD, STUFF_BOOK_CMD, BACK_CMD) bot.sendMessage(chat_id=message.chat_id, text=u'Ресурсы для обучения: busuu.com. Крутые приложения: memsrise, pleco, trainchinese', reply_markup=reply_markup) elif message.text == STUFF_BOOK_CMD: reply_markup = u'{{"keyboard" : [["{}", "{}", "{}"], ["{}", "{}"]], "resize_keyboard" : true}}'.\ format(STUFF_PIMSLER_CMD, STUFF_VIDEO_CMD, STUFF_RESOURCES_CMD, STUFF_BOOK_CMD, BACK_CMD) bot.sendMessage(chat_id=message.chat_id, text=u'Книга по ключам (https://vk.com/doc326978802_437453577?hash=0a34fc79dbdf96e3b8&dl=09475a5fd4ad299d57)', reply_markup=reply_markup) elif message.text == BACK_CMD: #reply_markup = MAIN_KEYBOARD_ADMIN if ((group_id == "admin") or (group_id == 'teacher')) else MAIN_KEYBOARD bot.sendMessage(chat_id=message.chat_id, text=u'Выберите команду:', reply_markup=reply_markup) state = 'MAIN_STATE' with db_session: chat = Chat.get(chat_id=message.chat.id) chat.primary_id, chat.group_id, chat.state, chat.silent_mode, chat.deleted, chat.realname, chat.news = \ primary_id, group_id, state, silent_mode, deleted, realname, news LAST_UPDATE_ID = update.update_id + 1
def run(bot, logfile, slackbot): global LAST_UPDATE_ID for update in bot.getUpdates(offset=LAST_UPDATE_ID, timeout=10): message = update.message chat = update_chat_db(message) primary_id, group_id, state, silent_mode, deleted, realname, news = \ chat.primary_id, chat.group_id, chat.state, chat.silent_mode, chat.deleted, chat.realname, chat.news log_update(update, logfile, slackbot, primary_id) #automata_step(message, chat) reply_markup = MAIN_KEYBOARD_ADMIN if ( (group_id == "admin") or (group_id == 'teacher')) else MAIN_KEYBOARD print(u"State: {}. Message: {}".format(state, message.text)) if state.startswith("REGISTER_STATE"): if len(state.split()) == 1: reply_markup = u'{{"keyboard" : [["{}"]], "resize_keyboard" : true, "one_time_keyboard" : true}}'.format( CONFIRM_CMD) realname = u"{} {}".format(message.from_user.first_name, message.from_user.last_name) text = u'Ваше имя и фамилия в Телеграме: {}. Подтвердите его (нажмите или наберите "{}") или введите Вашe имя и фамилию для использования в этом боте:'.format( realname, CONFIRM_CMD) bot.sendMessage(chat_id=message.chat_id, text=text, reply_markup=reply_markup) state = "REGISTER_STATE password" elif len(state.split()) == 2: if message.text != CONFIRM_CMD: realname = message.text bot.sendMessage(chat_id=message.chat_id, text=u"Ваше имя: {}".format(realname), reply_markup=telegram.ReplyKeyboardHide()) #bot.sendMessage(chat_id=message.chat_id, text=REGISTER_TEXT) #state = "REGISTER_STATE password realname" bot.sendMessage(chat_id=message.chat_id, text=u'Вы в группе 1! Выберите команду:', reply_markup=reply_markup) state = "MAIN_STATE" elif len(state.split()) == 3: password = message.text if password == "umbrella": group_id = "group1" bot.sendMessage(chat_id=message.chat_id, text="Спасибо, вы в группе 1!", reply_markup=MAIN_KEYBOARD) state = "MAIN_STATE" elif password == "butterfly": group_id = "group2" bot.sendMessage(chat_id=message.chat_id, text="Спасибо, вы в группе 2!", reply_markup=MAIN_KEYBOARD) state = "MAIN_STATE" elif password == "god": group_id = "teacher" bot.sendMessage(chat_id=message.chat_id, text="Вы учитель!", reply_markup=MAIN_KEYBOARD_ADMIN) state = "MAIN_STATE" elif password == "boss": group_id = "admin" bot.sendMessage(chat_id=message.chat_id, text="Вы администратор!", reply_markup=MAIN_KEYBOARD_ADMIN) state = "MAIN_STATE" else: bot.sendMessage(chat_id=message.chat_id, text="Кодовое слово мне неизвестно :(") bot.sendMessage(chat_id=message.chat_id, text=REGISTER_TEXT) elif state == "MAIN_STATE": if message.left_chat_member != None: if message.left_chat_member.id == bot.getMe().id: deleted = True elif message.new_chat_member != None: if message.new_chat_member.id == bot.getMe().id: deleted = False elif message.text == HELP_CMD: bot.sendMessage(chat_id=message.chat_id, \ text=HELP_ADMIN_TEXT if ((group_id == "admin") or (group_id == 'teacher')) else HELP_TEXT) bot.sendMessage(chat_id=message.chat_id, text=HELP_MORE_TEXT) # elif message.text == START_CMD: # silent_mode = False # deleted = False # bot.sendMessage(chat_id=message.chat_id, text=MESSAGE_START, reply_markup=reply_markup) # elif message.text == STOP_CMD: # silent_mode = True # bot.sendMessage(chat_id=message.chat_id, text=MESSAGE_STOP, reply_markup=reply_markup) elif message.text == GROUP_CHAT_CMD: if group_id == 'group1': bot.sendMessage(chat_id=message.chat_id, text=GROUP1_CHAT_LINK, reply_markup=reply_markup) elif group_id == 'group2': bot.sendMessage(chat_id=message.chat_id, text=GROUP2_CHAT_LINK, reply_markup=reply_markup) elif group_id == 'admin' or group_id == 'teacher': bot.sendMessage(chat_id=message.chat_id, text=GROUP1_CHAT_LINK, reply_markup=reply_markup) bot.sendMessage(chat_id=message.chat_id, text=GROUP2_CHAT_LINK, reply_markup=reply_markup) elif message.text == ADMIN_PASS: bot.sendMessage(chat_id=message.chat_id, text=u'Вы администратор!', reply_markup=MAIN_KEYBOARD_ADMIN) group_id = 'admin' elif message.text == NEWS_CMD: #news_message = get_news_message() if news == '': bot.sendMessage(chat_id=message.chat_id, text=u"Пока никаких новостей...", reply_markup=reply_markup) else: from_chat_id, message_id = map(int, news.split()) try: bot.forwardMessage(chat_id=message.chat_id, from_chat_id=from_chat_id, message_id=message_id) except telegram.TelegramError as error: print "TelegramError", error elif message.text == TEACHER_CMD: bot.sendMessage(chat_id=message.chat_id, text=TEACHER_TEXT, reply_markup=reply_markup) elif message.text == HOMEWORK_CMD: bot.sendMessage(chat_id=message.chat_id, text=HOMEWORK_TEXT, reply_markup=reply_markup) elif message.text == RESULTS_CMD: bot.sendMessage(chat_id=message.chat_id, text=RESULTS_TEXT, reply_markup=reply_markup) elif message.text == CARD_CMD: bot.sendMessage( chat_id=message.chat_id, text= u'Номер карты: 4276 5500 6960 1089, получатель: Климовская Динара Омирхановна. Сбербанк.\nПожалуйста, скиньте скрин платежа Яне (@yasaukova), как отправите перевод)', reply_markup=reply_markup) elif message.text == CHINESE_POD_CMD: bot.sendMessage( chat_id=message.chat_id, text= u'Доступ к Chinese Pod:\nlogin - [email protected]\npassword - lagou', reply_markup=reply_markup) elif message.text == STUFF_CMD: reply_markup = u'{{"keyboard" : [["{}", "{}", "{}"], ["{}", "{}"]], "resize_keyboard" : true}}'.\ format(STUFF_PIMSLER_CMD, STUFF_VIDEO_CMD, STUFF_RESOURCES_CMD, STUFF_BOOK_CMD, BACK_CMD) bot.sendMessage(chat_id=message.chat_id, text=u'Выберите материал:', reply_markup=reply_markup) state = 'STUFF_STATE' elif message.text == SCHEDULE_CMD: #bot.sendMessage(chat_id=message.chat_id, text="Расписание не установлено", reply_markup=reply_markup) #if group_id == "group1": # bot.sendMessage(chat_id=message.chat_id, text="Расписание не установлено", reply_markup=reply_markup) #elif group_id == "group2": # bot.sendMessage(chat_id=message.chat_id, text="Среда, с 19:30 до 20:00", reply_markup=reply_markup) #else: # schedule_message = get_schedule_message() # bot.sendMessage(chat_id=message.chat_id, text=schedule_message, reply_markup=reply_markup) schedule_message = get_schedule_message() bot.sendMessage(chat_id=message.chat_id, text=schedule_message, reply_markup=reply_markup) elif (group_id == "admin" or group_id == "teacher") and message.text == SEND_CMD: state = "SEND_STATE" reply_markup = u'{{"keyboard" : [["{}", "{}"]], "resize_keyboard" : true}}'.format( NEWS_CMD, CANCEL_CMD) bot.sendMessage(chat_id=message.chat_id, text=u"Отослать новость?", reply_markup=reply_markup) elif ((group_id == "admin") or (group_id == 'teacher')) and message.text == USER_LIST_CMD: print_userlist(bot, message) elif ( (group_id == "admin") or (group_id == 'teacher')) and message.text == GOOGLE_SHEET_CMD: bot.sendMessage( chat_id=message.chat_id, text=u'Ссылка на гуглшит: {}'.format(GOOGLE_SHEET), reply_markup=reply_markup) else: pass elif state.startswith("SEND_STATE"): if message.text == CANCEL_CMD: bot.sendMessage(chat_id=message.chat_id, text=u"Рассылка отменена", reply_markup=reply_markup) state = "MAIN_STATE" elif len(state.split()) == 1: if message.text == NEWS_CMD: state += " news" reply_markup = u'{{"keyboard" : [["{}", "{}", "{}"]], "resize_keyboard" : true}}'.format( GROUP1_CMD, ALL_CMD, CANCEL_CMD) bot.sendMessage(chat_id=message.chat_id, text=u"Выберите группу для рассылки:", reply_markup=reply_markup) elif message.text == HOMEWORK_CMD: state += " homework" reply_markup = u'{{"keyboard" : [["{}", "{}", "{}"]], "resize_keyboard" : true}}'.format( GROUP1_CMD, ALL_CMD, CANCEL_CMD) bot.sendMessage(chat_id=message.chat_id, text=u"Выберите группу для рассылки:", reply_markup=reply_markup) else: reply_markup = u'{{"keyboard" : [["{}", "{}"]], "resize_keyboard" : true}}'.format( NEWS_CMD, CANCEL_CMD) bot.sendMessage(chat_id=message.chat_id, text=u'Отослать новость', reply_markup=reply_markup) elif len(state.split()) == 2: if message.text == GROUP1_CMD: state += " group1" reply_markup = u'{{"keyboard" : [["{}"]], "resize_keyboard" : true}}'.format( CANCEL_CMD) bot.sendMessage( chat_id=message.chat_id, text= u"Введите сообщение для рассылки (или файл/картинку):", reply_markup=reply_markup) elif message.text == GROUP2_CMD: state += " group2" reply_markup = u'{{"keyboard" : [["{}"]], "resize_keyboard" : true}}'.format( CANCEL_CMD) bot.sendMessage( chat_id=message.chat_id, text= u"Введите сообщение для рассылки (или файл/картинку):", reply_markup=reply_markup) elif message.text == ALL_CMD: state += " all" reply_markup = u'{{"keyboard" : [["{}"]], "resize_keyboard" : true}}'.format( CANCEL_CMD) bot.sendMessage( chat_id=message.chat_id, text= u"Введите сообщение для рассылки (или файл/картинку):", reply_markup=reply_markup) else: reply_markup = u'{{"keyboard" : [["{}", "{}", "{}"]], "resize_keyboard" : true}}'.format( GROUP1_CMD, ALL_CMD, CANCEL_CMD) bot.sendMessage(chat_id=message.chat_id, text=u"Выберите группу для рассылки:", reply_markup=reply_markup) elif len(state.split()) == 3: state += " " + str(message.message_id) reply_markup = u'{{"keyboard" : [["{}", "{}"]], "resize_keyboard" : true}}'.format( CONFIRM_CMD, CANCEL_CMD) bot.sendMessage(chat_id=message.chat_id, text=u"Подтвердите отправку:", reply_markup=reply_markup) elif len(state.split()) == 4: if message.text == CONFIRM_CMD: _, _, group, message_id = state.split() forward_broad(bot, from_chat_id=message.chat_id, message_id=message_id, group=group) # Update news after broadcasting with db_session: chat = Chat.get(chat_id=message.chat.id) news = chat.news bot.sendMessage(chat_id=message.chat_id, text=u"Отправлено!", reply_markup=reply_markup) state = "MAIN_STATE" else: reply_markup = u'{"keyboard" : [["{}", "{}"]], "resize_keyboard" : true}'.format( CONFIRM_CMD, CANCEL_CMD) bot.sendMessage(chat_id=message.chat_id, text="Подтвердите отправку:", reply_markup=reply_markup) elif state.startswith('STUFF_STATE'): if message.text == STUFF_PIMSLER_CMD: reply_markup = u'{{"keyboard" : [["{}", "{}", "{}"], ["{}", "{}"]], "resize_keyboard" : true}}'.\ format(STUFF_PIMSLER_CMD, STUFF_VIDEO_CMD, STUFF_RESOURCES_CMD, STUFF_BOOK_CMD, BACK_CMD) bot.sendMessage( chat_id=message.chat_id, text=u'Пимслер -- https://yadi.sk/d/7E_5aVZLt5Nwf', reply_markup=reply_markup) elif message.text == STUFF_VIDEO_CMD: reply_markup = u'{{"keyboard" : [["{}", "{}", "{}"], ["{}", "{}"]], "resize_keyboard" : true}}'.\ format(STUFF_PIMSLER_CMD, STUFF_VIDEO_CMD, STUFF_RESOURCES_CMD, STUFF_BOOK_CMD, BACK_CMD) bot.sendMessage( chat_id=message.chat_id, text= u'Видео: \n https://yadi.sk/d/UZQt40fKtDLpW -- уровень 1\n https://yadi.sk/d/NvR0AXDhsM7iK -- уровень 2', reply_markup=reply_markup) elif message.text == STUFF_RESOURCES_CMD: reply_markup = u'{{"keyboard" : [["{}", "{}", "{}"], ["{}", "{}"]], "resize_keyboard" : true}}'.\ format(STUFF_PIMSLER_CMD, STUFF_VIDEO_CMD, STUFF_RESOURCES_CMD, STUFF_BOOK_CMD, BACK_CMD) bot.sendMessage( chat_id=message.chat_id, text= u'Ресурсы для обучения: busuu.com. Крутые приложения: memsrise, pleco, trainchinese', reply_markup=reply_markup) elif message.text == STUFF_BOOK_CMD: reply_markup = u'{{"keyboard" : [["{}", "{}", "{}"], ["{}", "{}"]], "resize_keyboard" : true}}'.\ format(STUFF_PIMSLER_CMD, STUFF_VIDEO_CMD, STUFF_RESOURCES_CMD, STUFF_BOOK_CMD, BACK_CMD) bot.sendMessage( chat_id=message.chat_id, text= u'Книга по ключам (https://vk.com/doc326978802_437453577?hash=0a34fc79dbdf96e3b8&dl=09475a5fd4ad299d57)', reply_markup=reply_markup) elif message.text == BACK_CMD: #reply_markup = MAIN_KEYBOARD_ADMIN if ((group_id == "admin") or (group_id == 'teacher')) else MAIN_KEYBOARD bot.sendMessage(chat_id=message.chat_id, text=u'Выберите команду:', reply_markup=reply_markup) state = 'MAIN_STATE' with db_session: chat = Chat.get(chat_id=message.chat.id) chat.primary_id, chat.group_id, chat.state, chat.silent_mode, chat.deleted, chat.realname, chat.news = \ primary_id, group_id, state, silent_mode, deleted, realname, news LAST_UPDATE_ID = update.update_id + 1