Ejemplo n.º 1
0
 def test_get_insecure_bot(self, anon, token):
     token.return_value = "token"
     self.assertTrue(
         isinstance(DialogBot.get_insecure_bot("endpoint", None),
                    DialogBot))
     self.assertTrue(anon.called)
     self.assertTrue(token.called)
Ejemplo n.º 2
0
 def __init__(self):
     load_dotenv('.env')
     self.con = sqlite3.connect('db.db', check_same_thread=False)
     self.bot = DialogBot.get_secure_bot(os.environ.get('BOT_ENDPOINT'),
                                         grpc.ssl_channel_credentials(),
                                         os.environ.get('BOT_TOKEN'))
     self.bad = []
     self.bot.messaging.on_message_async(self.on_msg, self.on_click)
     while True:
         time.sleep(50)
         cur = self.con.cursor()
         users = cur.execute('SELECT * FROM users').fetchall()
         schedule = cur.execute('SELECT * FROM schedule').fetchall()
         current_time = int(time.time()) / 60
         for i in schedule:
             for e in users:
                 if int(i[3]) <= current_time - int(e[5]) / 60 <= int(
                         i[3]) + 1:
                     question = self.get_question(str(i[1]), int(i[2]))
                     self.bot.messaging.send_message(
                         self.bot.users.get_user_peer_by_id(e[0]),
                         '\U0001F44B Привет!\n'
                         'Это автоматическое сообщение, в котором содержится важная для тебя информация '
                         '(по крайней мере, так подумали наши менеджеры).\n\n'
                         '*%s*\n'
                         '%s' % (str(question[1]), str(question[2])))
         cur.close()
Ejemplo n.º 3
0
 def test_get_secure_bot(self, auth, token):
     token.return_value = "token"
     self.assertTrue(
         isinstance(
             DialogBot.get_secure_bot("endpoint",
                                      grpc.ssl_channel_credentials(),
                                      "token"), DialogBot))
     self.assertEqual(auth.call_args.args[0], "token")
     self.assertTrue(token.called)
Ejemplo n.º 4
0
 def test_send_to_chat(self):
     config["email_config"]["to_chat"] = True
     cfg = config["bot_config"]
     bot = DialogBot.get_secure_bot(
         os.environ[cfg["endpoint"]],
         grpc.ssl_channel_credentials(),
         os.environ[cfg["token"]]
     )
     with patch('dialog_bot_sdk.messaging.Messaging.send_file') as perm_mock:
         perm_mock.return_value = 1
         self.assertEqual(send_to_chat(bot, "peer", file1), "File sent to chat")
Ejemplo n.º 5
0
 def __init__(self):
     load_dotenv('.env')
     self.con = sqlite3.connect('db.db', check_same_thread=False)
     self.bot = DialogBot.get_secure_bot(
         os.environ.get('BOT_ENDPOINT'),
         grpc.ssl_channel_credentials(),
         os.environ.get('BOT_TOKEN')
     )
     self.header_style = xlwt.easyxf(
         'pattern: pattern solid, fore_colour light_yellow;'
         'font: bold True;'
         'borders: top_color black, bottom_color black, right_color black, left_color black,'
         'left thin, right thin, top thin, bottom thin;'
     )
     self.bot.messaging.on_message_async(self.on_msg, self.on_click)
Ejemplo n.º 6
0
 def start(self, *args, **kwargs):
     self.bot = DialogBot.get_secure_bot(
         self.
         endpoint,  # bot endpoint (specify different endpoint if you want to connect to your on-premise environment)
         grpc.ssl_channel_credentials(
         ),  # SSL credentials (empty by default!)
         self.token,  # bot token
         verbose=
         False  # optional parameter, when it's True bot prints info about the called methods, False by default
     )
     if not self.async_:
         self.bot.messaging.on_message(self.on_msg, self.on_click)
     else:
         self.bot.messaging.on_message_async(self.on_msg, self.on_click)
         self.strategy()
