示例#1
0
def make_new_msg(tg_id: int, data: dict, content_type: str):
    user_context = mem.UserContext(tg_id)
    params = user_context.get_params()
    from_msg_id = params.get('from_msg_id')
    from_btn_id = params.get('from_btn_id')
    req_data = {
        'tg_id': tg_id,
        'content_type': content_type,
        'message': data.get('message'),
        'story_id': user_context.get_context('story_id'),
        'chapter_id': user_context.get_context('chapter_id'),
        'parrent_message_id':
        from_msg_id if from_msg_id and not from_btn_id else None,
        'is_start_msg': True if params.get('is_start_chapter_msg') else False,
    }

    new_msg_resp = json.loads(
        requests.post(
            DB_URL.format(item='message', cmd='make'),
            json=req_data,
        ).text)
    if content_type in ['photo', 'voice', 'video_note']:
        files = {
            'file_data': (data['name'], data['media'], data['content_type'])
        }
        payload = {
            'tg_id': tg_id,
            'message_id': new_msg_resp.get('id'),
        }
        requests.post(
            DB_URL.format(item='media', cmd='make'),
            files=files,
            data=payload,
        )

    if from_msg_id and from_btn_id:
        requests.post(
            DB_URL.format(item='message', cmd='edit_button'),
            json={
                'tg_id': tg_id,
                'msg_id': from_msg_id,
                'button_id': from_btn_id,
                'link_to_msg_id': new_msg_resp.get('id'),
            },
        )
    user_context.flush_params()
    _message = Message(new_msg_resp.get('id'))
    _message.show(tg_id)
示例#2
0
def make_new_story(tg_id: int, story_name: str):
    new_story_resp = json.loads(
        requests.post(
            DB_URL.format(item='story', cmd='make'),
            json={
                'tg_id': tg_id,
                'story_name': story_name,
            },
        ).text)
    _story = Story(new_story_resp['id'])
    _story.show(tg_id)
示例#3
0
 def __init__(self, story_id: int, chapter_id: int):
     chapter_resp = json.loads(
         requests.post(
             DB_URL.format(item='chapter', cmd='get'),
             json={
                 'story_id': story_id,
                 'chapter_id': chapter_id
             },
         ).text)
     first_msg = json.loads(
         requests.post(
             DB_URL.format(item='message', cmd='get_start_for_chapter'),
             json={
                 'chapter_id': chapter_id
             },
         ).text)
     self.id = int(chapter_resp.get('id'))
     self.name = chapter_resp.get('name')
     self.number = int(chapter_resp.get('number'))
     self.story_id = int(chapter_resp.get('story_id'))
     self.start_message = first_msg
示例#4
0
 def change_reaction(self, tg_id: int, reaction_id: int):
     if reaction_id:
         req_data = {
             'msg_id': self.id,
             'chapter_id': self.chapter_id,
             'reaction_id': reaction_id,
             'tg_id': tg_id,
         }
         edit_msg_resp = json.loads(
             requests.post(
                 DB_URL.format(item='message', cmd='edit'),
                 json=req_data,
             ).text)
         if edit_msg_resp.get('error'):
             msg = edit_msg_resp.get('error')
             tools.send_menu_msg(tg_id, msg)
         else:
             self.wait_reaction = edit_msg_resp.get('wait_reaction')
             self.show(tg_id)
     else:
         msg = 'Выберите реакцию:'
         story_reactions = json.loads(
             requests.post(
                 DB_URL.format(item='story', cmd='get-reactions'),
                 json={
                     'story_id': self.story_id,
                     'tg_id': tg_id,
                 },
             ).text)
         buttons = []
         for reaction in story_reactions['reactions']:
             buttons.append([
                 (reaction.get('name'),
                  tools.make_call_back(CHANGE_REACTION_PREFIX, {
                      'reaction_id': reaction.get('id'),
                  }))
             ])
         buttons.append([('Назад', tools.make_call_back(SHOW_PREFIX))])
         tools.send_menu_msg(tg_id, msg, buttons)
示例#5
0
 def set_reaction(self, tg_id: int, document: bytes):
     files = {'file_data': ('reactions.csv', document, 'document')}
     payload = {
         'tg_id': tg_id,
         'story_id': self.id,
     }
     resp = json.loads(
         requests.post(
             DB_URL.format(item='story', cmd='set-reactions'),
             files=files,
             data=payload,
         ).text)
     self.is_reactions = resp.get('is_reactions')
     self.show(tg_id)
