def from_api(cls, update: messaging_pb2.UpdateMessage) -> 'UpdateMessage':
     return cls(Peer.from_api(update.peer),
                Peer(update.sender_uid, PeerType.PEERTYPE_PRIVATE),
                UUID.from_api(update.mid),
                MessageContent.from_api(update.message),
                [UUID.from_api(x) for x in update.forward.mids],
                [UUID.from_api(x) for x in update.reply.mids],
                UUID.from_api(update.previous_mid), update.date)
 def from_api(cls, message: messaging_pb2.HistoryMessage) -> 'Message':
     return cls(UUID.from_api(message.mid), UUID.from_api(message.prev_mid),
                Peer(message.sender_uid, PeerType.PEERTYPE_PRIVATE),
                MessageContent.from_api(message.message),
                [UUID.from_api(x) for x in message.reply.mids],
                [UUID.from_api(x) for x in message.forward.mids],
                message.date, message.edited_at.value)
 def send_finish_msg(self, uid, periodicity, text, time, tz):
     if periodicity == 'everyday':
         if time.day != datetime.utcnow().day:
             periodicity = 'tomorrow'
         else:
             periodicity = 'today'
     day = [y for (x, y) in PERIODICITY if periodicity == x][0].lower()
     time += tz
     time = time.strftime("%H:%M")
     self.bot.messaging.send_message(Peer(uid, PeerType.PEERTYPE_PRIVATE),
                                      BOT_ANSWERS['FINISH'].format(day, text, time))
Exemple #4
0
class Group:
    def __init__(self, id_: int, data: GroupData) -> None:
        self.data = data
        self.peer = Peer(id_, PeerType.PEERTYPE_GROUP)

    @classmethod
    def from_api(cls, group: groups_pb2.Group) -> 'Group':
        return cls(group.id, GroupData.from_api(group.data))

    def __dict__(self):
        return {"data": self.data.__dict__(), "peer": self.peer.__dict__()}

    def __str__(self):
        return "Group({})".format(self.__dict__())
Exemple #5
0
class User:
    def __init__(self, id: int, data: UserData = None) -> None:
        self.data = data
        self.peer = Peer(id, PeerType.PEERTYPE_PRIVATE)

    @classmethod
    def from_api(cls, user: users_pb2.User) -> 'User':
        return cls(user.id, UserData.from_api(user.data))

    def __dict__(self):
        return {"data": self.data.__dict__(), "peer": self.peer.__dict__()}

    def __str__(self):
        return "User({})".format(self.__dict__())
Exemple #6
0
 def save_token(uid):
     if request.method == "POST":
         db = MongoClient(MONGODBLINK)[DBNAME]
         db["tokens"].replace_one(
             {'_id': int(uid)},
             {'value': request.form["token"].replace('#token=', '')},
             upsert=True)
         peer = Peer(int(uid), PeerType.PEERTYPE_PRIVATE)
         wrapper.strategy.bot.messaging.send_message(
             peer, ANSWERS['auth_success'].format(
                 wrapper.strategy.bot.users.get_user_by_id(
                     int(uid)).wait().data.name))
         wrapper.strategy._handle_menu(peer)
         return redirect('/success')
     else:
         return render_template('main.html')
Exemple #7
0
 def _find_publish(self, params, bot_name):
     text = params.message.text_message.text
     if '@' + bot_name in text:
         _id =  text.split(' ')[-1]
         poll_id = text.replace('@{} '.format(bot_name), '')
         group = self.bot.groups.find_group_by_id(params.peer.id).wait()
         title = self.get_value(poll_id, DBNames.TITLES.value)
         if not title:
             mid = UUID.from_api(params.mid)
             self.bot.messaging.reply(params.peer, [mid], config['WRONG_MESSAGE'])
             return
         uid = int(poll_id.split('p')[0])
         options = self.get_value(poll_id, DBNames.OPTIONS.value)
         self.send_poll(params.peer, title, options.split(' \n '), poll_id)
         self.send_poll(Peer(uid, PeerType.PEERTYPE_PRIVATE),
                         'Готово, опрос опубликован в группу {}. \n \n {}'.format(group.data.title, title), options.split(' \n '), creator=True, poll_id=poll_id)
         return True