Ejemplo n.º 7
0
    def __init__(self, name: str, log_level=None):
        self.name = name
        self._log = logging.getLogger(f'\tBot:{self.name}\t')

        if log_level is not None:
            self._log.level = log_level

        self._bot = DialogBot.get_secure_bot(
            getenv('BOT_ENDPOINT', 'hackathon-mob.transmit.im'),  # bot endpoint from environment
            grpc.ssl_channel_credentials(),  # SSL credentials (empty by default!)
            getenv('BOT_TOKEN', '28a9a67267691d886fa571fdf051514fdeb6604a')  # bot token from environment
        )
        self._handlers = []
        self._peers: Dict[int, Peer] = {}
        self._current_dialogs: Dict[int, Generator] = {}
Ejemplo n.º 8
0
 def __init__(self, config):
     bot = config["bot"]
     self.connect = sqlite3.connect(os.path.dirname(__file__) +
                                    config["database"],
                                    check_same_thread=False)
     self.cursor = self.connect.cursor()
     self.commands = config["commands"]
     self.locale = config["lang"]
     self.timezone = config["timezone"]
     self.bot = DialogBot.get_secure_bot(bot["endpoint"],
                                         grpc.ssl_channel_credentials(),
                                         bot["token"])
     self.tracked_users = {}
     self.default_tracked_groups = {}
     self.reminder = {}
     self.cron_time = CRON_TIME
                                            interactive_media.InteractiveMedia(
                                                1, button_inf,
                                                style='primary'),
                                            interactive_media.InteractiveMedia(
                                                2,
                                                button_feedback,
                                                style='primary'),
                                            interactive_media.InteractiveMedia(
                                                3,
                                                button_stats,
                                                style='primary'),
                                            interactive_media.InteractiveMedia(
                                                4,
                                                button_recommendations,
                                                style='primary'),
                                        ])
                                    ])


# In[14]:

if __name__ == '__main__':

    bot = DialogBot.get_secure_bot(
        "hackathon-mob.transmit.im",  # bot endpoint from environment
        grpc.ssl_channel_credentials(),  # SSL credentials (empty by default!)
        "be9ca5de6087c9ac19824217526cbd2c61519ada"  # bot token from environment
    )

    bot.messaging.on_message(on_msg, on_click)
        bot.messaging.send_message(params[0].peer,
                                   greets[0])  #sending help msg


def on_click(*params):
    global btn_group
    global answers
    user_peer = bot.users.get_user_outpeer_by_id(params[0].uid)
    bot.messaging.send_message(user_peer, answers[int(params[0].value)])
    sleep(5)
    bot.messaging.send_message(user_peer, "Что еще вам подсказать??",
                               btn_group)


if __name__ == "__main__":
    bot = DialogBot.get_secure_bot("hackathon-mob.transmit.im",
                                   grpc.ssl_channel_credentials(), "TOKEN")
    with open("./greets.txt", "r") as greet_file:
        greets = greet_file.read().split(';')
    with open("./answers.txt", "r") as answers_file:
        answers = answers_file.read().split(';')
    with open("./themes.txt", "r") as themes_file:
        themes = themes_file.read().split('\n')
        if themes[len(themes) - 1] == "":
            themes = themes[:len(themes) - 1]  #trying to remove '' element
    btn_group = [interactive_media.InteractiveMediaGroup([])
                 ]  #preparing bot FAQ buttons
    for i in range(len(themes)):
        if i < 5:
            btn_group[0].actions.append(
                interactive_media.InteractiveMedia(
                    str(i),
Ejemplo n.º 11
0
        users.append(params[0].peer.id)
        date = datetime.now()
        last_time.append(date.hour * 60 * 60 + date.minute * 60 + date.second)
        user_not_seen_notification[params[0].peer.id] = list(
            data["Id"].unique())

    adding_person(params[0].peer.id, params[0].message.textMessage.text)


# In[10]:

if __name__ == '__main__':

    bot = DialogBot.get_secure_bot(
        "hackathon-mob.transmit.im",  # bot endpoint from environment
        grpc.ssl_channel_credentials(),  # SSL credentials (empty by default!)
        "3cb658bc94752d76c86fb0b051f58ac9e783c8d0"  # bot token from environment
    )

    bot.messaging.on_message_async(on_msg, on_click)
    #бесконечный цикл запускающий Push-уведомления
    while True:
        #Если user нет просто проходим
        if ((len(users) == 0) or (len(users) != len(last_time))):
            continue
        else:
            #После 20:00 до 8:00 не уведомляем
            date = datetime.now()

            for i in range(len(datas)):
                if len(datas[i]) == 3 and notif[i][1] == 1:
Ejemplo n.º 12
0
from dialog_bot_sdk.bot import DialogBot
import grpc
import os


def on_msg(*params):
    print('on msg', params)
    bot.messaging.send_message(
        params[0].peer,
        'Reply to : ' + str(params[0].message.textMessage.text))


if __name__ == '__main__':

    bot = DialogBot.get_secure_bot('hackathon-mob.transmit.im:443',
                                   grpc.ssl_channel_credentials(),
                                   os.environ.get('BOT_TOKEN'))
    bot.messaging.on_message(on_msg)
Ejemplo n.º 13
0
                })
                bot.messaging.send_message(
                    peer, "Введите количество денег на счету")

            bot.messaging.on_message(getting_current_leftover)

        bot.messaging.on_message(waiting_of_creating_company)

    if value == "get_admin_token":
        current_time = str(int(time.time() * 1000.0))
        token = get_company(id) + current_time
        tokens.insert_one({
            "token": token,
            "type": "Office-manager",
            "company": get_company(id),
            "time": current_time,
        })
        bot.messaging.send_message(peer, "Ключ для офис менеджера: " + token)