示例#6
0
def make_new_chapter(tg_id: int, chapter_name: str):
    user_context = mem.UserContext(tg_id)
    new_chapter_resp = json.loads(
        requests.post(
            DB_URL.format(item='chapter', cmd='make'),
            json={
                'tg_id': tg_id,
                'story_id': user_context.get_context('story_id'),
                'chapter_name': chapter_name,
            },
        ).text)
    _chapter = Chapter(user_context.get_context('story_id'),
                       new_chapter_resp.get('id'))
    _chapter.show(tg_id)
示例#7
0
 def __init__(self, tg_id: int):
     user_resp = json.loads(
         requests.post(
             DB_URL.format(item='telegram_user', cmd='get'),
             json={
                 'tg_id': tg_id
             },
         ).text)
     self.id = int(user_resp['id'])
     self.telegram_id = int(user_resp['telegram_id'])
     self.stories = [
         story.Story(story_resp['id'])
         for story_resp in user_resp['stories']
     ]
示例#8
0
 def __init__(self, message_id: int, button_id: int):
     msg_resp = json.loads(
         requests.post(
             DB_URL.format(item='message', cmd='get'),
             json={'chapter_id': chapter_id, 'msg_id': message_id},
         ).text
     )
     self.id = int(msg_resp.get('id'))
     self.is_start_chapter = msg_resp.get('is_start_chapter')
     self.chapter_id = int(msg_resp.get('chapter_id'))
     self.message = msg_resp.get('message')
     self.link = msg_resp.get('link')
     self.parrent = msg_resp.get('parrent')
     self.buttons = msg_resp.get('buttons')
     pass
示例#9
0
 def rm(self, tg_id: int):
     req_data = {
         'msg_id': self.id,
         'tg_id': tg_id,
     }
     rm_msg_resp = json.loads(
         requests.post(
             DB_URL.format(item='message', cmd='rm'),
             json=req_data,
         ).text)
     if rm_msg_resp.get('error'):
         msg = rm_msg_resp.get('error')
         tools.send_menu_msg(tg_id, msg)
     else:
         chapter.Chapter(self.story_id, self.chapter_id).show(tg_id)
示例#10
0
 def get_reactions(self, tg_id: int):
     reactions_resp = json.loads(
         requests.post(
             DB_URL.format(item='story', cmd='get-reactions-list'),
             json={
                 'story_id': self.id,
                 'tg_id': tg_id,
             },
         ).text)
     lines = []
     for react in reactions_resp['reactions']:
         lines.append(f'{react["name"]}:')
         lines.append('{}\n'.format(', '.join(react['messages'])))
     tools.send_menu_msg(tg_id, '\n'.join(lines), exit_menu=True)
     self.show(tg_id)
示例#11
0
    def edit(self, tg_id: int, data: dict, content_type: str):
        if content_type in ['photo', 'voice', 'video_note']:
            files = {
                'file_data':
                (data['name'], data['media'], data['content_type'])
            }
            payload = {
                'tg_id': tg_id,
                'message_id': self.id,
            }
            requests.post(
                DB_URL.format(item='media', cmd='make'),
                files=files,
                data=payload,
            ).text
        req_data = {
            'msg_id': self.id,
            'chapter_id': self.chapter_id,
            'message': data['message'],
            'content_type': content_type,
            'tg_id': tg_id,
        }
        edit_msg_resp = json.loads(
            requests.post(
                DB_URL.format(item='message', cmd='edit'),
                json=req_data,
            ).text)

        if edit_msg_resp.get('error'):
            msg = edit_msg_resp.get('error')
            tools.send_menu_msg(tg_id, msg)
        else:
            self.message = edit_msg_resp.get('message')
            self.content_type = edit_msg_resp.get('content_type')
            self.media = edit_msg_resp.get('media')
            self.show(tg_id)