Exemple #8
0
    def find_group_by_id(self, group_id: int) -> Group or None:
        """Find and return Group by id

        :param group_id: group's
        :return: Group or None if could not find
        """
        out_peer = self.__get_out_peer(Peer(group_id, PeerType.PEERTYPE_GROUP))
        if out_peer is None:
            return None

        request = sequence_and_updates_pb2.RequestGetReferencedEntitites(
            groups=[out_peer])
        result = self.internal.updates.GetReferencedEntitites(request).groups
        self.manager.add_out_peer(
            peers_pb2.OutPeer(id=result[0].id,
                              type=PeerType.PEERTYPE_GROUP,
                              access_hash=result[0].access_hash))
        return Group.from_api(result[0])
 def strategy(self):
     while True:
         if self.kill:
             return
         try:
             now = datetime.utcnow()
             for x in self.db.events.find({'is_completed': True, 'time': {'$lt': now - timedelta(seconds=1),
                                                                      '$gt':now - timedelta(minutes=10)}}):
                 self.bot.messaging.send_message(Peer(x['uid'], PeerType.PEERTYPE_PRIVATE), 
                                             BOT_ANSWERS['REMIND'] + x['text'])
                 if x['periodicity'] == 'everyday':
                     time = x['time'] + timedelta(days=1)
                     self.update_value(x['_id'], 'time', time)
                 else:
                     self.db.events.remove(x)
         except Exception as e:
             logging.exception(e)
             continue
Exemple #10
0
class TestMessaging(unittest.TestCase):
    bot.internal.messaging = Messaging()
    bot.internal.updates = Updates()
    bot.internal.media_and_files = MediaAndFiles()

    test_file = "../dialog_bot_sdk/examples/files/example.png"

    peer = Peer(1, PEERTYPE_PRIVATE)
    message = Message(UUID(1, 1), UUID(0, 0), peer, None, [], [], 0, 0)
    outpeer = peers_pb2.OutPeer(type=PEERTYPE_PRIVATE, id=0, access_hash=0)
    mid = definitions_pb2.UUIDValue(msb=0, lsb=0)
    msg_content = messaging_pb2.MessageContent()
    msg_content.textMessage.text = "Hello"
    interactive_media = [
        InteractiveMediaGroup([
            InteractiveMedia("1", InteractiveMediaButton("Yes", "Да")),
            InteractiveMedia("2", InteractiveMediaButton("No", "Нет")),
        ])
    ]

    # msg_content_with_group = copy.deepcopy(msg_content)
    # group[0].render(msg_content_with_group.textMessage.media.add())
    # doc_msg = messaging_pb2.DocumentMessage(
    #     file_id=0,
    #     access_hash=0,
    #     file_size=60,
    #     name=""
    # )

    def test_send_message(self):
        send = bot.messaging.send_message(self.peer, "text",
                                          self.interactive_media)
        self.assertTrue(isinstance(send, AsyncTask))
        self.assertTrue(isinstance(send.wait(), UUID))

    def test_update_message(self):
        update = bot.messaging.update_message(self.message, "text",
                                              self.interactive_media)
        self.assertTrue(isinstance(update, AsyncTask))
        self.assertIsNone(update.wait())

    def test_delete_message(self):
        delete = bot.messaging.delete(self.message)
        self.assertTrue(isinstance(delete, AsyncTask))
        self.assertIsNone(delete.wait())

    def test_get_messages_by_id(self):
        msg = bot.messaging.get_messages_by_id([UUID(1, 1)])
        self.assertTrue(isinstance(msg, AsyncTask))
        self.assertTrue(isinstance(msg.wait()[0], Message))

    def test_messages_read(self):
        read = bot.messaging.messages_read(self.peer, 0)
        self.assertTrue(isinstance(read, AsyncTask))
        self.assertIsNone(read.wait())

    @patch('requests.put')
    def test_send_file(self, put):
        put.return_value = Put(200)
        send = bot.messaging.send_file(self.peer, self.test_file)
        self.assertTrue(isinstance(send, AsyncTask))
        self.assertTrue(isinstance(send.wait(), UUID))
        put.return_value = Put(400)
        send = bot.messaging.send_file(self.peer, self.test_file)
        self.assertTrue(isinstance(send, AsyncTask))
        self.assertIsNone(send.wait())

    @patch('requests.put')
    def test_send_media(self, put):
        put.return_value = Put(200)
        image = bot.internal.uploading.upload_file(self.test_file).wait()
        media = MessageMedia(image=ImageMedia(ImageLocation(image)))
        send = bot.messaging.send_media(self.peer, [media])
        self.assertTrue(isinstance(send, AsyncTask))
        self.assertTrue(isinstance(send.wait(), UUID))

    @patch('requests.put')
    def test_send_image(self, put):
        put.return_value = Put(200)
        send = bot.messaging.send_image(self.peer, self.test_file)
        self.assertTrue(isinstance(send, AsyncTask))
        self.assertTrue(isinstance(send.wait(), UUID))
        put.return_value = Put(400)
        send = bot.messaging.send_image(self.peer, self.test_file)
        self.assertTrue(isinstance(send, AsyncTask))
        self.assertIsNone(send.wait())

    def test_reply(self):
        reply = bot.messaging.reply(self.peer, [UUID(1, 1)], None,
                                    self.interactive_media)
        self.assertTrue(isinstance(reply, AsyncTask))
        self.assertTrue(isinstance(reply.wait(), UUID))

    def test_forward(self):
        forward = bot.messaging.forward(self.peer, [UUID(1, 1)], None,
                                        self.interactive_media)
        self.assertTrue(isinstance(forward, AsyncTask))
        self.assertTrue(isinstance(forward.wait(), UUID))

    def test_load_message_history(self):
        history = bot.messaging.load_message_history(
            self.peer, 0, ListLoadMode.LISTLOADMODE_BACKWARD, 1)
        self.assertTrue(isinstance(history, AsyncTask))
        self.assertTrue(isinstance(history.wait()[0], Message))
