def _handle_check_config(update: Update, context: CallbackContext): """Check if user's config is valid. Raises: DispatcherHandlerStop: The user's configuration is invalid, don't run any more handlers. """ if not context.user_data["opts"].get("file"): update.effective_message.reply_text( "No file is specified. Please ask the admin to specify a file for you." ) raise DispatcherHandlerStop() else: f: str = context.user_data["opts"]["file"] f = f.replace("%Y", f"{date.today():%Y}").replace("%M", f"{date.today():%m}") context.user_data["opts"]["file"] = f if not context.user_data["opts"].get("account"): update.effective_message.reply_text( "No account is specified. Please ask the admin to specify an account for you." ) raise DispatcherHandlerStop() if not context.user_data["opts"].get("withdrawal_account"): update.effective_message.reply_text( "No withdrawal account is specified. Please ask the admin to specify an account for you." ) raise DispatcherHandlerStop()
def has_rights(self, update: Update, context: CallbackContext): if update.message.from_user.name in AbstractModule.mutedAccounts: update.message.reply_text('..hot wer wos gsogt?') raise DispatcherHandlerStop() if update.message.from_user.last_name in AbstractModule.mutedAccounts: update.message.reply_text('..hot wer wos gsogt?') raise DispatcherHandlerStop()
def check_if_admin_handler(bot, update): chat_id = update.message.chat.id if not chat_id: raise DispatcherHandlerStop() message = update.message if not message.from_user: # No sender raise DispatcherHandlerStop() user_id = message.from_user.id # Get sender info in the chat chat_member = bot.get_chat_member(chat_id, user_id) if not chat_member: raise DispatcherHandlerStop() # Sender is not the creator or admin, stop handling the message if chat_member.status not in [ 'creator', 'administrator', ]: raise DispatcherHandlerStop() return
def handle_update( # type: ignore[override] self, update: HandlerArg, dispatcher: 'Dispatcher', check_result: CheckUpdateType, context: CallbackContext = None, ) -> Optional[object]: """Send the update to the callback for the current state and Handler Args: check_result: The result from check_update. For this handler it's a tuple of key, handler, and the handler's check result. update (:class:`telegram.Update`): Incoming telegram update. dispatcher (:class:`telegram.ext.Dispatcher`): Dispatcher that originated the Update. context (:class:`telegram.ext.CallbackContext`, optional): The context as provided by the dispatcher. """ update = cast(Update, update) # for mypy conversation_key, handler, check_result = check_result # type: ignore[assignment,misc] raise_dp_handler_stop = False with self._timeout_jobs_lock: # Remove the old timeout job (if present) timeout_job = self.timeout_jobs.pop(conversation_key, None) if timeout_job is not None: timeout_job.schedule_removal() try: new_state = handler.handle_update(update, dispatcher, check_result, context) except DispatcherHandlerStop as exception: new_state = exception.state raise_dp_handler_stop = True with self._timeout_jobs_lock: if self.conversation_timeout and new_state != self.END and dispatcher.job_queue: # Add the new timeout job self.timeout_jobs[ conversation_key] = dispatcher.job_queue.run_once( self._trigger_timeout, # type: ignore[arg-type] self.conversation_timeout, context=_ConversationTimeoutContext( conversation_key, update, dispatcher, context), ) if isinstance(self.map_to_parent, dict) and new_state in self.map_to_parent: self.update_state(self.END, conversation_key) if raise_dp_handler_stop: raise DispatcherHandlerStop(self.map_to_parent.get(new_state)) return self.map_to_parent.get(new_state) self.update_state(new_state, conversation_key) if raise_dp_handler_stop: # Don't pass the new state here. If we're in a nested conversation, the parent is # expecting None as return value. raise DispatcherHandlerStop() return None
def check(update: Update, context: CallbackContext) -> None: locale = gettext.translation('access', localedir = 'locales', languages = ['ru']) locale.install() _ = locale.gettext if not update.effective_user: raise DispatcherHandlerStop() user_id = update.effective_user.id bot_data = context.bot_data user_data = context.user_data if update.message: text = update.message.text if "settings" not in user_data and not match("^\/start$", text): raise DispatcherHandlerStop() if match("^\/.+$", text): logger.info( _("Пользователь {id} использовал команду {command}").format( id=user_id, command=update.message.text ) ) if update.effective_chat.type != "private": if not match("^\/show_chat_id", text): context.bot.send_message( chat_id=update.effective_chat.id, text="Все команды кроме /show_chat_id доступны только в ЛС!", ) raise DispatcherHandlerStop() else: logger.info( _("Пользователь {id} использовал команду /show_chat_id").format( id=user_id ) ) # else: # if match('^\/.*', text): # if not match('^\/show_id$', text): # if user_id in bot_data[consts.ADMINS_KEY]: # logger.info('Admin {} used command {}'.format(user_id, text)) # return # else: # logger.info('User {} tried to access admin only command {}'.format(user_id, text)) # raise DispatcherHandlerStop() # else: # logger.info('User {} used command {}'.format(user_id, update.message.text)) # return if update.inline_query: if user_id in bot_data[consts.ADMINS_KEY]: return else: raise DispatcherHandlerStop() if update.poll_answer: return
def handle_update( self, update: HandlerArg, dispatcher: Dispatcher, check_result: CheckUpdateType, context: CallbackContext = None, ) -> Optional[object]: """Copied from super method to run `collect_additional_context` and call `update_state` with more arguments """ if context: self.collect_additional_context(context, update, dispatcher, check_result) update = cast(Update, update) # for mypy conversation_key, handler, check_result = check_result raise_dp_handler_stop = False with self._timeout_jobs_lock: # Remove the old timeout job (if present) timeout_job = self.timeout_jobs.pop(conversation_key, None) if timeout_job is not None: timeout_job.schedule_removal() try: new_state = handler.handle_update(update, dispatcher, check_result, context) except DispatcherHandlerStop as exception: new_state = exception.state raise_dp_handler_stop = True with self._timeout_jobs_lock: if self.conversation_timeout and new_state != self.END and dispatcher.job_queue: # Add the new timeout job self.timeout_jobs[ conversation_key] = dispatcher.job_queue.run_once( self._trigger_timeout, self.conversation_timeout, context=_ConversationTimeoutContext( conversation_key, update, dispatcher, context), ) if isinstance(self.map_to_parent, dict) and new_state in self.map_to_parent: self.update_state(self.END, conversation_key, update, context) if raise_dp_handler_stop: raise DispatcherHandlerStop(self.map_to_parent.get(new_state)) return self.map_to_parent.get(new_state) self.update_state(new_state, conversation_key, update, context) if raise_dp_handler_stop: # Don't pass the new state here. If we're in a nested conversation, the parent is # expecting None as return value. raise DispatcherHandlerStop() return None
def handle_update(self, update, dispatcher, check_result, context=None): """Send the update to the callback for the current state and Handler Args: check_result: The result from check_update. For this handler it's a tuple of key, handler, and the handler's check result. update (:class:`telegram.Update`): Incoming telegram update. dispatcher (:class:`telegram.ext.Dispatcher`): Dispatcher that originated the Update. """ conversation_key, handler, check_result = check_result raise_dp_handler_stop = False with self._timeout_jobs_lock: # Remove the old timeout job (if present) timeout_job = self.timeout_jobs.pop(conversation_key, None) if timeout_job is not None: timeout_job.schedule_removal() try: new_state = handler.handle_update(update, dispatcher, check_result, context) except DispatcherHandlerStop as e: new_state = e.state raise_dp_handler_stop = True with self._timeout_jobs_lock: if self.conversation_timeout and new_state != self.END: # Add the new timeout job self.timeout_jobs[ conversation_key] = dispatcher.job_queue.run_once( self._trigger_timeout, self.conversation_timeout, context=_ConversationTimeoutContext( conversation_key, update, dispatcher, context)) if isinstance(self.map_to_parent, dict) and new_state in self.map_to_parent: self.update_state(self.END, conversation_key) if raise_dp_handler_stop: raise DispatcherHandlerStop(self.map_to_parent.get(new_state)) else: return self.map_to_parent.get(new_state) else: self.update_state(new_state, conversation_key) if raise_dp_handler_stop: # Don't pass the new state here. If we're in a nested conversation, the parent is # expecting None as return value. raise DispatcherHandlerStop()
def anti_flood(update: Update, context: CallbackContext): if not update.effective_chat: return last_msg = context.chat_data.get("last_msg", None) now = datetime.now(timezone.utc) context.chat_data["last_msg"] = now if last_msg and last_msg + timedelta(seconds=1) > now: raise DispatcherHandlerStop()
def tguser_check(update, context): if BOT_DEBUG == True and update.message.from_user.id != TG_BOT_MASTER: update.message.reply_text("DEBUGGING, Try again later.") raise DispatcherHandlerStop() user, _ = TGUser.get_or_create(userid=update.message.from_user.id) now_username = update.message.from_user.username or update.message.from_user.first_name if user.username != now_username: user.username = now_username user.save()
def packaged_fn(update, context): try: extra_args = cls._pass[module] if module in cls._pass else None install_me(update, context, extra_args) except DispatcherHandlerContinue: return except DispatcherHandlerStop: raise except Exception as err: msg = 'Error invoking ' + module + '.invoke: ' msg += traceback.format_exc() logging.error(msg) reply(update, 'Internal error.') raise DispatcherHandlerStop()
def video_from_telegram(bot: telegram.Bot, update: telegram.Update): """ if update.message: message: telegram.Message = update.message edited = False else: message: telegram.Message = update.edited_message edited = True """ message: telegram.Message = update.effective_message edited = (bool(getattr(update, "edited_message", None)) or bool(getattr(update, "edited_channel_post", None))) tg_group_id = message.chat_id # telegram group id forward_index = get_forward_index(tg_group_id=tg_group_id) if edited: recall_message(forward_index, message) # don't forward this message if (message.caption and message.caption.startswith('//')) or ( message.reply_to_message and message.reply_to_message.caption and message.reply_to_message.caption.startswith('//')) or ( message.reply_to_message and message.reply_to_message.text and message.reply_to_message.text.startswith('//')): logger.debug('Message ignored: matched comment pattern') raise DispatcherHandlerStop() reply_entity = list() reply_entity.append({'type': 'text', 'data': {'text': '[ 视频 ]'}}) if message.caption: reply_entity.append({ 'type': 'text', 'data': { 'text': message.caption } }) qq_message_id = send_from_tg_to_qq(forward_index, message=reply_entity, tg_group_id=tg_group_id, tg_user=update.effective_user, tg_forward_from=message, tg_reply_to=message.reply_to_message, edited=edited) global_vars.mdb.append_message(qq_message_id, message.message_id, forward_index, 0)
def _handle_auth(update: Update, context: CallbackContext): """Check if user is whitelisted to use this bot. Raises: DispatcherHandlerStop: The user is not authorized to use the bot, end the handler chain. """ with get_shelve() as data: u = str(update.effective_user.id) if not data.get(u): update.effective_message.reply_text( "You are not authorized to use this bot.") raise DispatcherHandlerStop() # Save user data for later use in our context if context.user_data.get("opts") != data[u]: context.user_data["opts"] = dict(data[u]).copy()
def link_from_telegram(bot, update): tg_group_id = update.message.chat_id # telegram group id qq_group_id, _, forward_index = get_forward_index( tg_group_id=int(tg_group_id)) link_regex = re.compile( r'^https?://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]$') text = update.message.text if link_regex.match(text): # feature, comment will no be send to qq article = Article(text) article.download() article.parse() sender_name = trim_emoji( get_full_user_name(update.message.from_user) ) + ':' # unicode emoji cannot pass into create_cq_share msg = create_cq_share(text, sender_name, article.title, article.top_image if article.top_image else '') cq_send(update, msg, qq_group_id) raise DispatcherHandlerStop()
def check_conversation_status(update: Update, context: CallbackContext) -> None: """ Checks if the user is currently in a conversation. If they are and the corresponding conversation does *not* handle the incoming update, the user will get a corresponding message and the update will be discarded. Args: update: The update. context: The context as provided by the :class:`telegram.ext.Dispatcher`. """ if not update.effective_user: return conversation = context.user_data.get(CONVERSATION_KEY, None) if not conversation: return conversation_check = not bool( conversations[conversation].check_update(update)) # Make sure that the callback queries for vcard requests are not processed if update.callback_query: contact_request_check = bool( re.match(inline.REQUEST_CONTACT_PATTERN, update.callback_query.data)) highscore_check = 'highscore' in update.callback_query.data else: contact_request_check = False highscore_check = False if conversation_check or contact_request_check or highscore_check: text = interrupt_replies[conversation] if update.callback_query: update.callback_query.answer(text=text, show_alert=True) elif update.effective_message: update.effective_message.reply_text(text) raise DispatcherHandlerStop()
def document_from_telegram(bot: telegram.Bot, update: telegram.Update): """ if update.message: message: telegram.Message = update.message edited = False else: message: telegram.Message = update.edited_message edited = True """ message: telegram.Message = update.effective_message edited = (bool(getattr(update, "edited_message", None)) or bool(getattr(update, "edited_channel_post", None))) tg_group_id = message.chat_id # telegram group id forward_index = get_forward_index(tg_group_id=tg_group_id) if edited: recall_message(forward_index, message) # don't forward this message if (message.caption and message.caption.startswith('//')) or ( message.reply_to_message and message.reply_to_message.caption and message.reply_to_message.caption.startswith('//')) or ( message.reply_to_message and message.reply_to_message.text and message.reply_to_message.text.startswith('//')): logger.debug('Message ignored: matched comment pattern') raise DispatcherHandlerStop() reply_entity = list() if message.document.mime_type == 'video/mp4': file_id = message.document.file_id if global_vars.JQ_MODE: tg_get_pic_url(file_id, 'gif', False) if os.path.getsize(os.path.join(CQ_IMAGE_ROOT, file_id + '.gif')) > 5242880: reply_entity.append({ 'type': 'text', 'data': { 'text': '[ 视频:大小超过 5 MB ]' } }) else: reply_entity.append({ 'type': 'image', 'data': { 'file': file_id + '.gif' } }) if message.caption: reply_entity.append({ 'type': 'text', 'data': { 'text': message.caption } }) elif IMAGE_LINK_MODE[forward_index]: pic_url = tg_get_pic_url(file_id, 'gif', True) if message.caption: reply_entity.append({ 'type': 'text', 'data': { 'text': '[ 视频, 请点击查看' + pic_url + ' ]' + message.caption } }) else: reply_entity.append({ 'type': 'text', 'data': { 'text': '[ 视频, 请点击查看' + pic_url + ' ]' } }) else: reply_entity.append({'type': 'text', 'data': {'text': '[ 视频 ]'}}) elif message.document.mime_type == 'image/gif': file_id = message.document.file_id if global_vars.JQ_MODE: file = global_vars.tg_bot.getFile(file_id) file.download(custom_path=os.path.join(CQ_IMAGE_ROOT, file_id + '.gif')) reply_entity.append({ 'type': 'image', 'data': { 'file': file_id + '.gif' } }) if message.caption: reply_entity.append({ 'type': 'text', 'data': { 'text': message.caption } }) elif IMAGE_LINK_MODE[forward_index]: file = global_vars.tg_bot.getFile(file_id) file.download(custom_path=os.path.join(CQ_IMAGE_ROOT, file_id + '.gif')) pic_url = get_short_url(SERVER_PIC_URL + file_id + '.gif') if message.caption: reply_entity.append({ 'type': 'text', 'data': { 'text': '[ GIF, 请点击查看' + pic_url + ' ]' + message.caption } }) else: reply_entity.append({ 'type': 'text', 'data': { 'text': '[ GIF, 请点击查看' + pic_url + ' ]' } }) else: reply_entity.append({'type': 'text', 'data': {'text': '[ GIF ]'}}) else: reply_entity.append({'type': 'text', 'data': {'text': '[ 文件 ]'}}) qq_message_id = send_from_tg_to_qq(forward_index, message=reply_entity, tg_group_id=tg_group_id, tg_user=update.effective_user, tg_forward_from=message, tg_reply_to=message.reply_to_message, edited=edited) global_vars.mdb.append_message(qq_message_id, message.message_id, forward_index, 0)
def photo_from_telegram(bot: telegram.Bot, update: telegram.Update): """ if update.message: message: telegram.Message = update.message edited = False else: message: telegram.Message = update.edited_message edited = True """ message: telegram.Message = update.effective_message edited = (bool(getattr(update, "edited_message", None)) or bool(getattr(update, "edited_channel_post", None))) tg_group_id = message.chat_id # telegram group id forward_index = get_forward_index(tg_group_id=tg_group_id) if edited: recall_message(forward_index, message) # don't forward this message if (message.caption and message.caption.startswith('//')) or ( message.reply_to_message and message.reply_to_message.caption and message.reply_to_message.caption.startswith('//')) or ( message.reply_to_message and message.reply_to_message.text and message.reply_to_message.text.startswith('//')): logger.debug('Message ignored: matched comment pattern') raise DispatcherHandlerStop() reply_entity = list() file_id = message.photo[-1].file_id if global_vars.JQ_MODE: tg_get_pic_url(file_id, 'jpg', False) reply_entity.append({ 'type': 'image', 'data': { 'file': file_id + '.jpg' } }) if message.caption: reply_entity.append({ 'type': 'text', 'data': { 'text': message.caption } }) elif IMAGE_LINK_MODE[forward_index]: pic_url = tg_get_pic_url(file_id, 'jpg', True) if message.caption: reply_entity.append({ 'type': 'text', 'data': { 'text': '[ 图片, 请点击查看' + pic_url + ' ]' + message.caption } }) else: reply_entity.append({ 'type': 'text', 'data': { 'text': '[ 图片, 请点击查看' + pic_url + ' ]' } }) else: reply_entity.append({ 'type': 'text', 'data': { 'text': '[ 图片 ]' + message.caption } }) qq_message_id = send_from_tg_to_qq(forward_index, message=reply_entity, tg_group_id=tg_group_id, tg_user=update.effective_user, tg_forward_from=message, tg_reply_to=message.reply_to_message, edited=edited) global_vars.mdb.append_message(qq_message_id, message.message_id, forward_index, 0)