示例#12
0
 def set_k_timeout(self, tg_id: int, k_timeout: int):
     edited_story_resp = json.loads(
         requests.post(
             DB_URL.format(item='story', cmd='edit'),
             json={
                 'story_id': self.id,
                 'tg_id': tg_id,
                 'k_timeout': k_timeout,
             },
         ).text)
     if edited_story_resp.get('error'):
         msg = edited_story_resp.get('error')
         tools.send_menu_msg(tg_id, msg)
     else:
         self.k_timeout = edited_story_resp.get('k_timeout')
         self.show(tg_id)
示例#13
0
 def add_button(self, tg_id: int, text: str):
     new_btn_msg_resp = json.loads(
         requests.post(
             DB_URL.format(item='message', cmd='add_button'),
             json={
                 'msg_id': self.id,
                 'tg_id': tg_id,
                 'text': text,
             },
         ).text)
     if new_btn_msg_resp.get('error'):
         msg = new_btn_msg_resp.get('error')
         tools.send_menu_msg(tg_id, msg)
     else:
         self.buttons.append(new_btn_msg_resp['buttons'][-1])
         self.show(tg_id)
示例#14
0
 def add_direct_link(self, tg_id: int, to_msg_id: str):
     edit_msg_resp = json.loads(
         requests.post(
             DB_URL.format(item='message', cmd='edit'),
             json={
                 'msg_id': self.id,
                 'tg_id': tg_id,
                 'next_message_id': int(to_msg_id),
             },
         ).text)
     if edit_msg_resp.get('error'):
         msg = edit_msg_resp.get('error')
         tools.send_menu_msg(tg_id, msg)
     else:
         self.link = int(to_msg_id)
         self.show(tg_id)
示例#15
0
 def replace(self, new_num: int, tg_id: int):
     up_chapter_resp = json.loads(
         requests.post(
             DB_URL.format(item='chapter', cmd='replace'),
             json={
                 'story_id': self.story_id,
                 'tg_id': tg_id,
                 'chapter_id': self.id,
                 'new_num': new_num,
             },
         ).text)
     if up_chapter_resp.get('error'):
         msg = up_chapter_resp.get('error')
         tools.send_menu_msg(tg_id, msg)
     else:
         story.Story(self.story_id).show_chapters(tg_id)
示例#16
0
 def __init__(self, story_id: int):
     story_resp = json.loads(
         requests.post(
             DB_URL.format(item='story', cmd='get'),
             json={
                 'story_id': story_id
             },
         ).text)
     self.id = int(story_resp.get('id'))
     self.name = story_resp.get('name')
     self.base_timeout = story_resp.get('base_timeout')
     self.k_timeout = story_resp.get('k_timeout')
     self.author_id = int(story_resp.get('author_id'))
     self.chapters = sorted(story_resp.get('chapters'),
                            key=lambda chapter: int(chapter.get('number')))
     self.is_reactions = story_resp.get('is_reactions')
示例#17
0
 def rename(self, tg_id: int, new_name: str):
     renamed_story_resp = json.loads(
         requests.post(
             DB_URL.format(item='story', cmd='rename'),
             json={
                 'story_id': self.id,
                 'tg_id': tg_id,
                 'new_name': new_name,
             },
         ).text)
     if renamed_story_resp.get('error'):
         msg = renamed_story_resp.get('error')
         tools.send_menu_msg(tg_id, msg)
     else:
         self.name = new_name
         self.show(tg_id)
示例#18
0
 def move_btn(self, tg_id: int, move: int, btn_id: int):
     edit_btn_msg_resp = json.loads(
         requests.post(
             DB_URL.format(item='message', cmd='edit_button'),
             json={
                 'msg_id': self.id,
                 'tg_id': tg_id,
                 'button_id': btn_id,
                 'move': move,
             },
         ).text)
     if edit_btn_msg_resp.get('error'):
         msg = edit_btn_msg_resp.get('error')
         tools.send_menu_msg(tg_id, msg)
     else:
         self.buttons = edit_btn_msg_resp.get('buttons')
         self.show(tg_id)
示例#19
0
 def edit(self, tg_id: int, text: str):
     edit_msg_resp = json.loads(
         requests.post(
             DB_URL.format(item='message', cmd='edit'),
             json={
                 'msg_id': self.id,
                 'chapter_id': self.chapter_id,
                 'tg_id': tg_id,
                 'message': text,
             },
         ).text
     )
     if edit_msg_resp.get('error'):
         msg = edit_msg_resp.get('error')
         tools.send_menu_msg(tg_id, msg)
     else:
         self.message = text
         self.show(tg_id)