if __name__ == "__main__":
    bot = DialogBot.get_secure_bot(
        "hackathon-mob.transmit.im",  # bot endpoint (specify different endpoint if you want to connect to your on-premise environment)
        grpc.ssl_channel_credentials(),  # SSL credentials (empty by default!)
        bot_token,
        verbose=
        False,  # optional parameter, when it's True bot prints info about the called methods, False by default
    )

bot.messaging.on_message(main, on_click)
Ejemplo n.º 14
0
# coding: utf-8
from dialog_bot_sdk.peers import private_peer
from dialog_bot_sdk.bot import DialogBot
from dialog_api import messaging_pb2
#from threading import Thread
from dialog_bot_sdk import interactive_media
import time


def on_msg(*params):
    print('on msg', params)


if __name__ == '__main__':
    d = DialogBot.get_insecure_bot("grpc-test.transmit.im:8080",
                                   "c1ff5ca4b7e5fa4660c6a730fdcb613e31deafd8")

    # d = DialogBot.get_insecure_bot("localhost:8080", "a4e1d8a184f2a94400dd19492119cbe427d38ef8")
    # d.messaging.send_message(private_peer(966246115), "test", )


    def sender(count=10):
        i = 0
        while i < count:
            i += 1
            if i % 2 == 0:
                d.messaging.send_message(private_peer(966246115),
                                         "Simple text")
            else:
                d.messaging.send_message(
                    private_peer(966246115), "Interactive media %d" % i, [
Ejemplo n.º 15
0
import grpc

from dialog_bot_sdk.bot import DialogBot

bot = DialogBot.get_secure_bot('endpoint', grpc.ssl_channel_credentials(),
                               'token')
def testvarsAttempt():
    try:
        import testvars
    except ImportError:
        common.conMsg('bot','Predefined test variables not found, continue with environment variables')
        return None
    else:
        common.conMsg('bot','Predefined test variables found, environment variables ignored')
        return None

if __name__ == '__main__':
    common.conMsg('bot','Starting bot')
    testvarsAttempt()
    lang = os.environ['LANGUAGE']
    mode = os.environ['ISSUE_TYPE_MODE']
    bot = DialogBot.get_secure_bot(os.environ['ENDPOINT'],grpc.ssl_channel_credentials(),os.environ['BOT_API_KEY'], verbose=False)

    if checkEnvs():
        credentials = common.parseCreds(os.environ['JIRA_CREDS'])
        link = credentials[2]
        projectId = jira.getProjectIdByProjectKey(credentials,os.environ['PROJECT_KEY'])
        if projectId:
            initializeBot()
            #dbInit()
            common.conMsg('bot','Started bot. Mode: ' + mode)
            while True:
                task_manager()
        else:
            common.conMsg('bot','Invalid JIRA Creds or JIRA Service Desk Project. Unable to start bot')
    else:
        common.conMsg('bot','Env variables error')
Ejemplo n.º 17
0
from dialog_bot_sdk.bot import DialogBot
import grpc
import os


def on_msg(*params):
    print('on msg', params)
    d.messaging.send_message(params[0].peer,
                             str(params[0].message.textMessage.text))


if __name__ == '__main__':
    d = DialogBot.get_secure_bot(
        'grpc-test.transmit.im:8080',  # bot endpoint
        grpc.ssl_channel_credentials(),  # SSL credentials
        os.environ.get('BOT_TOKEN')  # bot token
    )

    d.messaging.on_message(on_msg)
Ejemplo n.º 18
0
    except Exception as exception:
        print(exception)
        print_error(peer, _('Some internal error happens'))


if __name__ == '__main__':
    try:
        config = parse_config()

        gtmhub_config = config['gtmhubConfig']
        dialog_config = config['dialogConfig']

        handler = GtmHubMetricHandler(gtmhub_config['url'], gtmhub_config['token'], gtmhub_config['account'])

        scheduler = GtmHubScheduler(handler.get_usernames_list(), scheduled_overview)

        bot = DialogBot.get_secure_bot(
            dialog_config['host']+':'+dialog_config['port'],
            grpc.ssl_channel_credentials(),
            dialog_config['token']
        )

        bot.messaging.on_message(on_message, on_interact)
    except KeyboardInterrupt as ex:
        print(_('Stopping scheduler thread ...'))
        if scheduler.loop.is_running() is True:
            scheduler.loop.stop()
    except Exception as ex:
        print(_('Error initializing the bot - {}').format(str(ex)))
        raise ex
Ejemplo n.º 19
0
                bot.messaging.send_message(group, "Now you owner!\nBye!")
                bot.groups.leave_group(group)
            else:
                bot.messaging.forward(peer, [params.mid], "Example for this command:\ncreate group title short_name")
        else:
            bot.messaging.send_message(peer, "Reply: {}".format(text))
    else:
        print(params)


def on_event(params):
    peer = params.peer
    id = params.id
    value = params.value
    if id == "select_id":
        bot.messaging.send_message(peer, "selected {}".format(value))
    elif id == "button_yes":
        bot.messaging.send_message(peer, "Okey!")
    elif id == "button_no":
        bot.messaging.send_message(peer, "Why not? :(")


if __name__ == '__main__':
    bot = DialogBot.get_secure_bot(
        'endpoint',                                 # bot endpoint
        grpc.ssl_channel_credentials(),             # SSL credentials (empty by default!)
        'token'                                     # bot token
    )

    bot.messaging.on_message_async(on_msg, on_event)
Ejemplo n.º 20
0
def create_file(length=1_000_000):
    alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
    result = ''
    for _ in range(length):
        result += alphabet[random.randint(0, len(alphabet) - 1)]
    filename = 'testfile_' + result[:10]
    with open(filename, 'w+') as f:
        f.write(result)
    return filename


if __name__ == '__main__':

    bot1 = DialogBot.get_secure_bot(os.environ.get('BOT_ENDPOINT'),
                                    grpc.ssl_channel_credentials(),
                                    os.environ.get('FIRST_BOT_TOKEN'))
    bot2 = DialogBot.get_secure_bot(os.environ.get('BOT_ENDPOINT'),
                                    grpc.ssl_channel_credentials(),
                                    os.environ.get('SECOND_BOT_TOKEN'))

    start_http_server(8088)
    bot1_peer = bot1.peers.resolve_peer(bot1.user_info.user.data.nick.value)
    bot2_peer = bot1.peers.resolve_peer(bot2.user_info.user.data.nick.value)
    #a_zhvaluk_peer = bot1.peers.resolve_peer('a.zhvaluk')
    logging.basicConfig(filename="files-bot.log", level=logging.INFO)
    file_location_thread = Thread(
        target=bot2.messaging.on_message_async(on_msg)).start()

    while True:
        try:
Ejemplo n.º 21
0
import grpc
from dialog_bot_sdk.bot import DialogBot

from workers import workers


def get_worker(param, c_bot):
    for Worker in workers:
        if Worker.test(param.message.textMessage.text):
            return Worker(param, c_bot)


def on_msg(*params):
    worker = get_worker(params[0], bot)
    worker.run()


if __name__ == '__main__':
    bot = DialogBot.get_secure_bot('hackathon-mob.transmit.im',
                                   grpc.ssl_channel_credentials(),
                                   '7d099430b2a5d78e713aef40018ecfb44f89d5db')

    bot.messaging.on_message(on_msg)
Ejemplo n.º 22
0
                interactive_media.InteractiveMedia(
                    3,
                    interactive_media.InteractiveMediaButton("feedback", "Запросить FEEDBACK")
                ),
            ]
        )]
    )
    

