def wrapper(update, context): session = get_session() try: user = User.get_or_create(session, update.callback_query.from_user) if user.banned: return if config["mode"]["authorized_only"] and not user.authorized: return func(context.bot, update, session, user) session.commit() # Handle all not telegram relatated exceptions except Exception as e: if not ignore_exception(e): traceback.print_exc() if should_report_exception(context, e): sentry.capture_exception( tags={ "handler": "callback_query", }, extra={ "query": update.callback_query, }, ) finally: session.close()
def wrapper(bot, update): session = get_session() try: user = get_user(session, update) if not is_allowed( user, update, admin_only=admin_only, check_ban=check_ban): return func(bot, update, session, user) session.commit() except BadRequest as e: # An update for a reply keyboard has failed (Probably due to button spam) if str(e) == 'Message is not modified': # noqa print(e) return # It took to long to send the inline query response. # Probably due to slow network on client side. elif str(e) == 'Query_id_invalid': # noqa print(e) return traceback.print_exc() sentry.captureException() # Ignore network related errors except (TimedOut, NetworkError): pass except BaseException: traceback.print_exc() sentry.captureException() finally: session.close()
def wrapper(update, context): session = get_session() chat = None try: if hasattr(update, "message") and update.message: message = update.message elif hasattr(update, "edited_message") and update.edited_message: message = update.edited_message user = get_user(session, update) if config["mode"]["authorized_only"] and not user.authorized: text = "StickerFinder is officially offline. Access will still be granted for [Patreons](https://www.patreon.com/nukesor).\n" text += "Check the repository for the latest database dump in case you want to host your own bot." message.chat.send_message(text, parse_mode="Markdown") session.commit() return if not is_allowed( user, update, admin_only=admin_only, check_ban=check_ban): return chat_id = message.chat_id chat_type = message.chat.type chat = Chat.get_or_create(session, chat_id, chat_type) if not is_allowed(user, update, chat=chat, private=private): return response = func(context.bot, update, session, chat, user) session.commit() # Respond to user if hasattr(update, "message") and response is not None: message.chat.send_message(response) # A user banned the bot except Unauthorized: if chat is not None: session.delete(chat) # A group chat has been converted to a super group. except ChatMigrated: if chat is not None: session.delete(chat) # Handle all not telegram relatated exceptions except Exception as e: if not ignore_exception(e): traceback.print_exc() sentry.captureException() if send_message and message: session.close() call_tg_func(message.chat, "send_message", args=[error_text]) raise finally: session.close()
def wrapper(context): session = get_session() try: func(context, session) session.commit() finally: session.close()
def wrapper(update, context): session = get_session() try: user = get_user(session, update) if not is_allowed( user, update, admin_only=admin_only, check_ban=check_ban): return if hasattr(update, 'message') and update.message: message = update.message elif hasattr(update, 'edited_message') and update.edited_message: message = update.edited_message chat_id = message.chat_id chat_type = message.chat.type chat = Chat.get_or_create(session, chat_id, chat_type) if not is_allowed(user, update, chat=chat, private=private): return response = func(context.bot, update, session, chat, user) session.commit() # Respond to user if hasattr(update, 'message') and response is not None: call_tg_func(message.chat, 'send_message', args=[response]) # A user banned the bot except Unauthorized: session.delete(chat) # A group chat has been converted to a super group. except ChatMigrated: session.delete(chat) # Raise all telegram errors and let the generic error_callback handle it except TelegramError as e: raise e # Handle all not telegram relatated exceptions except: traceback.print_exc() sentry.captureException() if send_message: session.close() call_tg_func(message.chat, 'send_message', args=[error_text]) raise finally: session.close()
def wrapper(context): session = get_session() try: func(context, session) session.commit() except: # Capture all exceptions from jobs. We need to handle those inside the jobs traceback.print_exc() sentry.captureException() finally: session.close()
def wrapper(update, context): session = get_session() try: user = get_user(session, update) if not is_allowed(user, update, admin_only=admin_only, check_ban=check_ban): return func(context.bot, update, session, user) session.commit() # Raise all telegram errors and let the generic error_callback handle it finally: session.close()
def wrapper(context): session = get_session() try: func(context, session) session.commit() except: # Capture all exceptions from jobs. # We need to handle those inside the jobs traceback.print_exc() sentry.capture_exception(tags={"handler": "job"}) finally: context.job.enabled = True session.close()
def session(connection, monkeypatch): """Return an sqlalchemy session, and after the test tear down everything properly.""" # Begin the nested transaction transaction = connection.begin() # Use the connection with the already started transaction session = Session(bind=connection) def get_session(): return session from stickerfinder import db monkeypatch.setattr(db, "get_session", get_session) assert session == db.get_session() yield session # Since we are not committing things to the database directly when # testing, initially deferred constraints are not checked. The # following statement makes the DB check these constraints. We are # executing this command AFTER the tests and NOT BEFORE, because # within a transaction the DB is allowed to take temporarily # invalid state. Read # https://www.postgresql.org/docs/current/static/sql-set-constraints.html # for details. try: connection.execute("SET CONSTRAINTS ALL IMMEDIATE") except InternalError: # This is the case when we are doing something in the tests # that we expect it to fail by executing the statement above. # In this case, the transaction will be in an already failed # state, executing further SQL statements are ignored and doing # so raises an exception. pass session.close() # Roll back the broader transaction transaction.rollback() # Put back the connection to the connection pool connection.close()
def wrapper(update, context): session = get_session() try: user = get_user(session, update) if not is_allowed( user, update, admin_only=admin_only, check_ban=check_ban): return if config['mode']['authorized_only'] and not user.authorized: return func(context.bot, update, session, user) session.commit() # Handle all not telegram relatated exceptions except Exception as e: if not ignore_exception(e): traceback.print_exc() sentry.captureException() finally: session.close()
def wrapper(update, context): session = get_session() try: user = User.get_or_create(session, update.inline_query.from_user) if user.banned: return if config["mode"]["private_inline_query"] and not user.authorized: return func(context, update, session, user) session.commit() # Handle all not telegram relatated exceptions except Exception as e: if not ignore_exception(e): traceback.print_exc() sentry.capture_exception(tags={"handler": "inline_query"}) finally: session.close()
def wrapper(update, context): session = get_session() try: user = get_user(session, update) if not is_allowed( user, update, admin_only=admin_only, check_ban=check_ban): return func(context.bot, update, session, user) session.commit() # Raise all telegram errors and let the generic error_callback handle it except TelegramError as e: raise e # Handle all not telegram relatated exceptions except: traceback.print_exc() sentry.captureException() finally: session.close()
def handle_chosen_inline_result(update, context): session = get_session() """Save the chosen inline result.""" result = update.chosen_inline_result splitted = result.result_id.split(":") # This is a result from a banned user if len(splitted) < 2: return [search_id, sticker_id] = splitted # In sticker set search, the second parameter is the md5 of the set's name # We're not interested in this data, thereby simply drop it if len(sticker_id) == 32: return inline_query = session.query(InlineQuery).get(search_id) # Clean all cache values as soon as the user selects a result cache = context.bot_data["query_cache"] if inline_query.id in cache: del cache[inline_query.id] sticker = session.query(Sticker).filter( Sticker.id == sticker_id).one_or_none() # This happens, if the user clicks on a link in sticker set search. if sticker is None: return inline_query.sticker_file_unique_id = sticker.file_unique_id inline_query.sticker_file_unique_id = sticker.file_unique_id sticker_usage = StickerUsage.get_or_create(session, inline_query.user, sticker) sticker_usage.usage_count += 1 session.commit()
def handle_chosen_inline_result(update, context): session = get_session() """Save the chosen inline result.""" result = update.chosen_inline_result splitted = result.result_id.split(':') # This is a result from a banned user if len(splitted) < 2: return [search_id, file_id] = splitted inline_query = session.query(InlineQuery).get(search_id) # This happens, if the user clicks on a link in sticker set search. sticker = session.query(Sticker).get(file_id) if sticker is None: return inline_query.sticker_file_id = file_id sticker_usage = StickerUsage.get_or_create(session, inline_query.user, sticker) sticker_usage.usage_count += 1
#!/usr/bin/env python """Small helper script for debugging stuff.""" from stickerfinder.db import get_session from stickerfinder.helper.plot import get_user_activity session = get_session() image = get_user_activity(session)
def wrapper(update, context): session = get_session() chat = None message = None try: if hasattr(update, "message") and update.message: message = update.message elif hasattr(update, "edited_message") and update.edited_message: message = update.edited_message else: raise Exception("Update didn't have a message.") user = User.get_or_create(session, message.from_user) if config["mode"]["authorized_only"] and not user.authorized: if config["mode"]["private_inline_query"]: text = i18n.t( "text.misc.private_access_no_inline", username=config["telegram"]["bot_name"], ) else: text = i18n.t( "text.misc.private_access", username=config["telegram"]["bot_name"], ) message.chat.send_message( text, parse_mode="Markdown", disable_web_page_preview=True, ) session.commit() return if not is_allowed(user, update, admin_only=admin_only): return chat_id = message.chat_id chat_type = message.chat.type chat = Chat.get_or_create(session, chat_id, chat_type) if not is_allowed(user, update, chat=chat): return response = func(context.bot, update, session, chat, user) session.commit() # Respond to user if hasattr(update, "message") and response is not None: message.chat.send_message(response) # A user banned the bot except Unauthorized: if chat is not None: session.delete(chat) # A group chat has been converted to a super group. except ChatMigrated: if chat is not None: session.delete(chat) # Handle all not telegram relatated exceptions except Exception as e: if not ignore_exception(e): traceback.print_exc() if should_report_exception(context, e): sentry.capture_exception( tags={ "handler": "message", }, extra={ "update": update.to_dict(), "function": func.__name__, }, ) error_message = i18n.t("text.misc.error") try: if "message" is not None: message.chat.send_message(error_message) except Exception as e: if not ignore_exception(e): raise e finally: session.close()
def wrapper(bot, update): session = get_session() try: user = get_user(session, update) if not is_allowed( user, update, admin_only=admin_only, check_ban=check_ban): return chat_id = update.message.chat_id chat_type = update.message.chat.type chat = Chat.get_or_create(session, chat_id, chat_type) if not is_allowed(user, update, chat=chat, private=private): return response = func(bot, update, session, chat, user) # Respond to user if hasattr(update, 'message') and response is not None: session.commit() call_tg_func(update.message.chat, 'send_message', args=[response]) return session.commit() except BadRequest as e: # An update for a reply keyboard has failed (Probably due to button spam) if str(e) == 'Message is not modified': # noqa print(e) return # We are on dev db or a user deleted a chat. if str(e) == 'Chat not found': # noqa print(e) session.delete(chat) traceback.print_exc() sentry.captureException() # A user banned the bot except Unauthorized: session.delete(chat) return # A group chat has been converted to a super group. except ChatMigrated: session.delete(chat) return # Ignore network related errors except (TimedOut, NetworkError) as e: print(e) pass except BaseException: traceback.print_exc() sentry.captureException() if send_message: session.close() call_tg_func(update.message.chat, 'send_message', args=[error_text]) finally: session.close()