示例#20
0
    def rm(self, tg_id: int):
        result = json.loads(
            requests.post(
                DB_URL.format(item='chapter', cmd='rm'),
                json={
                    'story_id': self.story_id,
                    'tg_id': tg_id,
                    'chapter_id': self.id
                },
            ).text)
        if result.get('result') == 'ok':
            msg = 'Успешно.'
        else:
            msg = result.get('error')

        buttons = [
            [('Все главы', tools.make_call_back(story.SHOW_CHAPTERS_PREFIX))],
        ]
        tools.send_menu_msg(tg_id, msg, buttons)
示例#21
0
    def edit_referal_block(self, tg_id: int, num_referals: int):
        req_data = {
            'msg_id': self.id,
            'chapter_id': self.chapter_id,
            'referal_block': num_referals,
            'tg_id': tg_id,
        }
        edit_msg_resp = json.loads(
            requests.post(
                DB_URL.format(item='message', cmd='edit'),
                json=req_data,
            ).text)

        if edit_msg_resp.get('error'):
            msg = edit_msg_resp.get('error')
            tools.send_menu_msg(tg_id, msg)
        else:
            self.referal_block = edit_msg_resp['referal_block']
            self.show(tg_id)
示例#22
0
    def rm(self, tg_id: int):
        result = json.loads(
            requests.post(
                DB_URL.format(item='story', cmd='rm'),
                json={
                    'story_id': self.id,
                    'tg_id': tg_id,
                },
            ).text)
        if result.get('result') == 'ok':
            msg = 'Успешно.'
        else:
            msg = result.get('error')

        buttons = [
            [('Мои истории', tools.make_call_back(tg_user.SHOW_STORIES_PREFIX))
             ],
        ]
        tools.send_menu_msg(tg_id, msg, buttons)
示例#23
0
 def rm_btn(self, tg_id: int, btn_id: int, is_sure: bool = False):
     if not is_sure:
         self.make_sure_rm_btn(tg_id, btn_id)
         return
     else:
         rm_btn_msg_resp = json.loads(
             requests.post(
                 DB_URL.format(item='message', cmd='rm_button'),
                 json={
                     'msg_id': self.id,
                     'tg_id': tg_id,
                     'button_id': btn_id,
                 },
             ).text)
     if rm_btn_msg_resp.get('error'):
         msg = rm_btn_msg_resp.get('error')
         tools.send_menu_msg(tg_id, msg)
     else:
         self.buttons = rm_btn_msg_resp.get('buttons')
         self.show(tg_id)
示例#24
0
    def edit_timeout(self, tg_id: int, timeout: int):
        req_data = {
            'msg_id': self.id,
            'chapter_id': self.chapter_id,
            'timeout': timeout,
            'content_type': self.content_type,
            'tg_id': tg_id,
        }
        edit_msg_resp = json.loads(
            requests.post(
                DB_URL.format(item='message', cmd='edit'),
                json=req_data,
            ).text)

        if edit_msg_resp.get('error'):
            msg = edit_msg_resp.get('error')
            tools.send_menu_msg(tg_id, msg)
        else:
            self.timeout = edit_msg_resp['timeout']
            self.show(tg_id)
示例#25
0
def make_new_btn(tg_id: int, msg: str, text: str):
    user_context = mem.UserContext(tg_id)
    new_btn_msg_resp = json.loads(
        requests.post(
            DB_URL.format(item='message', cmd='add_button'),
            json={
                'msg_id': user_context.get_context('message_id'),
                'chapter_id': user_context.get_context('chapter_id'),
                'tg_id': tg_id,
                'text': text,
            },
        ).text
    )
    if new_btn_msg_resp.get('error'):
        msg = new_btn_msg_resp.get('error')
        tools.send_menu_msg(tg_id, msg)
    else:
        _button = Button(
            user_context.get_context('message_id'),
            new_btn_msg_resp.get('buttons')[-1].get('id'),
        )
        _button.show(tg_id)