def on_click(*params):
    print(params[0])
    which_button = params[0].value
    if which_button == "Yes":
        DataBase.insert_id(params[0].uid)
       # bot.messaging.update_message(p, text = "Всё супер")
    #id = params[0].uid
    #peer = {type: PEERTYPE_PRIVATE, id: id, str_id {}}
    #if which_button == "feedback":
    #    bot.messaging.send_message(peer, "Держи")
#print(params.id)
    #if params[0]

if __name__ == '__main__':
    bot = DialogBot.get_secure_bot(
        'hackathon-mob.transmit.im',  # bot endpoint (specify different endpoint if you want to connect to your on-premise environment)
        grpc.ssl_channel_credentials(), # SSL credentials (empty by default!)
        'b120071b560f1ef597b6a56363ee171bbbdd9fc9',  # bot token
        verbose=False # optional parameter, when it's True bot prints info about the called methods, False by default
    )

    bot.messaging.on_message(on_msg, on_click)
Ejemplo n.º 23
0
            f.write(user.org + '\n')
        bot.messaging.send_message(
            peer,
            "Новые отзывы от {0} получены!\nЕсли хотите сделать это позже, то напишите мне снова."
            .format(user.org))
        user.lock_msg = True
        return
    elif which_button == "No":
        group = edit_data()
        del_buttons(bot, peer)
        bot.messaging.send_message(peer, "Что Вы хотели бы исправить?", group)
        user.lock_msg = True
        return
    elif which_button == "all":
        user.last_key = "second_name"
        del_buttons(bot, peer)
        bot.messaging.send_message(peer, phrases["second_name"])
    else:
        user.last_key = "to_check_" + which_button
        del_buttons(bot, peer)
        bot.messaging.send_message(peer, phrases[which_button])
    user.lock_msg = False