Exemple #11
0
 def __init__(self, id_: int, data: GroupData) -> None:
     self.data = data
     self.peer = Peer(id_, PeerType.PEERTYPE_GROUP)
class TestGroups(unittest.TestCase):
    group_peer = Peer(id=0, type=PeerType.PEERTYPE_GROUP)
    user1 = Peer(id=0, type=PeerType.PEERTYPE_PRIVATE)
    test_file = "../dialog_bot_sdk/examples/files/example.png"

    bot.internal.groups = Groups()
    bot.internal.search = Search()
    bot.internal.media_and_files = MediaAndFiles()
    bot.internal.updates = Updates()

    def test_create_group(self):
        group = bot.groups.create_public_group("title", "short_name")
        self.assertTrue(isinstance(group, AsyncTask))
        self.assertTrue(isinstance(group.wait(), Group))
        group = bot.groups.create_private_group("title")
        self.assertTrue(isinstance(group, AsyncTask))
        self.assertTrue(isinstance(group.wait(), Group))
        group = bot.groups.create_public_channel("title", "short_name")
        self.assertTrue(isinstance(group, AsyncTask))
        self.assertTrue(isinstance(group.wait(), Group))
        group = bot.groups.create_private_channel("title")
        self.assertTrue(isinstance(group, AsyncTask))
        self.assertTrue(isinstance(group.wait(), Group))

    def test_find_group_by_short_name(self):
        group = bot.groups.find_group_by_short_name("title")
        self.assertTrue(isinstance(group, AsyncTask))
        self.assertIsNone(group.wait())
        bot.manager.add_out_peer(
            peers_pb2.OutPeer(id=1,
                              access_hash=1,
                              type=PeerType.PEERTYPE_GROUP))
        group = bot.groups.find_group_by_short_name("short_name")
        self.assertTrue(isinstance(group, AsyncTask))
        self.assertTrue(isinstance(group.wait(), Group))

    def test_find_group_by_id(self):
        group = bot.groups.find_group_by_id(1)
        self.assertTrue(isinstance(group, AsyncTask))
        self.assertIsNone(group.wait())
        bot.manager.add_out_peer(
            peers_pb2.OutPeer(id=1,
                              access_hash=1,
                              type=PeerType.PEERTYPE_GROUP))
        group = bot.groups.find_group_by_id(1)
        self.assertTrue(isinstance(group, AsyncTask))
        self.assertTrue(isinstance(group.wait(), Group))

    def test_load_members(self):
        members = bot.groups.load_members(self.group_peer, 2)
        self.assertTrue(isinstance(members, AsyncTask))
        self.assertTrue(isinstance(members.wait()[0], User))

    def test_kick_user(self):
        kick = bot.groups.kick_user(self.group_peer, self.user1)
        self.assertTrue(isinstance(kick, AsyncTask))
        self.assertIsNone(kick.wait())

    def test_invite_user(self):
        invite = bot.groups.invite_user(self.group_peer, self.user1)
        self.assertTrue(isinstance(invite, AsyncTask))
        self.assertIsNone(invite.wait())

    def test_set_default_group_permissions(self):
        permissions = bot.groups.set_default_group_permissions(self.group_peer)
        self.assertTrue(isinstance(permissions, AsyncTask))
        self.assertIsNone(permissions.wait())

    def test_set_member_permissions(self):
        permissions = bot.groups.set_member_permissions(
            self.group_peer, self.user1)
        self.assertTrue(isinstance(permissions, AsyncTask))
        self.assertIsNone(permissions.wait())

    def test_get_group_member_permissions(self):
        permissions = bot.groups.get_group_member_permissions(
            self.group_peer, [self.user1])
        self.assertTrue(isinstance(permissions, AsyncTask))
        self.assertEqual(permissions.wait(), [])

    def test_edit_group_title(self):
        title = bot.groups.edit_group_title(self.group_peer, "title")
        self.assertTrue(isinstance(title, AsyncTask))
        self.assertIsNone(title.wait())

    @patch('requests.put')
    def test_edit_avatar(self, put):
        put.return_value = Put(200)
        avatar = bot.groups.edit_avatar(self.group_peer, self.test_file)
        self.assertTrue(isinstance(avatar, AsyncTask))
        self.assertTrue(isinstance(avatar.wait(), Avatar))
        put.return_value = Put(400)
        avatar = bot.groups.edit_avatar(self.group_peer, self.test_file)
        self.assertTrue(isinstance(avatar, AsyncTask))
        self.assertIsNone(avatar.wait())

    def test_remove_group_avatar(self):
        remove = bot.groups.remove_group_avatar(self.group_peer)
        self.assertTrue(isinstance(remove, AsyncTask))
        self.assertIsNone(remove.wait())

    def test_edit_group_about(self):
        about = bot.groups.edit_group_about(self.group_peer, "about")
        self.assertTrue(isinstance(about, AsyncTask))
        self.assertIsNone(about.wait())

    def test_leave_group(self):
        leave = bot.groups.leave_group(self.group_peer)
        self.assertTrue(isinstance(leave, AsyncTask))
        self.assertIsNone(leave.wait())

    def test_make_user_admin(self):
        admin = bot.groups.make_user_admin(self.group_peer, self.user1, None)
        self.assertTrue(isinstance(admin, AsyncTask))
        self.assertIsNone(admin.wait())

    def test_transfer_ownership(self):
        owner = bot.groups.transfer_ownership(self.group_peer, self.user1)
        self.assertTrue(isinstance(owner, AsyncTask))
        self.assertIsNone(owner.wait())

    def test_get_group_invite_url(self):
        url = bot.groups.get_group_invite_url(self.group_peer)
        self.assertTrue(isinstance(url, AsyncTask))
        self.assertEqual(url.wait(), "url")

    def test_get_group_invite_url_base(self):
        url = bot.groups.get_group_invite_url_base()
        self.assertTrue(isinstance(url, AsyncTask))
        self.assertEqual(url.wait(), "url")

    def test_revoke_invite_url(self):
        url = bot.groups.revoke_invite_url(self.group_peer)
        self.assertTrue(isinstance(url, AsyncTask))
        self.assertEqual(url.wait(), "url")

    def test_join_group(self):
        group = bot.groups.join_group("url")
        self.assertTrue(isinstance(group, AsyncTask))
        self.assertTrue(isinstance(group.wait(), Group))

    def test_join_group_by_peer(self):
        group = bot.groups.join_group_by_peer(self.group_peer)
        self.assertTrue(isinstance(group, AsyncTask))
        self.assertIsNone(group.wait())
Exemple #13
0
 def __init__(self, id: int, data: UserData = None) -> None:
     self.data = data
     self.peer = Peer(id, PeerType.PEERTYPE_PRIVATE)
Exemple #14
0
 def from_api(cls, event: messaging_pb2.UpdateInteractiveMediaEvent) -> 'UpdateInteractiveMediaEvent':
     return cls(UUID.from_api(event.mid), event.id, event.value, Peer(event.uid, PeerType.PEERTYPE_PRIVATE))