示例#26
0
 def __init__(self, message_id: int):
     msg_resp = json.loads(
         requests.post(
             DB_URL.format(item='message', cmd='get'),
             json={
                 'msg_id': message_id
             },
         ).text)
     self.id = int(msg_resp.get('id'))
     self.story_id = msg_resp.get('story_id')
     self.content_type = msg_resp.get('content_type')
     self.timeout = msg_resp.get('timeout')
     self.is_start_chapter = msg_resp.get('is_start_chapter')
     self.chapter_id = int(msg_resp.get('chapter_id'))
     self.message = msg_resp.get('message')
     self.media = msg_resp.get('media')
     self.link = msg_resp.get('link')
     self.from_buttons = msg_resp.get('from_buttons')
     self.parrent = msg_resp.get('parrent')
     self.buttons = msg_resp.get('buttons')
     self.wait_reaction = msg_resp.get('wait_reaction')
     self.referal_block = msg_resp.get('referal_block')
示例#27
0
    def show(self, tg_id: int):
        if self.content_type == 'text':
            data = self.message
        elif self.content_type in ['photo', 'voice', 'video_note']:
            data = {}
            media = requests.get(DB_URL.format(
                item='media',
                cmd='get/{item_id}',
            ),
                                 params={
                                     'item_id':
                                     hashlib.sha224(
                                         bytes(f'{self.media["id"]}{self.id}',
                                               'utf-8')).hexdigest()
                                 }).content
            data['media'] = media
            data['caption'] = self.message
        user_context = mem.UserContext(tg_id)
        user_context.set_status('in_menu')
        user_context.update_context('message_id', str(self.id))
        buttons = []
        if not self.link:
            for btn in self.buttons:
                if btn['next_message_id']:
                    buttons.append([
                        (f'{btn["text"]} => К сообщению',
                         tools.make_call_back(SHOW_PREFIX, {
                             'msg_id': btn['next_message_id'],
                         }))
                    ])
                else:
                    buttons.append([
                        (f'{btn["text"]} => Создать сообщение',
                         tools.make_call_back(MAKE_PREFIX, {
                             'from_msg_id': self.id,
                             'from_btn_id': btn['id'],
                         }))
                    ])
                buttons.append([
                    ('Delete',
                     tools.make_call_back(RM_BUTTON_PREFIX,
                                          {'btn_id': btn['id']})),
                    ('New text',
                     tools.make_call_back(EDIT_BUTTON_PREFIX,
                                          {'btn_id': btn['id']})),
                    ('Add link',
                     tools.make_call_back(ADD_BUTTON_LINK_PREFIX,
                                          {'btn_id': btn['id']})),
                ])
                if btn['number'] < len(self.buttons) - 1:
                    buttons[-1].append(
                        ('Down',
                         tools.make_call_back(MOVE_BUTTON_PREFIX, {
                             'btn_id': btn['id'],
                             'move': 1,
                         })))
                if btn['number'] > 0:
                    buttons[-1].append(
                        ('Up',
                         tools.make_call_back(MOVE_BUTTON_PREFIX, {
                             'btn_id': btn['id'],
                             'move': -1,
                         })))
            buttons.append([
                ('Добавить ответ', tools.make_call_back(ADD_BUTTON_PREFIX)),
            ])
        direct_msg_buttons = []
        if self.parrent:
            direct_msg_buttons.append(('<=',
                                       tools.make_call_back(
                                           SHOW_PREFIX,
                                           {'msg_id': self.parrent},
                                       )))

        if not self.buttons:
            direct_msg_buttons.append(
                ('Add direct link',
                 tools.make_call_back(ADD_DIRECT_LINK_PREFIX, {
                     'from_msg_id': self.id,
                 })))
            if self.link:
                direct_msg_buttons.append(('=>',
                                           tools.make_call_back(
                                               SHOW_PREFIX,
                                               {'msg_id': self.link},
                                           )))
            else:
                direct_msg_buttons.append(
                    ('Add direct msg',
                     tools.make_call_back(MAKE_PREFIX, {
                         'from_msg_id': self.id,
                     })))

        buttons.append(direct_msg_buttons)
        back_from_buttons = []
        if self.from_buttons:
            for from_btn in self.from_buttons:
                back_from_buttons.append((
                    f'<= {from_btn["text"][:15]}',
                    tools.make_call_back(
                        SHOW_PREFIX,
                        {'msg_id': from_btn['parrent_message_id']}),
                ))
        buttons.append(back_from_buttons)
        buttons.append([
            ('Редактировать', tools.make_call_back(EDIT_PREFIX)),
            (f'Задержка - {self.timeout}с.',
             tools.make_call_back(EDIT_TIMEOUT_PREFIX)),
            (f'Реакция - {self.wait_reaction.get("name")}',
             tools.make_call_back(CHANGE_REACTION_PREFIX)),
        ])
        buttons.append([
            (f'Referal block - {self.referal_block}',
             tools.make_call_back(EDIT_REFERAL_BLOCK_PREFIX)),
            ('Все сообщения', None, '{app_url}chapter/{chapter_uid}'.format(
                app_url=APP_URL,
                chapter_uid=hashlib.sha224(
                    bytes(f'{self.chapter_id}{tg_id}', 'utf-8')).hexdigest(),
            )),
        ])
        buttons.append([
            ('Удалить', tools.make_call_back(RM_PREFIX)),
            ('К главе', tools.make_call_back(chapter.SHOW_PREFIX)),
        ])
        tools.send_menu_msg(tg_id,
                            data,
                            buttons,
                            content_type=self.content_type)