if __name__ == '__main__':
    cfg = config["bot_config"]
    bot = DialogBot.get_secure_bot(cfg['endpoint'],
                                   grpc.ssl_channel_credentials(),
                                   cfg['token'])
    bot.messaging.on_message_async(on_msg, on_click)
Ejemplo n.º 24
0
        del_file(files)
        bot.messaging.send_message(
            peer,
            "Письмо с визиткой отправлено на вашу почту {0}!\nЕсли хотите создать новую визитку, нажмите на кнопку."
            .format(user.e_mail), new_form())
        user.lock_msg = True
        return
    elif which_button == "No":
        group = edit_data()
        del_buttons(bot, peer)
        bot.messaging.send_message(peer, "Что Вы хотели бы исправить?", group)
        user.lock_msg = True
        return
    elif which_button == "all":
        user.last_key = "second_name"
        del_buttons(bot, peer)
        bot.messaging.send_message(peer, phrases["second_name"])
    else:
        user.last_key = "to_check_" + which_button
        del_buttons(bot, peer)
        bot.messaging.send_message(peer, phrases[which_button])
    user.lock_msg = False


if __name__ == '__main__':
    cfg = config["bot_config"]
    bot = DialogBot.get_secure_bot(os.environ[cfg["endpoint"]],
                                   grpc.ssl_channel_credentials(),
                                   os.environ[cfg["token"]])
    bot.messaging.on_message_async(on_msg, on_click)
Ejemplo n.º 25
0
from dialog_bot_sdk.bot import DialogBot
import grpc
import os


def on_msg(*params):
    print('on msg', params)
    bot.messaging.send_message(
        params[0].peer,
        'Reply to : ' + str(params[0].message.textMessage.text))


if __name__ == '__main__':
    bot = DialogBot.get_secure_bot(
        'grpc-test.transmit.im:9443',  # bot endpoint
        grpc.ssl_channel_credentials(),  # SSL credentials (empty by default!)
        os.environ.get('BOT_TOKEN')  # bot token
    )

    bot.messaging.on_message(on_msg)
Ejemplo n.º 26
0
from dialog_bot_sdk.bot import DialogBot
import grpc
import os


