class TtbDjSubscriberPropertyAdmin(admin.ModelAdmin): list_display = Utils.get_default_list_display(TtbDjSubscriberProperty) search_fields = ['value', 'description'] list_filter = ['p_type', 'code', 'created', 'updated'] inlines = [ TtbDjSubscriberPropertyInline, ] exclude = ('db_chat', )
def need_disable_user_by_last_activity_days(user, days=120): # type: (User, int) -> bool disable_user = False nt = now() ut = user.last_activity_time if ut: ut = Utils.datetime_from_unix_time(ut).astimezone() if ((nt - ut).total_seconds() > 60 * 60 * 24 * days) or user.name == 'DELETED USER': disable_user = True else: disable_user = True return disable_user
def translation_activate(language): if use_django: get_lang().activate(language) else: global LANG if language: calling_function_filename = Utils.get_calling_function_filename( translation_activate.__name__) if calling_function_filename: LANG = gettext.translation( 'django', os.path.join( os.path.dirname( os.path.abspath(calling_function_filename)), 'locale'), languages=[language]) else: # noinspection PyUnresolvedReferences LANG = gettext.translation('django', os.path.join(BASE_DIR, 'locale'), languages=[language])
def get_lang(): if use_django: # noinspection PyUnresolvedReferences from django.utils import translation return translation else: if LANG: return LANG else: calling_function_filename = Utils.get_calling_function_filename( get_lang.__name__, 2) if calling_function_filename: return gettext.translation( 'django', os.path.join( os.path.dirname( os.path.abspath(calling_function_filename)), 'locale'), languages=['ru']) # noinspection PyUnresolvedReferences return gettext.translation('django', os.path.join(BASE_DIR, 'locale'), languages=['ru'])
class TtbDjChatAvailableAdmin(admin.ModelAdmin): list_display = Utils.get_default_list_display(TtbDjChatAvailable)
class TtbPrevStepAdmin(admin.ModelAdmin): list_display = Utils.get_default_list_display(TtbPrevStep)
class TtbUserAdmin(admin.ModelAdmin): list_display = Utils.get_default_list_display(TtbUser) search_fields = ['name', 'username'] list_filter = ['language', 'enabled', 'created', 'updated', 'is_bot'] inlines = [TtbUserPropertyInline]
class TtbDjSubscriberAdmin(admin.ModelAdmin): list_display = Utils.get_default_list_display(TtbDjSubscriber) inlines = [TtbDjSubscriberPropertyInline] search_fields = ['chat_name'] list_filter = ['chat_type', 'language', 'created', 'updated']
from django.shortcuts import render from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from TamTamBot import TamTamBot from ttgb_cmn.cmn import Utils from TtBot.TtBot import TtBot from openapi_client import UserWithPhoto tt_bot = None # noinspection SpellCheckingInspection if sys.argv and (sys.argv[1] == 'runserver' or sys.argv[0].endswith('gunicorn')): tt_bot = TtBot() tt_bot.polling_sleep_time = 0 if Utils.get_environ_bool('TT_BOT_POLLING_MODE', False): t = Thread(target=tt_bot.polling, args=()) t.name = f'pooling-main-thr' t.setDaemon(True) t.start() if tt_bot and isinstance(tt_bot.info, UserWithPhoto): title = 'ТТ-бот: @%s (%s)' % (tt_bot.info.username, tt_bot.info.name) else: title = 'Должна была быть инфа о ТТ-боте, но что-то пошло не так...' # Create your views here. @csrf_exempt # exempt index() function from built-in Django protection def index(request): # type:(WSGIRequest) -> HttpResponse
def get_property_int(cls, property_set, p_type, code, def_val=None): # type: (QuerySet, str, str, int) -> int res_str = cls.get_property_str(property_set, p_type, code) return Utils.str_to_int(res_str, def_val)
def get_callback_index(callback): # type: (Callback) -> str ind = '%s#%s' % (callback.user.user_id, Utils.get_md5_hash_str(callback.payload)) return ind
def __init__(self, update, ttb=None): # type: (Update, object) -> None self.update_current = update self.update_type = update.update_type self.timestamp = update.timestamp self.message = None self.ttb = ttb self.cmd_bot = None self.cmd = None self.cmd_args = None self.link = None self.user = None self.user_id = None self.user_name = None self.user_id_recipient = None self.chat_id = None self.chat_type = None self.this_cmd_response = False self.required_cmd_response = False self.update_previous = None self.recipient = None self.user_locale = update.user_locale if hasattr( update, 'user_locale') else None if isinstance(update, MessageCallbackUpdate): self.cmd = update.callback.payload self.link = None try: payload = json.loads(update.callback.payload) except json.decoder.JSONDecodeError: payload = None if isinstance(payload, dict): self.cmd_bot = payload.get('bot') self.cmd = payload.get('cmd') self.cmd_args = payload.get('cmd_args') mid = payload.get('mid') or update.message.body.mid if mid: self.link = NewMessageLink(MessageLinkType.REPLY, mid) else: # Для совместимости со старым форматом payload cmd = TtUtils.get_param_value(update.callback.payload, 'cmd') if cmd: self.cmd = cmd mid = TtUtils.get_param_value(update.callback.payload, 'mid') if mid: self.link = NewMessageLink(MessageLinkType.REPLY, mid) fk = TtUtils.get_param_value(update.callback.payload, 'cmd_args') if fk: self.cmd_args = fk chat_id = Utils.str_to_int(fk) if chat_id is not None: self.cmd_args = {'chat_id': chat_id} else: self.cmd_args = {'id_str': fk} self.user = update.callback.user elif isinstance(update, MessageCreatedUpdate): self.cmd = update.message.body.text self.link = NewMessageLink(MessageLinkType.REPLY, update.message.body.mid) # Обработка аргументов команды типа /get_ids 1 2 7 # Поддерживается два формата: # * update.cmd_arg['l1']['c1'] - строка1, колонка 1 # * update.cmd_arg['c_parts'] - список строк, каждая из которых содержит список колонок # Разделение на строки и колоонки производится по реальным строкам и элементам в строке, разделённых пробелом # Также возможно передать аргументы в команде с двойными подчёркиваниями вида "/set_score__127__145". # В этом случае ТТ отображает команду с аргументом как единую как ссылку f = re.match(r'(/[a-zA-Zа-яА-Я_]+)(_{2}| )(.+)', self.cmd, re.DOTALL) if isinstance(f, Match): self.cmd = f.group(1) self.cmd_args = self.cmd_args or {} i = 1 for ln in f.group(3).split('\n'): if not isinstance(self.cmd_args.get('c_parts'), list): self.cmd_args['c_parts'] = [[]] else: self.cmd_args['c_parts'].append([]) ind_l = 'l%s' % i j = 1 for c in re.split(r'_{2}| ', ln): if len(c.strip()) > 0: self.cmd_args['c_parts'][-1].append(c) ind_c = 'c%s' % j if not self.cmd_args.get(ind_l): self.cmd_args[ind_l] = {} self.cmd_args[ind_l][ind_c] = c j += 1 i += 1 elif isinstance(update, BotStartedUpdate): self.cmd = '/start' self.chat_type = ChatType.DIALOG if self.user is None: if hasattr(update, 'user'): self.user = update.user elif hasattr(update, 'sender'): self.user = update.message.sender if self.chat_id is None: if hasattr(update, 'chat_id'): self.chat_id = update.chat_id if self.user_id is None: if hasattr(update, 'user_id'): self.user_id = update.user_id if hasattr(update, 'message') and isinstance(update.message, Message): self.message = update.message if isinstance(self.message, Message): if isinstance(self.message.recipient, Recipient): self.recipient = update.message.recipient self.chat_id = self.chat_id or self.recipient.chat_id self.chat_type = self.chat_type or self.recipient.chat_type self.user_id_recipient = self.user_id_recipient or self.recipient.user_id if isinstance(self.message.sender, User): self.user = self.user or self.message.sender if isinstance(self.user, User): self.user_id = self.user_id or self.user.user_id self.user_name = self.user_name or self.user.name if self.cmd: self.cmd = self.cmd[1:] self._index = None
import os import django_heroku from ttgb_cmn.cmn import Utils # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = "CHANGE_ME!!!! (P.S. the SECRET_KEY environment variable will be used, if set, instead)." # SECURITY WARNING: don't run with debug turned on in production! DEBUG = Utils.get_environ_bool('DJANGO_DEBUG_MODE', False) ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "djh_app", ]