def chapter_map(chapter_hash):
    chapter_map_resp = json.loads(
        requests.post(
            DB_URL.format(item='chapter', cmd='get_chapter_map'),
            json={
                'chapter_hash': chapter_hash,
            },
        ).text)
    story_dict = {}
    next_msgs = []
    writed_msgs = set()
    for msg in chapter_map_resp['messages']:
        if msg['is_start_chapter']:
            next_msgs = [msg['id']]
            writed_msgs = {msg['id']}
        story_dict[msg['id']] = msg
    messages = []
    next_chapter_msgs = []
    attach = True
    while len(next_msgs) > 0:
        msgs = []
        for msg_id in next_msgs:
            if msg_id in story_dict.keys():
                msgs.append(story_dict.get(msg_id))
            else:
                next_chapter_msgs.append(
                    json.loads(
                        requests.post(
                            DB_URL.format(item='message', cmd='get'),
                            json={
                                'msg_id': msg_id,
                            },
                        ).text))
                if next_chapter_msgs[-1]['content_type'] != 'text':
                    next_chapter_msgs[-1]['media'] = base64.b64encode(
                        requests.get(
                            DB_URL.format(
                                item='media',
                                cmd='get/{item_id}',
                            ),
                            params={
                                'item_id':
                                hashlib.sha224(
                                    bytes(
                                        f'{next_chapter_msgs[-1]["media"]["id"]}{next_chapter_msgs[-1]["id"]}',
                                        'utf-8')).hexdigest()
                            }).content).decode('utf-8')

        next_msgs = []
        for msg in msgs:
            if not msg:
                continue
            if msg['link'] and msg['link'] not in writed_msgs:
                next_msgs.append(msg['link'])
                writed_msgs.add(msg['link'])
            elif msg['buttons']:
                for btn in msg['buttons'][::-1]:
                    if btn['next_message_id'] not in writed_msgs and btn[
                            'next_message_id']:
                        next_msgs.append(btn['next_message_id'])
                        writed_msgs.add(btn['next_message_id'])
            if msg['content_type'] != 'text':
                msg['media'] = base64.b64encode(
                    requests.get(
                        DB_URL.format(
                            item='media',
                            cmd='get/{item_id}',
                        ),
                        params={
                            'item_id':
                            hashlib.sha224(
                                bytes(f'{msg["media"]["id"]}{msg["id"]}',
                                      'utf-8')).hexdigest()
                        }).content).decode('utf-8')
            messages.append({'data': msg, 'is_attach': attach})
        if len(next_msgs) == 0:
            attach = False
            unattached_keys = story_dict.keys() - writed_msgs
            for msg_id in unattached_keys:
                msg = story_dict[msg_id]
                if not msg['parrent'] and not msg['from_buttons']:
                    next_msgs.append(msg['id'])
                    writed_msgs.add(msg['id'])
                    break
    return render_template(
        'chapter_template.html',
        story_name=chapter_map_resp['story'],
        chapter_name=chapter_map_resp['name'],
        story_id=chapter_map_resp['story_id'],
        bot_url=BOT_URL,
        messages=messages,
        next_chapter_msgs=next_chapter_msgs,
    )