def on_msg(*params):
    message = bot.messaging.send_message(
        params[0].peer,
        'Reply to : ' + str(params[0].message.textMessage.text))


if __name__ == '__main__':
    bot = DialogBot.get_secure_bot(
        'eem.dlg.im:443',  # bot endpoint
        grpc.ssl_channel_credentials(),  # SSL credentials (empty by default!)
        'e60137c00345e62ea8a21506cfe31b2be10852ec'  # bot token
    )

    bot.messaging.on_message(on_msg)
Ejemplo n.º 27
0
from dialog_bot_sdk.bot import DialogBot
import grpc

token = '56b606b2217d28d75960fd0a41a75ac448882fd5'
endpoint = 'hackathon-mob.transmit.im'
bot = DialogBot.get_secure_bot(endpoint,
                               grpc.ssl_channel_credentials(),
                               token,
                               verbose=True)

DBHOST = 'localhost'
BDPORT = 27017
DBNAME = 'bot1'
Ejemplo n.º 28
0
    elif message == 'вывести расходы':
        out_cons(message, peer)
    elif message == 'удалить расход':
        delete_con(message, peer)
    elif message == 'удалить период':
        delete_period(message, peer)
    elif message == 'скачать файл':
        get_file(peer)
    else:
        bot.messaging.send_message(peer, "Введите 'help' для помощи")


if __name__ == '__main__':
    bot = DialogBot.get_secure_bot(
        "hackathon-mob.transmit.im",  # bot endpoint from environment
        grpc.ssl_channel_credentials(),  # SSL credentials (empty by default!)
        '7f38e457bebadf578dbba6d5ccbacd4b3e926938'  # bot token from environment
    )
    bot.messaging.on_message(on_msg, on_click)

# In[ ]:


def help(peer):
    msg = "Введите:\n"
    msg += "'добавить период' для добавления периода с остатком денежных средств;\n"
    msg += "'добавить расходы' для добавления расходов в выбранном периоде;\n"
    msg += "'вывести расходы' для отображения расходов для выбранного периода;\n"
    msg += "'удалить расход' для удаления расхода для выбранного периода;\n"
    msg += "'удалить период' для удаления периода со всеми расходами;\n"
    msg += "'скачать файл' для скачивания Excel файла со всеми расходами."
Ejemplo n.º 29
0
            return

        state = User.select().where(
            User.uid == params[0].sender_uid).get().state

        if params[0].message.textMessage.text == "/cancel" or params[
                0].message.textMessage.text == "/menu":
            utils.cancel_handler(bot, params)

        elif state == "NEW_REVIEW":
            new_review_handler(bot, params)

        elif state == "NEW_EVENT":
            new_event_handler(bot, params)

        else:
            unknown_message_handler(bot, params)

    except:
        error_handler(bot, params)


if __name__ == '__main__':
    bot = DialogBot.get_secure_bot(
        ENDPOINT,  # bot endpoint from environment
        grpc.ssl_channel_credentials(),  # SSL credentials (empty by default!)
        BOT_TOKEN  # bot token from environment
    )

    bot.messaging.on_message(on_msg, on_click)
Ejemplo n.º 30
0
    SETTINGS_PATH = "../settings.json"

    log = logging.getLogger()
    log.setLevel(logging.INFO)
    log.addHandler(logging.StreamHandler())

    if os.path.exists(SETTINGS_PATH):
        try:
            SETTINGS = json.load(open(SETTINGS_PATH))
        except:
            log.error("Can't load settings", exc_info=True)
            sys.exit(1)

        try:
            bot = DialogBot.get_secure_bot(
                os.environ.get('BOT_ENDPOINT'),  # bot endpoint
                grpc.ssl_channel_credentials(),  # SSL credentials (empty by default!)
                os.environ.get('BOT_TOKEN')  # bot token
            )

            # bot.messaging.on_message(on_msg)
            bot.messaging.on_message(on_msg, raw_callback=raw_handler)
            log.error("Ready")
        except:
            log.error("Can't initialize bot", exc_info=True)
            sys.exit(1)
    else:
        log.error("{0} not found. Create one using settings_default.json as reference.".format(SETTINGS_PATH),
                  exc_info=True)
        sys.exit(1)