def process_answer(bot, update): query = update.callback_query bot.edit_message_text( text="{}\n{}".format(query.message.text, query.data), chat_id=query.message.chat_id, message_id=query.message.message_id) quiz = quiz_storage.get_latest_quiz(query.message.chat_id) quiz_storage.save_answer(quiz, int(query.data)) if quiz.is_completed: bot.send_message(chat_id=query.message.chat_id, text="🏁\n{}".format(quiz.get_result())) else: question = quiz.get_question() if quiz.type_ == 'hars': send_hars_question(question, bot, query.message.chat_id) else: send_madrs_question(question, bot, query.message.chat_id)
def inline(message): key = types.InlineKeyboardMarkup() cat_button = types.InlineKeyboardButton(text='Cat', callback_data='cat') dog_button = types.InlineKeyboardButton(text='Dog', callback_data='dog') panda_button = types.InlineKeyboardButton(text='Panda', callback_data='panda') red_panda_button = types.InlineKeyboardButton(text='Red Panda', callback_data='red_panda') koala_button = types.InlineKeyboardButton(text='Koala', callback_data='koala') fox_button = types.InlineKeyboardButton(text='Fox', callback_data='fox') key.add(cat_button, dog_button, panda_button, red_panda_button, fox_button, koala_button) bot.send_message(message.chat.id, 'Select your pet', reply_markup=key) print(message)
def send_one_tip(bot, update): restriction = len(tips_library) chat = chat_storage.get_or_create(update.message.chat_id) num = chat['tips_id'] if num < restriction: bot.send_message(chat_id=update.message.chat_id, text=tips_library[num]) chat['tips_id'] += 1 chat_storage.save(chat) else: chat['tips_id'] = 0 num = chat['tips_id'] chat_storage.save(chat) bot.send_message(chat_id=update.message.chat_id, text=tips_library[num])
def number(bot, update): text = 'Начать' text2 = '⚙️Настройка' text3 = 'Узнать критичность' print('Was clicked') if update.message.text == text or update.message.text == text2 or update.message.text == text3: con_keyboard = KeyboardButton(text='Отправить номер', request_contact=True) custom_keyboard = [[con_keyboard]] reply_markup = telegram.ReplyKeyboardMarkup(custom_keyboard) bot.send_message(chat_id=update.message.chat_id, text="Отправьте свой номер", reply_markup=reply_markup) return PHONE else: return q2
def manageAnswers(bot, update): global results global wasQuestion if wasQuestion: results.append(update.message.text) wasQuestion = False result = risk_estimation() * 100 print("The number of clicks {}".format(counter)) custom_keyboard = [['Узнать критичность', '⚙️Настройка'], ['Как пользоваться?']] reply_markup = telegram.ReplyKeyboardMarkup(custom_keyboard) bot.send_message(chat_id=update.message.chat_id, text="""Критичность вызова {} \n {}""".format( result, speechafter), reply_markup=reply_markup) return CONV2
def __send_message_buffer(self, bot: telegram.Bot, chat_id: str, text: str, final=False, **kwargs): """ :param bot: Telegram bot :type bot: telegram.Bot :param chat_id: Chat ID to send the messages to :type chat_id: str :param text: The text to send :type text: str :param final: Last part of the message, i.e. flush the buffer? :type final: bool :param kwargs: args to pass to bot.send_message() :type kwargs: :return: :rtype: Sends a bunch of message lines to the chat_id, honoring telegram's max message length. If a single line (text) should exceed the maximum message length, an exception will be raised """ # Not sure if there should be a seperate buffer for eatch chat_id.. i.e. is this method thread safe? Does # it need to be? For now there won't be buffers per chat_id, only one single, global one. message_length = len(text) if message_length >= max_message_length: raise botexceptions.TelegramMessageLength(message_length) if len(self._output_buffer) + message_length >= max_message_length: bot.send_message(chat_id=chat_id, text=self._output_buffer, **kwargs) self._output_buffer = text else: self._output_buffer += text # There's no case final is set and there's an empty buffer: If buffer is full, buffer contains the # message containing the potential overflow. if final: bot.send_message(chat_id=chat_id, text=self._output_buffer, **kwargs) self._output_buffer = ""
def print_average(bot, update): chat_id = str(update.message.chat_id) sum = 0 cnt = 0 with open(counts_dir + chat_id + db_file, 'r') as db: for line in db.readlines(): tmp = int(line.split("\t")[0]) if tmp != 0: sum += tmp cnt += 1 if cnt == 0: avg = 0 # avoid dividing by 0 else: avg = round(float(sum / cnt), 2) bot.send_message(chat_id=chat_id, text="La nostra media attuale di asd settimanali è di " + str(avg) + " asd. Asdate di più per alzarla!")
def periodic_notifiction_callback(bot, job): for chat in chat_storage.get_chats(): if chat['frequency'] == 'none': continue created_at = datetime.strptime(chat['created_at'], '%Y-%m-%d %H-%M-%S') now = datetime.now() if created_at.hour != now.hour: continue if (chat['frequency'] == 'weekly') and (now.weekday() != created_at.weekday()): continue try: bot.send_message( chat_id=chat['id'], text=texts.PERIODIC_NOTIFICATION[chat['language']]) except BadRequest: pass
def start(bot, update): # Select language langs_markup = InlineKeyboardMarkup([[ InlineKeyboardButton('English {}'.format( b'\xF0\x9F\x87\xAC\xF0\x9F\x87\xA7'.decode()), callback_data='en'), InlineKeyboardButton('Русский {}'.format( b'\xF0\x9F\x87\xB7\xF0\x9F\x87\xBA'.decode()), callback_data='ru'), InlineKeyboardButton('Português {}'.format( b'\xF0\x9F\x87\xA7\xF0\x9F\x87\xB7'.decode()), callback_data='pt') ]]) bot.send_message( text='Choose your language / Выберите язык / Escolha seu idioma', reply_markup=langs_markup, chat_id=update.message.chat_id, )
def main(): # Loading config file path = os.path.dirname(os.path.realpath(__file__)) config = configparser.RawConfigParser() config.read(os.path.join(path, 'config', 'bot.cfg')) # Initialising bot bot = telegram.bot.Bot(config.get('api', 'token')) # Loading all chat ids from the database db_dirname = os.path.join(path, 'db') db = db_tools.DBTools(db_dirname) chat_ids = db.get_all_chats() # Building and sending messages to every chat for chat_id in chat_ids: bot.send_message(chat_id=chat_id, text=message_constructor.build_message())
def admin(update, context): msg = '*LIVE STREAMING*\nAdmin Control Panel' keyboard = [ [InlineKeyboardButton("View Log", callback_data='log')], [ InlineKeyboardButton("Recording Viewer Count", callback_data='latestcount') ], [InlineKeyboardButton("Login IP Report", callback_data='doipwarn')], [InlineKeyboardButton("Sync Loty Database", callback_data='syncloty')], [InlineKeyboardButton("Sync Life Database", callback_data='synclife')], [InlineKeyboardButton("Finalise Stream", callback_data='endstream')], ] reply_markup = InlineKeyboardMarkup(keyboard) bot.send_message(chat_id=group, reply_markup=reply_markup, text=msg, parse_mode=telegram.ParseMode.MARKDOWN)
def announce(self, update, context): """ Make an announcement """ bot = context.bot if self.id is None: update.message.reply_text("You have to register me first (using " "the /start command).") return if self.id != update.message.chat_id: logger.warning("Warning! Someone tried to make an announcement in " "a chat I'm not registered in!") bot.send_message(chat_id=self.id, text="Warning! Someone tried to make an " "announcement in another chat!") return if len(self.contests) == 0: update.answer(text="There's no contest I could announce this in.") return if len(self.contests) > 1: text = "Which contest would you like to announce this in?" kb = [[InlineKeyboardButton(text=self.contests[i].description, callback_data="A_"+str(i))] for i in range(len(self.contests)) ] + \ [[InlineKeyboardButton(text="<I would not.>", callback_data="A_N")]] else: text = "Would you like to announce the following?" kb = [[InlineKeyboardButton(text="Yes", callback_data="A_0"), InlineKeyboardButton(text="No", callback_data="A_N")]] announcement_text = update.message.text header, msg = split_off_header(strip_cmd(announcement_text)) text += "\n\n" + bold(escape(header)) + "\n" + escape(msg) bot.send_message(chat_id=self.id, reply_to_message_id=update.message.message_id, text=text, reply_markup=InlineKeyboardMarkup(kb), parse_mode="MarkdownV2")
def admin(update, context): msg = '*LIVE STREAMING*\nAdmin Control Panel' keyboard = [ [InlineKeyboardButton( "Start Stream (Sanctuary)", callback_data='stream1')], [InlineKeyboardButton( "Stop Stream (Sanctuary)", callback_data='kill1')], [InlineKeyboardButton( "Start Stream (MPH)", callback_data='stream2')], [InlineKeyboardButton( "Stop Stream (MPH)", callback_data='kill2')], [InlineKeyboardButton( "View Log (English Svc)", callback_data='englog')], [InlineKeyboardButton( "View Log (Chinese Svc)", callback_data='chilog')] ] reply_markup = InlineKeyboardMarkup(keyboard) bot.send_message( chat_id=group, reply_markup=reply_markup, text=msg, parse_mode=telegram.ParseMode.MARKDOWN)
def main_worker(): """ Основной воркер - обработчик обновлений """ try: update_data = request.get_json() update_obj = update.Update(update_data) if update_obj.message.voice: voice_file = bot.download_file(update_obj.message.voice.file_id) if not voice_file: return "ok" audio_file = audio.AudioFile(voice_file, "ogg", "mp3") voice_text = recognize(audio_file) bot.send_message(update_obj.message.chat.id, voice_text, reply_to_message_id=update_obj.message.message_id) # В любом случае отдаем "ok" чтобы повторно не получать обновление except Exception as exc: return "ok" return "ok"
def new(update, context): today = date.today().strftime('%d %b %Y') global checkin checkin[today] = {} checkout[today] = {} with open('checkin.json', 'w') as checkinfile: json.dump(checkin, checkinfile) with open('checkout.json', 'w') as checkoutfile: json.dump(checkout, checkoutfile) with open('tracing.txt', 'a+') as tracing: tracing.write('\n' + today + '\n') msg = '*YF Contact Tracing* ({})\n\n{}\n\n_0 checked in_\n_0 checked out_'.format( today, declaration) keyboard = InlineKeyboardMarkup( [[InlineKeyboardButton('CHECK IN', callback_data='checkin')], [InlineKeyboardButton('CHECK OUT', callback_data='checkout')]]) bot.send_message(chat_id=channel, reply_markup=keyboard, text=msg, parse_mode=telegram.ParseMode.MARKDOWN)
def skip_player(message): session = session_manager.active_chat_session(message.chat.id) if not session or session.id not in session_manager.get_player_sessions( message.from_user.id): return old, new = user_session_manager.step(session) if old: bot.send_message(old.user, 'Sorry! Your step was skipped!') bot.send_message(session.chat, 'Current player is skipped!') if new: save_id = user_session_manager.write_from_prev(old) if save_id: bot.send_message( new.user, 'Your turn!\nDownload the save: ' + google_docs.get_link(save_id)) else: bot.send_message(new.user, 'Your turn!\nYou are the first!') else: bot.send_message(session.chat, 'The round of game is end.')
def start_main_menu(bot, update, args=None): player, _ = utils.get_or_create_player(bot, update, args=args) player_quests = player.has_quests if player_quests: button_list = [ KeyboardButton(quest_utils.menu_text_full("MY_GAMES")), KeyboardButton(quest_utils.menu_text_full("ALL_GAMES")), KeyboardButton(quest_utils.menu_text_full("SETTINGS")), ] else: button_list = [ KeyboardButton(quest_utils.menu_text_full("ALL_GAMES")), KeyboardButton(quest_utils.menu_text_full("SETTINGS")), ] reply_markup = ReplyKeyboardMarkup(utils.build_menu(button_list, n_cols=1), resize_keyboard=True) bot.send_message(update.message.chat_id, config.MAIN_MENU_TEXT, reply_markup=reply_markup)
def viewcounter(id, name): try: connection = psycopg2.connect(user=dbuser, password=dbpass, host=dbhost, port=dbport, database=dbdata) cursor = connection.cursor() cursor.execute( f"SELECT id, name, date FROM events WHERE category_id={id} ORDER BY date" ) services = cursor.fetchall() compose = f'{name}\n\n' for data in services: i = data[0] name = data[1] if 'Service' in name: name = data[2].strftime('%d %b') cursor.execute( "SELECT COUNT(*) FROM(SELECT DISTINCT user_id FROM user_activities WHERE id > 59170 AND path='/api/content/event/%s/mediaentrylist') AS x", (i, )) eventclicks = cursor.fetchone()[0] cursor.execute( "SELECT COUNT(*) FROM(SELECT user_id FROM user_activities WHERE id > 59170 AND path='/api/content/event/%s/mediaentrylist') AS x", (i, )) eventviews = cursor.fetchone()[0] if int(eventclicks) > 0: compose += "{}: *{} views ({} users)*\n".format( name, eventviews, eventclicks) bot.send_message(chat_id=group, text=compose, parse_mode=telegram.ParseMode.MARKDOWN) except (Exception, psycopg2.Error) as error: print("Error", error) finally: if (connection): cursor.close() connection.close()
def bot_reload(bot, update): global const global command_module global current_job # global database # db if not check_admin(update.message.from_user.id): bot.send_message(chat_id=update.message.chat_id, text="permission_denied") return ## update constant const = importlib.reload(const) # database = importlib.reload(database) # db reload_admin_list() ## stop the jobs for job in current_job: job.schedule_removal() current_job = [] ## remove old handlers for current_module in command_module: dispatcher.remove_handler(current_module._handler) ## reload modules and update handlers try: command_module = [] for module_name in const.MODULE_NAME: current_module = importlib.import_module(module_name) current_module = importlib.reload(current_module) command_module.append(current_module) dispatcher.add_handler(current_module._handler) for job_name in const.JOB_NAME: job_module = importlib.import_module(job_name) job_module = importlib.reload(job_module) job = job_queue.run_repeating(job_module._callback, interval=job_module._interval, first=job_module._first) current_job.append(job) bot.send_message(chat_id=update.message.chat_id, text="reload_cmd_success") except Exception as e: failed_text = "reload_cmd_failed" bot.send_message(chat_id=update.message.chat_id, text=failed_text) bot.send_message(chat_id=update.message.chat_id, text=traceback.print_exc())
def conversationStarter(bot, update): print("HERE") custom_keyboard = [['Узнать критичность'], ['Как пользоваться?']] reply_markup = telegram.ReplyKeyboardMarkup(custom_keyboard) # [['Узнать критичность', '⚙️Настройка'], ['Как пользоваться?']] text = ['⚙️Настройка', 'Узнать критичность', 'Как пользоваться?'] if update.message.text == text[0]: bot.send_message(chat_id=update.message.chat_id, text="Ваши данные сохранены в базу, пройдите тест", reply_markup=reply_markup) return CONV elif update.message.text == text[1]: return START elif update.message.text == text[2]: bot.send_message( chat_id=update.message.chat_id, text= "Чтобы узнать уровень критичности ситуации, нажмите на Узнать критичность два раза", reply_markup=reply_markup) return CONV else: return ConversationHandler.END
def callbackquery(update, context): query = update.callback_query data = query.data first_name = query.from_user.first_name last_name = query.from_user.last_name full_name = (str(first_name or '') + ' ' + str(last_name or '')).strip() bot.send_message(chat_id=group, text='`Bot is responding to command by {}`'.format( full_name), parse_mode=telegram.ParseMode.MARKDOWN) if data == 'stream1': stream1() elif data == 'kill1': kill1() elif data == 'stream2': stream2() elif data == 'kill2': kill2() elif data == 'englog': log('English Service', 'GET /live.m3u8?') elif data == 'chilog': bot.send_message( chat_id=group, text='This feature is not implemented yet!') context.bot.answer_callback_query(query.id)
def get_text_messages(message): if message.text == "Привет": bot.send_message(message.from_user.id, "Привет.") elif message.text == "/help": bot.send_message(message.from_user.id, "Напиши Привет") else: bot.send_message(message.from_user.id, "Я тебя не понимаю. Напиши /help.")
def process_answer(bot, update): #ASS added quiz_answer to send individual weights for every question: query = update.callback_query quiz = quiz_storage.get_latest_quiz(query.message.chat_id) quiz_storage.save_answer(quiz, int(query.data)) lang = chat_storage.get_or_create(query.message.chat_id)['language'] if quiz.type_ == 'hars': bot.edit_message_text( text="{}\n{}".format(query.message.text, query.data), chat_id=query.message.chat_id, message_id=query.message.message_id) if quiz.is_completed: #ASS have added and hars bot.send_message(chat_id=query.message.chat_id, text="🏁\n{}".format(quiz.get_result())) else: question = quiz.get_question() answer_weight = quiz.get_answers_weight() send_hars_question(question, answer_weight, bot, query.message.chat_id) if quiz.type_ == 'amiready': n = int(query.data) quiz.process_direction(n) question = quiz.get_direction() send_amiready_question(question, bot, query.message.chat_id) if quiz.type_ == 'criticism': n = int(query.data) if quiz.question_number == 2: if n ==0: send_yes_no_keyboard(bot, chat_id = query.message.chat_id, qs_key = texts.CRITICISM_Q[lang][1]) else: bot.send_message(chat_id=query.message.chat_id, text= texts.CRIT_An[lang]) if quiz.question_number == 3: if n==0: send_yes_no_keyboard(bot, chat_id = query.message.chat_id, qs_key = texts.CRITICISM_Q[lang][2]) else: bot.send_message(chat_id=query.message.chat_id, text= texts.CRIT_An[lang]) if quiz.question_number == 4: if n== 0: bot.send_message(chat_id=query.message.chat_id, text=texts.CRITICISM_Q[lang][3]) else: bot.send_message(chat_id=query.message.chat_id, text=texts.CRIT_An[lang])
def process_answer(bot, update): #ASS added quiz_answer to send individual weights for every question: query = update.callback_query quiz = quiz_storage.get_latest_quiz(query.message.chat_id) quiz_storage.save_answer(quiz, int(query.data)) if quiz.type_ == 'hars': bot.edit_message_text(text="{}\n{}".format(query.message.text, query.data), chat_id=query.message.chat_id, message_id=query.message.message_id) if quiz.is_completed: #ASS have added and hars bot.send_message(chat_id=query.message.chat_id, text="🏁\n{}".format(quiz.get_result())) else: question = quiz.get_question() answer_weight = quiz.get_answers_weight() send_hars_question(question, answer_weight, bot, query.message.chat_id) elif quiz.type_ == 'amiready': n = int(query.data) quiz.process_direction(n) question = quiz.get_direction() send_amiready_question(question, bot, query.message.chat_id)
def send_notice(channel, text): ''' This function broadcasts the given text to the specified channel via MQBot. ''' #['return' not functioning as expected!!!] return kic_bot.send_message(chat_id = channel, disable_web_page_preview = True, parse_mode = 'HTML', text = text) ''' The below code may be used in place of the above code. But only one may be used at a time. The above delegates the message sending function to MQBot. The below executes the message sending function directly. ''' return bot.send_message(chat_id=channel, disable_web_page_preview=True, parse_mode='HTML', text=text)
def asd_counter(bot, update): """ this function increases the asd_count and writes it to disk when a new message on the filtered group contains at least 1 "asd" """ if update.message.chat.type == chat.Chat.SUPERGROUP and \ update.message.chat.title == "WEEE Chat": print(update.message.chat.title + " " + str(update.message.chat_id)) asd_increment = update.message.text.lower().count("asd") if asd_increment > 0: try: asd_count, date, week_start = get_current_count_content() print(asd_count, date) f = open("current_count.txt", 'w') asd_count += asd_increment f.write(str(asd_count) + " " + date) f.close() print("asd counter increased to " + str(asd_count)) except Exception as e: bot.send_message(chat_id=castes_chat_id, text="asd_counter_bot si è sminchiato perché:\n" + str(e)) print(e)
def index(): if request.method == 'POST': x = request.get_json(force=True) compose = '' compose += '<u>AWS Simple Email Service</u>\n' try: compose += '<b>Notification Type: </b>' + \ x['notificationType'] + '\n' except: print(x) return '{"success":"true"}', 200 for y in x['mail']['commonHeaders']['to']: compose += '<b>To: </b>' + y + '\n' compose += '<b>Subject: </b>' + x['mail']['commonHeaders']['subject'] try: x = x['bounce'] compose += '\n\n' compose += '<b>Bounce Type: </b>' + \ x['bounceType'] + ' (' + x['bounceSubType'] + ')\n' for y in x['bouncedRecipients']: compose += y['status'] + ' ' + y['action'].upper() + '\n' compose += y['diagnosticCode'] except: pass try: x = x['complaint'] compose += '\n\n' compose += '<b>Complaint: </b>' + \ x['complaintFeedbackType'] + ' - ' + x['userAgent'] + '\n' except: pass bot.send_message(chat_id=group, text=compose, parse_mode=telegram.ParseMode.HTML, disable_web_page_preview=True) return '{"success":"true"}', 200
def check_validity(update: Update, context: CallbackContext) -> None: if "fen" not in context.user_data: bot.send_message(update.message.chat.id, "Send photo of the chess board") else: fen = context.user_data["fen"] turn = context.args[0] stockfish_engine.set_fen_position(fen) validity = stockfish_engine.is_move_correct(turn) if validity is True: bot.send_message(update.message.chat.id, "Move is valid") elif validity is False: bot.send_message(update.message.chat.id, "Move is wrong")
def bot_reload(bot, update): global helper_const global helper_string global helper_database global command_module if not check_admin(update.message.from_user.id): permission_denied = helper_global.value("permission_denied_text", "") bot.send_message(chat_id=update.message.chat_id, text=permission_denied) return ## update constant helper_const = importlib.reload(helper_const) helper_string = importlib.reload(helper_string) helper_database = importlib.reload(helper_database) reload_admin_list() ## remove old handlers for current_module in command_module: dispatcher.remove_handler(current_module._handler) ## reload modules and update handlers try: command_module = [] for module_name in helper_const.MODULE_NAME: logger.msg("Reloading module \"%s\"..." % module_name, tag="main", log_level=100) current_module = importlib.import_module("modules." + module_name) current_module = importlib.reload(current_module) command_module.append(current_module) dispatcher.add_handler(current_module._handler) success_text = helper_global.value("reload_cmd_success", "") bot.send_message(chat_id=update.message.chat_id, text=success_text) except Exception as e: failed_text = helper_global.value("reload_cmd_failed", "") bot.send_message(chat_id=update.message.chat_id, text=failed_text) bot.send_message(chat_id=update.message.chat_id, text=traceback.print_exc())
def stream2(): global process2 bot.send_message(chat_id=group, text='_Starting stream from MPH..._', parse_mode=telegram.ParseMode.MARKDOWN) process2 = subprocess.Popen(['ffmpeg', '-i', rtsp2, '-vcodec', 'copy', '-acodec', 'copy', '-f', 'flv', rtmp2], stderr=subprocess.PIPE, universal_newlines=True) monitor = True while True: output = process2.stderr.readline() if output == '' and process2.poll() is not None: break if output: if monitor and 'speed=' in output: bot.send_message(chat_id=group, text='*MPH stream connected*', parse_mode=telegram.ParseMode.MARKDOWN) monitor = False elif 'failed' in output or 'error' in output: bot.send_message(chat_id=group, text='*MPH stream connection failure*', parse_mode=telegram.ParseMode.MARKDOWN) return bot.send_message(chat_id=group, text='*MPH stream disconnected*', parse_mode=telegram.ParseMode.MARKDOWN) return